-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
724 lines (525 loc) · 17.8 KB
/
index.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
import 'dotenv/config'
import axios from 'axios';
import fs from 'fs';
import path from 'path';
import rl from 'deadline';
import lineByLine from 'n-readlines';
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + Buffer.from(`${process.env.ZENDESK_EMAIL}/token:${process.env.ZENDESK_TOKEN}`).toString('base64'), // Base64 encoded "username:password"
};
const exportFolder = './exported/';
if (!fs.existsSync(exportFolder)) {
fs.mkdirSync(exportFolder);
console.log(`Folder "${exportFolder}" created successfully.`);
}
if (!fs.existsSync(exportFolder + 'attachments/')) {
fs.mkdirSync(exportFolder + 'attachments/');
console.log(`Folder "${exportFolder}attachments" created successfully.`);
}
const requestWithRateLimit = async (config) => {
const response = await axios(config);
if (response.status === 429) {
const secondsToWait = Number(response.headers["retry-after"])
await new Promise(resolve => setTimeout(resolve, (secondsToWait + 1) * 1000))
return requestWithRateLimit(config)
}
return response;
}
/**
* Retrieves tickets
* @async
* @param {boolean} cursor - Cursor for pagination.
* @returns {Promise<boolean>} Promise indicating success of operation.
*/
const getTickets = async (cursor = false) => {
var config = {
method: 'GET',
url: process.env.ZENDESK_API + 'incremental/tickets/cursor',
headers: headers,
params: {
'cursor': (cursor) ? cursor : '',
'start_time': '0',
},
};
return new Promise((resolve, reject) => {
requestWithRateLimit(config).then(function (response) {
//console.log(JSON.stringify(response.data.tickets));
for (const [key, value] of Object.entries(response.data.tickets)) {
//console.log(`${key}: ${value}`);
delete value.url;
fs.writeFileSync(exportFolder + 'tickets.json', JSON.stringify(value) + "\n", { flag: "a+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
console.log('end_of_stream:', response.data.end_of_stream);
//if (cursor) { console.log('stop!'); return false; }
if (false === response.data.end_of_stream) {
console.log('not the end, cursor: ' + response.data.after_cursor);
resolve(getTickets(response.data.after_cursor));
} else {
resolve(true);
}
}).catch(function (error) {
console.log(error);
});
});
}
/**
* Retrieves comments for a ticket
* @async
* @param {number} id - Ticket ID.
* @param {boolean} next_page - Next page of comments.
* @param {Array} comments - Array to store comments.
* @returns {Promise<void>} Promise indicating success of operation.
*/
const getTicketComments = async function(id, next_page = false, comments = [], errors_count = 0) {
return new Promise((resolve, reject) => {
console.log('getTicketComments');
var config = {
method: 'GET',
url: (next_page) ? next_page : process.env.ZENDESK_API + 'tickets/' + id + '/comments',
headers: headers,
params: {
//'include': 'users',
'include_inline_images': true,
//'sort_order': '',
},
};
requestWithRateLimit(config).then(async function (response) {
comments = [...comments, ...response.data.comments];
if (null !== response.data.next_page) { // has more than one page
console.log('id:', id);
console.log('error response.data.next_page:', response.data.next_page);
await getTicketComments(id, response.data.next_page, comments);
//process.exit();
} else {
//console.log(JSON.stringify(response.data.comments));
fs.writeFileSync(exportFolder + 'comments.json', id + "\n" + JSON.stringify(comments) + "\n", { flag: "a+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
resolve();
}).catch(function (error) {
if (10 < errors_count) {
console.log('skipping because of too many errors', id)
logError(`Skipping getTicketComments because of too many errors: ${JSON.stringify([id, next_page, comments, errors_count])}`)
resolve();
return;
}
if ('ERR_BAD_RESPONSE' === error.code) {
console.log('ERR_BAD_RESPONSE received, retring...', id, next_page, comments, errors_count);
resolve(getTicketComments(id, next_page, comments, ++errors_count))
} else if ('ERR_BAD_REQUEST' === error.code && 404 === error.response.status) {
console.log('Looks like ticket was removed, skipping it', id)
logError(`Looks like ticket was removed, skipping it ${id}`);
resolve();
} else {
console.log('!!!!Error code:', error.code);
console.log(error);
reject(); // ::TODO:: if 500 error or something just skipping and continuing
}
});
});
}
/**
* Logs an error message to a file.
* @param {string} message - The error message to log.
*/
const logError = (message) => {
fs.writeFileSync(exportFolder + 'errors.txt', message + "\n", { flag: "a+" }, (err) => {
if (err) throw err;
});
}
/**
* Retrieves comments for all tickets. Can be restarted and will automatically start where it finished
* @async
* @returns {Promise<void>} Promise indicating success of operation.
*/
const getAllTicketComments = async function() {
const saved_tickets_ids = getAllSavedTicketComments();
const liner = new lineByLine(exportFolder + 'tickets.json');
let line;
let lineNumber = 0;
while (line = liner.next()) {
//console.log('Line ' + lineNumber + ': ' + line);
let ticket = JSON.parse(line);
console.log(ticket.id);
if (!saved_tickets_ids.includes(ticket.id)) {
await getTicketComments(ticket.id);
} else {
console.log('skip');
}
lineNumber++;
}
console.log('end of line reached');
}
/**
* Retrieves IDs of all saved ticket comments from the exported file.
* @returns {Array<number>} Array of ticket IDs.
*/
const getAllSavedTicketComments = function() {
let saved_tickets_ids = [];
if (!fs.existsSync(exportFolder + 'comments.json')) {
return saved_tickets_ids;
}
const liner = new lineByLine(exportFolder + 'comments.json');
let line;
let lineNumber = 0;
while (line = liner.next()) {
//console.log('Line ' + lineNumber + ': ' + line);
if (0 == lineNumber%2) {
//console.log(''+ line);
saved_tickets_ids.push(parseInt(line));
}
lineNumber++;
}
console.log('getAllSavedTicketComments', saved_tickets_ids);
return saved_tickets_ids;
}
/**
* Retrieves users from Zendesk API.
* @param {boolean} cursor - Cursor for pagination.
* @returns {Promise<boolean>} Promise indicating success of operation.
*/
const getUsers = function(cursor = false) {
var config = {
method: 'GET',
url: process.env.ZENDESK_API + 'incremental/users/cursor',
headers: headers,
params: {
'cursor': (cursor) ? cursor : '',
'start_time': '0',
},
};
return new Promise((resolve, reject) => {
requestWithRateLimit(config).then(function (response) {
//console.log(JSON.stringify(response.data.tickets));
for (const [key, value] of Object.entries(response.data.users)) {
//console.log(`${key}: ${value}`);
delete value.url;
fs.writeFileSync(exportFolder + 'users.json', JSON.stringify(value) + "\n", { flag: "a+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
console.log('end_of_stream:', response.data.end_of_stream);
//if (cursor) { console.log('stop!'); return false; }
if (false === response.data.end_of_stream) {
console.log('not the end, cursor: ' + response.data.after_cursor);
resolve(getUsers(response.data.after_cursor));
} else {
resolve(true);
}
}).catch(function (error) {
console.log(error);
reject(error);
});
});
}
/**
* Downloads attachments from Zendesk comments.
* @async
* @param {boolean} cursor - Cursor for pagination.
* @returns {Promise<Array<number>>} Array of ticket IDs.
*/
const downloadAttachments = async function(cursor = false) {
var liner = new lineByLine(exportFolder + 'comments.json');
var line;
var lineNumber = 0;
let saved_tickets_ids = [];
while (line = liner.next()) {
//console.log('Line ' + lineNumber + ': ' + line);
if (lineNumber%2) {
let comments = JSON.parse(line);
for (let comment of comments) {
if (0 < comment.attachments.length) {
for (let attachment of comment.attachments) {
console.log(attachment.content_url);
const fileName = exportFolder + 'attachments/' + attachment.id + path.extname(attachment.file_name);
// if file already exists - skipping it
if (fs.existsSync(fileName)) {
continue;
}
var config = {
method: 'GET',
url: attachment.content_url,
headers: headers,
responseType: 'arraybuffer',
};
try {
let response = await axios.get(attachment.content_url, config);
//console.log(response.data);
fs.writeFileSync(fileName, Buffer.from(response.data), { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
} catch (e) {
console.log('error, skipping attachment id', attachment.id, 'Error', e.code, e.response.status);
logError(`Skipping attachment id ${attachment.id} Error: ${e.code} ${e.response.status}`);
}
/*
await requestWithRateLimit(config).then(function (response) {
console.log('writing file');
fs.writeFileSync(attachment.id, response.data + "\n", { flag: "a+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}).catch(function (error) { console.log(error);});
*/
//process.exit();
}
}
}
//console.log(''+ line);
saved_tickets_ids.push(parseInt(line));
}
lineNumber++;
}
console.log('getAllSavedTicketComments', saved_tickets_ids);
return saved_tickets_ids;
}
/**
* Retrieves views
* @async
* @param {boolean} next_page - Flag indicating whether there's a next page of views.
* @param {Array} items - Array to store views.
* @returns {Promise<void>} A Promise indicating the success of the operation.
*/
const getViews = async function(next_page = false, items = []) {
return new Promise((resolve, reject) => {
console.log('getViews');
var config = {
method: 'GET',
url: (next_page) ? next_page : process.env.ZENDESK_API + 'views/',
headers: headers,
params: {
},
};
requestWithRateLimit.axios(config).then(async function (response) {
items = [...items, ...response.data.views];
if (null !== response.data.next_page) { // has more than one page
console.log('error response.data.next_page:', response.data.next_page);
await getViews(response.data.next_page, items);
//process.exit();
} else {
//console.log(JSON.stringify(response.data.comments));
fs.writeFileSync(exportFolder + 'views.json', JSON.stringify(items) + "\n", { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
resolve();
}).catch(function (error) {
console.log('!!!!', error.code);
console.log(error);
resolve(); // if 500 error or something just skipping and continuing
});
});
}
/**
* Retrieves triggers
* @async
* @param {boolean} next_page - Next page of triggers.
* @param {Array} items - Array to store triggers.
* @returns {Promise<void>} Promise indicating success of operation.
*/
const getTriggers = async function(next_page = false, items = []) {
return new Promise((resolve, reject) => {
console.log('getTriggers');
var config = {
method: 'GET',
url: (next_page) ? next_page : process.env.ZENDESK_API + 'triggers/',
headers: headers,
params: {
},
};
requestWithRateLimit(config).then(async function (response) {
items = [...items, ...response.data.triggers];
if (null !== response.data.next_page) { // has more than one page
console.log('error response.data.next_page:', response.data.next_page);
await getTriggers(response.data.next_page, items);
//process.exit();
} else {
//console.log(JSON.stringify(response.data.comments));
fs.writeFileSync(exportFolder + 'triggers.json', JSON.stringify(items) + "\n", { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
resolve();
}).catch(function (error) {
console.log('!!!!', error.code);
console.log(error);
resolve(); // if 500 error or something just skipping and continuing
});
});
}
/**
* Retrieves macros from the Zendesk API.
* @async
* @param {boolean} next_page - Flag indicating whether there's a next page of macros.
* @param {Array} items - Array to store macros.
* @returns {Promise<void>} A Promise indicating the success of the operation.
*/
const getMacros = async function(next_page = false, items = []) {
return new Promise((resolve, reject) => {
console.log('getMacros');
var config = {
method: 'GET',
url: (next_page) ? next_page : process.env.ZENDESK_API + 'macros/',
headers: headers,
params: {
},
};
requestWithRateLimit(config).then(async function (response) {
items = [...items, ...response.data.macros];
if (null !== response.data.next_page) { // has more than one page
console.log('error response.data.next_page:', response.data.next_page);
await getMacros(response.data.next_page, items);
//process.exit();
} else {
//console.log(JSON.stringify(response.data.comments));
fs.writeFileSync(exportFolder + 'macros.json', JSON.stringify(items) + "\n", { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
resolve();
}).catch(function (error) {
console.log('!!!!', error.code);
console.log(error);
resolve(); // if 500 error or something just skipping and continuing
});
});
}
/**
* Retrieves automations
* @async
* @param {boolean} next_page - Next page of automations.
* @param {Array} items - Array to store automations.
* @returns {Promise<void>} Promise indicating success of operation.
*/
const getAutomations = async function(next_page = false, items = []) {
return new Promise((resolve, reject) => {
console.log('getAutomations');
var config = {
method: 'GET',
url: (next_page) ? next_page : process.env.ZENDESK_API + 'automations/',
headers: headers,
params: {
},
};
requestWithRateLimit(config).then(async function (response) {
items = [...items, ...response.data.automations];
if (null !== response.data.next_page) { // has more than one page
console.log('error response.data.next_page:', response.data.next_page);
await getAutomations(response.data.next_page, items);
//process.exit();
} else {
//console.log(JSON.stringify(response.data.comments));
fs.writeFileSync(exportFolder + 'automations.json', JSON.stringify(items) + "\n", { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
resolve();
}).catch(function (error) {
console.log('!!!!', error.code);
console.log(error);
resolve(); // if 500 error or something just skipping and continuing
});
});
}
/**
* Retrieves settings
* @param {boolean} cursor - Cursor for pagination.
* @returns {Promise<void>} Promise indicating success of operation.
*/
const getSettings = function(cursor = false) {
var config = {
method: 'GET',
url: process.env.ZENDESK_API + 'account/settings.json',
headers: headers,
};
requestWithRateLimit(config).then(function (response) {
//console.log(JSON.stringify(response.data.tickets));
fs.writeFileSync(exportFolder + 'settings.json', JSON.stringify(response.data.settings) + "\n", { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
//if (cursor) { console.log('stop!'); return false; }
}).catch(function (error) { console.log(error);});
}
const getSupportAddresses = async function(next_page = false, items = []) {
return new Promise((resolve, reject) => {
console.log('getSupportAddresses');
var config = {
method: 'GET',
url: (next_page) ? next_page : process.env.ZENDESK_API + 'recipient_addresses/',
headers: headers,
params: {
},
};
requestWithRateLimit(config).then(async function (response) {
items = [...items, ...response.data.recipient_addresses];
if (null !== response.data.next_page) { // has more than one page
console.log('error response.data.next_page:', response.data.next_page);
await getSupportAddresses(response.data.next_page, items);
//process.exit();
} else {
//console.log(JSON.stringify(response.data.comments));
fs.writeFileSync(exportFolder + 'recipient_addresses.json', JSON.stringify(items) + "\n", { flag: "w+" }, (err) => {
if (err) throw err;
//console.log('The file is created');
});
}
resolve();
}).catch(function (error) {
console.log('!!!!', error.code);
console.log(error);
resolve(); // if 500 error or something just skipping and continuing
});
});
}
// https://makedreamprofits.zendesk.com//api/v2/tags.json
const exportAll = async () => {
console.log('Exporting tickets...');
await getTickets();
console.log('Exporting tickets\' comments...');
await getAllTicketComments();
console.log('Exporting users...');
await getUsers();
console.log('Downloading attachments...');
await downloadAttachments();
console.log('Exporting views...');
await getViews();
console.log('Exporting triggers...');
await getTriggers();
console.log('Exporting macros...');
await getMacros();
console.log('Exporting automations...');
await getAutomations();
console.log('Exporting settings...');
await getSettings();
console.log('Exporting support addresses...');
await getSupportAddresses();
console.log('Finished');
}
(async () => {
await exportAll();
//await getTickets();
//await getTicketComments(17551);
//await getAllSavedTicketComments();
//await getAllTicketComments();
//await getUsers();
//await downloadAttachments();
//await getViews();
//await getTriggers();
//await getMacros();
//await getAutomations();
//await getSettings();
//await getSupportAddresses();
})();