UNPKG

8.82 kBJavaScriptView Raw
1/*
2 * periodic
3 * http://github.com/typesettin/periodic
4 *
5 * Copyright (c) 2014 Yaw Joseph Etse. All rights reserved.
6 */
7
8'use strict';
9
10var fs = require('fs-extra'),
11 merge = require('utils-merge'),
12 path = require('path'),
13 logger,
14 appSettings;
15
16/**
17 * A group of utility functions for restarting periodic's express application and helper functions to manipulate strings and other data structures.
18 * @{@link https://github.com/typesettin/periodicjs.core.utilities}
19 * @author Yaw Joseph Etse
20 * @copyright Copyright (c) 2014 Typesettin. All rights reserved.
21 * @license MIT
22 * @constructor
23 * @requires module:fs
24 * @requires module:util-merge
25 * @requires module:path
26 */
27var Utilities = function (resources) {
28 logger = resources.logger;
29 appSettings = resources.settings;
30};
31
32/**
33 * simple helper function for validating mongo object IDs
34 * @param {string} str mongo object id
35 * @return {Boolean} [description]
36 */
37Utilities.prototype.isValidObjectID = function (str) {
38 // coerce to string so the function can be generically used to test both strings and native objectIds created by the driver
39 str = str + '';
40 var len = str.length,
41 valid = false;
42 if (len === 12 || len === 24) {
43 valid = /^[0-9a-fA-F]+$/.test(str);
44 }
45 return valid;
46};
47
48/**
49 * shorthand method for running shell commands
50 * @param {string} cmd shell command
51 * @param {array} args command line arguments
52 * @param {function} callBack async callback
53 * @return {function} callback(response)
54 */
55Utilities.prototype.run_cmd = function (cmd, args, callBack) {
56 var spawn = require('child_process').spawn;
57 var child = spawn(cmd, args);
58 var resp = '';
59
60 child.stdout.on('data', function (buffer) {
61 resp += buffer.toString();
62 });
63 child.stdout.on('end', function () {
64 callBack(resp);
65 });
66 //run_cmd( "ls", ["-l"], function(text) { console.log (text) });
67};
68
69/**
70 * shorthand method for running shell commands
71 * @param {string} cmd shell command
72 * @param {array} args command line arguments
73 * @param {function} asynccallback async callback
74 * @param {function} callBack callback
75 * @return {function} callback(response)
76 */
77Utilities.prototype.async_run_cmd = function (cmd, args, asynccallback, callback) {
78 //logger.silly('cmd', cmd);
79 //logger.silly('args', args);
80 var spawn = require('child_process').spawn;
81 var child = spawn(cmd, args);
82 // var resp = '';
83
84 child.stdout.on('error', function (err) {
85 console.log('got error callback');
86 callback(err, null);
87 });
88 child.stdout.on('data', function (buffer) {
89 asynccallback(buffer.toString());
90 });
91 child.stderr.on('data', function (buffer) {
92 asynccallback(buffer.toString());
93 });
94 // child.stdout.on('end', function() {
95 // console.log('got stdout end callback');
96 // callback(null,"command run: "+cmd+" "+args);
97 // });
98 // child.stderr.on('end', function() {
99 // console.log("got stderr end callback");
100 // callback(null,"command run: "+cmd+" "+args);
101 // });
102 child.on('exit', function () {
103 if(logger){
104 logger.silly('got exit callback');
105 }
106 callback(null, 'command run: ' + cmd + ' ' + args);
107 }); //run_cmd( "ls", ["-l"], function(text) { console.log (text) });
108};
109
110/**
111 * shorthand method for restarting periodic by updating the node script's watch file content/config/restart.json
112 * @param {object} options restartfile - define a custom restart file
113 */
114Utilities.prototype.restart_app = function (options) {
115 var d = new Date(),
116 restartfile = (typeof options === 'object' && options.restartfile)? options.restartfile : path.join(process.cwd(), '/content/config/restart.json'),
117 callback = options.callback;
118
119 if(logger){
120 logger.silly('application restarted');
121 }
122 fs.outputFile(restartfile, 'restart log ' + d + '- \r\n ', function (err) {
123 if (err) {
124 if(logger){
125 logger.silly('application restarted');
126 }
127 else{
128 console.error(err);
129 }
130 }
131 if(callback){
132 callback(err,'application started');
133 }
134 });
135};
136
137/**
138 * custom object sort by field
139 * @example
140 * req.controllerData.searchdocuments = searchdocuments.sort(CoreUtilities.sortObject('desc', 'createdat'));
141 * @param {string} dir either asc or desc
142 * @param {string} field object property to seach
143 * @return {function} object sort compare function
144 */
145Utilities.prototype.sortObject = function (dir, field) {
146 var comparefunction;
147 if (dir === 'desc') {
148 comparefunction = function (a, b) {
149 if (a[field] < b[field]) {
150 return 1;
151 }
152 if (a[field] > b[field]) {
153 return -1;
154 }
155 return 0;
156 };
157 }
158 else {
159 comparefunction = function (a, b) {
160 if (a[field] < b[field]) {
161 return -1;
162 }
163 if (a[field] > b[field]) {
164 return 1;
165 }
166 return 0;
167 };
168 }
169
170 return comparefunction;
171};
172
173/**
174 * remove empty object properties that have empty values
175 * @param {object} obj object to remove empty fields from
176 * @return {object} object with empty values removed
177 */
178Utilities.prototype.removeEmptyObjectValues = function (obj) {
179 for (var property in obj) {
180 if (typeof obj[property] === 'object') {
181 this.removeEmptyObjectValues(obj[property]);
182 }
183 else {
184 if (obj[property] === '' || obj[property] === ' ' || obj[property] === null || obj[property] === undefined || Object.keys(obj).length === 0) {
185 delete obj[property];
186 }
187 }
188 }
189 return obj;
190};
191
192/**
193 * replace boolean strings with actual boolean values
194 * @example
195 * updatedThemeSettings = CoreUtilities.replaceBooleanStringObjectValues(updatedThemeSettings);
196 * @param {object} obj object to substitute values
197 * @return {object} object with boolean values
198 */
199Utilities.prototype.replaceBooleanStringObjectValues = function (obj) {
200 for (var property in obj) {
201 if (typeof obj[property] === 'object') {
202 this.replaceBooleanStringObjectValues(obj[property]);
203 }
204 else {
205 if(obj[property] === 'true'){
206 obj[property] = true;
207 }
208 else if(obj[property] === 'false'){
209 obj[property] = false;
210 }
211 }
212 }
213 return obj;
214};
215
216/**
217 * remove private data from user objects
218 * @param {object} obj user object
219 * @return {object} object with removed private data
220 */
221Utilities.prototype.removePrivateInfo = function (obj) {
222 // console.log("removePrivateInfo obj",obj);
223 if (typeof obj === 'object') {
224 obj.password = null;
225 obj.apikey = null;
226 obj.random = null;
227 }
228 return obj;
229};
230
231/**
232 * replace all non alpha numeric tags with dashes and lowercase
233 * @param {string} textinput string to manipulate
234 * @return {string} manipulated string
235 */
236Utilities.prototype.stripTags = function (textinput) {
237 if (textinput) {
238 return textinput.replace(/[^a-z0-9@._]/gi, '-').toLowerCase();
239 }
240 else {
241 return false;
242 }
243};
244
245/**
246 * replace all non alpha numeric tags with dashes and lowercase
247 * @param {string} username string to manipulate
248 * @return {string} manipulated string
249 */
250Utilities.prototype.makeNiceName = function (username) {
251 if (username) {
252 return username.replace(/[^a-z0-9]/gi, '-').toLowerCase();
253 }
254 else {
255 return false;
256 }
257};
258
259/**
260 * replace all non alpha numeric tags with dashes and lowercase
261 * @param {string} username string to manipulate
262 * @return {string} manipulated string
263 */
264Utilities.prototype.makeNiceAttribute = function (username) {
265 if (username) {
266 return username.replace(/[^a-z0-9]/gi, '_').toLowerCase();
267 }
268 else {
269 return false;
270 }
271};
272
273/**
274 * add additional admin interface items from periodic extensions
275 * @param {object} options config options
276 * @return {object} admin menu json object
277 */
278Utilities.prototype.getAdminMenu = function (options) {
279 var adminmenu = {
280 menu: {
281 Content: {},
282 Themes: {},
283 Extensions: {},
284 Settings: {},
285 User: {}
286 }
287 };
288 if(logger && logger.silly && options){
289 logger.silly(options);
290 }
291 for (var x in appSettings.extconf.extensions) {
292 if (appSettings.extconf.extensions[x].enabled === true && appSettings.extconf.extensions[x].periodicConfig['periodicjs.ext.admin']) {
293 var extmenudata = appSettings.extconf.extensions[x].periodicConfig['periodicjs.ext.admin'];
294 // console.log("before adminmenu",adminmenu);
295 if (extmenudata.menu.Content) {
296 adminmenu.menu.Content = merge(extmenudata.menu.Content, adminmenu.menu.Content);
297 }
298 if (extmenudata.menu.Themes) {
299 adminmenu.menu.Themes = merge(extmenudata.menu.Themes, adminmenu.menu.Themes);
300 }
301 if (extmenudata.menu.Extensions) {
302 adminmenu.menu.Extensions = merge(extmenudata.menu.Extensions, adminmenu.menu.Extensions);
303 }
304 if (extmenudata.menu.Settings) {
305 adminmenu.menu.Settings = merge(extmenudata.menu.Settings, adminmenu.menu.Settings);
306 }
307 if (extmenudata.menu.User) {
308 adminmenu.menu.User = merge(extmenudata.menu.User, adminmenu.menu.User);
309 }
310 // console.log("after adminmenu",adminmenu);
311 }
312 }
313 return adminmenu;
314};
315
316module.exports = Utilities;
\No newline at end of file