-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathcom_Config.js
More file actions
1166 lines (1101 loc) · 46.4 KB
/
com_Config.js
File metadata and controls
1166 lines (1101 loc) · 46.4 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
/*
* Project Name : Visual Python
* Description : GUI-based Python code generator
* File Name : com_Config.js
* Author : Black Logic
* Note : Configuration and settings control
* License : GNU GPLv3 with Visual Python special exception
* Date : 2021. 09. 16
* Change Date :
*/
//============================================================================
// [CLASS] Configuration
//============================================================================
define([
'./com_Const',
'./com_util',
'./com_interface',
__VP_TEXT_LOADER__('vp_base/python/userCommand.py'), // INTEGRATION: unified version of text loader
__VP_TEXT_LOADER__('vp_base/python/printCommand.py'), // INTEGRATION: unified version of text loader
__VP_TEXT_LOADER__('vp_base/python/fileNaviCommand.py'), // INTEGRATION: unified version of text loader
__VP_TEXT_LOADER__('vp_base/python/pandasCommand.py'), // INTEGRATION: unified version of text loader
__VP_TEXT_LOADER__('vp_base/python/variableCommand.py'), // INTEGRATION: unified version of text loader
__VP_TEXT_LOADER__('vp_base/python/visualizationCommand.py') // INTEGRATION: unified version of text loader
], function(com_Const, com_util, com_interface,
userCommandFile, printCommand, fileNaviCommand, pandasCommand, variableCommand, visualizationCommand) {
'use strict';
//========================================================================
// Define Inner Variable
//========================================================================
/**
* Type of mode
*/
const _MODE_TYPE = {
DEVELOP : 0,
RELEASE : 1
}
//========================================================================
// Declare Class
//========================================================================
/**
* Configuration and settings
*/
class Config {
//========================================================================
// Constructor
//========================================================================
/**
*
* @param {*} initialData
* @param {*} extensionType extension type: notebook/colab/lab/lite
*/
constructor(extensionType='notebook', initialData={}) {
// initial mode
this._isReady = { 'default': false };
this.extensionType = extensionType;
this.parentSelector = 'body';
if (extensionType === 'notebook') {
this.parentSelector = '#site';
} else if (extensionType === 'colab' || extensionType === 'lab' || extensionType === 'lite') {
// this.parentSelector = '.notebook-horizontal';
this.parentSelector = 'body';
}
// initial configuration
this.data = {
// Configuration
'vpcfg': {
'runType': 'run'
},
// User defined code for Snippets
'vpudf': {
'default import': [
'import numpy as np',
'import pandas as pd',
'import matplotlib.pyplot as plt',
'%matplotlib inline',
'import seaborn as sns',
'import plotly.express as px',
'import pyarrow as pa'
],
'matplotlib customizing': [
'import matplotlib.pyplot as plt',
'%matplotlib inline',
'',
"plt.rc('figure', figsize=(12, 8))",
'',
'from matplotlib import rcParams',
"rcParams['font.family'] = 'New Gulim'",
"rcParams['font.size'] = 10",
"rcParams['axes.unicode_minus'] = False"
],
'as_float': [
'def as_float(x):',
' """',
" usage: df['col'] = df['col'].apply(as_float)",
' """',
' if not isinstance(x, str):',
' return 0.0',
' else:',
' try:',
' result = float(x)',
' return result',
' except ValueError:',
' return 0.0'
],
'as_int': [
'def as_int(x):',
' """',
" usage: df['col'] = df['col'].apply(as_int)",
' """',
' if not isinstance(x, str):',
' return 0',
' else:',
' try:',
' result = int(x)',
' return result',
' except ValueError:',
' return 0.0'
]
},
'vpimport': [
{ library: 'numpy', alias:'np' },
{ library: 'pandas', alias:'pd' },
{ library: 'matplotlib.pyplot', alias:'plt',
include: [
'%matplotlib inline'
]
},
{ library: 'seaborn', alias:'sns' },
{
library: 'plotly.express', alias: 'px',
include: [
'from plotly.offline import init_notebook_mode',
'init_notebook_mode(connected=True)'
]
},
{ library: 'pyarrow', alias:'pa' },
]
}
this.data = {
...this.data,
...initialData
}
this.defaultConfig = {};
this.metadataSettings = {};
this.moduleDict = {
'np': {
code: 'import numpy as np',
type: 'package'
},
'pd': {
code: 'import pandas as pd',
type: 'package'
},
'plt': {
code: 'import matplotlib.pyplot as plt\n%matplotlib inline',
type: 'package'
},
'sns': {
code: 'import seaborn as sns',
type: 'package'
},
'metrics': {
code: 'from sklearn import metrics',
type: 'package'
},
'ProfileReport': {
code: 'from pandas_profiling import ProfileReport',
type: 'package'
},
'sweetviz': {
code: 'import sweetviz',
type: 'package'
},
'px': {
code: 'import plotly.express as px\nfrom plotly.offline import init_notebook_mode\ninit_notebook_mode(connected=True)',
type: 'package'
},
'WordCloud': {
code: 'from wordcloud import WordCloud',
type: 'package'
},
'fitz': {
code: 'import fitz',
type: 'package'
},
'nltk': {
code: "import nltk\nnltk.download('punkt')",
type: 'package'
},
'Counter': {
code: 'from collections import Counter',
type: 'package'
},
'joblib': {
code: 'import joblib',
type: 'package'
},
'stats': {
code: 'from scipy import stats',
type: 'package'
},
'scipy': {
code: 'import scipy',
type: 'package'
},
'sm': {
code: 'import statsmodels.api as sm',
type: 'package'
},
'pyarrow': {
code: 'import pyarrow as pa',
type: 'package'
}
}
this._readDefaultConfig();
this._readUserCommandList();
}
get isReady() {
let sessionId = 'default';
if (this.extensionType === 'lab' || this.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
if (sessionId in this._isReady) {
return this._isReady[sessionId];
}
return false;
}
set isReady(ready) {
let sessionId = 'default';
if (this.extensionType === 'lab' || this.extensionType === 'lite') {
let panelId = vpKernel.getLabPanelId();
if (panelId) {
sessionId = panelId;
}
}
this._isReady[sessionId] = ready;
}
showProtector(title='No kernel', content='You have to open the notebook or console to use Visual Python.') {
$('#vp_protector .vp-protector-title').text(title);
$('#vp_protector .vp-protector-content').text(content);
$('#vp_protector').show();
}
hideProtector() {
$('#vp_protector').hide();
}
/**
* Read dejault config
*/
_readDefaultConfig() {
// default values for system-wide configurable parameters
this.defaultConfig = {
indent: 4
};
// default values for per-notebook configurable parameters
this.metadataSettings = {
vp_config_version: '1.0.0',
vp_signature: 'VisualPython',
vp_position: {},
vp_section_display: false,
vp_note_display: false,
vp_menu_width: Config.MENU_MIN_WIDTH,
vp_note_width: Config.BOARD_MIN_WIDTH
};
let vp_width = Config.MENU_MIN_WIDTH + (this.metadataSettings.vp_note_display? Config.BOARD_MIN_WIDTH: 0) + Config.MENU_BOARD_SPACING;
this.metadataSettings['vp_position'] = {
// height: 'calc(100% - 110px)',
// width: vp_width + 'px',
// right: '0px',
// top: '110px',
width: vp_width
}
// merge default config
$.extend(true, this.defaultConfig, this.metadataSettings);
}
_readUserCommandList() {
let divider = '#'.repeat(6);
// get list of codes (ignore first 2 items)
let tmpList = userCommandFile.split(divider).slice(2);
// match key-codes-description
// { 'func_name': { code: '', description: '' } }
let funcDict = {};
let reg = /^def (.+)\(/;
let name = '';
let code = '';
let desc = '';
let packageAlias = {
'_vp_np': 'np',
'_vp_pd': 'pd',
'_vp_plt': 'plt',
'_vp_stats': 'stats',
'_vp_sm': 'sm'
}
for (let i = 0; i < tmpList.length; i += 2) {
desc = tmpList[i].trim();
code = tmpList[i + 1].trim();
let regResult = reg.exec(code);
if (regResult !== null) {
name = regResult[1];
// convert code's package alias
Object.keys(packageAlias).forEach(key => {
let desAlias = packageAlias[key];
code = code.replaceAll(key + '.', desAlias + '.');
});
// list up
funcDict[name] = { code: code, type: 'function', description: desc };
}
}
this.moduleDict = {
...this.moduleDict,
...funcDict
}
}
/**
* Read kernel functions for using visualpython
* - manually click restart menu (MenuFrame.js)
* - automatically restart on jupyter kernel restart (loadVisualpython.js)
*/
readKernelFunction() {
let that = this;
// CHROME: change method to load py files ($.get -> require)
return new Promise(function(resolve, reject) {
// if (that.extensionType === 'lite') {
// that.showProtector('Kernel loading', 'Required inner function is loading now...');
// }
var libraryList = [
printCommand, fileNaviCommand, pandasCommand, variableCommand, visualizationCommand
];
let promiseList = [];
// libraryList.forEach(libName => {
// var libPath = com_Const.PYTHON_PATH + libName;
// $.get(libPath).done(function(data) {
// var code_init = data;
// promiseList.push(vpKernel.execute(code_init, true));
// }).fail(function() {
// console.log('visualpython - failed to read library file', libName);
// });
// });
libraryList.forEach(libCode => {
promiseList.push(vpKernel.execute(libCode, true));
});
if (that.extensionType === 'lite') {
let preInstallCode = '';
let preInstallPackList = [
'seaborn',
'plotly',
'scikit-learn',
'scipy',
'statsmodels'
];
preInstallPackList.forEach((packName, idx) => {
preInstallCode += '%pip install ' + packName
if (idx < preInstallPackList.length - 1) {
preInstallCode += '\n';
}
});
// pre-install packages
promiseList.push(vpKernel.execute(preInstallCode, true));
}
// run all promises
let failed = false;
Promise.all(promiseList).then(function(resultObj) {
;
}).catch(function(resultObj) {
failed = true;
console.log('visualpython - failed to load library', resultObj);
// TODO: show to restart kernel
}).finally(function() {
// if (that.extensionType === 'lite') {
// that.hideProtector();
// }
if (!failed) {
console.log('visualpython - loaded libraries', libraryList);
resolve(true);
} else {
reject(false);
}
});
});
}
getMode() {
return Config.serverMode;
}
_checkMounted() {
return new Promise(function(resolve, reject) {
try {
vpKernel.getColabMounted().then(function(result) {
if (result==='True') {
resolve(true);
} else {
reject(false);
}
}).catch(function(err) {
reject(false);
})
} catch (ex) {
reject(false);
}
});
}
/**
* CHROME: Read from colab
* @param {*} configKey config key to read
*/
_readFromColab(configKey='vpudf') {
return new Promise(function(resolve, reject) {
// mounted
// read /content/drive/MyDrive/.visualpython
vpKernel.getColabConfig(configKey).then(function(resultObj) {
let { result } = resultObj;
try {
if (result && result.trim() != '') {
let parsedResult = JSON.parse(result);
resolve(parsedResult);
} else {
resolve({});
}
} catch (err) {
reject(err);
}
}).catch(function(err) {
reject(err);
})
});
}
/**
* CHROME: Write to colab
* @param {*} data data to write
*/
_writeToColab(data={}, configKey='vpudf') {
return new Promise(function(resolve, reject) {
// mounted
// write to /content/drive/MyDrive/.visualpython
vpKernel.setColabConfig(JSON.stringify(data), configKey).then(function(result) {
resolve(result);
}).catch(function(err) {
reject(err);
});
});
}
/**
* LAB: Read from lab
* @param {*} configKey config key to read
*/
_readFromLab(configKey='vpudf') {
return new Promise(function(resolve, reject) {
// mounted
// read USER_PATH/.visualpython
vpKernel.getLabConfig(configKey).then(function(resultObj) {
let { result } = resultObj;
try {
if (result && result.trim() != '') {
let parsedResult = JSON.parse(result);
resolve(parsedResult);
} else {
resolve({});
}
} catch (err) {
reject(err);
}
}).catch(function(err) {
reject(err);
})
});
}
/**
* LAB: Write to lab
* @param {*} data data to write
*/
_writeToLab(data={}, configKey='vpudf') {
return new Promise(function(resolve, reject) {
// write to USER_PATH/.visualpython
vpKernel.setLabConfig(JSON.stringify(data), configKey).then(function(result) {
resolve(result);
}).catch(function(err) {
reject(err);
});
});
}
loadData(configKey = 'vpudf') {
let that = this;
return new Promise(function(resolve, reject) {
if (that.extensionType === 'notebook') {
Jupyter.notebook.config.load();
Jupyter.notebook.config.loaded.then(function() {
var data = Jupyter.notebook.config.data[configKey];
if (data == undefined) {
data = {};
}
resolve(data);
});
} else if (that.extensionType === 'colab') {
// CHROME: edited to use .visualpython files
that._checkMounted().then(function() {
that._readFromColab('', configKey).then(function(result) {
resolve(result);
}).catch(function(err) {
reject(err);
})
}).catch(function() {
// not mounted
reject('Colab Drive is not mounted!');
})
} else if (that.extensionType === 'lab' || that.extensionType === 'lite') {
// LAB: edited to use .visualpython files
that._readFromLab('', configKey).then(function(result) {
resolve(result);
}).catch(function(err) {
reject(err);
})
}
});
};
/**
* Get configuration data (on server)
* @param {String} dataKey
* @param {String} configKey
* @returns
*/
getData(dataKey='', configKey='vpudf') {
let that = this;
return new Promise(function(resolve, reject) {
if (that.extensionType === 'notebook') {
Jupyter.notebook.config.load();
Jupyter.notebook.config.loaded.then(function() {
var data = Jupyter.notebook.config.data[configKey];
if (data == undefined) {
resolve(data);
return;
}
if (dataKey == '') {
resolve(data);
return;
}
if (Object.keys(data).length > 0) {
resolve(data[dataKey]);
return;
}
reject('No data available.');
});
} else if (that.extensionType === 'colab') {
// CHROME: use drive .visualpython files
that._checkMounted().then(function() {
that._readFromColab(configKey).then(function(result) {
let data = result;
if (data == undefined || (data instanceof Object && Object.keys(data).length === 0)) {
resolve(data);
return;
}
if (dataKey == '') {
resolve(data);
return;
}
if (data instanceof Object && Object.keys(data).length > 0) {
resolve(data[dataKey]);
return;
}
reject('No data available.');
}).catch(function(err) {
reject(err);
})
}).catch(function() {
// not mounted
reject('Colab Drive is not mounted!');
})
} else if (that.extensionType === 'lab' || that.extensionType === 'lite') {
// LAB: use local .visualpython files
that._readFromLab(configKey).then(function(result) {
let data = result;
if (data == undefined || (data instanceof Object && Object.keys(data).length === 0)) {
resolve(data);
return;
}
if (dataKey == '') {
resolve(data);
return;
}
if (data instanceof Object && Object.keys(data).length > 0) {
resolve(data[dataKey]);
return;
}
reject('No data available.');
}).catch(function(err) {
reject(err);
})
}
});
}
getDataSimple(dataKey='', configKey='vpudf') {
if (this.extensionType === 'notebook') {
Jupyter.notebook.config.load();
var data = Jupyter.notebook.config.data[configKey];
if (data == undefined) {
return undefined;
}
if (dataKey == '') {
return data;
}
if (Object.keys(data).length > 0) {
return data[dataKey];
}
} else if (this.extensionType === 'colab') {
// CHROME: TODO: no way to simply get data
return undefined;
}
return undefined;
}
/**
* Set configuration data (on server)
* @param {Object} dataObj
* @param {String} configKey vpcfg / vpudf / vpimport / vppackman
*/
setData(dataObj, configKey='vpudf') {
let that = this;
return new Promise(function(resolve, reject) {
if (that.extensionType === 'notebook') {
// set data using key
Jupyter.notebook.config.loaded.then(function() {
Jupyter.notebook.config.update({[configKey]: dataObj});
resolve(true);
});
} else if (that.extensionType === 'colab') {
// CHROME: use .visualpython files
that.getData('', configKey).then(function(data) {
let newDataObj = {};
if (data && typeof data === 'object') {
newDataObj = {
...data
};
}
newDataObj = {
...newDataObj,
...dataObj
}
that._writeToColab(newDataObj, configKey).then(function() {
resolve();
}).catch(function() {
reject();
});
});
} else if (that.extensionType === 'lab' || that.extensionType === 'lite') {
// LAB: use .visualpython files
that.getData('', configKey).then(function(data) {
let newDataObj = {};
if (data && typeof data === 'object') {
newDataObj = {
...data
};
}
newDataObj = {
...newDataObj,
...dataObj
}
that._writeToLab(newDataObj, configKey).then(function() {
resolve();
}).catch(function() {
reject();
});
});
}
});
}
removeData(key, configKey = 'vpudf') {
let that = this;
return new Promise(function(resolve, reject) {
if (that.extensionType === 'notebook') {
// if set value to null, it removes from config data
Jupyter.notebook.config.loaded.then(function() {
Jupyter.notebook.config.update({[configKey]: {[key]: null}});
});
resolve(true);
} else if (that.extensionType === 'colab') {
// CHROME: use .visualpython files
that.getData('', configKey).then(function(data) {
let dataObj = data;
delete dataObj[key];
that._writeToColab(dataObj, configKey).then(function() {
resolve(true);
}).catch(function() {
reject(false);
});
}).catch(function(err) {
reject(false);
})
} else if (that.extensionType === 'lab' || that.extensionType === 'lite') {
// LAB: use .visualpython files
that.getData('', configKey).then(function(data) {
let dataObj = data;
delete dataObj[key];
that._writeToLab(dataObj, configKey).then(function() {
resolve(true);
}).catch(function() {
reject(false);
});
}).catch(function(err) {
reject(false);
})
}
});
}
/**
* Get metadata (on jupyter file)
* @param {String} dataKey
* @param {String} configKey
*/
getMetadata(dataKey='', configKey='vp') {
if (this.extensionType === 'notebook') {
let metadata = Jupyter.notebook.metadata[configKey];
if (metadata) {
// update this metadataSetting
this.metadataSettings = {
...this.metadataSettings,
...metadata
};
// no datakey, return all metadata
if (dataKey == '') {
return metadata;
}
return metadata[dataKey];
}
} else if (this.extensionType === 'colab') {
// CHROME: use colab.global.notebookModel.metadata
let metadata = colab.global.notebookModel.metadata[configKey];
if (metadata) {
// update this metadataSetting
this.metadataSettings = {
...this.metadataSettings,
...metadata
};
// no datakey, return all metadata
if (dataKey == '') {
return metadata;
}
return metadata[dataKey];
}
}
return {};
}
/**
* Set metadata (on jupyter file)
* @param {Object} dataObj
* @param {String} configKey
*/
setMetadata(dataObj, configKey='vp') {
if (this.extensionType === 'notebook') {
let oldData = Jupyter.notebook.metadata[configKey];
Jupyter.notebook.metadata[configKey] = {
...oldData,
...dataObj
};
Jupyter.notebook.set_dirty();
} else if (this.extensionType === 'colab') {
// CHROME: use colab.global.notebookModel.metadata
let oldData = colab.global.notebookModel.metadata[configKey];
colab.global.notebookModel.metadata[configKey] = {
...oldData,
...dataObj
};
}
// update this metadataSetting
this.metadataSettings = {
...this.metadataSettings,
...dataObj
};
}
/**
* Reset metadata (on jupyter file)
* @param {String} configKey
*/
resetMetadata(configKey='vp') {
if (this.extensionType === 'notebook') {
Jupyter.notebook.metadata[configKey] = {};
} else if (this.extensionType === 'colab') {
// CHROME: use colab.global.notebookModel.metadata
colab.global.notebookModel.metadata[configKey] = {};
}
}
/**
* Check vp pypi package version (Promise)
* usage:
* vpConfig.getPackageVersion('visualpython').then(function(version) {
* // do something after loading version
* ...
* }).catch(function(err) {
* // error handling
* ...
* })
*/
getPackageVersion(packName='visualpython') {
let url = `https://pypi.org/pypi/${packName}/json`;
// using the Fetch API
return new Promise(function(resolve, reject) {
try {
fetch(url).then(function (response) {
// if (response.statusCode === 200) {
// return response.json();
// } else if (response.statusCode === 204) {
// throw new Error('No Contents', response);
// } else if (response.statusCode === 404) {
// throw new Error('Page Not Found', response);
// } else if (response.statusCode === 500) {
// throw new Error('Internal Server Error', response);
// } else {
// throw new Error('Unexpected Http Status Code', response);
// }
if (response.ok) {
return response.json();
} else {
throw new Error('Error', response);
}
}).then(function (data) {
resolve(data.info.version, data.releases);
}).catch(function(err) {
let errMsg = err.message;
if (errMsg.includes('Failed to fetch')) {
errMsg = 'Network connection error';
}
reject(errMsg);
});
} catch (err) {
reject(err);
}
});
}
getVpInstalledVersion() {
return Config.version;
}
checkVersionTimestamp = function() {
let that = this;
// check version timestamp
let nowDate = new Date();
this.getData('version_timestamp', 'vpcfg').then(function(data) {
let doCheckVersion = false;
vpLog.display(VP_LOG_TYPE.DEVELOP, 'Checking its version timestamp... : ' + data);
if (data == undefined || (data instanceof Object && Object.keys(data).length === 0)) {
// no timestamp, check version
doCheckVersion = true;
} else if (data != '') {
let lastCheck = new Date(parseInt(data));
let diffCheck_now = new Date(nowDate.getFullYear(), nowDate.getMonth() + 1, nowDate.getDate());
let diffCheck_last = new Date(lastCheck.getFullYear(), lastCheck.getMonth() + 1, lastCheck.getDate());
let diff = Math.abs(diffCheck_now.getTime() - diffCheck_last.getTime());
diff = Math.ceil(diff / (1000 * 3600 * 24));
if (diff >= 1) {
// if More than 1 day passed, check version
doCheckVersion = true;
}
}
// check version and update version_timestamp
if (doCheckVersion == true) {
that.checkVpVersion(true);
}
}).catch(function(err) {
vpLog.display(VP_LOG_TYPE.ERROR, err);
})
}
checkVpVersion(background=false) {
let that = this;
let nowVersion = this.getVpInstalledVersion();
let packageName = 'visualpython';
if (this.extensionType === 'lab' || this.extensionType === 'lite') {
packageName = 'jupyterlab-visualpython';
}
this.getPackageVersion(packageName).then(function(latestVersion) {
let showUpdater = false;
if (nowVersion !== latestVersion) {
let nowVerParts = nowVersion.split('.').map(x => ~~x);
let latVerParts = latestVersion.split('.').map(x => ~~x);
for (var i = 0; i < nowVerParts.length; i++) {
const a = nowVerParts[i];
const b = latVerParts[i];
if (a < b) {
showUpdater = true;
break;
} else if (a > b) {
break;
}
}
}
if (showUpdater === false) {
// if it's already up to date
// hide version update icon
$('#vp_versionUpdater').hide();
if (background === true) {
;
} else {
let msg = com_util.formatString('Visual Python is up to date. ({0})', nowVersion);
com_util.renderInfoModal(msg);
}
// update version_timestamp
that.setData({ 'version_timestamp': new Date().getTime() }, 'vpcfg');
} else {
let msg = com_util.formatString('Visual Python updates are available.<br/>(Latest version: {0} / Your version: {1})',
latestVersion, nowVersion);
// show version update icon
$('#vp_versionUpdater').attr('title', msg.replace('<br/>', ''));
$('#vp_versionUpdater').data('version', latestVersion);
$('#vp_versionUpdater').show();
// render update modal
com_util.renderModal({
title: 'Update version',
message: msg,
buttons: ['Cancel', 'Update'],
defaultButtonIdx: 0,
buttonClass: ['cancel', 'activated'],
finish: function(clickedBtnIdx) {
switch (clickedBtnIdx) {
case 0:
// cancel
// update version_timestamp
that.setData({ 'version_timestamp': new Date().getTime() }, 'vpcfg');
break;
case 1:
// update
if (that.extensionType === 'notebook') {
let info = [
'## Visual Python Upgrade',
'NOTE: ',
'- Refresh your web browser to start a new version.',
'- Save VP Note before refreshing the page.'
];
com_interface.insertCell('markdown', info.join('\n'));
com_interface.insertCell('code', '!pip install visualpython --upgrade');
com_interface.insertCell('code', '!visualpy install');
} else if (that.extensionType === 'colab') {
// CHROME: update chrome extension
let info = [
'## Visual Python Upgrade',
'NOTE: ',
'- Go to chrome webstore and update visualpython',
'- Refresh your web browser to start a new version.',
'- Save VP Note before refreshing the page.'
];
com_interface.insertCell('markdown', info.join('\n'));
} else if (that.extensionType === 'lab') {
// LAB: update lab extension
let info = [
'## Visual Python Upgrade',
'NOTE: ',
'- Refresh your web browser to start a new version.',
'- Save VP Note before refreshing the page.'
];
com_interface.insertCell('markdown', info.join('\n'));
com_interface.insertCell('code', '!pip install jupyterlab-visualpython --upgrade');
} else if (that.extensionType === 'lite') {
// LITE: update lab extension on lite
let info = [
'## Visual Python Upgrade',
'NOTE: ',
'- Refresh your web browser to start a new version.',
'- Save VP Note before refreshing the page.'