forked from patriceac/Easy-Diffusion-Plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin-manager.plugin.js
1208 lines (1069 loc) · 46.5 KB
/
plugin-manager.plugin.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
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
(function () {
/*
Plugin Manager
by Patrice
A simple plugin manager with a search box, that installs and auto updates plugins from GitHub.
Devs, please feel free to add your plugins to the catalog at: https://github.com/patriceac/Easy-Diffusion-Plugins
Mandatory fields to add a plugin to the plugin catalog are: id, name, url. All other fields are optional.
*/
"use strict"
const PLUGIN_CATALOG = 'https://raw.githubusercontent.com/patriceac/Easy-Diffusion-Plugins/main/plugins.json'
const PLUGIN_CATALOG_GITHUB = 'https://github.com/patriceac/Easy-Diffusion-Plugins/blob/main/plugins.json'
if (document.querySelector("#plugin-manager .parameters-table") !== null) {
console.log('Plugin Manager already running, do not reload.')
return
}
var styleSheet = document.createElement("style")
styleSheet.textContent = `
.plugins-table {
display: flex;
flex-direction: column;
gap: 1px;
}
.plugins-table > div {
background: var(--background-color2);
display: flex;
padding: 0px 4px;
}
.plugins-table > div > div {
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.plugins-table small {
color: rgb(153, 153, 153);
}
.plugins-table > div > div:nth-child(1) {
font-size: 20px;
width: 45px;
}
.plugins-table > div > div:nth-child(2) {
flex: 1;
flex-direction: column;
text-align: left;
justify-content: center;
align-items: start;
gap: 4px;
}
.plugins-table > div > div:nth-child(3) {
text-align: right;
}
.plugins-table > div:first-child {
border-radius: 12px 12px 0px 0px;
}
.plugins-table > div:last-child {
border-radius: 0px 0px 12px 12px;
}
.plugin-manager-intro {
margin: 0 0 16px 0;
}
#plugin-filter {
box-sizing: border-box;
width: 100%;
margin: 4px 0 6px 0;
padding: 10px;
}
#refresh-plugins {
box-sizing: border-box;
width: 100%;
padding: 0px;
}
#refresh-plugins a {
cursor: pointer;
}
#refresh-plugins a:active {
transition-duration: 0.1s;
position: relative;
top: 1px;
left: 1px;
}
.plugin-installed-locally {
font-style: italic;
font-size: small;
}
.plugin-source {
font-size: x-small;
}
.plugin-warning {
color: orange;
font-size: smaller;
}
.plugin-warning.hide {
display: none;
}
.plugin-warning ul {
list-style: square;
margin: 0 0 8px 16px;
padding: 0;
}
.plugin-warning li {
margin-left: 8px;
padding: 0;
}
/* TOASTS */
.plugin-toast {
position: fixed;
bottom: 10px;
right: -300px;
width: 300px;
background-color: #333;
color: #fff;
padding: 10px 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
z-index: 9999;
animation: slideInRight 0.5s ease forwards;
transition: bottom 0.5s ease; // Add a transition to smoothly reposition the toasts
}
.plugin-toast-error {
color: red;
}
@keyframes slideInRight {
from {
right: -300px;
}
to {
right: 10px;
}
}
.plugin-toast.hide {
animation: slideOutRight 0.5s ease forwards;
}
@keyframes slideOutRight {
from {
right: 10px;
}
to {
right: -300px;
}
}
@keyframes slideDown {
from {
bottom: 10px;
}
to {
bottom: 0;
}
}
/* MODAL DIALOG */
#pluginDialog-input-dialog {
position: fixed;
z-index: 1000;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
.pluginDialog-dialog-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(32, 33, 36, 50%);
}
.pluginDialog-dialog-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 80%;
max-width: 600px;
background: var(--background-color2);
border: solid 1px var(--background-color3);
border-radius: 6px;
box-shadow: 0px 0px 30px black;
}
.pluginDialog-dialog-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
}
.pluginDialog-dialog-header h2 {
margin: 0;
}
.pluginDialog-dialog-close-button {
font-size: 24px;
font-weight: bold;
line-height: 1;
border: none;
background-color: transparent;
cursor: pointer;
}
.pluginDialog-dialog-close-button:hover {
color: #555;
}
.pluginDialog-dialog-content {
padding: 0 16px 0 16px;
}
.pluginDialog-dialog-content textarea {
width: 100%;
height: 300px;
border-radius: var(--input-border-radius);
padding: 4px;
accent-color: var(--accent-color);
background: var(--input-background-color);
border: var(--input-border-size) solid var(--input-border-color);
color: var(--input-text-color);
font-size: 9pt;
resize: none;
}
.pluginDialog-dialog-buttons {
display: flex;
justify-content: flex-end;
padding: 16px;
}
.pluginDialog-dialog-buttons button {
margin-left: 8px;
padding: 8px 16px;
font-size: 16px;
border-radius: 4px;
/*background: var(--accent-color);*/
/*border: var(--primary-button-border);*/
/*color: rgb(255, 221, 255);*/
background-color: #3071a9;
border: none;
cursor: pointer;
}
.pluginDialog-dialog-buttons button:hover {
/*background: hsl(var(--accent-hue), 100%, 50%);*/
background-color: #428bca;
}
`
document.head.appendChild(styleSheet)
/* plugin tab */
//document.querySelector('.tab-container #tab-news')?.insertAdjacentHTML('beforebegin', `
document.querySelector('.tab-container')?.insertAdjacentHTML('beforeend', `
<span id="tab-plugin" class="tab">
<span><i class="fa fa-puzzle-piece icon"></i> Plugins</span>
</span>
`)
document.querySelector('#tab-content-wrapper')?.insertAdjacentHTML('beforeend', `
<div id="tab-content-plugin" class="tab-content">
<div id="plugin" class="tab-content-inner">
Loading...
</div>
</div>
`)
const tabPlugin = document.querySelector('#tab-plugin')
if (tabPlugin) {
linkTabContents(tabPlugin)
}
const plugin = document.querySelector('#plugin')
plugin.innerHTML = `
<div id="plugin-manager" class="tab-content-inner">
<h1>Plugin Manager</h1>
<div class="plugin-manager-intro">Changes take effect after reloading the page<br /></div>
<div class="parameters-table"></div>
</div>`
const pluginsTable = document.querySelector("#plugin-manager .parameters-table")
/* search box */
function filterPlugins() {
let search = pluginFilter.value.toLowerCase();
let searchTerms = search.split(' ');
let labels = pluginsTable.querySelectorAll("label.plugin-name");
for (let i = 0; i < labels.length; i++) {
let label = labels[i].innerText.toLowerCase();
let match = true;
for (let j = 0; j < searchTerms.length; j++) {
let term = searchTerms[j].trim();
if (term && label.indexOf(term) === -1) {
match = false;
break;
}
}
if (match) {
labels[i].closest('.plugin-container').style.display = "flex";
} else {
labels[i].closest('.plugin-container').style.display = "none";
}
}
}
// Call debounce function on filterImageModifierList function with 200ms wait time. Thanks JeLuf!
const debouncedFilterPlugins = debounce(filterPlugins, 200);
// add the searchbox
pluginsTable.insertAdjacentHTML('beforebegin', `<input type="text" id="plugin-filter" placeholder="Search for..." autocomplete="off"/>`)
const pluginFilter = document.getElementById("plugin-filter") // search box
// Add the debounced function to the keyup event listener
pluginFilter.addEventListener('keyup', debouncedFilterPlugins);
// select the text on focus
pluginFilter.addEventListener('focus', function(event) {
pluginFilter.select()
});
// empty the searchbox on escape
pluginFilter.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
pluginFilter.value = '';
filterPlugins();
}
});
// focus on the search box upon tab selection
document.addEventListener("tabClick", (e) => {
if (e.detail.name == 'plugin') {
pluginFilter.focus()
}
})
// refresh link
pluginsTable.insertAdjacentHTML('afterend', `<p id="refresh-plugins"><small><a id="refresh-plugins-link">Refresh plugins</a></small></p>
<p><small>(Plugin developers, add your plugins to <a href='${PLUGIN_CATALOG_GITHUB}' target='_blank'>plugins.json</a>)</small></p>`)
const refreshPlugins = document.getElementById("refresh-plugins")
refreshPlugins.addEventListener("click", async function(event) {
event.preventDefault()
await initPlugins(true)
})
function showToast(message, duration = 5000, error = false) {
if (duration === null || duration === undefined) {
duration = 5000
}
const toast = document.createElement("div");
toast.classList.add("plugin-toast");
if (error === true) {
toast.classList.add("plugin-toast-error");
}
toast.innerHTML = message;
document.body.appendChild(toast);
// Set the position of the toast on the screen
const toastCount = document.querySelectorAll(".plugin-toast").length;
const toastHeight = toast.offsetHeight;
const previousToastsHeight = Array.from(document.querySelectorAll(".plugin-toast"))
.slice(0, -1) // exclude current toast
.reduce((totalHeight, toast) => totalHeight + toast.offsetHeight + 10, 0); // add 10 pixels for spacing
toast.style.bottom = `${10 + previousToastsHeight}px`;
toast.style.right = "10px";
// Delay the removal of the toast until animation has completed
let removeTimeoutId = null;
const removeToast = () => {
toast.classList.add("hide");
removeTimeoutId = setTimeout(() => {
toast.remove();
// Adjust the position of remaining toasts
const remainingToasts = document.querySelectorAll(".plugin-toast");
const removedToastBottom = toast.getBoundingClientRect().bottom;
remainingToasts.forEach((toast) => {
if (toast.getBoundingClientRect().bottom < removedToastBottom) {
toast.classList.add("slide-down");
}
});
// Wait for the slide-down animation to complete
setTimeout(() => {
// Remove the slide-down class after the animation has completed
const slidingToasts = document.querySelectorAll(".slide-down");
slidingToasts.forEach((toast) => {
toast.classList.remove("slide-down");
});
// Adjust the position of remaining toasts again, in case there are multiple toasts being removed at once
const remainingToastsDown = document.querySelectorAll(".plugin-toast");
let heightSoFar = 0;
remainingToastsDown.forEach((toast) => {
toast.style.bottom = `${10 + heightSoFar}px`;
heightSoFar += toast.offsetHeight + 10; // add 10 pixels for spacing
});
}, 0); // The duration of the slide-down animation (in milliseconds)
}, 500);
};
// Remove the toast after specified duration
setTimeout(() => {
removeToast();
}, duration);
}
function matchPluginFileNames(fileName1, fileName2) {
const regex = /^(.+?)(?:-\d+(\.\d+)*)?\.plugin\.js$/;
const match1 = fileName1.match(regex);
const match2 = fileName2.match(regex);
if (match1 && match2 && match1[1] === match2[1]) {
return true; // the two file names match
} else {
return false; // the two file names do not match
}
}
function extractFilename(filepath) {
// Normalize the path separators to forward slashes and make the file names lowercase
const normalizedFilePath = filepath.replace(/\\/g, "/").toLowerCase();
// Strip off the path from the file name
const fileName = normalizedFilePath.substring(normalizedFilePath.lastIndexOf("/") + 1);
return fileName
}
function checkFileNameInArray(paths, filePath) {
// Strip off the path from the file name
const fileName = extractFilename(filePath);
// Check if the file name exists in the array of paths
return paths.some(path => {
// Strip off the path from the file name
const baseName = extractFilename(path);
// Check if the file names match and return the result as a boolean
return matchPluginFileNames(fileName, baseName);
});
}
function isGitHub(url) {
return url.startsWith("https://raw.githubusercontent.com/") === true
}
/* fill in the plugins table */
function getIncompatiblePlugins(pluginId) {
const enabledPlugins = plugins.filter(plugin => plugin.enabled && plugin.id !== pluginId);
const incompatiblePlugins = enabledPlugins.filter(plugin => plugin.compatIssueIds?.includes(pluginId));
const pluginNames = incompatiblePlugins.map(plugin => plugin.name);
if (pluginNames.length === 0) {
return null;
}
const pluginNamesList = pluginNames.map(name => `<li>${name}</li>`).join('');
return `<ul>${pluginNamesList}</ul>`;
}
async function initPluginTable(plugins) {
pluginsTable.innerHTML = ''
plugins.sort((a, b) => a.name.localeCompare(b.name, undefined, {sensitivity: 'base'}))
plugins.forEach(plugin => {
const name = plugin.name
const author = plugin.author ? ', by ' + plugin.author : ''
const version = plugin.version ? ' (version: ' + plugin.version + ')' : ''
const warning = getIncompatiblePlugins(plugin.id) ? `<span class="plugin-warning${plugin.enabled ? '' : ' hide'}">This plugin might conflict with:${getIncompatiblePlugins(plugin.id)}</span>` : ''
const note = plugin.description ? `<small>${plugin.description.replaceAll('\n', '<br>')}</small>` : `<small>No description</small>`;
const icon = plugin.icon ? `<i class="fa ${plugin.icon}"></i>` : '<i class="fa fa-puzzle-piece"></i>';
const newRow = document.createElement('div')
const localPluginFound = checkFileNameInArray(localPlugins, plugin.url)
newRow.innerHTML = `
<div>${icon}</div>
<div><label class="plugin-name">${name}${author}${version}</label>${warning}${note}<span class='plugin-source'>Source: <a href="${plugin.url}" target="_blank">${extractFilename(plugin.url)}</a><span></div>
<div>
${localPluginFound ? "<span class='plugin-installed-locally'>Installed locally</span>" :
(plugin.localInstallOnly ? '<span class="plugin-installed-locally">Download and<br />install manually</span>' :
(isGitHub(plugin.url) ?
'<input id="plugin-' + plugin.id + '" name="plugin-' + plugin.id + '" type="checkbox">' :
'<button id="plugin-' + plugin.id + '-install" class="tertiaryButton"></button>'
)
)
}
</div>`;
newRow.classList.add('plugin-container')
//console.log(plugin.id, plugin.localInstallOnly)
pluginsTable.appendChild(newRow)
const pluginManualInstall = pluginsTable.querySelector('#plugin-' + plugin.id + '-install')
updateManualInstallButtonCaption()
// checkbox event handler
const pluginToggle = pluginsTable.querySelector('#plugin-' + plugin.id)
if (pluginToggle !== null) {
pluginToggle.checked = plugin.enabled // set initial state of checkbox
pluginToggle.addEventListener('change', async () => {
const container = pluginToggle.closest(".plugin-container");
const warningElement = container.querySelector(".plugin-warning");
// if the plugin got enabled, download the plugin's code
plugin.enabled = pluginToggle.checked
if (plugin.enabled) {
const pluginSource = await getDocument(plugin.url);
if (pluginSource !== null) {
// Store the current scroll position before navigating away
const currentPosition = window.pageYOffset;
initPluginTable(plugins)
// When returning to the page, set the scroll position to the stored value
window.scrollTo(0, currentPosition);
warningElement?.classList.remove("hide");
plugin.code = pluginSource
console.log(`Plugin ${plugin.name} installed`);
showToast("Plugin " + plugin.name + " installed");
}
else
{
plugin.enabled = false
pluginToggle.checked = false
console.error(`Couldn't download plugin ${plugin.name}`);
showToast("Failed to install " + plugin.name + " (Couldn't fetch " + extractFilename(plugin.url) + ")", 5000, true);
}
} else {
warningElement?.classList.add("hide");
// Store the current scroll position before navigating away
const currentPosition = window.pageYOffset;
initPluginTable(plugins)
// When returning to the page, set the scroll position to the stored value
window.scrollTo(0, currentPosition);
}
await setStorageData('plugins', JSON.stringify(plugins))
})
}
// manual install event handler
if (pluginManualInstall !== null) {
pluginManualInstall.addEventListener('click', async () => {
pluginDialogOpenDialog(inputOK, inputCancel)
pluginDialogTextarea.value = plugin.code ? plugin.code : ''
pluginDialogTextarea.select()
pluginDialogTextarea.focus()
})
}
// Dialog OK
async function inputOK() {
let pluginSource = pluginDialogTextarea.value
// remove empty lines and trim existing lines
plugin.code = pluginSource
if (pluginSource.trim() !== '') {
plugin.enabled = true
console.log(`Plugin ${plugin.name} installed`);
showToast("Plugin " + plugin.name + " installed");
}
else
{
plugin.enabled = false
console.log(`No code provided for plugin ${plugin.name}, disabling the plugin`);
showToast("No code provided for plugin " + plugin.name + ", disabling the plugin");
}
updateManualInstallButtonCaption()
await setStorageData('plugins', JSON.stringify(plugins))
}
// Dialog Cancel
async function inputCancel() {
plugin.enabled = false
console.log(`Installation of plugin ${plugin.name} cancelled`);
showToast("Cancelled installation of " + plugin.name);
}
// update button caption
function updateManualInstallButtonCaption() {
if (pluginManualInstall !== null) {
pluginManualInstall.innerHTML = plugin.code === undefined || plugin.code.trim() === '' ? 'Install' : 'Edit'
}
}
})
prettifyInputs(pluginsTable)
filterPlugins()
}
/* version management. Thanks Madrang! */
const parseVersion = function(versionString, options = {}) {
if (typeof versionString === "undefined") {
throw new Error("versionString is undefined.");
}
if (typeof versionString !== "string") {
throw new Error("versionString is not a string.");
}
const lexicographical = options && options.lexicographical;
const zeroExtend = options && options.zeroExtend;
let versionParts = versionString.split('.');
function isValidPart(x) {
const re = (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/);
return re.test(x);
}
if (!versionParts.every(isValidPart)) {
throw new Error("Version string is invalid.");
}
if (zeroExtend) {
while (versionParts.length < 4) {
versionParts.push("0");
}
}
if (!lexicographical) {
versionParts = versionParts.map(Number);
}
return versionParts;
};
const versionCompare = function(v1, v2, options = {}) {
if (typeof v1 == "undefined") {
throw new Error("vi is undefined.");
}
if (typeof v2 === "undefined") {
throw new Error("v2 is undefined.");
}
let v1parts;
if (typeof v1 === "string") {
v1parts = parseVersion(v1, options);
} else if (Array.isArray(v1)) {
v1parts = [...v1];
if (!v1parts.every (p => typeof p === "number" && p !== NaN)) {
throw new Error("v1 part array does not only contains numbers.");
}
} else {
throw new Error("v1 is of an unexpected type: " + typeof v1);
}
let v2parts;
if (typeof v2 === "string") {
v2parts = parseVersion(v2, options);
} else if (Array.isArray(v2)) {
v2parts = [...v2];
if (!v2parts.every(p => typeof p === "number" && p !== NaN)) {
throw new Error("v2 part array does not only contains numbers.");
}
} else {
throw new Error("v2 is of an unexpected type: " + typeof v2);
}
while (v1parts.length < v2parts.length) {
v1parts.push("0");
}
while (v2parts.length < v1parts.length) {
v2parts.push("0");
}
for (let i = 0; i < v1parts.length; ++i) {
if (v2parts.length == i) {
return 1;
}
if (v1parts[i] == v2parts[i]) {
continue;
} else if (v1parts[i] > v2parts[i]) {
return 1;
} else {
return -1;
}
}
return 0;
};
function filterPluginsByMinEDVersion(plugins, EDVersion) {
const filteredPlugins = plugins.filter(plugin => {
if (plugin.minEDVersion) {
return versionCompare(plugin.minEDVersion, EDVersion) <= 0;
}
return true;
});
return filteredPlugins;
}
function extractVersionNumber(elem) {
const versionStr = elem.innerHTML;
const regex = /v(\d+\.\d+\.\d+)/;
const matches = regex.exec(versionStr);
if (matches && matches.length > 1) {
return matches[1];
} else {
return null;
}
}
const EasyDiffusionVersion = extractVersionNumber(document.querySelector('#top-nav > #logo'))
/* PLUGIN MANAGEMENT */
let plugins
let localPlugins
let initPluginsInProgress = false
async function initPlugins(refreshPlugins = false) {
let pluginsLoaded
if(initPluginsInProgress === true) {
return
}
initPluginsInProgress = true
const res = await fetch('/get/ui_plugins')
if (!res.ok) {
console.error(`Error HTTP${res.status} while loading plugins list. - ${res.statusText}`)
}
else
{
localPlugins = await res.json()
}
if (refreshPlugins === false) {
// try and load plugins from local cache
plugins = await getStorageData('plugins')
if (plugins !== undefined) {
plugins = JSON.parse(await getStorageData('plugins'))
// remove duplicate entries if any (should not happen)
plugins = deduplicatePluginsById(plugins)
// remove plugins that don't meet the min ED version requirement
plugins = filterPluginsByMinEDVersion(plugins, EasyDiffusionVersion)
// remove from plugins the entries that don't have mandatory fields (id, name, url)
plugins = plugins.filter((plugin) => { return plugin.id !== '' && plugin.name !== '' && plugin.url !== ''; });
// populate the table
initPluginTable(plugins)
await loadPlugins(plugins)
pluginsLoaded = true
}
else
{
plugins = []
pluginsLoaded = false
}
}
// update plugins asynchronously (updated versions will be available next time the UI is loaded)
if(refreshAllowed()) {
let pluginCatalog = await getDocument(PLUGIN_CATALOG)
if (pluginCatalog !== null) {
try {
pluginCatalog = JSON.parse(pluginCatalog);
console.log('Plugin catalog successfully downloaded');
if (pluginCatalog.length > plugins.length) {
showToast("New plugins are available");
}
} catch (error) {
console.error('Error parsing plugin catalog:', error);
}
await downloadPlugins(pluginCatalog, plugins, refreshPlugins)
// update compatIssueIds
updateCompatIssueIds()
// remove plugins that don't meet the min ED version requirement
plugins = filterPluginsByMinEDVersion(plugins, EasyDiffusionVersion)
// remove from plugins the entries that don't have mandatory fields (id, name, url)
plugins = plugins.filter((plugin) => { return plugin.id !== '' && plugin.name !== '' && plugin.url !== ''; });
// remove from plugins the entries that no longer exist in the catalog
plugins = plugins.filter((plugin) => { return pluginCatalog.find((p) => p.id === plugin.id) });
// save the remaining plugins
await setStorageData('plugins', JSON.stringify(plugins))
// refresh the display of the plugins table
initPluginTable(plugins)
if (pluginsLoaded && pluginsLoaded === false) {
loadPlugins(plugins)
}
}
else
{
console.error('Could not download the plugin catalog from ' + PLUGIN_CATALOG)
}
if (refreshPlugins) {
showToast('Plugins refreshed')
}
}
else
{
if (refreshPlugins) {
showToast('Plugins have been refreshed recently, refresh will be available within 1 hour', 5000, true)
}
}
initPluginsInProgress = false
}
setTimeout(initPlugins, 1000);
function updateCompatIssueIds() {
// Loop through each plugin
plugins.forEach(plugin => {
// Check if the plugin has `compatIssueIds` property
if (plugin.compatIssueIds !== undefined) {
// Loop through each of the `compatIssueIds`
plugin.compatIssueIds.forEach(issueId => {
// Find the plugin with the corresponding `issueId`
const issuePlugin = plugins.find(p => p.id === issueId);
// If the corresponding plugin is found, initialize its `compatIssueIds` property with an empty array if it's undefined
if (issuePlugin) {
if (issuePlugin.compatIssueIds === undefined) {
issuePlugin.compatIssueIds = [];
}
// If the current plugin's ID is not already in the `compatIssueIds` array, add it
if (!issuePlugin.compatIssueIds.includes(plugin.id)) {
issuePlugin.compatIssueIds.push(plugin.id);
}
}
});
} else {
// If the plugin doesn't have `compatIssueIds` property, initialize it with an empty array
plugin.compatIssueIds = [];
}
});
}
function deduplicatePluginsById(plugins) {
const seenIds = new Set();
const deduplicatedPlugins = [];
for (const plugin of plugins) {
if (!seenIds.has(plugin.id)) {
seenIds.add(plugin.id);
deduplicatedPlugins.push(plugin);
} else {
// favor dupes that have enabled == true
const index = deduplicatedPlugins.findIndex(p => p.id === plugin.id);
if (index >= 0) {
if (plugin.enabled) {
deduplicatedPlugins[index] = plugin;
}
}
}
}
return deduplicatedPlugins;
}
async function loadPlugins(plugins) {
plugins.forEach((plugin) => {
if (plugin.enabled === true && plugin.localInstallOnly !== true) {
const localPluginFound = checkFileNameInArray(localPlugins, plugin.url);
if (!localPluginFound) {
try {
// Indirect eval to work around sloppy plugin implementations
const indirectEval = { eval };
indirectEval.eval(plugin.code)
console.log("Plugin " + plugin.name + " loaded");
} catch (err) {
showToast("Error loading plugin " + plugin.name + " (" + err.message + ")", null, true)
console.error("Error loading plugin " + plugin.name + ": " + err.message);
}
} else {
console.log("Skipping plugin " + plugin.name + " (installed locally)");
}
}
});
}
async function getFileHash(url) {
const regex = /^https:\/\/raw\.githubusercontent\.com\/(?<owner>[^/]+)\/(?<repo>[^/]+)\/(?<branch>[^/]+)\/(?<filePath>.+)$/;
const match = url.match(regex);
if (!match) {
console.error('Invalid GitHub repository URL.');
return Promise.resolve(null);
}
const owner = match.groups.owner;
const repo = match.groups.repo;
const branch = match.groups.branch;
const filePath = match.groups.filePath;
const apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}?ref=${branch}`;
const response = await fetch(apiUrl);
const data = await response.json();
// Store the new sha value for future reference
return data.sha;
}
// only allow two refresh per hour
function refreshAllowed() {
const lastRuns = JSON.parse(localStorage.getItem('lastRuns') || '[]');
const currentTime = new Date().getTime();
const numRunsLast60Min = lastRuns.filter(run => currentTime - run <= 60 * 60 * 1000).length;
if (numRunsLast60Min >= 2) {
console.log(`Next refresh available in ${3600 - Math.round((currentTime - lastRuns[lastRuns.length - 1]) / 1000)} seconds`)
return false;
}
lastRuns.push(currentTime);
localStorage.setItem('lastRuns', JSON.stringify(lastRuns));
return true;
}
async function downloadPlugins(pluginCatalog, plugins, refreshPlugins) {
// download the plugins as needed
for (const plugin of pluginCatalog) {
//console.log(plugin.id, plugin.url)
const existingPlugin = plugins.find(p => p.id === plugin.id);
// get the file hash in the GitHub repo
let sha
if (isGitHub(plugin.url) && existingPlugin?.enabled === true) {
sha = await getFileHash(plugin.url)
}
if (plugin.localInstallOnly !== true && isGitHub(plugin.url) && existingPlugin?.enabled === true && (refreshPlugins || (existingPlugin.sha !== undefined && existingPlugin.sha !== sha) || existingPlugin?.code === undefined)) {
const pluginSource = await getDocument(plugin.url);
if (pluginSource !== null && pluginSource !== existingPlugin.code) {
console.log(`Plugin ${plugin.name} updated`);
showToast("Plugin " + plugin.name + " updated", 20000);
// Update the corresponding plugin
const updatedPlugin = {
...existingPlugin,
icon: plugin.icon ? plugin.icon : "fa-puzzle-piece",
id: plugin.id,
name: plugin.name,
description: plugin.description,
url: plugin.url,
localInstallOnly: Boolean(plugin.localInstallOnly),
version: plugin.version,
code: pluginSource,
author: plugin.author,
sha: sha,
compatIssueIds: plugin.compatIssueIds
};
// Replace the old plugin in the plugins array
const pluginIndex = plugins.indexOf(existingPlugin);
if (pluginIndex >= 0) {
plugins.splice(pluginIndex, 1, updatedPlugin);
} else {
plugins.push(updatedPlugin);
}
}
}
else if (existingPlugin !== undefined) {
// Update the corresponding plugin's metadata
const updatedPlugin = {
...existingPlugin,
icon: plugin.icon ? plugin.icon : "fa-puzzle-piece",
id: plugin.id,
name: plugin.name,
description: plugin.description,
url: plugin.url,
localInstallOnly: Boolean(plugin.localInstallOnly),
version: plugin.version,
author: plugin.author,
compatIssueIds: plugin.compatIssueIds
};
// Replace the old plugin in the plugins array
const pluginIndex = plugins.indexOf(existingPlugin);
plugins.splice(pluginIndex, 1, updatedPlugin);
}
else
{
plugins.push(plugin);
}
}
}
async function getDocument(url) {
try {
let response = await fetch(url === PLUGIN_CATALOG ? PLUGIN_CATALOG : url, { cache: "no-cache" });
if (!response.ok) {
throw new Error(`Response error: ${response.status} ${response.statusText}`);
}
let document = await response.text();
return document;
} catch (error) {
showToast("Couldn't fetch " + extractFilename(url) + " (" + error + ")", null, true);