generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.ts
348 lines (304 loc) · 8.92 KB
/
main.ts
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
import { checkConnection, getDriveClient } from "helpers/drive";
import { refreshAccessToken } from "helpers/ky";
import { pull } from "helpers/pull";
import { push } from "helpers/push";
import { reset } from "helpers/reset";
import {
App,
debounce,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
TAbstractFile,
TFile,
} from "obsidian";
interface PluginSettings {
refreshToken: string;
operations: Record<string, "create" | "delete" | "modify">;
driveIdToPath: Record<string, string>;
lastSyncedAt: number;
changesToken: string;
}
const DEFAULT_SETTINGS: PluginSettings = {
refreshToken: "",
operations: {},
driveIdToPath: {},
lastSyncedAt: 0,
changesToken: "",
};
export default class ObsidianGoogleDrive extends Plugin {
settings: PluginSettings;
accessToken = {
token: "",
expiresAt: 0,
};
drive = getDriveClient(this);
ribbonIcon: HTMLElement;
syncing: boolean;
async onload() {
const { vault } = this.app;
await this.loadSettings();
this.addSettingTab(new SettingsTab(this.app, this));
if (!this.settings.refreshToken) {
new Notice(
"Please add your refresh token to Google Drive Sync through our website or our readme/this plugin's settings. If you haven't already, PLEASE read through this plugin's readme or website CAREFULLY for instructions on how to use this plugin. If you don't know what you're doing, your data could get DELETED.",
0
);
return;
}
this.ribbonIcon = this.addRibbonIcon(
"refresh-cw",
"Push to Google Drive",
() => push(this)
);
this.addCommand({
id: "push",
name: "Push to Google Drive",
callback: () => push(this),
});
this.addCommand({
id: "pull",
name: "Pull from Google Drive",
callback: () => pull(this),
});
this.addCommand({
id: "reset",
name: "Reset local vault to Google Drive",
callback: () => reset(this),
});
this.registerEvent(
this.app.workspace.on("quit", () => this.saveSettings())
);
this.app.workspace.onLayoutReady(() =>
this.registerEvent(vault.on("create", this.handleCreate.bind(this)))
);
this.registerEvent(vault.on("delete", this.handleDelete.bind(this)));
this.registerEvent(vault.on("modify", this.handleModify.bind(this)));
this.registerEvent(vault.on("rename", this.handleRename.bind(this)));
checkConnection().then(async (connected) => {
if (connected) {
this.syncing = true;
this.ribbonIcon.addClass("spin");
await pull(this, true);
await this.endSync();
}
});
}
onunload() {
return this.saveSettings();
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
saveSettings() {
return this.saveData(this.settings);
}
debouncedSaveSettings = debounce(this.saveSettings.bind(this), 500, true);
handleCreate(file: TAbstractFile) {
if (this.settings.operations[file.path] === "delete") {
if (file instanceof TFile) {
this.settings.operations[file.path] = "modify";
} else {
delete this.settings.operations[file.path];
}
} else {
this.settings.operations[file.path] = "create";
}
this.debouncedSaveSettings();
}
handleDelete(file: TAbstractFile) {
if (this.settings.operations[file.path] === "create") {
delete this.settings.operations[file.path];
} else {
this.settings.operations[file.path] = "delete";
}
this.debouncedSaveSettings();
}
handleModify(file: TFile) {
const operation = this.settings.operations[file.path];
if (operation === "create" || operation === "modify") {
return;
}
this.settings.operations[file.path] = "modify";
this.debouncedSaveSettings();
}
handleRename(file: TAbstractFile, oldPath: string) {
this.handleDelete({ ...file, path: oldPath });
this.handleCreate(file);
this.debouncedSaveSettings();
}
async createFolder(path: string) {
const oldOperation = this.settings.operations[path];
await this.app.vault.createFolder(path);
this.settings.operations[path] = oldOperation;
if (!oldOperation) delete this.settings.operations[path];
}
async createFile(
path: string,
content: ArrayBuffer,
modificationDate?: number | string | Date
) {
const oldOperation = this.settings.operations[path];
if (typeof modificationDate === "string") {
modificationDate = new Date(modificationDate);
}
if (modificationDate instanceof Date) {
modificationDate = modificationDate.getTime();
}
await this.app.vault.createBinary(path, content, {
mtime: modificationDate,
});
this.settings.operations[path] = oldOperation;
if (!oldOperation) delete this.settings.operations[path];
}
async modifyFile(
file: TFile,
content: ArrayBuffer,
modificationDate?: number | string | Date
) {
const oldOperation = this.settings.operations[file.path];
if (typeof modificationDate === "string") {
modificationDate = new Date(modificationDate);
}
if (modificationDate instanceof Date) {
modificationDate = modificationDate.getTime();
}
await this.app.vault.modifyBinary(file, content, {
mtime: modificationDate,
});
this.settings.operations[file.path] = oldOperation;
if (!oldOperation) delete this.settings.operations[file.path];
}
async upsertFile(
file: string,
content: ArrayBuffer,
modificationDate?: number | string | Date
) {
const oldOperation = this.settings.operations[file];
if (typeof modificationDate === "string") {
modificationDate = new Date(modificationDate);
}
if (modificationDate instanceof Date) {
modificationDate = modificationDate.getTime();
}
await this.app.vault.adapter.writeBinary(file, content, {
mtime: modificationDate,
});
this.settings.operations[file] = oldOperation;
if (!oldOperation) delete this.settings.operations[file];
}
async deleteFile(file: TAbstractFile) {
const oldOperation = this.settings.operations[file.path];
await this.app.fileManager.trashFile(file);
delete this.settings.operations[file.path];
if (!oldOperation) delete this.settings.operations[file.path];
}
async startSync() {
if (!(await checkConnection())) {
throw new Notice(
"You are not connected to the internet, so you cannot sync right now. Please try syncing once you have connection again."
);
}
this.ribbonIcon.addClass("spin");
this.syncing = true;
return new Notice("Syncing (0%)", 0);
}
async endSync(syncNotice?: Notice, retainConfigChanges = true) {
if (retainConfigChanges) {
const configFilesToSync = await this.drive.getConfigFilesToSync();
this.settings.lastSyncedAt = Date.now();
await Promise.all(
configFilesToSync.map(async (file) =>
this.app.vault.adapter.writeBinary(
file,
await this.app.vault.adapter.readBinary(file),
{ mtime: Date.now() }
)
)
);
} else {
this.settings.lastSyncedAt = Date.now();
}
const changesToken = await this.drive.getChangesStartToken();
if (!changesToken) {
return new Notice(
"An error occurred fetching Google Drive changes token."
);
}
this.settings.changesToken = changesToken;
await this.saveSettings();
this.ribbonIcon.removeClass("spin");
this.syncing = false;
syncNotice?.hide();
}
}
class SettingsTab extends PluginSettingTab {
plugin: ObsidianGoogleDrive;
constructor(app: App, plugin: ObsidianGoogleDrive) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
const { vault } = this.app;
containerEl.empty();
containerEl.createEl("a", {
href: "https://ogd.richardxiong.com",
text: "Get refresh token",
});
new Setting(containerEl)
.setName("Refresh token")
.setDesc(
"A refresh token is required to access your Google Drive for syncing. We suggest cloning your Google Drive vault to the current vault BEFORE syncing."
)
.addText((text) => {
const cancel = () => {
this.plugin.settings.refreshToken = "";
text.setValue("");
return this.plugin.saveSettings();
};
text.setPlaceholder("Enter your refresh token")
.setValue(this.plugin.settings.refreshToken)
.onChange(async (value) => {
this.plugin.settings.refreshToken = value;
if (!value) {
return this.plugin.debouncedSaveSettings();
}
if (!(await refreshAccessToken(this.plugin))) {
text.setValue("");
return;
}
if (
vault
.getAllLoadedFiles()
.filter(({ path }) => path !== "/").length > 0
) {
new Notice(
"Your current vault is not empty! If you want our plugin to handle the initial sync, you have to clear out the current vault. Check the readme or website for more details.",
0
);
return cancel();
}
const changesToken =
await this.plugin.drive.getChangesStartToken();
if (!changesToken) {
return new Notice(
"An error occurred fetching Google Drive changes token."
);
}
this.plugin.settings.changesToken = changesToken;
await this.plugin.saveSettings();
new Notice(
"Refresh token saved! Reload Obsidian to activate sync.",
0
);
});
});
}
}