This repository has been archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
381 lines (327 loc) · 11.2 KB
/
server.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
var project = require('pillars'),
Scheduled = require("scheduled"),
jade = require('jade'),
config = require('./config'),
firebase = require('firebase'),
ProviderRSS = require('./providers/rss'),
ProviderSheets = require('./providers/sheets'),
providerDomestika = require('./providers/scraping/domestika'),
statsTwitter = require('./realtime/stream').stats,
realtimeTweets = require('./realtime/stream').mostrarTweets,
startSpanish = require('./realtime/stream').startSpanish,
startEnglish = require('./realtime/stream').startEnglish,
slackLog = require("./bots/slackBot"),
hangouts = require("./bots/hangouts"),
fs = require('fs');
slackLog("[SERVER] Iniciando el servidor...");
// Prototypes
Array.prototype.inArray = function(word) {
var _self = this;
for(var i = 0; i < _self.length; i++) {
if(_self[i] == word){
return true;
}
}
return false;
};
String.prototype.inString = function(array) {
var _self = this;
for(var i = 0; i < array.length; i++) {
if(_self.indexOf(array[i]) > -1){
return true;
}
}
return false;
};
String.prototype.textCleaner = function() {
var _self = this;
var finalText;
finalText = _self.replace(/(<([^>]+)>)/ig,"");
finalText = finalText.replace(/(]]>)/ig,"");
finalText = finalText.replace(/(&([^>]+);)/ig,"");
finalText = finalText.replace(/\r?\n|\r/ig," ");
finalText = finalText.trim();
if (finalText.length > 400){
finalText = finalText.substring(0,400) + ' ...';
}
return finalText;
};
Date.prototype.getWeek = function(){
var today = new Date();
var StartDate = new Date();
StartDate.setDate(StartDate.getDate() - 6);
return [StartDate.getTime(), today.getTime()];
};
Date.prototype.isInWeek = function(dateTarget){
var _self = this;
var currentWeek = _self.getWeek();
return _self.getTime() <= currentWeek[1] && _self.getTime() >= currentWeek[0];
};
Date.prototype.isIn2Days = function(dateTarget){
var _self = this;
var daysAgo2 = new Date();
daysAgo2.setDate(daysAgo2.getDate() - 2);
return _self.getTime() >= daysAgo2.getTime();
};
Date.prototype.isIn15Days = function(dateTarget){
var _self = this;
var daysAgo2 = new Date();
daysAgo2.setDate(daysAgo2.getDate() - 15);
return _self.getTime() >= daysAgo2.getTime();
};
// Inicialización de Firebase
firebase.initializeApp({
serviceAccount: ".secret/serviceAccountCredentials.json",
databaseURL: config.databaseURL
});
// Stream Twitter
slackLog("[SERVER] Iniciando el streaming de tweets...");
startSpanish();
startEnglish();
// Fuentes RSS
var betabeers = new ProviderRSS({
url: "https://betabeers.com/post/feed/",
provider_db: "betabeers",
provider: "Betabeers Empleos",
provider_logo: "img/betabeers_jobs.png",
outstanding: false
});
var stackoverflow = new ProviderRSS({
url: "http://stackoverflow.com/jobs/feed",
provider_db: "stackoverflow",
provider: "Stackoverflow Jobs",
provider_logo: "img/stackoverflow_jobs.png",
outstanding: false
});
var github = new ProviderRSS({
url: "https://jobs.github.com/positions.atom",
provider_db: "github",
provider: "Github Jobs",
provider_logo: "img/github_jobs.png",
outstanding: false
});
// Fuentes destacados
var destacados = new ProviderSheets({
id: config.sheetCode,
provider_db: "destacados",
outstanding: true
});
// Fuentes exclusivo
var exclusives = new ProviderSheets({
id: config.sheetCodeExclusives,
provider_db: "exclusives",
outstanding: true,
router: true
});
// Starting the project
project.services.get('http').configure({
port: process.env.PORT || 8080
}).start();
// Template Engine
var templated = global.templated;
templated.addEngine('jade', function compiler(source, path) {
return jade.compile(source, {
filename: path,
pretty: false,
debug: false,
compileDebug: false
});
});
// Routes definition
var index = new Route({
id: "index",
path: "/"
},
function(gw) {
gw.render('./templates/index.jade', {datos: datos});
});
var realtime = new Route({
id: "realtime",
path: "/realtime"
},
function(gw, io) {
realtimeTweets(gw, io);
});
var detailsRoute = new Route({
id: "sheet",
path: "/job/*:path"
},
function(gw) {
if (gw.pathParams.path === "") {
gw.redirect("/");
} else {
datosDetalle.forEach(function(item){
if (gw.pathParams.path === item.id) {
gw.render('./templates/details.jade', {item: item});
console.log("Premio!!");
} else {
gw.redirect("/");
}
});
}
});
var estatics = new Route({
id: 'estatics',
path: '/*:path',
directory: {
path: './public',
listing: true
}
});
// Adding Routes to Pillars
project.routes.add(realtime);
project.routes.add(index);
project.routes.add(detailsRoute);
project.routes.add(estatics);
// Gestión de tareas automáticas
// Subiendo stadisticas cada día a Firebase.
var previousDailyStats = {
english: {
totalAnalyzed: 0,
totalValid: 0
},
spanish: {
totalAnalyzed: 0,
totalValid: 0
},
totalAnalyzed: 0,
totalValid: 0,
startDate: ""
};
var statsFirebaseDailyJob = new Scheduled({
id: "statsFirebaseDailyJob",
pattern: "59 23 * * * *", // 23:59
task: function(){
var stats = statsTwitter();
stats.english.totalAnalyzed -= previousDailyStats.english.totalAnalyzed;
stats.english.totalValid -= previousDailyStats.english.totalValid;
stats.spanish.totalAnalyzed -= previousDailyStats.spanish.totalAnalyzed;
stats.spanish.totalValid -= previousDailyStats.spanish.totalValid;
stats.totalValid -= previousDailyStats.totalValid;
stats.totalAnalyzed -= previousDailyStats.totalAnalyzed;
stats.frequency = 86400000;
stats.timestamp = new Date().getTime();
var ref = firebase.database().ref('stats/day/'+stats.timestamp);
ref.set(stats, function(error){
if (error) {
console.warn('[FIREBASE] ERROR - Sincronización fallida con la subida diaria de estadísticas!');
}
previousDailyStats = stats;
});
}
}).start();
var previousHourlyStats = {
english: {
totalAnalyzed: 0,
totalValid: 0
},
spanish: {
totalAnalyzed: 0,
totalValid: 0
},
totalAnalyzed: 0,
totalValid: 0,
startDate: ""
};
// Subiendo stadisticas cada hora a Firebase.
var statsFirebaseHourlyJob = new Scheduled({
id: "statsFirebaseHourlyJob",
pattern: "59 * * * * *", // **:59
task: function(){
var stats = statsTwitter();
stats.english.totalAnalyzed -= previousHourlyStats.english.totalAnalyzed;
stats.english.totalValid -= previousHourlyStats.english.totalValid;
stats.spanish.totalAnalyzed -= previousHourlyStats.spanish.totalAnalyzed;
stats.spanish.totalValid -= previousHourlyStats.spanish.totalValid;
stats.totalValid -= previousHourlyStats.totalValid;
stats.totalAnalyzed -= previousHourlyStats.totalAnalyzed;
stats.frequency = 3600000;
stats.timestamp = new Date().getTime();
var ref = firebase.database().ref('stats/hour/'+stats.timestamp);
ref.set(stats, function(error){
if (error) {
console.warn('[FIREBASE] ERROR - Sincronización fallida con la subida (**:59) de estadísticas!');
}
previousHourlyStats = stats;
});
}
}).start();
var datos;
var datosDetalle = [];
var rssJob = new Scheduled({
id: "rssJob",
pattern: "2 5 * * * *", // 05:02
task: function(){
slackLog("[SERVER] Iniciando la actualización programada de los proveedores RSS...");
github.uploadJobs();
stackoverflow.uploadJobs();
betabeers.uploadJobs();
}
}).start().launch();
var sheetJob = new Scheduled({
id: "sheetJob",
pattern: "0 5 * * * *", // 05:02
task: function(){
slackLog("[SERVER] Iniciando la actualización programada de Google Sheets...");
destacados.uploadJobs();
exclusives.uploadJobs();
}
}).start().launch();
var scrapingJob = new Scheduled({
id: "scrapingJob",
pattern: "0 5 * * * *", // 05:02
task: function(){
slackLog("[SERVER] Iniciando la actualización programada de Domestica...");
providerDomestika.uploadJobs();
}
}).start().launch();
setTimeout(function(){
var updateView = new Scheduled({
id: "updateView",
pattern: "5 5 * * * *", // 05:02
task: function(){
firebase.database().ref('/data/').once('value').then(function(snapshot) {
// Unificación
datos = snapshot.val();
if(!datos.betabeers){
slackLog("[SERVER][INFO] Betabeers vacío...");
}
if(!datos.stackoverflow){
slackLog("[SERVER][INFO] Stackoverflow vacío...");
}
if(!datos.github){
slackLog("[SERVER][INFO] Github vacío...");
}
if(!datos.domestika){
slackLog("[SERVER][INFO] Domestika vacío...");
}
if(!datos.destacados){
slackLog("[SERVER][INFO] Destacados vacío...");
}
if(!datos.exclusives){
slackLog("[SERVER][INFO] Ofertas exclusivas vacío...");
}
var newDatos = [];
for (var dato in datos) {
for (var i = 0; i < datos[dato].length; i++) {
if(dato === "exclusives"){
datosDetalle.push(datos[dato][i]);
}
newDatos.push(datos[dato][i]);
}
}
newDatos.sort(function(obj1, obj2) {
return new Date(obj2.pubdate) - new Date(obj1.pubdate);
});
datos = newDatos;
var finalBlock = JSON.stringify(datos, null, 2);
fs.writeFile('temp/datos.json', finalBlock, "UTF-8", function (err){
if (err) {
throw err;
}
slackLog("[SERVER][INFO] temp/datos.json actualizado...");
});
});
}
}).start().launch();
}, 120000);