-
Notifications
You must be signed in to change notification settings - Fork 10
/
fetchCallsStats.js
68 lines (56 loc) · 2.16 KB
/
fetchCallsStats.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
const conferences = require("../lib/conferences")
const db = require("../lib/db")
const fetchCallIds = async (phoneNumber) => {
const latestRecordedCall = await db.getLastSuccessfulCallStatsJob(phoneNumber)
const intervalStartDate = latestRecordedCall ? latestRecordedCall.dateBegin.toISOString() : undefined
console.log("Fetching calls for phone number", phoneNumber, "from", intervalStartDate, "to now")
const callIds = await conferences.getCallsForPhoneNumber(phoneNumber, intervalStartDate)
console.log("Got", callIds.length, "calls")
return callIds
}
const insertCallHistory = async (history, phoneNumber, summary) => {
const id = await db.insertCallHistory(phoneNumber, history)
if (id) {
console.log(`${id} inserted`)
summary.insertedRows++
} else {
console.log(`${phoneNumber}_${history.id} already inserted`)
summary.alreadyInsertedRows++
}
}
const recordSuccessfulJob = async (phoneNumber) => {
const lastCall = await db.getLatestCallHistory(phoneNumber)
await db.insertLastSuccessfulCallStatsJob(phoneNumber, lastCall)
}
module.exports = async () => {
console.debug("Start of fetchCallsStats job")
try {
const phoneNumbers = await conferences.getAllPhoneNumbers()
console.log("Got", phoneNumbers.length, "phone numbers.")
if (!phoneNumbers.length) {
console.log("No numbers found. Check your configuration.")
process.exit(1)
}
const summary = {
phoneNumbersLength: phoneNumbers.length,
insertedRows: 0,
alreadyInsertedRows: 0,
}
const sortedPhoneNumbers = phoneNumbers.sort()
for (const phoneNumber of sortedPhoneNumbers) {
const callIds = await fetchCallIds(phoneNumber)
for (const callId of callIds) {
const history = await conferences.getHistoryForCall(phoneNumber, callId)
await insertCallHistory(history, phoneNumber, summary)
}
// Record that this batch of inserts was successful
await recordSuccessfulJob(phoneNumber)
}
console.dir({ summary })
console.debug("End of fetchCallsStats job.")
return summary
} catch(err) {
console.error("fetchCallsStats job abort on error", err)
process.exit(1)
}
}