UNPKG

8.72 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
118 if(logger){
119 logger.silly('application restarted');
120 }
121 fs.outputFile(restartfile, 'restart log ' + d + '- \r\n ', function (err) {
122 if (err) {
123 if(logger){
124 logger.silly('application restarted');
125 }
126 else{
127 console.error(err);
128 }
129 }
130 });
131};
132
133/**
134 * custom object sort by field
135 * @example
136 * req.controllerData.searchdocuments = searchdocuments.sort(CoreUtilities.sortObject('desc', 'createdat'));
137 * @param {string} dir either asc or desc
138 * @param {string} field object property to seach
139 * @return {function} object sort compare function
140 */
141Utilities.prototype.sortObject = function (dir, field) {
142 var comparefunction;
143 if (dir === 'desc') {
144 comparefunction = function (a, b) {
145 if (a[field] < b[field]) {
146 return 1;
147 }
148 if (a[field] > b[field]) {
149 return -1;
150 }
151 return 0;
152 };
153 }
154 else {
155 comparefunction = function (a, b) {
156 if (a[field] < b[field]) {
157 return -1;
158 }
159 if (a[field] > b[field]) {
160 return 1;
161 }
162 return 0;
163 };
164 }
165
166 return comparefunction;
167};
168
169/**
170 * remove empty object properties that have empty values
171 * @param {object} obj object to remove empty fields from
172 * @return {object} object with empty values removed
173 */
174Utilities.prototype.removeEmptyObjectValues = function (obj) {
175 for (var property in obj) {
176 if (typeof obj[property] === 'object') {
177 this.removeEmptyObjectValues(obj[property]);
178 }
179 else {
180 if (obj[property] === '' || obj[property] === ' ' || obj[property] === null || obj[property] === undefined || Object.keys(obj).length === 0) {
181 delete obj[property];
182 }
183 }
184 }
185 return obj;
186};
187
188/**
189 * replace boolean strings with actual boolean values
190 * @example
191 * updatedThemeSettings = CoreUtilities.replaceBooleanStringObjectValues(updatedThemeSettings);
192 * @param {object} obj object to substitute values
193 * @return {object} object with boolean values
194 */
195Utilities.prototype.replaceBooleanStringObjectValues = function (obj) {
196 for (var property in obj) {
197 if (typeof obj[property] === 'object') {
198 this.replaceBooleanStringObjectValues(obj[property]);
199 }
200 else {
201 if(obj[property] === 'true'){
202 obj[property] = true;
203 }
204 else if(obj[property] === 'false'){
205 obj[property] = false;
206 }
207 }
208 }
209 return obj;
210};
211
212/**
213 * remove private data from user objects
214 * @param {object} obj user object
215 * @return {object} object with removed private data
216 */
217Utilities.prototype.removePrivateInfo = function (obj) {
218 // console.log("removePrivateInfo obj",obj);
219 if (typeof obj === 'object') {
220 obj.password = null;
221 obj.apikey = null;
222 obj.random = null;
223 }
224 return obj;
225};
226
227/**
228 * replace all non alpha numeric tags with dashes and lowercase
229 * @param {string} textinput string to manipulate
230 * @return {string} manipulated string
231 */
232Utilities.prototype.stripTags = function (textinput) {
233 if (textinput) {
234 return textinput.replace(/[^a-z0-9@._]/gi, '-').toLowerCase();
235 }
236 else {
237 return false;
238 }
239};
240
241/**
242 * replace all non alpha numeric tags with dashes and lowercase
243 * @param {string} username string to manipulate
244 * @return {string} manipulated string
245 */
246Utilities.prototype.makeNiceName = function (username) {
247 if (username) {
248 return username.replace(/[^a-z0-9]/gi, '-').toLowerCase();
249 }
250 else {
251 return false;
252 }
253};
254
255/**
256 * replace all non alpha numeric tags with dashes and lowercase
257 * @param {string} username string to manipulate
258 * @return {string} manipulated string
259 */
260Utilities.prototype.makeNiceAttribute = function (username) {
261 if (username) {
262 return username.replace(/[^a-z0-9]/gi, '_').toLowerCase();
263 }
264 else {
265 return false;
266 }
267};
268
269/**
270 * add additional admin interface items from periodic extensions
271 * @param {object} options config options
272 * @return {object} admin menu json object
273 */
274Utilities.prototype.getAdminMenu = function (options) {
275 var adminmenu = {
276 menu: {
277 Content: {},
278 Themes: {},
279 Extensions: {},
280 Settings: {},
281 User: {}
282 }
283 };
284 if(logger && logger.silly && options){
285 logger.silly(options);
286 }
287 for (var x in appSettings.extconf.extensions) {
288 if (appSettings.extconf.extensions[x].enabled === true && appSettings.extconf.extensions[x].periodicConfig['periodicjs.ext.admin']) {
289 var extmenudata = appSettings.extconf.extensions[x].periodicConfig['periodicjs.ext.admin'];
290 // console.log("before adminmenu",adminmenu);
291 if (extmenudata.menu.Content) {
292 adminmenu.menu.Content = merge(extmenudata.menu.Content, adminmenu.menu.Content);
293 }
294 if (extmenudata.menu.Themes) {
295 adminmenu.menu.Themes = merge(extmenudata.menu.Themes, adminmenu.menu.Themes);
296 }
297 if (extmenudata.menu.Extensions) {
298 adminmenu.menu.Extensions = merge(extmenudata.menu.Extensions, adminmenu.menu.Extensions);
299 }
300 if (extmenudata.menu.Settings) {
301 adminmenu.menu.Settings = merge(extmenudata.menu.Settings, adminmenu.menu.Settings);
302 }
303 if (extmenudata.menu.User) {
304 adminmenu.menu.User = merge(extmenudata.menu.User, adminmenu.menu.User);
305 }
306 // console.log("after adminmenu",adminmenu);
307 }
308 }
309 return adminmenu;
310};
311
312module.exports = Utilities;
\No newline at end of file