-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnode_helper.js
282 lines (260 loc) · 8.33 KB
/
node_helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const NodeHelper = require("node_helper");
const path = require("path");
const fs = require('fs');
module.exports = NodeHelper.create({
start: function(){
this.createRoutes(this);
this.configPath = path.join(__dirname, "../..", "config/config.js");
this.tempConfigPath = path.join(__dirname, "../..", "config/config.page_selector_temp.js");
this.tempPath = path.join(__dirname, "temp.json")
},
//Page can also be changed externally by calling to the /selectPage endpoint
createRoutes: function() {
const self = this;
self.expressApp.get("/selectPage/:pageId", (req, res) => {
self.sendSocketNotification("PAGE_SELECT", req.params.pageId.toLowerCase());
res.send(`Updating page to ${req.params.pageId.toLowerCase()}`);
});
},
socketNotificationReceived: function(notification, payload) {
const self = this;
if(notification === "UPDATE_PAGES"){
self.getModulePages();
}else if(notification === "WRITE_TEMP"){
self.writeTemp(payload);
}else if(notification === "RESTORE_PAGE"){
self.restorePage()
}
},
getTempObject: function(){
try{
var obj = fs.readFileSync(this.tempPath);
jsonObj = JSON.parse(obj);
return jsonObj;
}catch(err){
return {};
}
},
writeTemp: function(updateVals){
//updateVals is an object that gets written into the temp file
const self = this;
temp = self.getTempObject();
keys = Object.keys(updateVals);
keys.forEach(key => {
temp[key] = updateVals[key];
})
return new Promise((resolve, reject) => {
fs.writeFile(self.tempPath, JSON.stringify(temp), function(err) {
if(err) {
reject(err);
}
resolve();
});
})
},
getTemp: function(keys){
//keys defines the info that will be returned from the temp object
const self = this;
res_temp = {};
temp = self.getTempObject();
keys.forEach(key => {
if(temp.hasOwnProperty(key)){
res_temp[key] = temp[key]
}
})
return res_temp
},
restorePage: function(){
const self = this;
temp = self.getTemp(["page"]);
if(temp.hasOwnProperty("page")){
self.sendSocketNotification("PAGE_SELECT", temp["page"]);
}else{
self.sendSocketNotification("PAGE_SELECT", 0)
}
},
moveOldConfig: function(){
const self = this;
return new Promise(resolve => {
fs.rename(self.configPath, self.tempConfigPath, () =>{
resolve();
})
})
},
myStringify: function(json){
const functions = [];
const jsonReplacer = function (key, val) {
if (typeof val === 'function') {
functions.push(val.toString());
return "{func_" + (functions.length - 1) + "}";
}
return val;
};
const funcReplacer = function (match, id) {
return functions[id];
};
return JSON.stringify(json, jsonReplacer, 4).replace(/"\{func_(\d+)\}"/g, funcReplacer);
},
writeNewConfig: function(config){
const self = this;
let fileString = ""
fileString += "//Auto-Generated by page selector in order to save your config while it messes with positions\n\n";
fileString += "var config = "
fileString += self.myStringify(config) + "\n";
fileString += "/*************** DO NOT EDIT THE LINE BELOW ***************/\nif (typeof module !== 'undefined') {\nmodule.exports = config;\n}";
return new Promise((resolve, reject) => {
fs.writeFile(self.configPath, fileString, function(err) {
if(err) {
reject(err);
}
resolve();
});
})
},
restoreOldConfig: function(){
const self = this;
return new Promise(resolve => {
fs.rename(self.tempConfigPath, self.configPath, () => {
resolve()
})
})
},
getModulePages: async function(){
const self = this;
//WHY NODE?
delete require.cache[require.resolve(self.configPath)]
const config = require(self.configPath);
const pageConfig = {};
let exclusions = [];
//This tells Page-Selector whether there are modules that dont have positions and so need to be re-rendered
let reRender = false;
// There are two options when defining pages and locations.
// If the pages are explicitly defined then that definition is used.
// If they are not, then the config for each module is searched to find the pages key
if(config.hasOwnProperty("pages")){
const pages = config.pages;
const modules = config.modules;
const pageNames = Object.keys(pages);
pageNames.forEach(page_name => {
const page = pages[page_name];
const page_module_names = Object.keys(page);
const page_store = {};
pageConfig[page_name.toLowerCase()] = Array(page_module_names.length);
modules.forEach((module, index) => {
const module_name = module.module;
const name = module.name;
const id = `module_${index}_${module_name}`;
if(page_module_names.includes(module_name)){
if(typeof module.position === "undefined"){
reRender = true;
module.position = page[module_name]
}
page_store[id] = {position: page[module_name], index: page_module_names.indexOf(module_name)};
}
if(name !== undefined && page_module_names.includes(name)){
if(typeof module.position === "undefined"){
let newPos = page[name];
if(typeof newPos === "undefined" || newPos.toLowerCase() === "none" || newPos === false){
newPos = undefined
}
if(typeof newPos !== "undefined"){
reRender = true;
module.position = page[name];
}
}
page_store[id] = {position: page[name], index: page_module_names.indexOf(name)};
}
})
pagePositions = []
Object.keys(page_store).forEach(id => {
let count = 0;
while(typeof pagePositions[page_store[id].index] !== "undefined"){
if(count > 1000){
throw "Breaking out of loop. If you had this many modules with the same name you messed up anyways."
}
count++;
page_store[id].index++;
}
pagePositions[page_store[id].index] = {
"position": page_store[id].position,
"identifier": id
}
})
pageConfig[page_name.toLowerCase()] = pagePositions
})
if(config.hasOwnProperty("exclusions")){
const excluded_names = Object.keys(config.exclusions);
modules.forEach((module, index) => {
const module_name = module.module;
const name = module.name;
const id = `module_${index}_${module_name}`;
if(excluded_names.includes(module_name) || excluded_names.includes(name)){
let selector = "";
if(excluded_names.includes(name)) selector = name
if(excluded_names.includes(module_name)) selector = module_name
if(typeof module.position === "undefined"){
let newPos = config.exclusions[selector];
if(typeof newPos === "undefined" || newPos.toLowerCase() === "none" || newPos === false){
newPos = undefined
}
if(typeof newPos !== "undefined"){
reRender = true;
module.position = config.exclusions[selector];
}
}
exclusions.push({
"identifier": id,
"position": config.exclusions[selector],
})
}
})
}
}else{
const modules = config.modules;
const pageList = [];
modules.forEach((module, index) => {
const name = module.module;
const pages = module.pages;
if(typeof pages === "object"){
const modulePages = Object.keys(pages);
if(typeof module.position === "undefined"){
let newPos = pages[modulePages[0]];
if(typeof newPos === "undefined" || newPos.toLowerCase() === "none" || newPos === false){
newPos = undefined
}
if(typeof newPos !== "undefined"){
reRender = true;
module.position = pages[modulePages[0]]
}
}
if(modulePages.includes("all")){
exclusions.push({
"identifier": `module_${index}_${name}`,
"position": pages["all"] || pages["All"],
});
}else{
modulePages.forEach(page => {
if(pageList.indexOf(page.toLowerCase()) === -1){
pageList.push(page.toLowerCase());
pageConfig[page.toLowerCase()] = [];
}
pageConfig[page.toLowerCase()].push({
"position": pages[page],
"identifier": `module_${index}_${name}`
})
})
}
}
});
}
if(reRender){
await self.moveOldConfig();
await self.writeNewConfig(config);
self.sendSocketNotification("RESTART_DOM");
}else if(fs.existsSync(self.tempConfigPath)){
self.restoreOldConfig();
}
self.sendSocketNotification("SET_PAGE_CONFIG", pageConfig);
self.sendSocketNotification("SET_EXCLUSIONS_CONFIG", exclusions);
}
})