generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.ts
793 lines (713 loc) · 26.6 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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
import {Plugin, Notice, RequestUrlParam, requestUrl, PluginSettingTab, Setting, App, TFile, moment} from "obsidian";
import i18n from 'i18next';
import enTranslation from './locales/en.json';
import jaTranslation from './locales/ja.json';
interface MisskeyPluginSettings {
isConvertToWebP: boolean;
multiLinePostingSection: string;
accounts: Account[];
}
interface Account {
isSelected: boolean;
memo: string;
domain: string;
prevText: string;
postText: string;
isFileNameHidden: boolean;
visibility: "public" | "home" | "followers"; // "specified"はサポートしない
uploadAllowedList: string[];
embedFormat: string;
accountToken: null | string;
}
const createDefaultAccount = (): Account => ({
isSelected: false,
memo: "",
domain: "",
prevText: "",
postText: "",
isFileNameHidden: false,
visibility: "public",
uploadAllowedList: ["png", "jpg", "jpeg", "gif", "bmp", "svg", "mp3", "webm", "wav", "m4a", "ogg", "3gp", "flac", "mp4", "webm", "ogv"],
embedFormat: "html",
accountToken: null,
});
const selectedAccount = createDefaultAccount();
selectedAccount.isSelected = true;
const DEFAULT_SETTINGS: Partial<MisskeyPluginSettings> = {
isConvertToWebP: false,
multiLinePostingSection: "---\\n",
accounts: [selectedAccount],
}
export class MisskeyPluginSettingsTab extends PluginSettingTab {
plugin: MisskeyPlugin;
constructor(app: App, plugin: MisskeyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName(i18n.t("isConvertToWebP.name"))
.setDesc(i18n.t("isConvertToWebP.desc"))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.isConvertToWebP)
.onChange(async (value) => {
this.plugin.settings.isConvertToWebP = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(i18n.t("multiLinePostingSection.name"))
.setDesc(i18n.t("multiLinePostingSection.desc"))
.addText(text => text
.setPlaceholder(i18n.t("multiLinePostingSection.placeholder"))
.setValue(this.plugin.settings.multiLinePostingSection)
.onChange(async (value) => {
this.plugin.settings.multiLinePostingSection = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName(i18n.t("addAccount.name"))
.addButton(button => button
.setButtonText(i18n.t("addAccount.buttonText"))
.onClick(async () => {
this.plugin.settings.accounts.push(createDefaultAccount());
await this.plugin.saveSettings();
this.display();
}));
for (const accountSetting of this.plugin.settings.accounts) {
new Setting(containerEl)
.setHeading()
.setName(i18n.t("accountHeading.name"))
.setDesc(accountSetting.isSelected ? i18n.t("accountHeading.desc") : "")
if (!accountSetting.isSelected) {
new Setting(containerEl)
.setName(i18n.t("useThisAccount.name"))
.addButton(button => button
.setButtonText(i18n.t("useThisAccount.buttonText"))
.onClick(async () => {
for (const account of this.plugin.settings.accounts) {
account.isSelected = false;
}
accountSetting.isSelected = true;
await this.plugin.saveSettings();
this.display();
}));
}
new Setting(containerEl)
.setName(i18n.t("memo.name"))
.setDesc(i18n.t("memo.desc"))
.addTextArea(text => text
.setPlaceholder(i18n.t("memo.placeholder"))
.setValue(accountSetting.memo)
.onChange(async (value) => {
accountSetting.memo = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(i18n.t("domain.name"))
.setDesc(i18n.t("domain.desc"))
.addText(text => text
.setPlaceholder(i18n.t("domain.placeholder"))
.setValue(accountSetting.domain)
.onChange(async (value) => {
accountSetting.domain = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(i18n.t("prevText.name"))
.setDesc(i18n.t("prevText.desc"))
.addTextArea(text => text
.setPlaceholder(i18n.t("prevText.placeholder"))
.setValue(accountSetting.prevText)
.onChange(async (value) => {
accountSetting.prevText = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(i18n.t("postText.name"))
.setDesc(i18n.t("postText.desc"))
.addTextArea(text => text
.setPlaceholder(i18n.t("postText.placeholder"))
.setValue(accountSetting.postText)
.onChange(async (value) => {
accountSetting.postText = value;
await this.plugin.saveSettings();
}));
// 俺にはこれが必要なのか分からないけどMisskeyプラグインがあるので作っておく
// プラグイン: https://misskey.io/notes/9d7mdepqx3
new Setting(containerEl)
.setName(i18n.t("isFileNameHidden.name"))
.setDesc(i18n.t("isFileNameHidden.desc"))
.addToggle(toggle => toggle
.setValue(accountSetting.isFileNameHidden)
.onChange(async (value) => {
accountSetting.isFileNameHidden = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(i18n.t("visibility.name"))
.setDesc(i18n.t("visibility.desc"))
.addDropdown(dropdown => dropdown
.addOptions(
{
"public": "public",
"home": "home",
"followers": "followers"
},
).onChange(
async (value) => {
if (value !== "public" && value !== "home" && value !== "followers"){
new Notice(i18n.t("visibility.valueError"))
return;
}
accountSetting.visibility = value;
await this.plugin.saveSettings();
}
).setValue(
accountSetting.visibility
)
);
new Setting(containerEl)
.setName(i18n.t("uploadAllowedList.name"))
.setDesc(i18n.t("uploadAllowedList.desc"))
.addTextArea(text => text
.setPlaceholder(i18n.t("uploadAllowedList.placeholder"))
.setValue(
accountSetting.uploadAllowedList.length === 0 ?
"" : accountSetting.uploadAllowedList.join(", ")
)
.onChange(async (value) => {
accountSetting.uploadAllowedList = value.split(",").map((item) => item.trim());
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(i18n.t("embedFormat.name"))
.setDesc(i18n.t("embedFormat.desc"))
.addDropdown(dropdown => dropdown
.addOptions(
{
"markdown": "Markdown",
"html": "HTML"
},
).onChange(
async (value) => {
if (value !== "markdown" && value !== "html"){
new Notice(i18n.t("embedFormat.valueError"))
return;
}
accountSetting.embedFormat = value;
await this.plugin.saveSettings();
}
).setValue(
accountSetting.embedFormat
)
);
new Setting(containerEl)
.setName(i18n.t("tokenSetting.name"))
.setDesc(i18n.t("tokenSetting.desc"))
.addButton(button => button
.setButtonText(i18n.t("tokenSetting.buttonText"))
.onClick(async () => {
// MiAuthを使用してアクセストークンを取得します
const domain = accountSetting.domain;
if (domain === "") {
new Notice(i18n.t("tokenSetting.domainNotSet"))
return;
}
// MiAuthのセッションIDを生成
const array = new Uint8Array(32);
window.crypto.getRandomValues(array);
const sessionId = Array.from(array, byte => ('0' + (byte & 0xFF).toString(16)).slice(-2)).join('');
const appName = "obsidian-plugin-for-misskey"
const iconURL = "https://raw.githubusercontent.com/minimarimo3/Obsidian-plugin-for-Misskey/master/documents/icon_ki.png"
const authURL = `https://${domain}/miauth/${sessionId}?name=${appName}&icon=${iconURL}&permission=write:notes,write:drive`
const checkURL = `https://${domain}/api/miauth/${sessionId}/check`
window.open(`${authURL}`)
let intervalCount = 0;
const maxIntervalCount = 60 * 2 / 5;
const intervalId = setInterval(async () => {
if (intervalCount >= maxIntervalCount) {
clearInterval(intervalId);
new Notice(i18n.t("tokenSetting.timeOut"))
return;
}
// NOTE: requestUrlを使った際、macOSでは正常に動いたもののAndroidでは
// 415(Unsupported Media Type)が返ったのでfetchを使ってる。
const data = await (await fetch(checkURL, {method: "POST"})).json()
if (data.ok) {
new Notice(i18n.t("tokenSetting.tokenSettingsComplete"))
clearInterval(intervalId);
accountSetting.accountToken = data.token;
await this.plugin.saveSettings();
}
intervalCount++;
}, 5000)
}));
new Setting(containerEl)
.setName(i18n.t("deleteAccount.name"))
.setDesc(i18n.t("deleteAccount.desc"))
.addButton(button => button
.setButtonText(i18n.t("deleteAccount.buttonText"))
.setWarning()
.onClick(async () => {
if (accountSetting.isSelected){
new Notice(i18n.t("deleteAccount.selectedAccountError"))
return;
}
if (this.plugin.settings.accounts.length === 1){
new Notice(i18n.t("deleteAccount.lastAccountError"))
return;
}
if (!confirm(i18n.t("deleteAccount.confirm"))) {
return;
}
this.plugin.settings.accounts = this.plugin.settings.accounts.filter((item) => item !== accountSetting);
await this.plugin.saveSettings();
this.display();
new Notice(i18n.t("deleteAccount.accountDeleted"))
}));
}
}
}
/**
* - 現在のカーソルにある文章とメディアをMisskeyへ投稿するコマンド(`Misskeyへ現在の行を投稿する`)
* - Misskeyのノートを引用形式で埋め込めるコマンド(`Misskeyのノート(note)を埋め込む`)
*/
export default class MisskeyPlugin extends Plugin {
settings: MisskeyPluginSettings;
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
/**
* noteから画像をアップロードし、その画像のIDを返す
* @param note 投稿内容
* @private
*/
private async uploadFileToMisskey(note: string): Promise<string[]> {
// ![[path]]をすべて検索する
const matches = note.matchAll(/!\[\[(.*?)]]/g);
const imageIDList: string[] = [];
await Promise.all(Array.from(matches).map(async match => {
// data:やhttp(s)://で始まるURLはアップロードしない
// 別にdataはサポートしてもよさそうだけど使ってる人いるかな。リクエスト来るまではとりあえず無効にしとく
const fileName = match[1];
if (/^(data:|https?:\/\/)/.test(fileName)) {
return
}
const selectedAccount = this.getSelectedAccount();
let targetFile = null; // 探しているファイルへの参照を保持するための変数
// もし![[fileName]]がファイルパスそのものをさしていた場合
const file = this.app.vault.getAbstractFileByPath(fileName);
if (file instanceof TFile) {
targetFile = file;
} else {
// NOTE: Avoid iterating all files to find a file by its path
// https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines#Avoid+iterating+all+files+to+find+a+file+by+its+path
// pathからファイルを探すならこの方法は避けるように書いてある。ただ`![[filePath]]`記法があった時に、ファイルはディレクトリの下にあるがfilePathはフルパスでない場合がある。
// そのため、`filePath`がファイルの場所を直接指していない場合、この方法でしかファイルを探せないと自分は理解している。
for (const file of this.app.vault.getFiles()) {
if (file.name === fileName) {
targetFile = file;
break;
}
}
if (targetFile === null) {
new Notice(i18n.t("fileNotFound") + fileName);
return;
}
}
// ファイルの拡張子を取得
const extension = targetFile.extension;
// アップロードが許可されている拡張子かチェック
if (!selectedAccount.uploadAllowedList.includes(extension)) {
new Notice(i18n.t("thisFileTypeIsNotAllowed") + fileName);
return;
}
// ファイルを読み込んで、Misskeyにアップロードする
new Notice(i18n.t("uploadingImage"))
const fileContent = await this.app.vault.readBinary(targetFile);
const domain = selectedAccount.domain;
const token = selectedAccount.accountToken;
if (token === null) {
new Notice("アクセストークンが設定されていません。設定画面から設定してください。");
return;
}
let blob = new Blob([fileContent], {type: "application/octet-stream"});
// 画像をwebpに変換
if (this.settings.isConvertToWebP && extension !== "webp"){
const image = new Image();
image.src = URL.createObjectURL(blob);
await new Promise((resolve) => {
image.onload = resolve;
image.onerror = resolve;
});
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext("2d");
if (context) {
context.drawImage(image, 0, 0, image.width, image.height);
await new Promise((resolve) => {
canvas.toBlob((webPBlob) => {
if (webPBlob) {
blob = webPBlob;
}
resolve(null);
// NOTE:
// 0.7は下のUsageに書いてあったそれっぽい値をとってきただけ。実際にこの値が使われてるのかは知らない。
// https://github.com/misskey-dev/browser-image-resizer?tab=readme-ov-file#in-the-main-thread
}, "image/webp", 0.7);
});
}
}
const formData = new FormData();
formData.append('i', token);
formData.append('file', blob, selectedAccount.isFileNameHidden ? new Date().toISOString() : fileName);
// 画像をアップロード
try{
const data = await (await fetch(`https://${domain}/api/drive/files/create`, {
method: "POST",
body: formData
})).json();
new Notice(data.error ? ("Error:" + data.error.message) : i18n.t("imageUploaded"));
imageIDList.push(data.id);
} catch (error) {
new Notice(i18n.t("imageCannotBeUploaded") + error);
return;
}
}));
return imageIDList;
}
/**
* Misskeyへノートを投稿する。
* @param note 投稿内容
* @param noteVisibility 投稿の公開範囲。ただし"specified"はサポートしない
* @param fileIds 添付ファイルのドライブにあるID。省略可能
* @private
*/
private async postToMisskey(note: string, noteVisibility: "public" | "home" | "followers",
fileIds: string[] = []): Promise<void> {
const domain = this.getSelectedAccount().domain;
const token = this.getSelectedAccount().accountToken;
if (token === null) {
new Notice("アクセストークンが設定されていません。設定画面から設定してください。");
return;
}
// 投稿の前部分と後部分を取得
const prevText = this.getSelectedAccount().prevText;
const postText = this.getSelectedAccount().postText;
let bodyObject: object = {
i: token,
text: prevText.replace("\\n", "\n") + note + postText.replace("\\n", "\n"),
visibility: noteVisibility
};
// fileIdsに空配列を渡すとエラーが出るので、空の場合は省略
if (fileIds.length > 0) {
bodyObject = {
...bodyObject,
fileIds: fileIds
}
}
const urlParams: RequestUrlParam = {
"url": `https://${domain}/api/notes/create`,
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(bodyObject)
};
try {
const data = (await requestUrl(urlParams)).json;
new Notice(data.error ? ("Error:" + data.error.message) : i18n.t("noteSent"));
return data;
} catch (error) {
new Notice(i18n.t("noteCannotBeSend") + error);
}
}
/**
* Misskeyのノートを取得し、引用形式で返す
* @param urls ノートのURL。複数指定可能
* @param isResolveRenote リノートを解決するかどうか
*/
private async quoteFromMisskeyNote(urls: string[] | string, isResolveRenote=true): Promise<string[][]> {
const embedFormat = this.getSelectedAccount().embedFormat;
if (typeof urls === "string") {
urls = [urls];
}
const notes: string[][] = [];
for (const url of urls) {
// URLの形式が正しいかチェック
const regex = /https?:\/\/([a-zA-Z0-9.-]+)\/notes\/([a-zA-Z0-9]+)(?=[^a-zA-Z0-9]|$)/g;
let match;
if ((match = regex.exec(url)) === null) {
new Notice(i18n.t("urlIsNotCorrect") + url);
continue;
}
const misskeyDomain = match[1];
const noteId = match[2];
let bodyObject: object = {
noteId: noteId
};
// URLが現在のプロフィールのドメインと一緒だった場合、アクセストークンを送る。
// これは公開範囲が限定されたノートを取得するため
if (this.getSelectedAccount().domain === misskeyDomain) {
bodyObject = {
...bodyObject,
"i": this.getSelectedAccount().accountToken
};
}
const urlParams: RequestUrlParam = {
"url": `https://${misskeyDomain}/api/notes/show`,
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(bodyObject)
};
const response = await requestUrl(urlParams).catch(
() => {
new Notice(i18n.t("noteCannotBeQuoted") + url);
return;
}
);
if (response === undefined) {
continue;
}
// Misskeyのドメインを網羅することはできないので200が帰ってきたらMisskeyのノートとみなす
if (response.status !== 200) {
new Notice(i18n.t("noteCannotBeQuoted") + url);
continue;
}
const data = await response.json;
// ノートが非公開(ダイレクトかフォロワー)の場合は引用できない。isHiddenがtrueの場合は非公開
if (data.isHidden) {
new Notice(i18n.t("noteIsHidden") + url);
continue;
}
// ノートには本文がなく、画像だけが添付されている場合がある。
let note = data.text ? data.text + "\n" : "";
// 添付ファイルがある場合は対象のURLを取得し、メディアとして埋め込む
for (const file of (data.files || [])) {
if (embedFormat === "markdown") {
note += `\n`
} else if (file.type.startsWith("image")){
note += `<img src="${file.url}" alt="${file.name}">\n`;
} else if (file.type.startsWith("video")) {
note += `<video controls><source src="${file.url}"></video>\n`;
} else if (file.type.startsWith("audio")) {
note += `<audio controls src="${file.url}"></audio>\n`;
} else {
note += `[${file.name}](${file.url})\n`
}
}
// 引用元のノートがある場合、それを引用として表示する
if (isResolveRenote && data.renote?.id){
const renote = (await this.quoteFromMisskeyNote(`https://${misskeyDomain}/notes/${data.renote.id}`, false))
if (renote.length){
note += `
> RN:
>
> ${renote[0][1]}
`;
}
}
// 引用元のユーザー情報を表示するための処理
note += "\n";
// 初期アイコンはidenticon(一度移動する必要がある)なので、それ以外の場合のみアイコンを埋め込む
if (new URL(data.user.avatarUrl).pathname.split('/')[1] !== 'identicon') {
const iconSize = 20;
if (embedFormat === "markdown") {
note += ``;
} else if (embedFormat === "html") {
note += `<img src="${data.user.avatarUrl}" alt="${data.user.username}" width="${iconSize}">`;
}
}
// data.user.nameはバージョンによってはnullの場合がある。少なくともv2023.11ではnull。空文字にしとく
note += ` ${data.user.name || ""}[`+ i18n.t("openOriginalNote", { username: data.user.username}) +`](${url})`;
note = note.split("\n").map((line) => "> " + line).join("\n");
const pattern = /:(\w+):/g;
// 絵文字を走査する。ユーザー名に絵文字が含まれている場合があるためこの位置になる
while ((match = pattern.exec(note)) !== null) {
const urlParams: RequestUrlParam = {
"url": `https://${misskeyDomain}/api/notes/show`,
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(bodyObject)
};
const noteResponse = await requestUrl(urlParams).catch(
() => {
new Notice(i18n.t("noteCannotBeQuoted") + url);
return;
}
);
if (!noteResponse){ continue; }
// uriがあればリモートのノートを見てる状態なので絵文字のホストされているドメインを取得しそっちから絵文字を解決
const emojiHostedDomain = noteResponse.json.uri ? (new URL(noteResponse.json.uri)).hostname : misskeyDomain;
const emojiName = match[1];
const url = `https://${emojiHostedDomain}/api/emoji?name=${emojiName}`;
const response = await requestUrl({
"url": url,
"method": "GET"
}).catch(() => {
new Notice(i18n.t("emojiCannotBeFetched") + emojiName);
return;
});
if (response?.status != 200){
new Notice(i18n.t("emojiCannotBeFetched") + emojiName);
continue;
}
const data = await response.json;
const emojiSize = 20;
if (embedFormat === "markdown") {
note = note.replace(`:${emojiName}:`, ``);
} else if (embedFormat === "html") {
note = note.replace(`:${emojiName}:`, `<img src="${data.url}" alt="${emojiName}" width="${emojiSize}">`);
}
}
note = "\n" + note + "\n";
notes.push([url, note]);
}
// 複数個ノートがある場合、それらは別々の引用として表示されるべき
for (let i = 0; i < notes.length - 1; i++) {
notes[i][1] += "\n";
}
return notes;
}
private isSettingsValid(): boolean {
if (this.getSelectedAccount() === null) {
new Notice(i18n.t("accountNotSelectedError"))
return false;
}
if (this.settings.multiLinePostingSection === "") {
new Notice(i18n.t("multiLinePostingSectionNotSetError"))
return false;
}
const selectedAccount = this.getSelectedAccount();
if (selectedAccount.domain === "") {
new Notice(i18n.t("domainNotSetError"))
return false;
}
if (selectedAccount.accountToken === null) {
new Notice(i18n.t("accountTokenNotSetError"))
return false;
}
if (selectedAccount.embedFormat !== "markdown" && selectedAccount.embedFormat !== "html") {
new Notice(i18n.t("embedFormatValueError"))
return false;
}
if (selectedAccount.visibility !== "public" && selectedAccount.visibility !== "home" && selectedAccount.visibility !== "followers") {
new Notice(i18n.t("visibilityValueError"))
return false;
}
return true;
}
private getSelectedAccount(): Account {
const account = this.settings.accounts.find((account) => account.isSelected);
if (account === undefined) {
// 異常事態。設定画面で選択されているアカウントがない場合はデフォルトのアカウントを返す
return this.settings.accounts[0];
}
return account;
}
async onload() {
await this.loadSettings();
await i18n.init({
// リソースとなる言語と翻訳を設定
resources: {
ja: { translation: jaTranslation },
en: { translation: enTranslation },
},
// デフォルト言語を設定
lng: moment.locale(),
fallbackLng: "en",
});
this.addSettingTab(new MisskeyPluginSettingsTab(this.app, this));
this.addCommand({
id: "post-to-misskey",
name: "Post the current line to Misskey",
editorCallback: async (editor) => {
if (!this.isSettingsValid()) { return; }
new Notice(i18n.t("postingToMisskey"))
const text = editor.getLine(editor.getCursor().line);
const imageIDs = await this.uploadFileToMisskey(text);
// ![[path]]を削除。拡張子による除外などでアップロードされていないファイルがある可能性があるものの
// この記法はObsidianの独自記法なので削除しても問題ないと判断
const pattern = /!\[\[.*?]]/g;
await this.postToMisskey(text.replace(pattern, ''),
this.getSelectedAccount().visibility, imageIDs);
},
});
// 現在の行から初めて、multiLinePostingSectionが現れるまでの行を取得後、それをMisskeyに投稿する
this.addCommand({
id: "post-to-misskey-multi-line",
name: "Post the current section to Misskey",
editorCallback: async (editor) => {
if (!this.isSettingsValid()) { return; }
new Notice(i18n.t("postingToMisskey"))
const cursor = editor.getCursor();
const lineCount = editor.lineCount();
const multiLinePostingSection = this.settings.multiLinePostingSection.replace("\\n", "\n");
const textFromCursorToEnd = editor.getRange(cursor, {line: lineCount, ch: 0});
const match = textFromCursorToEnd.split(multiLinePostingSection);
if (match.length === 1) {
new Notice(i18n.t("noSectionFound"))
return;
}
const text = match[0];
const imageIDs = await this.uploadFileToMisskey(text);
const pattern = /!\[\[.*?]]/g;
await this.postToMisskey(text.replace(pattern, ''),
this.getSelectedAccount().visibility, imageIDs);
},
})
this.addCommand({
id: "embed-misskey-note",
name: "Embed a Misskey note",
editorCallback: async (editor) => {
if (!this.isSettingsValid()) { return; }
new Notice(i18n.t("collectingNotes"))
const text = editor.getLine(editor.getCursor().line);
// URLを見つけるための正規表現パターン
const urlPattern = /(\b(https?):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
// テキストからURLを抽出
const urls = text.match(urlPattern);
if (!urls) { return; }
// URLからMisskeyのノートを取得
const notes = await this.quoteFromMisskeyNote(urls);
for (const [url, note] of notes) {
const replacedText = editor.getLine(editor.getCursor().line).replace(url, note);
editor.setLine(editor.getCursor().line, replacedText);
}
new Notice(i18n.t("noteQuoted"))
},
});
this.addCommand({
id: "embed-all-misskey-note",
name: "Embed all Misskey notes",
editorCallback: async (editor) => {
if (!this.isSettingsValid()) { return; }
new Notice(i18n.t("collectingNotes"))
// URLを見つけるための正規表現パターン
const urlPattern = /(^|\s)((https?):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])(?=\s|$)/ig
for (let i = 0; i < editor.lineCount(); i++) {
let replaceText = editor.getLine(i);
const urls = replaceText.match(urlPattern);
if (!urls) { continue; }
const notes = await this.quoteFromMisskeyNote(urls.map((url) => url.trim()));
for (const [url, note] of notes) {
replaceText = replaceText.replace(url, note);
}
editor.setLine(i, replaceText);
}
new Notice(i18n.t("noteQuoted"))
},
});
}
}