-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplugins.js
532 lines (495 loc) · 12.5 KB
/
plugins.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
'use strict'
const path = require('path')
const fs = require('fs')
const vm = require('vm')
const { clone, pull } = require('isomorphic-git')
const http = require('isomorphic-git/http/node')
const ss = require('string-similarity')
const loc = require('./loc.js')
const dh = require('./web/display-helpers.js')
const users = require('./users.js')
const lg = require('./logger.js')
/* understand/
* we hold information about the plugins here so they
* can be accessed by the various functions
*/
let state = {
dir: null,
plugins: {},
}
/* way/
* download the latest plugin
*/
function getPluginRepo(url, cb) {
state = { dir: null, plugins: {} }
getLatest(url, loc.plugin(), (err, dir) => {
if(err) cb(err)
else {
state.dir = dir
cb()
}
})
}
/* understand/
* Promisi-fied version of `getPluginRepo`
*/
function get(url) {
return new Promise((resolve, reject) => {
getPluginRepo(url, err => {
if(err) reject(err)
else resolve()
})
})
}
/* way/
* if the repo is downloaded update it otherwise clone
* the repo
*/
function getLatest(from, to, cb) {
let url
try {
url = new URL(from)
} catch(e) {
return cb(e)
}
let name = path.basename(url.pathname, ".git")
to = path.join(to, name)
fs.lstat(to, (err, stats) => {
if(err && err.code === "ENOENT") cloneRepo(from, to, cb)
else if(err) cb(err)
else updateRepo(from, to, cb)
})
}
function cloneRepo(from, to, cb) {
clone({
fs,
http,
dir: to,
url: from,
}).then(() => cb(null, to))
.catch(cb)
}
function updateRepo(from, to, cb) {
pull({
fs,
http,
dir: to,
fastForwardOnly: true,
author: { name: "invalid", email: "[email protected]" },
}).then(() => cb(null, to))
.catch(cb)
}
/* way/
* run the plugin and return the info
*/
function getInfo(name, cb) {
getPlugin(name, (err, plugin) => {
if(err) return cb(err)
let context = {
console,
plugin: {name, info:{}},
}
try {
vm.createContext(context)
plugin.code.runInContext(context)
return cb(null, context.plugin.info.name)
} catch(e) {
cb(e)
}
})
}
/* way/
* Promisi-fied version of `getInfo`
*/
function info(name) {
return new Promise((resolve, reject) => {
getInfo(name, (err, name) => {
if(err) reject(err)
else resolve(name)
})
})
}
/* way/
* ask the plugin for a chat message corresponding to
* what the plugin is doing
*/
function getChat(task, status, cb) {
if(!task.action) return cb_("Task missing 'action' key")
getPlugin(task.action, (err, plugin) => {
if(err) return cb(err)
let context = {
console,
plugin: {name: task.action, info:{}},
}
try {
vm.createContext(context)
plugin.code.runInContext(context)
let chat = context.plugin.info.chat
if(!chat || typeof chat !== "function") {
chat = default_chat_1
}
const chatmsg = chat(task, status, context.plugin.name)
if(!chatmsg) cb(`Error getting chat for status: ${JSON.stringify(status)}`)
else cb(null, chatmsg)
} catch(e) {
cb(e)
}
})
function chatname_1(status) {
if(status == 102) return "sayOnStart"
if(status == 200) return "sayOnEnd"
}
function default_chat_1(task, status, name) {
if(!name) name = task.action
const msgs = {
102: [
`Ok trying ${name}...`,
`Doing ${name}...`,
`I'm going to do ${name} now...`,
],
200: [
`${name} completed!`,
`Done with ${name}...`,
],
202: [
`${name} sent to server!`,
`Completed ${name}...`,
],
400: [
`Error in task data for "${name}" (id: ${task.id})`,
`Cannot perform task (id: ${task.id})`,
],
504: [
`Timeout trying ${name}!`,
`Task ${name} took too long...timing out...`,
],
500: [
`Hit an unexpected error when trying to do "${name}"`,
`Unexpected error caused ${name} task ${task.id} to fail...`,
],
501: [
`No plugin found to perform ${name}`,
],
401: [
`User intervention required! The site needs you to prove that you are a human (and I'm not!) ` + dh.anEmoji("face"),
],
403: [
`The site has refused to accept this user! Please see how you can get back on...`
],
}
return dh.oneOf(msgs[status.code])
}
}
/* way/
* Promisi-fied version of `getChat`
*/
function chat(task, status) {
return new Promise((resolve, reject) => {
getChat(task, status, (err, chat) => {
if(err) reject(err)
else resolve(chat)
})
})
}
/* understand/
* return the user's log
*/
function getLogger(task, cb) {
let uctx = users.get(task.userId)
if(!uctx) return cb("User for task not found")
if(!uctx.logger) {
let n = `User-${task.userId}`
uctx.logger = lg(n, process.env.DEBUG)
}
cb(null, uctx.logger)
}
/* way/
* provide a valid browser logged in to linkedin page as context
* to the task plugin and record the start and all other status
* in the user log.
*/
function performTask(auth, task, cb) {
getLogger(task, (err, log) => {
if(err) return cb(err)
users.browser(users.get(task.userId)).then(browser => {
const cfg = {
timeout: task.timeout || undefined
}
users.linkedInPage(cfg, auth, browser).then(page => {
getPlugin(task.action, (err, plugin) => {
if(err) {
status_noplugin_1("err/task/noplugin")
page.close().catch(e => console.error(e))
return cb(err)
}
status_started_1(err => {
if(err) {
status_servererr_1(err)
page.close().catch(e => console.error(e))
return cb(err)
}
try {
cb()
let context = context_1(browser, cfg, page, task)
vm.createContext(context)
plugin.code.runInContext(context)
} catch(e) {
console.error(e)
status_servererr_1(e)
}
})
})
})
.catch(err => {
if(err === users.NEEDS_CAPCHA) {
status_capcha_1("err/task/capcha")
return cb("Need CAPCHA")
}
if(err === users.LOGIN_ERR) {
status_baduser_1("err/login/err")
return cb(`Invalid Linkedin credential`)
}
if(err === users.PREMIUM_ERR) {
status_baduser_1("err/need/salesnavigator")
return cb("You need a Sales Navigator or Premium account")
}
return cb(err.stack? err.stack : err)
})
})
.catch(err => {
status_servererr_1(err)
cb(err)
})
/* way/
* create a context to provide the plugin access to
* (a) the status logging functions,
* (b) the browser, page, console, and so on and
* (c) parameters: the time outs etc
*/
function context_1(browser, cfg, page, task) {
return {
log: {
trace: m => {
log(`trace/${task.action}/${task.id}`, m)
},
err: m => {
log(`err/${task.action}/${task.id}`, m)
}
},
cfg,
status: {
done: m => status_done_1(page, m),
notify: (m,d) => status_done_1(page, null, m, d),
usererr: m => status_usererr_1(page, m),
timeout: m => status_timeout_1(page, m),
servererr: m => status_servererr_1(page, m),
errcapcha: m => status_capcha_1(page, m),
baduser: m => status_baduser_1(page, m),
},
browser,
page,
console,
autoScroll: users.autoScroll,
util: {
compareTwoStrings: ss.compareTwoStrings,
},
plugin: {name: task.action, info:{}, task},
}
}
/* way/
* log task as started in the user log so we can keep
* track of it going forward
*/
function status_started_1(cb) {
log("task/status", {
id: task.id,
msg: "task/started",
code: 102
}, cb)
}
let status_set = false
function status_done_1(page, msg, notify, notifydata) {
if(status_set) return
status_set = true
if(!msg) msg = "task/done"
let s = { id: task.id, msg, code: 200 }
if(notify) s.notify = notify
if(notifydata) s.notifydata = notifydata
log("task/status", s)
page.close().catch(e => console.error(e))
}
function status_usererr_1(page, err) {
status_with_1(page, 400, err)
}
function status_timeout_1(page, err) {
status_with_1(page, 504, err)
}
function status_servererr_1(page, err) {
status_with_1(page, 500, err)
}
function status_noplugin_1(page, err) {
status_with_1(page, 501, err)
}
function status_capcha_1(page, err) {
status_with_1(page, 401, err)
}
function status_baduser_1(page, err) {
status_with_1(page, 403, err)
}
function status_with_1(page, code, err) {
if(status_set) return
status_set = true
if(!err) err = "err/task"
else if(err.stack) err = err.stack
log("task/status", { id: task.id, err, code })
page && page.close && page.close()
}
})
}
function perform(auth, task) {
return new Promise((resolve, reject) => {
performTask(auth, task, (err, resp) => {
if(err) reject(err)
else resolve(resp)
})
})
}
/* way/
* load the plugin from disk or return it from cache
*/
function getPlugin(name, cb) {
if(!state.dir) return cb("plugins.js: not initialized")
let plugin = state.plugins[name]
if(plugin && plugin.code) return cb(null, plugin)
plugin = {
p: path.join(state.dir, name + ".js")
}
fs.readFile(plugin.p, (err, code) => {
if(err) cb(err)
else {
try {
plugin.code = new vm.Script(wrap_1(code))
state.plugins[name] = plugin
cb(null, plugin)
} catch(e) {
cb(e)
}
}
})
/* problem/
* while plugin authors will do their best it is possible
* they could throw some error/exception without meaning to
* during the execution of the plugin. This error is hard
* to find/see in the logs once the program is running.
* way/
* wrap a call to a "standard" function we expect called
* "performTask" in a try catch block and report it as the
* correct error to the user
*/
function wrap_1(code) {
return `${code}
if(plugin.task) {
try {
performTask(plugin.task)
.then(() => {
status.done()
})
.catch(err => {
if(err.name == 'TimeoutError') status.timeout(err)
else status.servererr(err)
})
} catch(err) {
if(err.name == 'TimeoutError') status.timeout(err)
else status.servererr(err)
}
}
`
}
}
/* understand/
* record the new tasks in the user logs
*/
function addTasks(tasks, cb) {
add_ndx_1(0)
function add_ndx_1(ndx) {
if(ndx >= tasks.length) return cb()
const task = tasks[ndx]
getLogger(task, (err, log) => {
if(err) return cb(err)
log("task/new", task, err => {
if(err) return cb(err)
else add_ndx_1(ndx+1)
})
})
}
}
/* understand/
* Promisi-fied version of `addTasks`
*/
function add(tasks) {
return new Promise((resolve, reject) => {
addTasks(tasks, (err, resp) => {
if(err) reject(err)
else resolve(resp)
})
})
}
/* understand/
* record an intent to retry this task in the user's log
*/
function retryTask(task, cb) {
getLogger(task, (err, log) => {
if(err) return cb(err)
const msg = "task/retry"
log("task/status", { id: task.id, msg, code: 0 }, cb)
})
}
/* understand/
* Promisi-fied version of `retryTask`
*/
function retry(task) {
return new Promise((resolve, reject) => {
retryTask(task, err => {
if(err) reject(err)
else resolve()
})
})
}
/* understand/
* record task updates sent to server
*/
function sentTasks(tasks, cb) {
record_ndx_1(0)
function record_ndx_1(ndx) {
if(ndx >= tasks.length) return cb()
const task = tasks[ndx]
getLogger(task, (err, log) => {
if(err) return cb(err)
const msg = "task/completed"
log("task/status", { id:task.id, msg, code:202 }, err => {
if(err) return cb(err)
else record_ndx_1(ndx+1)
})
})
}
}
/* understand/
* Promisi-fied version of `sentTasks`
*/
function sent(tasks) {
return new Promise((resolve, reject) => {
sentTasks(tasks, err => {
if(err) reject(err)
else resolve()
})
})
}
module.exports = {
get,
info,
chat,
perform,
add,
retry,
sent,
}