-
Notifications
You must be signed in to change notification settings - Fork 480
Expand file tree
/
Copy pathplugin_loader.js
More file actions
1791 lines (1696 loc) Β· 59.1 KB
/
Copy pathplugin_loader.js
File metadata and controls
1791 lines (1696 loc) Β· 59.1 KB
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
var onUninstall, onInstall;
const Plugins = {
Vue: [], //Vue Object
installed: [], //Simple List of Names
json: undefined, //Json from website
download_stats: {},
all: [], //Vue Object Data
registered: {},
currently_loading: '',
api_path: settings.cdn_mirror.value ? 'https://blckbn.ch/cdn/plugins' : 'https://cdn.jsdelivr.net/gh/JannisX11/blockbench-plugins/plugins',
devReload() {
let reloads = 0;
for (let i = Plugins.all.length-1; i >= 0; i--) {
let plugin = Plugins.all[i];
if (plugin.source == 'file' && plugin.isReloadable()) {
Plugins.all[i].reload()
reloads++;
}
}
Blockbench.showQuickMessage(tl('message.plugin_reload', [reloads]))
console.log('Reloaded '+reloads+ ' plugin'+pluralS(reloads))
},
sort() {
Plugins.all.sort((a, b) => {
if (a.tags.find(tag => tag.match(/deprecated/i))) return 1;
if (b.tags.find(tag => tag.match(/deprecated/i))) return -1;
let download_difference = (Plugins.download_stats[b.id] || 0) - (Plugins.download_stats[a.id] || 0);
if (download_difference) {
return download_difference
} else {
return sort_collator.compare(a.title, b.title);
}
});
}
}
const ENVIRONMENT_CUSTOM_PLUGINS = []
const ENVIRONMENT_PLUGINS = []
if (process.env.BLOCKBENCH_INSTALL_CUSTOM_PLUGINS) {
ENVIRONMENT_CUSTOM_PLUGINS.push(...process.env.BLOCKBENCH_INSTALL_CUSTOM_PLUGINS
.split(',')
.map(file => file.trim())
)
}
if (process.env.BLOCKBENCH_INSTALL_PLUGINS) {
ENVIRONMENT_PLUGINS.push(...process.env.BLOCKBENCH_INSTALL_PLUGINS
.split(',')
.map(url => url.trim())
)
}
StateMemory.init('installed_plugins', 'array')
if (process.env.BLOCKBENCH_CLEAN_INSTALLED_PLUGINS === 'TRUE') {
Plugins.installed = StateMemory.installed_plugins = StateMemory.installed_plugins.filter(
p => p && typeof p == 'object' && !ENVIRONMENT_CUSTOM_PLUGINS.includes(p.path) && !ENVIRONMENT_PLUGINS.includes(p.id)
)
} else {
app.terminal.log('--clean-installed-plugins: Clearing installed plugins')
Plugins.installed = StateMemory.installed_plugins = []
}
async function runPluginFile(path, plugin_id) {
let file_content;
if (path.startsWith('http')) {
if (!path.startsWith('https')) {
throw 'Cannot load plugins over http: ' + path;
}
await new Promise((resolve, reject) => {
$.ajax({
cache: false,
url: path,
success(data) {
file_content = data;
resolve();
},
error() {
reject('Failed to load plugin ' + plugin_id);
}
});
})
} else if (isApp) {
file_content = fs.readFileSync(path, {encoding: 'utf-8'});
} else {
throw 'Failed to load plugin: Unknown URL format'
}
if (typeof file_content != 'string' || file_content.length < 20) {
throw `Issue loading plugin "${plugin_id}": Plugin file empty`;
}
let func = new Function(file_content + `\n//# sourceURL=PLUGINS/(Plugin):${plugin_id}.js`);
func();
return file_content;
}
class Plugin {
constructor(id, data) {
this.id = id||'unknown';
this.installed = false;
this.title = '';
this.author = '';
this.description = '';
this.about = '';
this.icon = '';
this.tags = [];
this.dependencies = [];
this.contributors = [];
this.version = '0.0.1';
this.variant = 'both';
this.min_version = '';
this.max_version = '';
this.deprecation_note = '';
this.website = '';
this.source = 'store';
this.creation_date = 0;
this.contributes = {};
this.await_loading = false;
this.has_changelog = false;
this.changelog = null;
this.details = null;
this.about_fetched = false;
this.changelog_fetched = false;
this.disabled = false;
this.new_repository_format = false;
this.cache_version = 0;
this.extend(data)
Plugins.all.safePush(this);
}
extend(data) {
if (!(data instanceof Object)) return this;
Merge.boolean(this, data, 'installed')
Merge.string(this, data, 'title')
Merge.string(this, data, 'author')
Merge.string(this, data, 'description')
Merge.string(this, data, 'about')
Merge.string(this, data, 'icon')
Merge.string(this, data, 'version')
Merge.string(this, data, 'variant')
Merge.string(this, data, 'min_version')
Merge.string(this, data, 'max_version')
Merge.string(this, data, 'deprecation_note')
Merge.string(this, data, 'website')
Merge.string(this, data, 'repository')
Merge.string(this, data, 'bug_tracker')
Merge.boolean(this, data, 'await_loading');
Merge.boolean(this, data, 'has_changelog');
Merge.boolean(this, data, 'disabled');
if (data.creation_date) this.creation_date = Date.parse(data.creation_date);
if (data.tags instanceof Array) this.tags.safePush(...data.tags.slice(0, 3));
if (data.contributors instanceof Array) this.contributors.safePush(...data.contributors);
if (data.dependencies instanceof Array) this.dependencies.safePush(...data.dependencies);
if (data.new_repository_format) this.new_repository_format = true;
if (this.min_version != '' && !compareVersions('4.8.0', this.min_version)) {
this.new_repository_format = true;
}
if (typeof data.contributes == 'object') {
this.contributes = data.contributes;
}
Merge.function(this, data, 'onload')
Merge.function(this, data, 'onunload')
Merge.function(this, data, 'oninstall')
Merge.function(this, data, 'onuninstall')
return this;
}
get name() {
return this.title;
}
async install() {
if (this.tags.includes('Deprecated') || this.deprecation_note) {
let message = tl('message.plugin_deprecated.message');
if (this.deprecation_note) {
message += '\n\n*' + this.deprecation_note + '*';
}
let answer = await new Promise((resolve) => {
Blockbench.showMessageBox({
icon: 'warning',
title: this.title,
message,
cancelIndex: 0,
buttons: ['dialog.cancel', 'message.plugin_deprecated.install_anyway']
}, resolve)
})
if (answer == 0) return;
}
return await this.download(true);
}
async load(first, cb) {
var scope = this;
Plugins.registered[this.id] = this;
return await new Promise((resolve, reject) => {
let path = Plugins.path + scope.id + '.js';
if (!isApp && this.new_repository_format) {
path = `${Plugins.path}${scope.id}/${scope.id}.js`;
}
runPluginFile(path, this.id).then((content) => {
if (cb) cb.bind(scope)()
scope.bindGlobalData(first)
if (first && scope.oninstall) {
scope.oninstall()
}
if (first) Blockbench.showQuickMessage(tl('message.installed_plugin', [this.title]));
resolve()
}).catch((error) => {
if (isApp) {
console.log('Could not find file of plugin "'+scope.id+'". Uninstalling it instead.')
scope.uninstall()
}
if (first) Blockbench.showQuickMessage(tl('message.installed_plugin_fail', [this.title]));
reject()
console.error(error)
})
this.remember()
scope.installed = true;
})
}
async installDependencies(first) {
let required_dependencies = [];
for (let id of this.dependencies) {
let saved_install = !first && Plugins.installed.find(p => p.id == id);
if (saved_install) {
continue;
}
let plugin = Plugins.all.find(p => p.id == id);
if (plugin) {
if (plugin.installed == false) required_dependencies.push(plugin);
continue;
}
required_dependencies.push(id);
}
if (required_dependencies.length) {
let failed_dependency = required_dependencies.find(p => {
return !p.isInstallable || p.isInstallable() != true
});
if (failed_dependency) {
let error_message = failed_dependency;
if (failed_dependency instanceof Plugin) {
error_message = `**${failed_dependency.title}**: ${failed_dependency.isInstallable()}`;
}
Blockbench.showMessageBox({
title: 'message.plugin_dependencies.title',
message: `Updating **${this.title||this.id}**:\n\n${tl('message.plugin_dependencies.invalid')}\n\n${error_message}`,
});
return false;
}
let list = required_dependencies.map(p => `**${p.title}** ${tl('dialog.plugins.author', [p.author])}`);
let response = await new Promise(resolve => {
Blockbench.showMessageBox({
title: 'message.plugin_dependencies.title',
message: `${tl('message.plugin_dependencies.' + (first ? 'message1' : 'message1_update'), [this.title])} \n\n* ${ list.join('\n* ') }\n\n${tl('message.plugin_dependencies.message2')}`,
buttons: ['dialog.continue', first ? 'dialog.cancel' : 'dialog.plugins.uninstall'],
width: 512,
}, button => {
resolve(button == 0);
})
})
if (!response) {
if (this.installed) this.uninstall();
return false;
}
for (let dependency of required_dependencies) {
await dependency.install();
}
}
return true;
}
bindGlobalData() {
var scope = this;
if (onUninstall) {
scope.onuninstall = onUninstall
}
if (onUninstall) {
scope.onuninstall = onUninstall
}
if (window.plugin_data) {
console.warn(`plugin_data is deprecated. Please use Plugin.register instead. (${plugin_data.id || 'unknown plugin'})`)
}
window.onInstall = window.onUninstall = window.plugin_data = undefined
return this;
}
async download(first) {
let response = await this.installDependencies(first);
if (response == false) return;
var scope = this;
function register() {
if (!Plugins.json[scope.id]) return;
jQuery.ajax({
url: 'https://blckbn.ch/api/event/install_plugin',
type: 'POST',
data: {
plugin: scope.id
}
})
}
if (!isApp) {
if (first) register();
return await scope.load(first)
}
// Download files
async function copyFileToDrive(origin_filename, target_filename, callback) {
var file = originalFs.createWriteStream(PathModule.join(Plugins.path, target_filename));
https.get(Plugins.api_path+'/'+origin_filename, function(response) {
response.pipe(file);
if (callback) response.on('end', callback);
});
}
return await new Promise(async (resolve, reject) => {
// New system
if (this.new_repository_format) {
copyFileToDrive(`${this.id}/${this.id}.js`, `${this.id}.js`, () => {
if (first) register();
setTimeout(async function() {
await scope.load(first);
resolve()
}, 20)
});
if (this.hasImageIcon()) {
copyFileToDrive(`${this.id}/${this.icon}`, this.id + '.' + this.icon);
}
await this.fetchAbout();
if (this.about) {
fs.writeFileSync(PathModule.join(Plugins.path, this.id + '.about.md'), this.about, 'utf-8');
}
} else {
// Legacy system
copyFileToDrive(`${this.id}.js`, `${this.id}.js`, () => {
if (first) register();
setTimeout(async function() {
await scope.load(first);
resolve()
}, 20)
});
}
});
}
async loadFromFile(file, first) {
var scope = this;
if (!isApp && !first) return this;
if (first) {
if (isApp) {
if (!confirm(tl('message.load_plugin_app'))) return;
} else {
if (!confirm(tl('message.load_plugin_web'))) return;
}
}
this.id = pathToName(file.path);
Plugins.registered[this.id] = this;
Plugins.all.safePush(this);
this.source = 'file';
this.tags.safePush('Local');
if (isApp) {
let content = await runPluginFile(file.path, this.id).catch((error) => {
console.error(error);
});
if (content) {
if (window.plugin_data) {
scope.id = (plugin_data && plugin_data.id)||pathToName(file.path)
scope.extend(plugin_data)
scope.bindGlobalData()
}
if (first && scope.oninstall) {
scope.oninstall()
}
scope.path = file.path;
}
} else {
try {
new Function(file.content + `\n//# sourceURL=PLUGINS/(Plugin):${this.id}.js`)();
} catch (err) {
reject(err)
}
if (!Plugins.registered && window.plugin_data) {
scope.id = (plugin_data && plugin_data.id)||scope.id
scope.extend(plugin_data)
scope.bindGlobalData()
}
if (first && scope.oninstall) {
scope.oninstall()
}
}
this.installed = true;
this.remember();
Plugins.sort();
}
async loadFromURL(url, first) {
if (first) {
if (isApp) {
if (!confirm(tl('message.load_plugin_app'))) return;
} else {
if (!confirm(tl('message.load_plugin_web'))) return;
}
}
this.id = pathToName(url)
Plugins.registered[this.id] = this;
Plugins.all.safePush(this)
this.tags.safePush('Remote');
this.source = 'url';
let content = await runPluginFile(url, this.id).catch((error) => {
if (isApp) {
this.load().then(resolve).catch(resolve)
}
console.error(error);
})
if (content) {
if (window.plugin_data) {
this.id = (plugin_data && plugin_data.id)||pathToName(url)
this.extend(plugin_data)
this.bindGlobalData()
}
if (first && this.oninstall) {
this.oninstall()
}
this.installed = true
this.path = url
this.remember()
Plugins.sort()
// Save
if (isApp) {
await new Promise((resolve, reject) => {
let file = originalFs.createWriteStream(Plugins.path+this.id+'.js')
https.get(url, (response) => {
response.pipe(file);
response.on('end', resolve)
}).on('error', reject);
})
}
}
return this;
}
remember(id = this.id, path = this.path) {
let entry = Plugins.installed.find(plugin => plugin.id == this.id);
let already_exists = !!entry;
if (!entry) entry = {};
entry.id = id;
entry.version = this.version;
entry.path = path;
entry.source = this.source;
entry.disabled = this.disabled ? true : undefined;
if (!already_exists) Plugins.installed.push(entry);
StateMemory.save('installed_plugins')
return this;
}
uninstall() {
try {
this.unload();
if (this.onuninstall) {
this.onuninstall();
}
} catch (err) {
console.error(`Error in unload or uninstall method of "${this.id}": `, err);
}
delete Plugins.registered[this.id];
let in_installed = Plugins.installed.find(plugin => plugin.id == this.id);
Plugins.installed.remove(in_installed);
StateMemory.save('installed_plugins')
this.installed = false;
this.disabled = false;
if (isApp && this.source !== 'store') {
Plugins.all.remove(this)
}
if (isApp && this.source != 'file') {
function removeCachedFile(filepath) {
if (fs.existsSync(filepath)) {
fs.unlink(filepath, (err) => {
if (err) console.log(err);
});
}
}
removeCachedFile(Plugins.path + this.id + '.js');
removeCachedFile(Plugins.path + this.id + '.' + this.icon);
removeCachedFile(Plugins.path + this.id + '.about.md');
}
StateMemory.save('installed_plugins')
return this;
}
unload() {
if (this.onunload) {
this.onunload()
}
return this;
}
reload() {
if (!isApp && this.source == 'file') return this;
this.cache_version++;
this.unload()
this.tags.empty();
this.contributors.empty();
this.dependencies.empty();
Plugins.all.remove(this);
this.details = null;
let had_changelog = this.changelog_fetched;
this.changelog_fetched = false;
if (this.source == 'file') {
this.loadFromFile({path: this.path}, false)
} else if (this.source == 'url') {
this.loadFromURL(this.path, false)
}
this.fetchAbout(true);
if (had_changelog && this.has_changelog) {
this.fetchChangelog(true);
}
return this;
}
toggleDisabled() {
if (!this.disabled) {
this.disabled = true;
this.unload()
} else {
if (this.onload) {
this.onload()
}
this.disabled = false;
}
this.remember();
}
showContextMenu(event) {
//if (!this.installed) return;
this.menu.open(event, this);
}
isReloadable() {
return this.installed && !this.disabled && ((this.source == 'file' && isApp) || (this.source == 'url'));
}
isInstallable() {
var scope = this;
var result =
scope.variant === 'both' ||
(
isApp === (scope.variant === 'desktop') &&
isApp !== (scope.variant === 'web')
);
if (result && scope.min_version) {
result = Blockbench.isOlderThan(scope.min_version) ? 'outdated_client' : true;
}
if (result && scope.max_version) {
result = Blockbench.isNewerThan(scope.max_version) ? 'outdated_plugin' : true
}
if (result === false) {
result = (scope.variant === 'web') ? 'web_only' : 'app_only'
}
return (result === true) ? true : tl('dialog.plugins.'+result);
}
hasImageIcon() {
return this.icon.endsWith('.png') || this.icon.endsWith('.svg');
}
getIcon() {
if (this.hasImageIcon()) {
if (isApp) {
if (this.installed && this.source == 'store') {
return Plugins.path + this.id + '.' + this.icon;
}
if (this.source != 'store')
return this.path.replace(/\w+\.js$/, this.icon + (this.cache_version ? '?'+this.cache_version : ''));
}
return `${Plugins.api_path}/${this.id}/${this.icon}`;
}
return this.icon;
}
async fetchAbout(force) {
if (((!this.about_fetched && !this.about) || force) && this.new_repository_format) {
if (isApp && this.installed) {
try {
let about_path;
if (this.source == 'store') {
about_path = PathModule.join(Plugins.path, this.id + '.about.md');
} else {
about_path = this.path.replace(/\w+\.js$/, 'about.md');
}
let content = fs.readFileSync(about_path, {encoding: 'utf-8'});
this.about = content;
this.about_fetched = true;
return;
} catch (err) {
console.error('failed to get about for plugin ' + this.id);
}
}
let url = `${Plugins.api_path}/${this.id}/about.md`;
let result = await fetch(url).catch(() => {
console.error('about.md missing for plugin ' + this.id);
});
if (result.ok) {
this.about = await result.text();
}
this.about_fetched = true;
}
}
async fetchChangelog(force) {
if ((!this.changelog_fetched && !this.changelog) || force) {
function reverseOrder(input) {
let output = {};
Object.keys(input).forEachReverse(key => {
output[key] = input[key];
})
return output;
}
if (isApp && this.installed && this.source != 'store') {
try {
let changelog_path = this.path.replace(/\w+\.js$/, 'changelog.json');
let content = fs.readFileSync(changelog_path, {encoding: 'utf-8'});
this.changelog = reverseOrder(JSON.parse(content));
this.changelog_fetched = true;
return;
} catch (err) {
console.error('failed to get changelog for plugin ' + this.id, err);
}
}
let url = `${Plugins.api_path}/${this.id}/changelog.json`;
let result = await fetch(url).catch(() => {
console.error('changelog.json missing for plugin ' + this.id);
});
if (result.ok) {
this.changelog = reverseOrder(await result.json());
}
this.changelog_fetched = true;
}
}
getPluginDetails() {
if (this.details) return this.details;
this.details = {
version: this.version,
last_modified: 'N/A',
creation_date: 'N/A',
last_modified_full: '',
creation_date_full: '',
min_version: this.min_version ? (this.min_version+'+') : '-',
max_version: this.max_version || '',
website: this.website || '',
repository: this.repository || '',
bug_tracker: this.bug_tracker || '',
contributors: this.contributors.join(', '),
author: this.author,
variant: this.variant == 'both' ? 'All' : this.variant,
weekly_installations: separateThousands(Plugins.download_stats[this.id] || 0),
};
let trackDate = (input_date, key) => {
let date = getDateDisplay(input_date);
this.details[key] = date.short;
this.details[key + '_full'] = date.full;
}
if (this.source == 'store') {
if (!this.details.bug_tracker) {
this.details.bug_tracker = `https://github.com/JannisX11/blockbench-plugins/issues/new?title=[${this.title}]`;
}
if (!this.details.repository) {
this.details.repository = `https://github.com/JannisX11/blockbench-plugins/tree/master/plugins/${this.id + (this.new_repository_format ? '' : '.js')}`;
}
let github_path = (this.new_repository_format ? (this.id+'/'+this.id) : this.id) + '.js';
let commit_url = `https://api.github.com/repos/JannisX11/blockbench-plugins/commits?path=plugins/${github_path}`;
fetch(commit_url).catch((err) => {
console.error('Cannot access commit info for ' + this.id, err);
}).then(async response => {
let commits = await response.json().catch(err => console.error(err));
if (!commits || !commits.length) return;
trackDate(Date.parse(commits[0].commit.committer.date), 'last_modified');
if (!this.creation_date) {
trackDate(Date.parse(commits.last().commit.committer.date), 'creation_date');
}
});
}
if (this.creation_date) {
trackDate(this.creation_date, 'creation_date');
}
return this.details;
}
/**
* Logs output to the terminal Blockbench was started from with a fancy plugin-specific prefix
* @example
* myPlugin.log('Hello World!')
* /// [Blockbench] <my-plugin> Hello World!
*/
log(...args) {
Blockbench.log(`\x1b[90m<\x1b[33m${this.id}\x1b[90m>\x1b[0m`, ...args)
}
}
Plugin.prototype.menu = new Menu([
new MenuSeparator('installation'),
{
name: 'generic.share',
icon: 'share',
condition: plugin => Plugins.json[plugin.id],
click(plugin) {
let url = `https://www.blockbench.net/plugins/${plugin.id}`;
new Dialog('share_plugin', {
title: tl('generic.share') + ': ' + plugin.title,
icon: 'extension',
form: {
link: {type: 'text', value: url, readonly: true, share_text: true}
}
}).show();
}
},
'_',
{
name: 'dialog.plugins.install',
icon: 'add',
condition: plugin => (!plugin.installed && plugin.isInstallable() == true),
click(plugin) {
plugin.install();
}
},
{
name: 'dialog.plugins.uninstall',
icon: 'delete',
condition: plugin => (plugin.installed),
click(plugin) {
plugin.uninstall();
}
},
{
name: 'dialog.plugins.disable',
icon: 'bedtime',
condition: plugin => (plugin.installed && !plugin.disabled),
click(plugin) {
plugin.toggleDisabled();
}
},
{
name: 'dialog.plugins.enable',
icon: 'bedtime',
condition: plugin => (plugin.installed && plugin.disabled),
click(plugin) {
plugin.toggleDisabled();
}
},
new MenuSeparator('developer'),
{
name: 'dialog.plugins.reload',
icon: 'refresh',
condition: plugin => (plugin.installed && plugin.isReloadable()),
click(plugin) {
plugin.reload();
}
},
{
name: 'menu.animation.open_location',
icon: 'folder',
condition: plugin => (isApp && plugin.source == 'file'),
click(plugin) {
showItemInFolder(plugin.path);
}
},
]);
// Alias for typescript
const BBPlugin = Plugin;
Plugin.register = function(id, data) {
if (typeof id !== 'string' || typeof data !== 'object') {
console.warn('Plugin.register: not enough arguments, string and object required.')
return;
}
var plugin = Plugins.registered[id];
if (!plugin) {
plugin = Plugins.registered.unknown;
if (plugin) {
delete Plugins.registered.unknown;
plugin.id = id;
Plugins.registered[id] = plugin;
}
}
if (!plugin) {
Blockbench.showMessageBox({
translateKey: 'load_plugin_failed',
message: tl('message.load_plugin_failed.message', [id])
})
return;
};
plugin.extend(data)
if (plugin.isInstallable() == true && plugin.disabled == false) {
if (plugin.onload instanceof Function) {
Plugins.currently_loading = id;
plugin.onload();
Plugins.currently_loading = '';
}
}
return plugin;
}
if (isApp) {
Plugins.path = app.getPath('userData')+osfs+'plugins'+osfs
fs.readdir(Plugins.path, function(err) {
if (err) {
fs.mkdir(Plugins.path, function(a) {})
}
})
} else {
Plugins.path = Plugins.api_path+'/';
}
Plugins.loading_promise = new Promise((resolve, reject) => {
$.ajax({
cache: false,
url: Plugins.api_path+'.json',
dataType: 'json',
success(data) {
Plugins.json = data;
resolve();
Plugins.loading_promise.resolved = true;
},
error() {
console.log('Could not connect to plugin server')
$('#plugin_available_empty').text('Could not connect to plugin server')
resolve();
Plugins.loading_promise.resolved = true;
if (settings.cdn_mirror.value == false && navigator.onLine) {
settings.cdn_mirror.set(true);
console.log('Switching to plugin CDN mirror. Restart to apply.');
}
}
});
})
$.getJSON('https://blckbn.ch/api/stats/plugins?weeks=2', data => {
Plugins.download_stats = data;
if (Plugins.json) {
Plugins.sort();
}
})
async function loadInstalledPlugins() {
if (!Plugins.loading_promise.resolved) {
await Plugins.loading_promise;
}
const install_promises = [];
if (Plugins.json instanceof Object && navigator.onLine) {
//From Store
let to_install = [];
for (let id in Plugins.json) {
let plugin = new Plugin(id, Plugins.json[id]);
to_install.push(plugin);
}
Plugins.sort();
for (let plugin of to_install) {
let installed_match = Plugins.installed.find(p => {
return p && p.id == plugin.id && p.source == 'store'
});
if (installed_match) {
plugin.installed = true;
if (installed_match.disabled) plugin.disabled = true;
if (isApp && (
(installed_match.version && plugin.version && !compareVersions(plugin.version, installed_match.version)) ||
Blockbench.isOlderThan(plugin.min_version)
)) {
// Get from file
let promise = plugin.load(false);
install_promises.push(promise);
} else {
// Update
let promise = plugin.download();
if (plugin.await_loading) {
install_promises.push(promise);
}
}
}
}
} else if (Plugins.installed.length > 0 && isApp) {
//Offline
Plugins.installed.forEach(function(plugin_data) {
if (plugin_data.source == 'store') {
let instance = new Plugin(plugin_data.id);
let promise = instance.load(false, function() {
Plugins.sort();
})
install_promises.push(promise);
}
})
}
if (Plugins.installed.length > 0) {
var load_counter = 0;
Plugins.installed.forEachReverse(function(plugin) {
if (plugin.source == 'file') {
//Dev Plugins
if (isApp && fs.existsSync(plugin.path)) {
var instance = new Plugin(plugin.id, {disabled: plugin.disabled});
install_promises.push(instance.loadFromFile({path: plugin.path}, false));
load_counter++;
console.log(`π§©π Loaded plugin "${plugin.id || plugin.path}" from file`);
} else {
Plugins.installed.remove(plugin);
}
} else if (plugin.source == 'url') {
if (plugin.path) {
var instance = new Plugin(plugin.id, {disabled: plugin.disabled});
install_promises.push(instance.loadFromURL(plugin.path, false));
load_counter++;
console.log(`π§©π Loaded plugin "${plugin.id || plugin.path}" from URL`);
} else {
Plugins.installed.remove(plugin);
}
} else {
if (Plugins.all.find(p => p.id == plugin.id)) {
load_counter++;
console.log(`π§©π Loaded plugin "${plugin.id}" from store`);
} else if (Plugins.json instanceof Object && navigator.onLine) {
Plugins.installed.remove(plugin);
}
}
})
console.log(`Loaded ${load_counter} plugin${pluralS(load_counter)}`)
}
StateMemory.save('installed_plugins')
// CLI Environment Plugins
for (const path of ENVIRONMENT_CUSTOM_PLUGINS) {
const id = PathModule.basename(path, '.js');
const pathType = path.startsWith('http') ? 'URL' : 'File';
const alreadyInstalled = Plugins.installed.find(plugin => plugin.id === id)
if (alreadyInstalled) {
app.terminal.error(`Failed to install Environment plugin "${id}":`)
app.terminal.error(`A Plugin with the ID "${id}" already exists in the installed plugins list!`)
app.exit(1)
}
// Remove the plugin from the installed plugins list when Blockbench is closed.
Blockbench.on('before_closing', () => {
const plugin = Plugins.installed.find(plugin => plugin.id === id)
Plugins.installed.remove(plugin)
StateMemory.save('installed_plugins')
app.terminal.log(`Uninstalled Environment plugin "${id}"`)
})
if (pathType === 'URL') {
app.terminal.log(`Installing Environment plugin "${id || url}" from URL...`);
if (!(Plugins.json instanceof Object && navigator.onLine)) {
app.terminal.error(`Failed to install Environment plugins:`)
app.terminal.error(`Blockbench cannot install plugins by URL when offline.`)
app.exit(1)
}
const instance = new Plugin(id);
install_promises.push(instance.loadFromURL(url, false)
.then(() => {
app.terminal.log(`Loaded Environment plugin "${id || url}" from URL`);
console.log(`π§©π π Loaded Environment plugin "${id || url}" from URL`);
})
.catch(err => {
app.terminal.error(`Failed to load Environment plugin "${id || url}":`)
app.terminal.error(err)
app.exit(1)
})
);
} else {
if (!fs.existsSync(path)) {
app.terminal.error(`Failed to install Environment plugin "${id}":`)
app.terminal.error(`The specified plugin file does not exist: "${path}"`)
app.exit(1)
}
app.terminal.log(`Installing Environment plugin "${id || path}" from file...`);
const instance = new Plugin(id);
install_promises.push(instance.loadFromFile({path}, false)
.then(() => {
app.terminal.log(`Loaded Environment plugin "${id || path}" from file`);
console.log(`π§©π π Loaded Environment plugin "${id || path}" from file`);
})
.catch(err => {
app.terminal.error(`Failed to load Environment plugin "${id || path}":`)
app.terminal.error(err)
app.exit(1)
})
);
}
}
// Cannot install plugins by URL when offline
if (ENVIRONMENT_PLUGINS.length > 0 && !(Plugins.json instanceof Object && navigator.onLine)) {