-
Notifications
You must be signed in to change notification settings - Fork 5
/
sheets-service.js
97 lines (92 loc) · 2.51 KB
/
sheets-service.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
var request = require('request');
var GoogleSpreadsheet = require('./lib/google-spreadsheet');
var creds = require('./data/google-credentials.json');
var async = require('async');
var fs = require('fs');
var ws = [];
var worksheets;
var interval;
try{
worksheets = DB_Load();
async.forEachOf(worksheets, function(sheet, key, callback){
if(Number(key)>=0){
var user = new GoogleSpreadsheet(sheet.id);
user.useServiceAccountAuth(creds, function(){
ws.push({instance:user, index: key});
console.log("pushed");
callback();
});
}else
callback();
}, function(err){
console.log("No. of sheets to watch -", ws.length);
fs.writeFileSync(__dirname+"/service-pid", String(process.pid), "utf8");
setTimeout(watch, 0);
});
}catch(e){
console.log(e.message);
}
//Utils
function watch(){
async.forEachOf(ws, function(sheet, index, callback){
sheet.instance.getInfo(function(err, info){
if(!err){
var lastUpdated = new Date(worksheets[sheet.index].updated);
var newdate = new Date(info.updated);
if(newdate>lastUpdated){
publish(sheet.index, info, function(){
callback();
});
}else{
console.log('no update.');
callback();
}
}else{
console.log(err);
callback();
}
});
}, function(err){
setTimeout(watch, 20000);
});
}
function publish(index, info, cb){
var id = info.id.match(/worksheets\/(.*?)\//)[1];
var file_buffer = DB_Load();
file_buffer[index] = {url: info.id, id: id, title: info.title, updated: info.updated};
DB_Write(file_buffer);
worksheets[index] = file_buffer[index];
console.log("updated", info.title);
if(worksheets.callback){
request({method: 'POST', uri: worksheets.callback, body: worksheets[index], json:true, timeout: 1000}, function(error, response, body){
cb();
});
}else
cb();
}
function DB_Load(){
var FILE_PATH = __dirname + '/data/data.json';
var file_buffer;
try{
if(fs.existsSync(FILE_PATH))
file_buffer = JSON.parse(fs.readFileSync(FILE_PATH));
else{
file_buffer = {counter:0};
fs.writeFileSync(FILE_PATH, JSON.stringify(file_buffer), "utf8");
}
return file_buffer;
}catch(e){
console.log(e);
console.log(chalk.red("Could not create data file. Please give neccessary permissions."));
process.exit(1);
}
}
function DB_Write(file_buffer){
var FILE_PATH = __dirname + '/data/data.json';
try{
fs.writeFileSync(FILE_PATH, JSON.stringify(file_buffer), "utf8");
}catch(e){
console.log(chalk.red("Could not write to data file. Please give neccessary permissions."));
process.exit(1);
}
}