forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor.ts
More file actions
195 lines (175 loc) · 7.16 KB
/
Copy pathprocessor.ts
File metadata and controls
195 lines (175 loc) · 7.16 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
/**
* Copyright (c) 2022 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import syncDb from "@db/backup-database"
import statDb from "@db/stat-database"
import optionHolder from "../components/option-holder"
import { getCid, updateBackUpTime } from "../meta-service"
import GistCoordinator from "./gist/coordinator"
import ObsidianCoordinator from "./obsidian/coordinator"
import WebDAVCoordinator from "./web-dav/coordinator"
type AuthCheckResult = {
option: tt4b.option.BackupOption
auth: tt4b.backup.Auth
ext: tt4b.backup.TypeExt
type: tt4b.backup.Type
coordinator: tt4b.backup.Coordinator<unknown>
errorMsg?: string
}
class CoordinatorContextWrapper<Cache> implements tt4b.backup.CoordinatorContext<Cache> {
auth: tt4b.backup.Auth
ext?: tt4b.backup.TypeExt
cache: Cache = {} as unknown as Cache
type: tt4b.backup.Type
cid: string
constructor(cid: string, auth: tt4b.backup.Auth, ext: tt4b.backup.TypeExt, type: tt4b.backup.Type) {
this.cid = cid
this.auth = auth
this.ext = ext
this.type = type
}
async init(): Promise<tt4b.backup.CoordinatorContext<Cache>> {
this.cache = await syncDb.getCache(this.type) as Cache
return this
}
handleCacheChanged(): Promise<void> {
return syncDb.updateCache(this.type, this.cache)
}
}
async function syncFull(
context: tt4b.backup.CoordinatorContext<unknown>,
coordinator: tt4b.backup.Coordinator<unknown>,
client: tt4b.backup.Client
): Promise<void> {
// 1. select rows
const rows = await statDb.select()
const allDates = rows.map(r => r.date).sort((a, b) => a == b ? 0 : a > b ? 1 : -1)
client.maxDate = allDates[allDates.length - 1]
client.minDate = allDates[0]
// 2. upload
await coordinator.upload(context, rows)
}
function filterClient(c: tt4b.backup.Client, excludeLocal: boolean, localClientId: string, start?: string, end?: string) {
// Exclude local client
if (excludeLocal && c.id === localClientId) return false
// Judge range
if (start && c.maxDate && c.maxDate < start) return false
if (end && c.minDate && c.minDate > end) return false
return true
}
function prepareAuth(option: tt4b.option.BackupOption): tt4b.backup.Auth {
const type = option?.backupType || 'none'
const token = option?.backupAuths?.[type]
const login = option.backupLogin?.[type]
return { token, login }
}
class Processor {
coordinators: {
[type in tt4b.backup.Type]: tt4b.backup.Coordinator<unknown>
}
constructor() {
this.coordinators = {
none: null as unknown as tt4b.backup.Coordinator<never>,
gist: new GistCoordinator(),
obsidian_local_rest_api: new ObsidianCoordinator(),
web_dav: new WebDAVCoordinator(),
}
}
async syncData(): Promise<string | undefined> {
const { option, auth, ext, type, coordinator, errorMsg } = await this.checkAuth()
if (errorMsg) return errorMsg
const cid = await getCid()
const context: tt4b.backup.CoordinatorContext<unknown> = await new CoordinatorContextWrapper<unknown>(cid, auth, ext, type).init()
const client: tt4b.backup.Client = {
id: cid,
name: option.clientName,
minDate: undefined,
maxDate: undefined
}
try {
await syncFull(context, coordinator, client)
const clients = (await coordinator.listAllClients(context)).filter(a => a.id !== cid)
clients.push(client)
await coordinator.updateClients(context, clients)
// Update time
await updateBackUpTime(type, Date.now())
} catch (e) {
console.error("Error to sync data", e)
return e instanceof Error ? e.message : String(e ?? 'Unknown Error')
}
}
async listClients(): Promise<(tt4b.backup.Client & { current: boolean })[]> {
const { auth, ext, type, coordinator, errorMsg } = await this.checkAuth()
if (errorMsg) throw new Error(errorMsg)
const cid = await getCid()
const context = await new CoordinatorContextWrapper<unknown>(cid, auth, ext, type).init()
const clients = await coordinator.listAllClients(context)
return clients.map(c => ({ ...c, current: c.id === cid }))
}
async checkAuth(): Promise<AuthCheckResult> {
const option = await optionHolder.get()
const { backupType: type, backupExts } = option
const ext = backupExts?.[type] ?? {}
const auth = prepareAuth(option)
const coordinator: tt4b.backup.Coordinator<unknown> = type && this.coordinators[type]
if (!coordinator) {
// no coordinator, do nothing
return { option, auth, ext, type, coordinator, errorMsg: "Invalid type" }
}
let errorMsg
try {
errorMsg = await coordinator.testAuth(auth, ext)
} catch (e) {
errorMsg = (e as Error)?.message || 'Unknown error'
}
return { option, auth, ext, type, coordinator, errorMsg }
}
async query(param: tt4b.backup.RemoteQuery): Promise<tt4b.backup.Row[]> {
const { type, coordinator, auth, ext, errorMsg } = await this.checkAuth()
if (errorMsg || !coordinator) {
return []
}
const { start, end, specCid, excludeLocal } = param
let localCid = await getCid()
// 1. init context
const context: tt4b.backup.CoordinatorContext<unknown> = await new CoordinatorContextWrapper<unknown>(localCid, auth, ext, type).init()
// 2. query all clients, and filter them
const allClients = (await coordinator.listAllClients(context))
.filter(c => filterClient(c, !!excludeLocal, localCid, start, end))
.filter(c => !specCid || c.id === specCid)
// 3. iterate clients
const result: tt4b.backup.Row[] = []
await Promise.all(
allClients.map(async client => {
const { id, name } = client
const rows = await coordinator.download(context, start, end, id)
rows.forEach(row => result.push({
...row,
cid: id,
cname: name,
}))
})
)
console.log(`Queried ${result.length} remote items`)
return result
}
async clear(cid: string): Promise<string | undefined> {
const { auth, ext, type, coordinator, errorMsg } = await this.checkAuth()
if (errorMsg) return errorMsg
let localCid = await getCid()
const context: tt4b.backup.CoordinatorContext<unknown> = await new CoordinatorContextWrapper<unknown>(localCid, auth, ext, type).init()
// 1. Find the client
const allClients = await coordinator.listAllClients(context)
const client = allClients?.filter(c => c?.id === cid)?.[0]
if (!client) return
// 2. clear
await coordinator.clear(context, client)
// 3. remove client
const newClients = allClients.filter(c => c?.id !== cid)
await coordinator.updateClients(context, newClients)
}
}
export default new Processor()