generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmain.ts
1118 lines (1006 loc) · 31.1 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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
App,
Editor,
Notice,
Plugin,
PluginSettingTab,
Setting,
TextComponent,
setIcon,
FileSystemAdapter,
RequestUrlParam,
requestUrl,
TFile,
MarkdownView,
} from "obsidian";
import { HttpRequest, HttpResponse } from "@aws-sdk/protocol-http";
import { HttpHandlerOptions } from "@aws-sdk/types";
import { buildQueryString } from "@aws-sdk/querystring-builder";
import { requestTimeout } from "@smithy/fetch-http-handler/dist-es/request-timeout";
import {
FetchHttpHandler,
FetchHttpHandlerOptions,
} from "@smithy/fetch-http-handler";
import { filesize } from "filesize";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import imageCompression from "browser-image-compression";
// Remember to rename these classes and interfaces!!
interface pasteFunction {
(
this: HTMLElement,
event: ClipboardEvent | DragEvent,
editor: Editor,
): void;
}
interface S3UploaderSettings {
accessKey: string;
secretKey: string;
region: string;
bucket: string;
folder: string;
imageUrlPath: string;
uploadOnDrag: boolean;
localUpload: boolean;
localUploadFolder: string;
useCustomEndpoint: boolean;
customEndpoint: string;
forcePathStyle: boolean;
useCustomImageUrl: boolean;
customImageUrl: string;
uploadVideo: boolean;
uploadAudio: boolean;
uploadPdf: boolean;
bypassCors: boolean;
queryStringValue: string;
queryStringKey: string;
enableImageCompression: boolean;
maxImageCompressionSize: number;
imageCompressionQuality: number;
maxImageWidthOrHeight: number;
}
const DEFAULT_SETTINGS: S3UploaderSettings = {
accessKey: "",
secretKey: "",
region: "",
bucket: "",
folder: "",
imageUrlPath: "",
uploadOnDrag: true,
localUpload: false,
localUploadFolder: "",
useCustomEndpoint: false,
customEndpoint: "",
forcePathStyle: false,
useCustomImageUrl: false,
customImageUrl: "",
uploadVideo: false,
uploadAudio: false,
uploadPdf: false,
bypassCors: false,
queryStringValue: "",
queryStringKey: "",
enableImageCompression: false,
maxImageCompressionSize: 1,
imageCompressionQuality: 0.7,
maxImageWidthOrHeight: 4096,
};
export default class S3UploaderPlugin extends Plugin {
settings: S3UploaderSettings;
s3: S3Client;
pasteFunction: pasteFunction;
private async replaceText(
editor: Editor,
target: string,
replacement: string,
): Promise<void> {
const content = editor.getValue();
const position = content.indexOf(target);
console.log("replaceText called:", { target, replacement });
if (position !== -1) {
console.log("Target found at position:", position);
// Check if we're in a table by looking for pipe characters around the target
const surroundingBefore = content.substring(
Math.max(0, position - 20),
position,
);
const surroundingAfter = content.substring(
position + target.length,
Math.min(content.length, position + target.length + 20),
);
console.log("Surrounding text:", {
before: surroundingBefore,
after: surroundingAfter,
});
const isInTable =
surroundingBefore.includes("|") &&
surroundingAfter.includes("|");
console.log("Is in table:", isInTable);
// For tables, we need to be more careful with the replacement
if (isInTable) {
// Get the line containing the target
const from = editor.offsetToPos(position);
const to = editor.offsetToPos(position + target.length);
console.log("Table replacement positions:", { from, to });
try {
// Use a more direct approach for tables
editor.transaction({
changes: [
{
from,
to,
text: replacement,
},
],
});
console.log("Table transaction completed");
// Force a refresh of the editor to ensure the table renders correctly
setTimeout(() => {
try {
editor.refresh();
console.log("Editor refreshed");
} catch (e) {
console.error("Error refreshing editor:", e);
}
}, 100); // Increased timeout for better reliability
} catch (e) {
console.error("Error during table transaction:", e);
}
} else {
// Normal replacement for non-table content
const from = editor.offsetToPos(position);
const to = editor.offsetToPos(position + target.length);
console.log("Normal replacement positions:", { from, to });
try {
editor.transaction({
changes: [
{
from,
to,
text: replacement,
},
],
});
console.log("Normal transaction completed");
} catch (e) {
console.error("Error during normal transaction:", e);
}
}
} else {
console.log("Target not found in content");
}
}
async uploadFile(file: File, key: string): Promise<string> {
const buf = await file.arrayBuffer();
await this.s3.send(
new PutObjectCommand({
Bucket: this.settings.bucket,
Key: key,
Body: new Uint8Array(buf),
ContentType: file.type,
}),
);
let urlString = this.settings.imageUrlPath + key;
if (this.settings.queryStringKey && this.settings.queryStringValue) {
const urlObject = new URL(urlString);
// The searchParams property provides methods to manipulate query parameters
urlObject.searchParams.append(
this.settings.queryStringKey,
this.settings.queryStringValue,
);
urlString = urlObject.toString();
}
return urlString;
}
async compressImage(file: File): Promise<ArrayBuffer> {
const compressedFile = await imageCompression(file, {
useWebWorker: false,
maxWidthOrHeight: this.settings.maxImageWidthOrHeight,
maxSizeMB: this.settings.maxImageCompressionSize,
initialQuality: this.settings.imageCompressionQuality,
});
const fileBuffer = await compressedFile.arrayBuffer();
const originalSize = filesize(file.size); // Input file size
const newSize = filesize(compressedFile.size);
new Notice(`Image compressed from ${originalSize} to ${newSize}`);
return fileBuffer;
}
async pasteHandler(
ev: ClipboardEvent | DragEvent | Event | null,
editor: Editor,
directFile?: File,
): Promise<void> {
if (ev?.defaultPrevented) {
return;
}
const noteFile = this.app.workspace.getActiveFile();
if (!noteFile || !noteFile.name) return;
const fm = this.app.metadataCache.getFileCache(noteFile)?.frontmatter;
const localUpload = fm?.localUpload ?? this.settings.localUpload;
const uploadVideo = fm?.uploadVideo ?? this.settings.uploadVideo;
const uploadAudio = fm?.uploadAudio ?? this.settings.uploadAudio;
const uploadPdf = fm?.uploadPdf ?? this.settings.uploadPdf;
let files: File[] = [];
if (directFile) {
files = [directFile];
} else if (ev) {
switch (ev.type) {
case "paste":
files = Array.from(
(ev as ClipboardEvent).clipboardData?.files || [],
);
break;
case "drop":
if (
!this.settings.uploadOnDrag &&
!(fm && fm.uploadOnDrag)
) {
return;
}
files = Array.from(
(ev as DragEvent).dataTransfer?.files || [],
);
break;
case "input":
files = Array.from(
(ev.target as HTMLInputElement).files || [],
);
break;
}
}
// Only prevent default if we have files to handle
if (files.length > 0) {
if (ev) ev.preventDefault();
new Notice("Uploading files...");
// Remember cursor position before any changes
const cursorPos = editor.getCursor();
const uploads = files.map(async (file) => {
let thisType = "";
if (file.type.match(/video.*/) && uploadVideo) {
thisType = "video";
} else if (file.type.match(/audio.*/) && uploadAudio) {
thisType = "audio";
} else if (file.type.match(/application\/pdf/) && uploadPdf) {
thisType = "pdf";
} else if (file.type.match(/image.*/)) {
thisType = "image";
} else if (
file.type.match(/presentation.*/) ||
file.type.match(/powerpoint.*/)
) {
thisType = "ppt";
}
if (!thisType) {
return;
}
// Process the file
let buf = await file.arrayBuffer();
const digest = await generateFileHash(new Uint8Array(buf));
const newFileName = `${digest}.${file.name.split(".").pop()}`;
// Determine folder
let folder = "";
if (localUpload) {
folder =
fm?.uploadFolder ?? this.settings.localUploadFolder;
} else {
folder = fm?.uploadFolder ?? this.settings.folder;
}
const currentDate = new Date();
folder = folder
.replace("${year}", currentDate.getFullYear().toString())
.replace(
"${month}",
String(currentDate.getMonth() + 1).padStart(2, "0"),
)
.replace(
"${day}",
String(currentDate.getDate()).padStart(2, "0"),
);
const key = folder ? `${folder}/${newFileName}` : newFileName;
try {
// Upload the file
let url;
// Image compression
if (
thisType === "image" &&
this.settings.enableImageCompression
) {
buf = await this.compressImage(file);
file = new File([buf], newFileName, {
type: file.type,
});
}
if (!localUpload) {
url = await this.uploadFile(file, key);
} else {
await this.app.vault.adapter.writeBinary(
key,
new Uint8Array(buf),
);
url =
this.app.vault.adapter instanceof FileSystemAdapter
? this.app.vault.adapter.getFilePath(key)
: key;
}
// Generate the markdown
return wrapFileDependingOnType(url, thisType, "");
} catch (error) {
console.error(error);
return `Error uploading file: ${error.message}`;
}
});
try {
// Wait for all uploads to complete
const results = await Promise.all(uploads);
// Filter out undefined results (from unsupported file types)
const validResults = results.filter(
(result) => result !== undefined,
);
// Insert all results at once at the cursor position
if (validResults.length > 0) {
// Use a safer approach to insert text
const text = validResults.join("\n");
// Use transaction API instead of replaceSelection
editor.transaction({
changes: [
{
from: cursorPos,
text: text,
},
],
});
new Notice("All files uploaded successfully");
}
} catch (error) {
console.error("Error during upload or insertion:", error);
new Notice(`Error: ${error.message}`);
}
}
}
async onload() {
await this.loadSettings();
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new S3UploaderSettingTab(this.app, this));
const apiEndpoint = this.settings.useCustomEndpoint
? this.settings.customEndpoint
: `https://s3.${this.settings.region}.amazonaws.com/`;
this.settings.imageUrlPath = this.settings.useCustomImageUrl
? this.settings.customImageUrl
: this.settings.forcePathStyle
? apiEndpoint + this.settings.bucket + "/"
: apiEndpoint.replace("://", `://${this.settings.bucket}.`);
if (this.settings.bypassCors) {
this.s3 = new S3Client({
region: this.settings.region,
credentials: {
// clientConfig: { region: this.settings.region },
accessKeyId: this.settings.accessKey,
secretAccessKey: this.settings.secretKey,
},
endpoint: apiEndpoint,
forcePathStyle: this.settings.forcePathStyle,
requestHandler: new ObsHttpHandler({ keepAlive: false }),
});
} else {
this.s3 = new S3Client({
region: this.settings.region,
credentials: {
// clientConfig: { region: this.settings.region },
accessKeyId: this.settings.accessKey,
secretAccessKey: this.settings.secretKey,
},
endpoint: apiEndpoint,
forcePathStyle: this.settings.forcePathStyle,
requestHandler: new ObsHttpHandler({ keepAlive: false }),
});
}
this.addCommand({
id: "upload-image",
name: "Upload image",
icon: "image-plus",
mobileOnly: false,
editorCallback: (editor) => {
const input = document.createElement("input");
input.type = "file";
input.oninput = (event) => {
if (!event.target) return;
this.pasteHandler(event, editor);
};
input.click();
input.remove(); // delete element
},
});
this.pasteFunction = (
event: ClipboardEvent | DragEvent,
editor: Editor,
) => {
this.pasteHandler(event, editor);
};
this.registerEvent(
this.app.workspace.on("editor-paste", this.pasteFunction),
);
this.registerEvent(
this.app.workspace.on("editor-drop", this.pasteFunction),
);
// Add mobile-specific event monitoring
this.registerEvent(
this.app.vault.on("create", async (file) => {
if (!(file instanceof TFile)) return;
if (!file.path.match(/\.(jpg|jpeg|png|gif|webp)$/i)) return;
const activeView =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeView) return;
try {
const fileContent = await this.app.vault.readBinary(file);
const newFile = new File([fileContent], file.name, {
type: `image/${file.extension}`,
});
// Do the upload
await this.pasteHandler(null, activeView.editor, newFile);
// Small delay to ensure editor content is updated
await new Promise((resolve) => setTimeout(resolve, 50));
// Now remove the original link if it exists
const content = activeView.editor.getValue();
const obsidianLink = `![[${file.name}]]`; // Exact pattern we want to find
const position = content.indexOf(obsidianLink);
if (position !== -1) {
const from = activeView.editor.offsetToPos(position);
const to = activeView.editor.offsetToPos(
position + obsidianLink.length,
);
activeView.editor.replaceRange("", from, to);
} else {
new Notice(`Failed to find: ${obsidianLink}`);
}
await this.app.vault.delete(file);
} catch (error) {
new Notice(`Error processing file: ${error.message}`);
}
}),
);
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData(),
);
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class S3UploaderSettingTab extends PluginSettingTab {
plugin: S3UploaderPlugin;
// Add properties to store compression setting elements
private compressionSizeSettings: Setting;
private compressionQualitySettings: Setting;
private compressionDimensionSettings: Setting;
constructor(app: App, plugin: S3UploaderPlugin) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Toggle visibility of compression settings
* @param show Whether to show the compression settings
*/
private toggleCompressionSettings(show: boolean): void {
if (
this.compressionSizeSettings &&
this.compressionQualitySettings &&
this.compressionDimensionSettings
) {
const displayStyle = show ? "" : "none";
this.compressionSizeSettings.settingEl.style.display = displayStyle;
this.compressionQualitySettings.settingEl.style.display =
displayStyle;
this.compressionDimensionSettings.settingEl.style.display =
displayStyle;
}
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Settings for S3 Image Uploader" });
containerEl.createEl("br");
const coffeeDiv = containerEl.createDiv("coffee");
const coffeeLink = coffeeDiv.createEl("a", {
href: "https://www.buymeacoffee.com/jvsteiner",
});
const coffeeImg = coffeeLink.createEl("img", {
attr: {
src: "https://cdn.buymeacoffee.com/buttons/v2/default-blue.png",
},
});
coffeeImg.height = 45;
containerEl.createEl("br");
new Setting(containerEl)
.setName("AWS Access Key ID")
.setDesc("AWS access key ID for a user with S3 access.")
.addText((text) => {
wrapTextWithPasswordHide(text);
text.setPlaceholder("access key")
.setValue(this.plugin.settings.accessKey)
.onChange(async (value) => {
this.plugin.settings.accessKey = value.trim();
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("AWS Secret Key")
.setDesc("AWS secret key for that user.")
.addText((text) => {
wrapTextWithPasswordHide(text);
text.setPlaceholder("secret key")
.setValue(this.plugin.settings.secretKey)
.onChange(async (value) => {
this.plugin.settings.secretKey = value.trim();
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Region")
.setDesc("AWS region of the S3 bucket.")
.addText((text) =>
text
.setPlaceholder("aws region")
.setValue(this.plugin.settings.region)
.onChange(async (value) => {
this.plugin.settings.region = value.trim();
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("S3 Bucket")
.setDesc("S3 bucket name.")
.addText((text) =>
text
.setPlaceholder("bucket name")
.setValue(this.plugin.settings.bucket)
.onChange(async (value) => {
this.plugin.settings.bucket = value.trim();
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Bucket folder")
.setDesc(
"Optional folder in s3 bucket. Support the use of ${year}, ${month}, and ${day} variables.",
)
.addText((text) =>
text
.setPlaceholder("folder")
.setValue(this.plugin.settings.folder)
.onChange(async (value) => {
this.plugin.settings.folder = value.trim();
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Upload on drag")
.setDesc(
"Upload drag and drop images as well as pasted images. To override this setting on a per-document basis, you can add `uploadOnDrag: true` to YAML frontmatter of the note.",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.uploadOnDrag)
.onChange(async (value) => {
this.plugin.settings.uploadOnDrag = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Upload video files")
.setDesc(
"Upload videos. To override this setting on a per-document basis, you can add `uploadVideo: true` to YAML frontmatter of the note.",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.uploadVideo)
.onChange(async (value) => {
this.plugin.settings.uploadVideo = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Upload audio files")
.setDesc(
"Upload audio files. To override this setting on a per-document basis, you can add `uploadAudio: true` to YAML frontmatter of the note.",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.uploadAudio)
.onChange(async (value) => {
this.plugin.settings.uploadAudio = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Upload pdf files")
.setDesc(
"Upload and embed PDF files. To override this setting on a per-document basis, you can add `uploadPdf: true` to YAML frontmatter of the note. Local uploads are not supported for PDF files.",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.uploadPdf)
.onChange(async (value) => {
this.plugin.settings.uploadPdf = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Copy to local folder")
.setDesc(
"Copy images to local folder instead of s3. To override this setting on a per-document basis, you can add `localUpload: true` to YAML frontmatter of the note. This will copy the images to a folder in your local file system, instead of s3.",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.localUpload)
.onChange(async (value) => {
this.plugin.settings.localUpload = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Local folder")
.setDesc(
'Local folder to save images, instead of s3. To override this setting on a per-document basis, you can add `uploadFolder: "myFolder"` to YAML frontmatter of the note. This affects only local uploads.',
)
.addText((text) =>
text
.setPlaceholder("folder")
.setValue(this.plugin.settings.localUploadFolder)
.onChange(async (value) => {
this.plugin.settings.localUploadFolder = value.trim();
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Use custom endpoint")
.setDesc("Use the custom api endpoint below.")
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.useCustomEndpoint)
.onChange(async (value) => {
this.plugin.settings.useCustomEndpoint = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Custom S3 Endpoint")
.setDesc(
"Optionally set a custom endpoint for any S3 compatible storage provider.",
)
.addText((text) =>
text
.setPlaceholder("https://s3.myhost.com/")
.setValue(this.plugin.settings.customEndpoint)
.onChange(async (value) => {
value = value.match(/^https?:\/\//) // Force to start http(s)://
? value
: "https://" + value;
value = value.replace(/([^/])$/, "$1/"); // Force to end with slash
this.plugin.settings.customEndpoint = value.trim();
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("S3 Path Style URLs")
.setDesc(
"Advanced option to force using (legacy) path-style s3 URLs (s3.myhost.com/bucket) instead of the modern AWS standard host-style (bucket.s3.myhost.com).",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.forcePathStyle)
.onChange(async (value) => {
this.plugin.settings.forcePathStyle = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Use custom image URL")
.setDesc("Use the custom image URL below.")
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.useCustomImageUrl)
.onChange(async (value) => {
this.plugin.settings.useCustomImageUrl = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Custom Image URL")
.setDesc(
"Advanced option to force inserting custom image URLs. This option is helpful if you are using CDN.",
)
.addText((text) =>
text
.setValue(this.plugin.settings.customImageUrl)
.onChange(async (value) => {
value = value.match(/^https?:\/\//) // Force to start http(s)://
? value
: "https://" + value;
value = value.replace(/([^/])$/, "$1/"); // Force to end with slash
this.plugin.settings.customImageUrl = value.trim();
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Bypass local CORS check")
.setDesc(
"Bypass local CORS preflight checks - it might work on later versions of Obsidian.",
)
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.bypassCors)
.onChange(async (value) => {
this.plugin.settings.bypassCors = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Query String Key")
.setDesc("Appended to the end of the URL. Optional")
.addText((text) =>
text
.setPlaceholder("Empty means no query string key")
.setValue(this.plugin.settings.queryStringKey)
.onChange(async (value) => {
this.plugin.settings.queryStringKey = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Query String Value")
.setDesc("Appended to the end of the URL. Optional")
.addText((text) =>
text
.setPlaceholder("Empty means no query string value")
.setValue(this.plugin.settings.queryStringValue)
.onChange(async (value) => {
this.plugin.settings.queryStringValue = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Enable Image Compression")
.setDesc("This will reduce the size of images before uploading.")
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.enableImageCompression)
.onChange(async (value) => {
this.plugin.settings.enableImageCompression = value;
await this.plugin.saveSettings();
// Show or hide compression settings based on toggle value
this.toggleCompressionSettings(value);
});
});
// Always create the compression settings, but control visibility
this.compressionSizeSettings = new Setting(containerEl)
.setName("Max Image Size")
.setDesc(
"Maximum size of the image after compression in MB. Default is 1MB.",
)
.addText((text) =>
text
.setPlaceholder("1")
.setValue(
this.plugin.settings.maxImageCompressionSize.toString(),
)
.onChange(async (value) => {
// It must be a number, it must be greater than 0
const newValue = parseFloat(value);
if (isNaN(newValue) || newValue <= 0) {
new Notice(
"Max Image Compression Size must be a number greater than 0",
);
return;
}
this.plugin.settings.maxImageCompressionSize = newValue;
await this.plugin.saveSettings();
}),
);
this.compressionQualitySettings = new Setting(containerEl)
.setName("Image Compression Quality")
.setDesc(
"Maximum quality of the image after compression. Default is 0.7.",
)
.addSlider((slider) => {
slider.setDynamicTooltip();
slider.setLimits(0.0, 1.0, 0.05);
slider.setValue(this.plugin.settings.imageCompressionQuality);
slider.onChange(async (value) => {
this.plugin.settings.imageCompressionQuality = value;
await this.plugin.saveSettings();
});
});
this.compressionDimensionSettings = new Setting(containerEl)
.setName("Max Image Width or Height")
.setDesc(
"Maximum width or height of the image after compression. Default is 4096px.",
)
.addText((text) =>
text
.setPlaceholder("4096")
.setValue(
this.plugin.settings.maxImageWidthOrHeight.toString(),
)
.onChange(async (value) => {
const parsedValue = parseInt(value);
if (isNaN(parsedValue) || parsedValue <= 0) {
new Notice(
"Max Image Width or Height must be a number greater than 0",
);
return;
}
this.plugin.settings.maxImageWidthOrHeight =
parsedValue;
await this.plugin.saveSettings();
}),
);
// Set initial visibility based on current settings
this.toggleCompressionSettings(
this.plugin.settings.enableImageCompression,
);
}
}
const wrapTextWithPasswordHide = (text: TextComponent) => {
const hider = text.inputEl.insertAdjacentElement(
"beforebegin",
createSpan(),
);
if (!hider) {
return;
}
setIcon(hider as HTMLElement, "eye-off");
hider.addEventListener("click", () => {
const isText = text.inputEl.getAttribute("type") === "text";
if (isText) {
setIcon(hider as HTMLElement, "eye-off");
text.inputEl.setAttribute("type", "password");
} else {
setIcon(hider as HTMLElement, "eye");
text.inputEl.setAttribute("type", "text");
}
text.inputEl.focus();
});
text.inputEl.setAttribute("type", "password");
return text;
};
const wrapFileDependingOnType = (
location: string,
type: string,
localBase: string,
) => {
const srcPrefix = localBase ? "file://" + localBase + "/" : "";
if (type === "image") {
return ``;
} else if (type === "video") {
return `<video src="${srcPrefix}${location}" controls />`;
} else if (type === "audio") {
return `<audio src="${srcPrefix}${location}" controls />`;
} else if (type === "pdf") {
if (localBase) {
throw new Error("PDFs cannot be embedded in local mode");
}
return `<iframe frameborder=0 border=0 width=100% height=800
src="https://docs.google.com/viewer?embedded=true&url=${location}?raw=true">
</iframe>`;
} else if (type === "ppt") {
return `<iframe
src='https://view.officeapps.live.com/op/embed.aspx?src=${location}'
width='100%' height='600px' frameborder='0'>
</iframe>`;
} else {
throw new Error("Unknown file type");
}
};
////////////////////////////////////////////////////////////////////////////////
// special handler using Obsidian requestUrl