-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
489 lines (479 loc) · 17.6 KB
/
main.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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => RelayMdPLugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian6 = require("obsidian");
// src/settings.ts
var import_obsidian = require("obsidian");
var DEFAULT_SETTINGS = {
auth_url: "https://relay.md",
vault_base_folder: "relay.md",
fetch_recent_documents_interval: 5 * 60,
api_key: "",
api_username: "",
base_uri: "https://api.relay.md"
};
var RelayMDSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
new import_obsidian.Setting(containerEl).setName("relay.md instance").setDesc("Main site to link against").addText((text) => text.setPlaceholder("Enter your URL").setValue(this.plugin.settings.auth_url).onChange(async (value) => {
this.plugin.settings.auth_url = value;
await this.plugin.saveSettings();
}));
if (!this.plugin.settings.api_key || this.plugin.settings.api_key === DEFAULT_SETTINGS.api_key) {
new import_obsidian.Setting(containerEl).setName("Link account").setDesc("Link with your account on the instance").addButton(
(button) => button.setButtonText("Obtain access to relay.md").onClick(async () => {
window.open(this.plugin.settings.auth_url + "/configure/obsidian");
})
);
} else {
new import_obsidian.Setting(containerEl).setName("API Access").setDesc(`Logged in as @${this.plugin.settings.api_username}`).addButton(
(button) => button.setButtonText(`Logout!`).onClick(async () => {
this.plugin.settings.api_key = DEFAULT_SETTINGS.api_key;
this.plugin.settings.api_username = DEFAULT_SETTINGS.api_username;
this.plugin.settings.base_uri = DEFAULT_SETTINGS.base_uri;
await this.plugin.saveSettings();
this.display();
})
);
}
new import_obsidian.Setting(containerEl).setName("Vault relay.md inbox").setDesc("Base folder to synchronize into").addText((text) => text.setPlaceholder("relay.md").setValue(this.plugin.settings.vault_base_folder).onChange(async (value) => {
this.plugin.settings.vault_base_folder = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Fetch recent documents interval").setDesc("How often to look for document updates in seconds").addText((text) => text.setPlaceholder("300").setValue(this.plugin.settings.fetch_recent_documents_interval.toString()).onChange(async (value) => {
const as_float = parseFloat(value);
if (isNaN(as_float) || !isFinite(+as_float)) {
new import_obsidian.Notice("Interval must be an number!");
} else {
this.plugin.settings.fetch_recent_documents_interval = as_float;
await this.plugin.saveSettings();
this.plugin.register_timer();
}
}));
new import_obsidian.Setting(containerEl).setHeading().setName("Advanced Settings");
new import_obsidian.Setting(containerEl).setName("API Address").addText((text) => text.setValue(this.plugin.settings.base_uri.toString()).onChange(async (value) => {
this.plugin.settings.base_uri = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("API Access key").addText((text) => text.setValue(this.plugin.settings.api_key.toString()).onChange(async (value) => {
this.plugin.settings.api_key = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("API user").addText((text) => text.setValue(this.plugin.settings.api_username.toString()).onChange(async (value) => {
this.plugin.settings.api_username = value;
await this.plugin.saveSettings();
}));
}
};
// src/document.ts
var import_obsidian5 = require("obsidian");
// src/embed.ts
var import_obsidian4 = require("obsidian");
// src/api.ts
var import_obsidian2 = require("obsidian");
var API = class {
constructor(plugin) {
this.plugin = plugin;
this.uploadQueue = [];
}
async post(endpoint, body, retries = 1) {
const options = {
url: this.plugin.settings.base_uri + endpoint,
method: "POST",
headers: {
"X-API-KEY": this.plugin.settings.api_key
},
body
};
const response = await (0, import_obsidian2.requestUrl)(options);
if (response.json.error) {
console.error("API server returned an error", response.json.error.message);
new import_obsidian2.Notice("API returned an error: " + response.json.error.message);
return null;
}
return response;
}
async postRaw(endpoint, body, retries = 4) {
const options = {
url: this.plugin.settings.base_uri + endpoint,
method: "POST",
headers: {
"X-API-KEY": this.plugin.settings.api_key
},
body
};
const response = await (0, import_obsidian2.requestUrl)(options);
if (response.json.error) {
console.error("API server returned an error", response.json.error.message);
new import_obsidian2.Notice("API returned an error: " + response.json.error.message);
return null;
}
return response;
}
async put(endpoint, body, retries = 4) {
const options = {
url: this.plugin.settings.base_uri + endpoint,
method: "PUT",
headers: {
"X-API-KEY": this.plugin.settings.api_key
},
body
};
const response = await (0, import_obsidian2.requestUrl)(options);
if (response.json.error) {
console.error("API server returned an error", response.json.error.message);
new import_obsidian2.Notice("API returned an error: " + response.json.error.message);
return null;
}
return response;
}
async putRaw(endpoint, data, retries = 1) {
return null;
}
async get(endpoint, content_type = "application/json", retries = 1) {
const options = {
url: this.plugin.settings.base_uri + endpoint,
method: "GET",
headers: {
"X-API-KEY": this.plugin.settings.api_key,
"Content-Type": content_type
}
};
const response = await (0, import_obsidian2.requestUrl)(options);
if (content_type == "application/json") {
if (response.json.error) {
console.error("API server returned an error", response.json.error.message);
new import_obsidian2.Notice("API returned an error: " + response.json.error.message);
return null;
}
}
return response;
}
async getRaw(endpoint, data, retries = 4) {
return null;
}
// Queue
async queueUpload(item) {
return null;
}
async queueDownload(item) {
return null;
}
async processQueue() {
return null;
}
};
// src/utils.ts
var import_obsidian3 = require("obsidian");
var Utils = class {
static async calculateSHA256Checksum(buffer) {
const data = new Uint8Array(buffer);
try {
const hashBuffer = await window.crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const checksum = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
return checksum;
} catch (error) {
throw new Error(`Error calculating SHA-256 checksum: ${error}`);
}
}
static make_directory_recursively(app, path) {
path.split("/").slice(0, -1).reduce(
(directories = "", directory) => {
directories += `${directory}/`;
if (!(app.vault.getAbstractFileByPath(directories) instanceof import_obsidian3.TFolder)) {
app.vault.createFolder(directories);
}
return directories;
},
""
);
}
};
// src/embed.ts
var EmbedRepo = class {
constructor(plugin) {
this.plugin = plugin;
this.api = new API(this.plugin);
}
async load_embeds(embed, document) {
document["relay-to"].forEach(async (team_topic) => {
const parts = team_topic.split("@", 2);
const team = parts[1];
if (!team)
return;
const folder = (0, import_obsidian4.normalizePath)(this.plugin.settings.vault_base_folder + "/" + team + "/_attachments");
const path = (0, import_obsidian4.normalizePath)(folder + "/" + embed.filename);
Utils.make_directory_recursively(this.plugin.app, path);
const file = this.plugin.app.vault.getAbstractFileByPath(path);
if (file instanceof import_obsidian4.TFile) {
const local_content = await this.plugin.app.vault.readBinary(file);
const checksum = await Utils.calculateSHA256Checksum(local_content);
if (checksum != embed.checksum_sha256) {
const content = await this.get_embeded_binary(embed);
if (!content)
return;
this.plugin.app.vault.modifyBinary(file, content);
console.log("Binary file " + path + " has been updated!");
}
} else {
const content = await this.get_embeded_binary(embed);
if (!content)
return;
this.plugin.app.vault.createBinary(path, content);
console.log("Binary file " + path + " has been created!");
}
});
}
async get_embeded_binary(embed) {
const response = await this.api.get("/v1/assets/" + embed.id, "application/octet-stream");
if (!response)
return;
return response.arrayBuffer;
}
async upload_asset(id, link, file) {
const content = await this.plugin.app.vault.readBinary(file);
const response = await this.api.postRaw("/v1/assets/" + id + "?filename=" + encodeURIComponent(file.path), content);
if (!response)
return;
console.log("Successfully uploaded " + file.path + " as " + response.json.result.id);
}
};
// src/document.ts
var DocumentRepo = class {
constructor(plugin) {
this.plugin = plugin;
this.api = new API(this.plugin);
this.embed_repo = new EmbedRepo(this.plugin);
}
async get_recent_documents() {
const response = await this.api.get("/v1/docs");
if (!response)
return;
response.json.result.map(async (item) => {
new import_obsidian5.Notice("Obtaining " + item["relay-filename"]);
await this.load_document(item["relay-document"]);
});
}
async load_document(id) {
const response = await this.api.get("/v1/doc/" + id);
if (!response)
return;
const result = response.json.result;
const embeds = result.embeds;
if (embeds) {
embeds.map((embed) => {
this.embed_repo.load_embeds(embed, result);
});
}
this.load_document_body(result);
}
async load_document_body(result) {
const id = result["relay-document"];
const filename = result["relay-filename"];
const relay_to = result["relay-to"];
const remote_checksum = result["checksum_sha256"];
const response = await this.api.get("/v1/doc/" + id, "text/markdown");
if (!response)
return;
const body = response.text;
const located_documents = await this.locate_document(id);
if (located_documents == null ? void 0 : located_documents.length) {
located_documents.forEach(async (located_document) => {
const local_content = await this.plugin.app.vault.readBinary(located_document);
const checksum = await Utils.calculateSHA256Checksum(local_content);
if (checksum != remote_checksum) {
this.upsert_document(located_document.path, body);
} else {
console.log("No change detected on " + located_document.path);
}
});
} else {
for (const to of relay_to) {
const tos = to.split("@", 2);
const team = tos[1];
const topic = tos[0];
let folder = this.plugin.settings.vault_base_folder + "/";
if (team != "_")
folder += team + "/";
folder += topic;
const path = (0, import_obsidian5.normalizePath)(folder + "/" + filename);
this.upsert_document(path, body);
}
}
}
async upsert_document(path, body) {
Utils.make_directory_recursively(this.plugin.app, path);
const fileRef = this.plugin.app.vault.getAbstractFileByPath(path);
if (fileRef === void 0 || fileRef === null) {
await this.plugin.app.vault.create(path, body);
new import_obsidian5.Notice("File " + path + " has been created!");
} else if (fileRef instanceof import_obsidian5.TFile) {
await this.plugin.app.vault.modify(fileRef, body);
new import_obsidian5.Notice("File " + path + " has been modified!");
}
}
async locate_document(document_id) {
const files = this.plugin.app.vault.getMarkdownFiles();
let located_files = [];
for (let i = 0; i < files.length; i++) {
const activeFile = files[i];
const metadata = this.plugin.app.metadataCache.getCache(activeFile.path);
if (!metadata || !metadata.frontmatter) {
continue;
}
if (metadata.frontmatter["relay-document"] === document_id) {
console.log("Found an existing file with the document id " + document_id);
located_files.push(activeFile);
}
}
return located_files;
}
async send_document(activeFile) {
if (!activeFile) {
return;
}
if (activeFile.extension !== "md") {
return;
}
const metadata = this.plugin.app.metadataCache.getCache(activeFile.path);
if (!metadata || !metadata.frontmatter) {
return;
}
if (!("relay-to" in metadata.frontmatter) || !metadata.frontmatter["relay-to"]) {
return;
}
let id = metadata.frontmatter["relay-document"];
const body = await this.plugin.app.vault.cachedRead(activeFile);
let response;
if (id) {
response = await this.api.put("/v1/doc/" + id, body);
} else {
response = await this.api.post("/v1/doc?filename=" + encodeURIComponent(activeFile.path), body);
}
if (!response)
return;
console.log("Successfully sent to " + this.plugin.settings.base_uri);
try {
id = response.json.result["relay-document"];
this.plugin.app.fileManager.processFrontMatter(activeFile, (frontmatter) => {
frontmatter["relay-document"] = id;
});
} catch (e) {
console.log(e);
}
if (!metadata.embeds) {
return;
}
metadata.embeds.map(async (item) => {
let file = this.plugin.app.vault.getAbstractFileByPath(item.link);
if (!(file instanceof import_obsidian5.TFile)) {
file = this.plugin.app.metadataCache.getFirstLinkpathDest(item.link, "");
}
if (!file || !(file instanceof import_obsidian5.TFile)) {
console.log(`Embed ${item.link} was not found!`);
} else {
this.embed_repo.upload_asset(id, item.link, file);
}
});
}
};
// src/main.ts
var RelayMdPLugin = class extends import_obsidian6.Plugin {
async onload() {
await this.loadSettings();
this.document_repo = new DocumentRepo(this);
this.registerObsidianProtocolHandler("relay.md:access-token", (params) => {
if (!params.token) {
return;
}
this.settings.api_key = params.token;
this.settings.api_username = params.username;
this.settings.base_uri = params.api_url;
this.saveSettings();
let get_over_complile_error_app = this.app;
let app_setting = get_over_complile_error_app.setting;
if (app_setting.activeTab) {
app_setting.activeTab.display();
}
new import_obsidian6.Notice("Access credentials for relay.md have been succesfully installed!");
});
this.addCommand({
id: "send-current-active-file",
name: "Send current open file",
callback: async () => {
new import_obsidian6.Notice("Sending document to relay.md");
const activeFile = this.app.workspace.getActiveFile();
await this.document_repo.send_document(activeFile);
}
});
this.addCommand({
id: "fetch-documents",
name: "Retreive recent files",
callback: async () => {
new import_obsidian6.Notice("Retreiving documents from relay.md");
await this.document_repo.get_recent_documents();
}
});
this.registerEvent(this.app.metadataCache.on("changed", (file) => {
if (file instanceof import_obsidian6.TFile) {
this.document_repo.send_document(file);
}
}));
this.registerEvent(this.app.vault.on("create", (file) => {
if (file instanceof import_obsidian6.TFile) {
this.document_repo.send_document(file);
}
}));
this.register_timer();
this.addSettingTab(new RelayMDSettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
register_timer() {
if (this.fetch_recent_document_timer) {
window.clearInterval(
this.fetch_recent_document_timer
);
}
this.fetch_recent_document_timer = window.setInterval(() => {
this.document_repo.get_recent_documents();
}, this.settings.fetch_recent_documents_interval * 1e3);
this.registerInterval(this.fetch_recent_document_timer);
}
};