-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollectData.js
More file actions
272 lines (251 loc) · 9.8 KB
/
collectData.js
File metadata and controls
272 lines (251 loc) · 9.8 KB
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
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var async = require('async');
var MongoClient = require('mongodb').MongoClient;
var moment = require('moment');
var schedule = require('node-schedule');
var q = require('q');
var db;
var standalone = !module.parent;
var mongohost = 'localhost:27017';
var mongodb = 'backupDB';
var mongoConnection = 'mongodb://' + mongohost + '/' + mongodb;
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.modify'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-api-quickstart.json';
/**
* Main function.
*/
var start = function() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Gmail API.
connectMongo().then(function(db) {
authorize(JSON.parse(content)).then(function(auth) {
listBackupMails(auth).then(function(mails) {
parseMails(mails).then(function() {
console.log("done");
GLOBAL.db.close();
});
});
});
});
});
};
/*
* Connect to MongoDB and store the connection.
*/
var connectMongo = function() {
var deferred = q.defer();
MongoClient.connect(mongoConnection, function(err, db) {
if (!db) {
console.log(err);
deferred.rejcet(err);
}
GLOBAL.db = db;
deferred.resolve(db);
});
return deferred.promise;
};
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var deferred = q.defer();
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken().then(function(oauth2Client) {
deferred.resolve(oauth2Client);
});
} else {
oauth2Client.credentials = JSON.parse(token);
deferred.resolve(oauth2Client);
}
});
return deferred.promise;
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var deferred = q.defer();
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
q.resolve(oauth2Client);
});
});
return deferred.promise;
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Get the latest 99 Mail IDs from Gmail.
*
* @param {Object} auth The OAuth2Client object.
*/
function listBackupMails(auth) {
var deferred = q.defer();
var mails = [];
var gmail = google.gmail('v1');
// get a list of all messages
gmail.users.messages.list({
auth: auth,
userId: 'me',
maxResults: 99,
q: 'label:backup-notification'
}, function(err, response) {
var messages = response.messages;
async.eachLimit(messages, 5, function(message, cb) {
var id = message.id;
// get a specific message
gmail.users.messages.get({
auth: auth,
userId: 'me',
id: id
}, function(err, message){
// decode the mail to a string
var buf = new Buffer(message.payload.body.data, 'base64').toString('ascii');
message._id = message.id;
message.payload.body.plainText = buf;
mails.push(message);
cb();
});
}, function() {
// all emails saved, now parse them!
console.log("maillength", mails.length);
console.log(new Date(), "loaded all mails.");
deferred.resolve(mails);
});
});
return deferred.promise;
}
/*
Parse the collected mails and save them as "areca statistics objects" in our database.
*/
var parseMails = function(mails) {
var deferred = q.defer();
async.eachLimit(mails, 5, function(mail, cb) {
var plainText = mail.payload.body.plainText;
if (/Overall Status : Success/g.test(plainText)) {
var backupDetails = {};
backupDetails._id = mail._id;
backupDetails.name = "-";
backupDetails.targetId = 0;
backupDetails.backupStartDate = null;
backupDetails.backupEndDate = null;
backupDetails.writtenKb = 0;
backupDetails.numberOfSourceFiles = 0;
backupDetails.sourceFilesSize = 0;
backupDetails.numberOfArchives = 0;
backupDetails.archivePhysicalSize = 0;
backupDetails.physicalSizeRatio = 0;
backupDetails.sizeWithoutHistory = 0;
backupDetails.sizeOfHistory = 0;
backupDetails.fileList = [];
for (var i = 0; i < mail.payload.headers.length; i++) {
var header = mail.payload.headers[i];
// read areca target
if (header.name === "X-Areca-Target") backupDetails.targetId = header.value;
// read backupEndDate
if (header.name === "Date") backupDetails.backupEndDate = moment(Date.parse(header.value)).toISOString();
}
// get start date in a nice format
var backupStartDateString = plainText.match(/(\) on)([.\s\S]*?)\n/g)[0].split("on")[1].trim();
var startDateFormat = "";
if (backupStartDateString.indexOf(".") != -1) {
// 23.06.2015 18:00
startDateFormat = "DD.MM.YYYY HH:mm";
} else {
// Jun 23, 2015 9:33 AM
startDateFormat = "MMM DD, YYYY hh:mm A";
}
// extract properties
backupDetails.name = plainText.match(/(^)([.\s\S]*?)(\()/g)[0].split("(")[0].trim();
backupDetails.backupStartDate = moment(backupStartDateString, startDateFormat).toISOString();
backupDetails.writtenKb = plainText.match(/(Written kbytes)([.\s\S]*?)\n/g)[0].split(":")[1].trim().replace(/\.|,/g, "");
backupDetails.numberOfSourceFiles = plainText.match(/(\((NOF)\))([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
backupDetails.numberOfArchives = plainText.match(/(\((NOA)\))([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
backupDetails.archivePhysicalSize = plainText.match(/(\((APS)\))([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
backupDetails.physicalSizeRatio = plainText.match(/(\((PSR)\))([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
backupDetails.sizeWithoutHistory = plainText.match(/(\((SWH)\))([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
backupDetails.sizeOfHistory = plainText.match(/(SOH)([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
backupDetails.sourceFilesSize = plainText.match(/(\(SFS\))([.\s\S]*?)\n/g)[0].split(" ")[2].trim().replace(/\.|,/g, "");
// read fileList
if (backupDetails.writtenKb > 0) {
backupDetails.fileList = plainText.match(/(?:\[Beginning\])([.\s\S]*)\[End\]/g)[0].split("\r\n");
backupDetails.fileList.splice(0, 1);
backupDetails.fileList.splice(backupDetails.fileList.length-1, 1);
}
// save to database
var collection = GLOBAL.db.collection('backups');
console.log(backupDetails._id);
collection.updateOne(
{_id: backupDetails._id},
backupDetails,
{upsert: true},
function(err, result) {
if (err) console.log(err);
cb();
}
);
}
}, function() {
// all mails parsed
deferred.resolve();
});
return deferred.promise;
};
if (standalone) start();
module.exports = { start: start };