This repository has been archived by the owner on May 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
1018 lines (833 loc) · 32.1 KB
/
main.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
'use strict';
// you have to require the utils module and call adapter function
const utils = require(__dirname + '/lib/utils'); // Get common adapter utils
const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const os = require('os');
const fs = require('fs');
const request = require('request');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
let plattform = os.platform();
// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.adapter_studio.0
const adapter = new utils.Adapter('adapter-studio');
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', (callback) => {
try {
adapter.log.info('cleaned everything up...');
callback();
} catch (e) {
callback();
}
});
// is called if a subscribed object changes
adapter.on('objectChange', (id, obj) => {
// Warning, obj can be null if it was deleted
adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj));
});
// is called if a subscribed state changes
adapter.on('stateChange', (id, state) => {
// Warning, state can be null if it was deleted
adapter.log.info('stateChange ' + id + ' ' + JSON.stringify(state));
// you can use the ack flag to detect if it is status (true) or command (false)
if (state && !state.ack) {
adapter.log.info('ack is not set!');
}
});
// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', (obj) => {
adapter.log.info(JSON.stringify(obj));
if (typeof obj === 'object' && obj.message) {
if (obj.command === 'send') {
// e.g. send email or pushover or whatever
//adapter.log.debug('send command');
// Send response in callback if required
//if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
if(obj.message === 'getAdapterList'){
getAdapters((res) => {
//adapter.log.info(`Callback ${res}`);
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
})
}
if(obj.message.command === 'getAdapterFiles'){
getAdapterFiles(obj.message.folder, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'openFile'){
openFile(obj.message.file, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'saveFile'){
saveFile(obj.message.file, obj.message.data, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'uploadFiles'){
uploadFiles(obj.message.adapterName, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'ssAdapter'){
ssAdapter(obj.message.adapterName, obj.message.cmd, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'createAdapter'){
createAdapter(obj.message, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'getRunningState'){
getRunningState(obj.message.adapterName, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'npmPublish'){
npmPublish(obj.message.adapterName, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'npmAddUser'){
npmAdduser(obj.message.user, obj.message.password, obj.message.email, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'checkoutGithub'){
checkoutGithub(obj.message.link, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'githubPublish'){
createNewGHRepo(obj.message.adapterName, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
if(obj.message.command === 'updateVersion'){
updateVersion(obj.message.typeOfUpdate, obj.message.changes, obj.message.adapterName, (res) => {
if (obj.callback) adapter.sendTo(obj.from, obj.command, res, obj.callback);
});
}
}
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', () => {
main();
});
function main() {
adapter.log.info(plattform);
adapter.log.info(__dirname);
}
let ready = true;
let s;
switch(plattform){
case 'win32':
s = '\\';
break;
case 'linux':
s = '/';
break;
}
function createAdapter(data, callback){
//adapter.log.info(JSON.stringify(data));
let newName = data.name;
newName = newName.replace(' ', '-');
newName = newName.toLowerCase();
let odir = __dirname;
let path = odir.replace('iobroker.adapter-studio', `iobroker.${newName}`);
let remove = ['.git'];
let addFiles = [];
let newFile = [];
if(data.widgets === false){
remove.push('widgets')
}
if(data.webpage === false){
remove.push('www')
}
if(data.adminv2 === false){
remove.push(`admin${s}index.html`);
}
if(data.license !== 'MIT'){
let folder = `${s}licenses${s}`;
remove.push('LICENSE');
switch(data.license){
case 'Apache 2.0':
addFiles.push(`${folder}Apache_2.0`);
break;
case 'CC-BY':
addFiles.push(`${folder}CC-BY`);
break;
case 'CC-BY-NC':
addFiles.push(`${folder}CC-BY-NC`);
break;
case 'CC-BY-NC-SA':
addFiles.push(`${folder}CC-BY-NC-SA`);
break;
case 'OFL-1.1':
addFiles.push(`${folder}OFL_1.1`);
break;
case 'EPL':
addFiles.push(`${folder}EPL`);
break;
case 'LGPL':
addFiles.push(`${folder}LGPL_v3`);
break;
case 'GPLv3':
addFiles.push(`${folder}GPLv3`);
break;
case 'GPLv2':
addFiles.push(`${folder}GPLv2`);
break;
}
newFile.push('LICENSE');
}
if(data.adminv2 === true){
addFiles.push('tab.html');
newFile.push(`admin${s}tab.html`);
}
if(data.tab === true){
addFiles.push('tab_m.html');
addFiles.push('tab.js');
newFile.push(`admin${s}tab_m.html`);
newFile.push(`admin${s}tab.js`);
}
let gclone = `git clone --depth=1 https://github.com/ioBroker/ioBroker.template.git ${path}`;
let child = exec(gclone);
child.stderr.pipe(process.stdout);
child.on('exit', () => {
//if (callback) callback(adapter);
for(let i = 0; i <= remove.length -1; i++){
let rm = new RemoveFaF(remove[i], path);
}
for(let i = 0; i <= addFiles.length -1; i++){
let rm = new AddTFiles(addFiles[i], path, newFile[i]);
}
fs.readFile(`${path}${s}io-package.json`, (err, output) => {
let json = JSON.parse(output);
if (err) throw err;
if(data.mode.toLowerCase() === 'schedule'){
json.common.schedule = data.cron
}
json.common.mode = data.mode.toLowerCase();
json.common.license = data.license;
json.common.enabled = data.enabled;
json.common.loglevel = data.logLevel;
json.common.type = data.type;
json.common.messagebox = data.messagebox;
if(data.tab === true){
json.common.materializeTab = true;
json.common.adminTab = {"name": newName};
}
//Keywords
let keywords = data.keywords;
keywords = keywords.split(', ');
json.common.keywords = keywords;
json.common.version = '0.0.1';
json.common.news = {"0.0.1": { "en": "initial version created with Adapter-Studio by Jey Cee", "de": "erste Version erstellt mit Adapter-Studio von Jey Cee", "ru": "начальная версия, созданная с помощью Adapter-Studio by Jey Cee", "pt": "versão inicial criada com o Adapter-Studio por Jey Cee", "nl": "eerste versie gemaakt met Adapter-Studio door Jey Cee", "fr": "Version initiale créée avec Adapter-Studio par Jey Cee", "it": "versione iniziale creata con Adapter-Studio di Jey Cee", "es": "versión inicial creada con Adapter-Studio por Jey Cee", "pl": "początkowa wersja stworzona za pomocą Adapter-Studio przez Jey Cee"}};
if(data.widgets === true){
json.restartAdapters = ["vis"];
}
//Adapter dependencies
if(data.depAdapters.length === 0){
}else {
let adapters = data.depAdapters;
adapters = adapters.split(', ');
let arr = {};
for (let i in adapters) {
let x = adapters[i].split(' ');
arr[x[0]] = `${x[1]}`;
}
//let jsonArr = `"dependencies": [${arr}]`;
json.common.dependencies = arr;
}
fs.writeFile(`${path}${s}io-package.json`, JSON.stringify(json, null, 4), (err) => {
if (err) throw err;
adapter.log.info('The file io-package.json has been saved!');
});
});
fs.readFile(`${path}${s}package.json`, (err, output) => {
let json = JSON.parse(output);
if (err) throw err;
json.license = data.license;
json.version = '0.0.1';
//Keywords
let keywords = data.keywords;
keywords = keywords.split(', ');
json.keywords = keywords;
//dependencies
if(data.dependencies.length > 0){
let dependencies = data.dependencies;
dependencies = dependencies.split(', ');
let arr = {};
for(let i in dependencies){
let x = dependencies[i].split(' ');
arr[x[0]] = `${x[1]}`;
}
if(arr.length === 0){
json.dependencies = '';
}else{
json.dependencies = arr;
}
}
json.scripts = {"gulp": "gulp"};
fs.writeFile(`${path}${s}package.json`, JSON.stringify(json, null, 4), (err) => {
let email = data.email;
let author = data.author;
adapter.log.info(`rename information: ${email}, ${author}`);
if (err) throw err;
adapter.log.info('The file package.json has been saved!');
installDependencies(path, (data)=>{
if(data === 'Error'){
callback('Error');
}else{
adapter.log.info(`rename information: ${email}, ${author}`);
rename(path, newName, email, author, () => {
let cmd = 'git init & git add .';
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
if(code === 0){
callback('Error')
}else{
callback('Done')
}
child.stderr.on('data',(data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data',(data) => {
adapter.log.info('stdout: ' + data.toString());
});
});
});
}
});
});
});
});
}
function RemoveFaF(name, path){
ready = false;
let cmd;
switch(plattform){
case 'win32':
cmd = `del /Q /S /F ${name} & rd /S /Q ${name}`;
break;
case 'linux':
cmd = `rm -r ${name}`;
break;
}
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', () => {
});
}
function AddTFiles(file, path, newFile){
ready = false;
let cmd;
switch(plattform){
case 'win32':
cmd = `copy ${__dirname}\\templates\\${file} ${newFile}`;
break;
case 'linux':
cmd = `mv ${__dirname}/templates/${file} ${newFile}`;
break;
}
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', () => {
});
}
function cacheClean(path, callback){
let cmd = `npm cache clean --force`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code cache clean: ${code}`);
callback('Done')
});
}
function installDependencies(path, callback){
cacheClean(path, (result)=>{
if(result === 'Done'){
let cmd = `npm install`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code install dependencies: ${code}`);
if(code === 0){
let cmd = `npm install --only=dev`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code install dev dependencies: ${code}`);
if(code === 0){
callback('Done');
}else{
callback('Error');
}
});
}else{
callback('Error');
}
});
}
})
}
function rename(path, name, email, author, callback){
let cmd = `npm install --global gulp-cli`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
let cmd = `npm run gulp -- rename --name ${name} --email ${email} --author "${author}"`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
if (code !== 0) {
callback('Error');
} else {
callback('Done');
}
});
child.stderr.on('data',(data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data',(data) => {
adapter.log.info('stdout: ' + data.toString());
});
});
child.stderr.on('data',(data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data',(data) => {
adapter.log.info('stdout: ' + data.toString());
});
}
function getAdapters(callback){
//adapter.log.debug('Get list of adapters');
let odir = __dirname;
let node_modules = odir.replace('iobroker.adapter-studio', ``);
fs.readdir(node_modules,(err, files) =>{
let arrA = [];
for(let x in files){
const patt = new RegExp(/io(b|B)roker..*/g);
const patt2 = new RegExp(/.rar$/g);
let name = files[x].match(patt);
if(name !== null){
let nA = name[0].match(patt2);
if(nA === null) {
arrA.push(name[0]);
}
}
}
callback(arrA);
})
}
function getAdapterFiles(name, callback){
let odir = __dirname;
let folder;
const patt = new RegExp(/.io(b|B)roker\.\w*.\w*.\w*/g);
let test = name.match(patt);
if(test !== null){
if(plattform === 'win32'){
let patt2 = new RegExp('/', 'g');
name = name.replace(patt2, s);
}
folder = name;
}else{
folder = odir.replace('iobroker.adapter-studio', `${s}${name}`);
}
fs.readdir(folder,(err, files) => {
if(err){adapter.log.error(err)}
let arrA = {};
for (let x in files) {
if(fs.lstatSync(`${folder}${s}${files[x]}`).isDirectory()){
arrA[x] = {"name": files[x], "type": "folder", "parent": folder};
}else{
arrA[x]= {"name": files[x], "type": "file", "parent": folder};
}
}
adapter.log.info('Read files');
callback(arrA);
});
}
function openFile(file, callback){
adapter.log.info('open file');
if(plattform === 'win32'){
let patt2 = new RegExp('/', 'g');
file = file.replace(patt2, s);
}
const patt = new RegExp('.png');
let res = patt.test(file);
fs.readFile(file, (err, output) => {
if(err){adapter.log.error(err)};
//adapter.log.debug(output);
if(!res){
callback(output)
}else{
let Buffer = require('buffer').Buffer;
let picture = Buffer.from(output).toString('base64');
callback(picture);
}
})
}
function saveFile(file, data, callback){
if(plattform === 'win32'){
let patt2 = new RegExp('/', 'g');
file = file.replace(patt2, s);
}
fs.writeFile(file, data, (err, output) => {
if (err) throw err;
adapter.log.info(`The file ${file} has been saved!`);
callback('Done');
})
}
function uploadFiles(adapterName, callback){
let odir = __dirname;
let baseDir = odir.match(/.*io(b|B)roker(\/|\\)/);
//baseDir = JSON.stringify(baseDir[0]);
exec(`iobroker upload ${adapterName}`, {cwd: baseDir[0]}, (error, stderr, stdout) => {
//adapter.log.info('stdout: ' + stdout);
//adapter.log.info('stderr: ' + stderr);
if (error !== null) {
adapter.log.error('exec error: ' + error);
}
callback('Done');
});
}
function ssAdapter(adapterName, cmd, callback){
let odir = __dirname;
let baseDir = odir.match(/.*io(b|B)roker(\/|\\)/);
//baseDir = JSON.stringify(baseDir[0]);
exec(`iobroker ${cmd} ${adapterName}`, {cwd: baseDir[0]}, (error, stderr, stdout) => {
//adapter.log.info('stdout: ' + stdout);
//adapter.log.info('stderr: ' + stderr);
if (error !== null) {
adapter.log.error('exec error: ' + error);
}else {
const patt = new RegExp(/Adapter .* (started|stopped|restarted)./gm);
if (patt.test(stderr)) {
callback('Done');
} else if (patt.test(stdout)) {
callback('Done');
} else {
ssAdapter(adapterName, 'restart', callback);
}
}
});
}
function getRunningState(adapterName, callback){
adapter.getForeignState(`system.adapter.${adapterName}.0.alive`, (err, state) => {
adapter.log.info(JSON.stringify(state));
if(err){
callback('Error')
}else if(state === null){
callback('false')
}else if(state !== null && state !== undefined){
callback(state.val)
}
})
}
function npmPublish(adapterName, callback){
let odir = __dirname;
let path = odir.replace('iobroker.adapter-studio', `${s}${adapterName}`);
let cmd = `npm publish`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code npmPublish: ${code}`);
if(code === 4294963248){
callback('Login required')
}else if(code === 0){
callback('Done');
}else if(code > 0){
callback('Error')
}
});
child.stderr.on('data',(data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data',(data) => {
adapter.log.info('stdout: ' + data.toString());
});
}
function npmAdduser(user, password, email, callback){
let odir = __dirname;
let cmd = `npm adduser`;
const child = exec(cmd, {cwd: odir});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code npmPublish: ${code}`);
if (code === 0) {
callback('Done');
} else if (code > 0) {
callback('Error')
}
});
child.stdin.write(user + '\n' + password + '\n' +email + '\n');
//child.stdin.write(password + '\n');
//child.stdin.write(email + '\n');
child.stderr.on('data', (data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data', (data) => {
adapter.log.info('stdout: ' + data.toString());
switch(data.toString().trim()){
case 'Username:':
child.stdin.write(user + '\n');
break;
case 'Password:':
child.stdin.write(password + '\n');
break;
case 'Email: (this IS public)':
child.stdin.write(email + '\n');
break;
}
});
//child.stdin.end();
}
function createNewGHRepo(adapterName, callback){
let token = adapter.config.ghtoken;
let content = JSON.stringify({"scope": "repo", "name": adapterName, "has_wiki": "false"});
let options = {
url: 'https://api.github.com/user/repos',
method: 'POST',
headers: {
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json; charset=utf-8',
'User-Agent': 'Adapter Studio (ioBroker)',
'Content-Length': content.length,
'Authorization': `token ${token}`
}
};
let req = request(options, function (error, res, body){
if(error){
callback('Error');
adapter.log.error(error);
}
adapter.log.info('STATUS: ' + res.statusCode);
switch(res.statusCode){
case 422:
callback('Error');
adapter.log.info('Repo already exists on this account: ' + body);
adapter.log.info('options: ' + JSON.stringify(options));
break;
case 404:
callback('Error');
adapter.log.info('Create repo not found: ' + body);
adapter.log.info('options: ' + JSON.stringify(options));
break;
case 403:
callback('Error');
adapter.log.info('Create repo forbidden: ' + body);
break;
case 401:
callback('Error');
adapter.log.info('Unauthorized: ' + body);
break;
case 400:
callback('Error');
adapter.log.info('Bad request: ' + body);
break;
case 201:
commitToGH(adapterName, 'Initial commit (by ioBroker Adapter Studio)', true, callback);
adapter.log.info('Repository successfully created');
break;
case 200:
commitToGH(adapterName, 'Initial commit (by ioBroker Adapter Studio)', true, callback);
adapter.log.info('Repository successfully created');
break;
}
});
req.write(content);
}
function commitToGH(adapterName, commitMessage, initial, callback){
let user = adapter.config.ghuser;
let email = adapter.config.ghemail;
let odir = __dirname;
let path = odir.replace(`${s}iobroker.adapter-studio`, `${s}${adapterName}`);
let cmd = `git config --global user.name "${user}" & git config --global user.email "${email}" & git add -u & git commit -m "${commitMessage}"`;
let child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
adapter.log.info('adapterName: ' + adapterName + ' Commit message: ' + commitMessage + ' Initial: ' + initial + ' User: ' + user + ' Path: ' + path);
child.on('exit', (code) => {
adapter.log.info(`Exit code commitToGH: ${code}`);
if (code === 0) {
if(initial === true) {
cmd = `git remote add origin https://github.com/${user}/${adapterName}.git`;
child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code commitToGH: ${code}`);
if (code === 0) {
cmd = `git push -u origin master --force`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code commitToGH: ${code}`);
if (code === 0) {
callback('Done');
} else if (code > 0) {
callback('Error')
}
});
} else if (code > 0) {
callback('Error')
}
});
child.stderr.on('data', (data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data', (data) => {
adapter.log.info('stdout: ' + data.toString());
});
}else if (initial === false){
cmd = `git push - u origin master`;
child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code commitToGH: ${code}`);
if (code === 0) {
callback('Done');
} else if (code > 0) {
callback('Error')
}
});
child.stderr.on('data', (data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data', (data) => {
adapter.log.info('stdout: ' + data.toString());
});
}
} else if (code > 0) {
callback('Error');
}
});
child.stderr.on('data', (data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data', (data) => {
adapter.log.info('stdout: ' + data.toString());
});
}
function checkoutGithub(link, callback){
let odir = __dirname;
let path = odir.replace(`${s}iobroker.adapter-studio`, ``);
let cmd = `git clone ${link}`;
const child = exec(cmd, {cwd: path});
child.stderr.pipe(process.stdout);
child.on('exit', (code) => {
adapter.log.info(`Exit code checkoutGithub: ${code}`);
if (code === 0) {
callback('Done');
} else if (code > 0) {
callback('Error')
}
});
child.stderr.on('data', (data) => {
adapter.log.info('stderr: ' + data.toString());
});
child.stdout.on('data', (data) => {
adapter.log.info('stdout: ' + data.toString());
});
}
function updateVersion(typeOfUpdate, changes, adapterName, callback){
let newVersion;
let odir = __dirname;
let path = odir.replace('iobroker.adapter-studio', `${s}${adapterName}`);
fs.readFile(`${path}${s}package.json`, (err, output) => {
let json = JSON.parse(output);
if (err) throw err;
let oldVersion = json.version;
let arrVersion = oldVersion.split('.');
let patch;
let minor;
let major;
switch(typeOfUpdate){
case 'patch':
major = arrVersion[0];
minor = arrVersion[1];
patch = parseInt(arrVersion[2]) + 1;
break;
case 'minor':
major = arrVersion[0];
minor = parseInt(arrVersion[1]) + 1;
patch = 0;
break;
case 'major':
major = parseInt(arrVersion[0]) + 1;
minor = 0;
patch = 0;
break;
}
newVersion = `${major}.${minor}.${patch}`;
json.version = newVersion;
fs.writeFile(`${path}${s}package.json`, JSON.stringify(json, null, 4), (err) => {
if (err) throw err;
});
fs.readFile(`${path}${s}io-package.json`, (err, output) => {
let json = JSON.parse(output);
if (err) throw err;
json.common.version = newVersion;
translateGoogleWeb(changes, (result) => {
adapter.log.info('result :' + JSON.stringify(result));
json.common.news[newVersion] = result;
fs.writeFile(`${path}${s}io-package.json`, JSON.stringify(json, null, 4), (err) => {
if (err) throw err;
});
});
});
fs.readFile(`${path}${s}README.md`, 'utf8', (err, output) => {
if (err) throw err;
let n = output.indexOf('## Changelog');
let arrChanges = changes.split(';');
let addText = `\r\n\r\n### ${newVersion}\r\n`;
for(let obj in arrChanges){
if(arrChanges[obj] != ''){
addText += `* ${arrChanges[obj]}\r\n`
}
}
let newOutput = [output.slice(0, n+12), addText, output.slice(n+12)].join('');
fs.writeFile(`${path}${s}README.md`, newOutput, (err) => {
if (err) throw err;
});
});
});
}
function translateGoogleWeb(text, callback){
let langs = ['en', 'de', 'ru', 'pt', 'nl', 'fr', 'it', 'es', 'pl'];
let json = {
"en": "",
"de": "",
"ru": "",
"pt": "",
"nl": "",
"fr": "",
"it": "",
"es": "",
"pl": ""
};
for(let l in langs){
request(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${langs[l]}&dt=t&q=` + encodeURI(text), (error, res, body) =>{
adapter.log.info('STATUS: ' + res.statusCode);
if(res.statusCode === 403){
adapter.log.info('Access forbidden google translate');
}else if(res.statusCode === 200){