forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremote.ts
More file actions
84 lines (77 loc) · 2.63 KB
/
remote.ts
File metadata and controls
84 lines (77 loc) · 2.63 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
/**
* Copyright (c) 2022 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import type { StatCondition } from "@db/stat-database"
import processor from "@service/backup/processor"
import { identifyStatKey } from "@util/stat"
import { getBirthday } from "@util/time"
import { cvt2SiteRow } from "./common"
export async function processRemote(origin: timer.stat.SiteRow[], param?: StatCondition): Promise<timer.stat.SiteRow[]> {
if (!await canReadRemote()) {
return origin
}
// Map to merge
const originMap: Record<string, MakeRequired<timer.stat.SiteRow, 'composition'>> = {}
origin.forEach(row => originMap[identifyStatKey(row)] = {
...row,
composition: {
focus: [row.focus],
time: [row.time],
run: row.run ? [row.run] : [],
}
})
// Predicate with host
const { keys, date } = param ?? {}
const keyArr = typeof keys === 'string' ? [keys] : keys
const predicate = keyArr?.length
? ({ host }: timer.core.Row) => keyArr.includes(host)
: () => true
// 1. query remote
let start: Date | undefined = undefined, end: Date | undefined = undefined
if (Array.isArray(date)) {
[start, end] = date
} else {
start = date
}
start = start ?? getBirthday()
end = end ?? new Date()
const remote = await processor.query({ excludeLocal: true, start, end })
remote.filter(predicate).forEach(row => processRemoteRow(originMap, row))
return Object.values(originMap)
}
/**
* Enabled to read remote backup data
*
* @since 1.2.0
* @returns T/F
*/
export async function canReadRemote(): Promise<boolean> {
const { errorMsg } = await processor.checkAuth()
return !errorMsg
}
function processRemoteRow(rowMap: Record<string, MakeRequired<timer.stat.SiteRow, 'composition'>>, remoteBase: timer.core.Row) {
const row = cvt2SiteRow(remoteBase)
const key = identifyStatKey(row)
let exist = rowMap[key]
!exist && (exist = rowMap[key] = {
date: row.date,
siteKey: row.siteKey,
time: 0,
focus: 0,
composition: {
focus: [],
time: [],
run: [],
},
} satisfies MakeRequired<timer.stat.SiteRow, 'composition'>)
const { focus = 0, time = 0, run = 0, cid = '', cname } = row
exist.focus += focus
exist.time += time
run && (exist.run = run)
focus && exist.composition.focus.push({ cid, cname, value: focus })
time && exist.composition.time.push({ cid, cname, value: time })
run && exist.composition.run.push({ cid, cname, value: run })
}