-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathgulpfile-disabled.js
4139 lines (4137 loc) · 177 KB
/
gulpfile-disabled.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
/* eslint-disable no-process-env,semi,space-infix-ops,block-spacing,object-shorthand,no-unused-vars,one-var */
try {
var dotenv = require('dotenv')
dotenv.config({path: './secrets/.env'});
} catch (e) {
console.error(e);
}
var QUANTIMODO_CLIENT_ID = process.env.QUANTIMODO_CLIENT_ID || process.env.CLIENT_ID;
var devCredentials;
var androidArm7DebugApkName = 'android-armv7-debug';
var androidX86DebugApkName = 'android-x86-debug';
var androidArm7ReleaseApkName = 'android-armv7-release';
var androidX86ReleaseApkName = 'android-x86-release';
/** @namespace process.env.DEBUG_BUILD */
/** @namespace process.env.BUILD_DEBUG */
/** @namespace process.env.DO_NOT_MINIFY */
function isTruthy(value) {return (value && value !== "false");}
//var buildPath = './build'; Can't use . because => Updated ....... app_uploads/quantimodo/./build/quantimodo-chrome-extension.zip
var buildPath = 'build';
var circleCIPathToRepo = '~/quantimodo-android-chrome-ios-web-app';
var chromeExtensionBuildPath = buildPath + '/chrome_extension';
var qmPlatform = {
buildingFor: {
getPlatformBuildingFor: function(){
if(qmPlatform.buildingFor.android()){return 'android';}
if(qmPlatform.buildingFor.ios()){return 'ios';}
if(qmPlatform.buildingFor.chrome()){return 'chrome';}
if(qmPlatform.buildingFor.web()){return 'web';}
qmLog.error("What platform are we building for?");
return null;
},
setChrome: function(){
qmPlatform.buildingFor.platform = qmPlatform.chrome;
},
platform: null,
web: function () {
return !qmPlatform.buildingFor.android() && !qmPlatform.buildingFor.ios() && !qmPlatform.buildingFor.chrome();
},
android: function () {
if (qmPlatform.buildingFor.platform === 'android'){ return true; }
if (process.env.BUDDYBUILD_SECURE_FILES) { return true; }
if (process.env.TRAVIS_OS_NAME === "osx") { return false; }
return process.env.BUILD_ANDROID;
},
ios: function () {
if (qmPlatform.buildingFor.platform === qmPlatform.ios){ return true; }
if (process.env.BUDDYBUILD_SCHEME) {return true;}
if (process.env.TRAVIS_OS_NAME === "osx") { return true; }
return process.env.BUILD_IOS;
},
chrome: function () {
if (qmPlatform.buildingFor.platform === qmPlatform.chrome){ return true; }
return process.env.BUILD_CHROME;
},
mobile: function () {
return qmPlatform.buildingFor.android() || qmPlatform.buildingFor.ios();
}
},
setBuildingFor: function(platform){
qmPlatform.buildingFor.platform = platform;
},
isOSX: function(){
return process.platform === 'darwin';
},
isLinux: function(){
return process.platform === 'linux';
},
isWindows: function(){
return !qmPlatform.isOSX() && !qmPlatform.isLinux();
},
getPlatform: function(){
if(qmPlatform.buildingFor){return qmPlatform.buildingFor;}
if(qmPlatform.isOSX()){return qmPlatform.ios;}
if(qmPlatform.isWindows()){return qmPlatform.android;}
return qmPlatform.web;
},
ios: 'ios',
android: 'android',
web: 'web',
chrome: 'chrome'
};
// Setup platforms to build that are supported on current hardware
// See https://taco.visualstudio.com/en-us/docs/tutorial-gulp-readme/
//var winPlatforms = ["android", "windows"], //Android is having problems so I'm only building windows for now
var winPlatforms = ['windows'],
linuxPlatforms = ['android'],
osxPlatforms = ['ios'],
platformsToBuild = process.platform === 'darwin' ? osxPlatforms :
(process.platform === 'linux' ? linuxPlatforms : winPlatforms),
// Build config to use for build - Use Pascal case to match paths set by VS
buildConfig = 'Release',
// Arguments for build by platform. Warning: Omit the extra "--" when referencing platform
// specific options (Ex:"-- --gradleArg" is "--gradleArg").
buildArgs = {
android: ['--' + buildConfig.toLocaleLowerCase(), '--device', '--gradleArg=--no-daemon'],
ios: ['--' + buildConfig.toLocaleLowerCase(), '--device'],
windows: ['--' + buildConfig.toLocaleLowerCase(), '--device']
},
// Paths used by build
buildPaths = {
tsconfig: 'scripts/tsconfig.json',
ts: './scripts/**/*.ts',
apk: ['./platforms/android/ant-build/*.apk',
'./platforms/android/bin/*.apk',
'./platforms/android/build/outputs/apk/*.apk'],
binApk: './bin/Android/' + buildConfig,
ipa: ['./platforms/ios/build/device/*.ipa',
'./platforms/ios/build/device/*.app.dSYM'],
binIpa: './bin/iOS/' + buildConfig,
appx: './platforms/windows/AppPackages/**/*',
binAppx: './bin/Windows/' + buildConfig
};
var appIds = {
'moodimodo': 'homaagppbekhjkalcndpojiagijaiefm',
'mindfirst': 'jeadacoeabffebaeikfdpjgpjbjinobl',
'energymodo': 'aibgaobhplpnjmcnnmdamabfjnbgflob',
'quantimodo': true,
'medimodo': true
};
var paths = {
apk: {//android\app\build\outputs\apk\release\app-release.apk
combinedRelease: "platforms/android/app/build/outputs/apk/release/app-release.apk",
combinedDebug: "platforms/android/app/build/outputs/apk/release/app-debug.apk",
arm7Release: "platforms/android/app/build/outputs/apk/release/app-arm7-release.apk",
x86Release: "platforms/android/app/build/outputs/apk/release/app-x86-release.apk",
outputFolder: "platforms/android/app/build/outputs/apk",
builtApk: null,
},
sass: ['./src/scss/**/*.scss'],
src:{
devCredentials: "src/dev-credentials.json",
defaultPrivateConfig: "src/default.private_config.json",
icons: "src/img/icons",
firebase: "src/lib/firebase/**/*",
js: "src/js/*.js",
serviceWorker: "src/firebase-messaging-sw.js",
data: "src/data",
},
www: {
devCredentials: "www/dev-credentials.json",
defaultPrivateConfig: "www/default.private_config.json",
icons: "www/img/icons",
firebase: "www/lib/firebase/",
js: "www/js/",
scripts: "www/scripts",
data: "www/data",
},
chcpLogin: '.chcplogin',
};
var argv = require('yargs').argv;
var defaultRequestOptions = {strictSSL: false};
var fs = require('fs');
var gulp = require('gulp');
var q = require('q');
var replace = require('gulp-string-replace');
var runSequence = require('run-sequence');
var AWS_ACCESS_KEY_ID = process.env.QM_AWS_ACCESS_KEY_ID || process.env.AWS_ACCESS_KEY_ID; // Netlify has their own
var AWS_SECRET_ACCESS_KEY = process.env.QM_AWS_SECRET_ACCESS_KEY || process.env.AWS_SECRET_ACCESS_KEY; // Netlify has their own
var s3Options = {accessKeyId: AWS_ACCESS_KEY_ID, secretAccessKey: AWS_SECRET_ACCESS_KEY};
var qmLog = {
error: function (message, metaData, maxCharacters) {
metaData = qmLog.addMetaData(metaData);
console.error(qmLog.obfuscateStringify(message, metaData, maxCharacters));
metaData.build_info = qmGulp.buildInfoHelper.getCurrentBuildInfo();
bugsnag.notify(new Error(qmLog.obfuscateStringify(message), qmLog.obfuscateSecrets(metaData)));
},
info: function (message, object, maxCharacters) {
if(typeof message !== "string"){
object = message;
message = null;
}
console.log(qmLog.obfuscateStringify(message, object, maxCharacters));
},
debug: function (message, object, maxCharacters) {
if(isTruthy(process.env.BUILD_DEBUG || process.env.DEBUG_BUILD)){
qmLog.info("DEBUG: " + message, object, maxCharacters);
}
},
logErrorAndThrowException: function (message, object) {
qmLog.error(message, object);
throw message;
},
addMetaData: function(metaData){
metaData = metaData || {};
metaData.environment = qmLog.obfuscateSecrets(process.env);
metaData.subsystem = { name: qmLog.getCurrentServerContext() };
metaData.client_id = QUANTIMODO_CLIENT_ID;
metaData.build_link = qmGulp.buildInfoHelper.getBuildLink();
return metaData;
},
obfuscateStringify: function(message, object, maxCharacters) {
if(maxCharacters !== false){maxCharacters = maxCharacters || 140;}
var objectString = '';
if(object){
object = qmLog.obfuscateSecrets(object);
objectString = ': ' + qmLog.prettyJSONStringify(object);
}
if (maxCharacters !== false && objectString.length > maxCharacters) {objectString = objectString.substring(0, maxCharacters) + '...';}
message += objectString;
if(process.env.QUANTIMODO_CLIENT_SECRET){message = message.replace(process.env.QUANTIMODO_CLIENT_SECRET, 'HIDDEN');}
if(AWS_SECRET_ACCESS_KEY){message = message.replace(AWS_SECRET_ACCESS_KEY, 'HIDDEN');}
if(process.env.ENCRYPTION_SECRET){message = message.replace(process.env.ENCRYPTION_SECRET, 'HIDDEN');}
if(process.env.QUANTIMODO_ACCESS_TOKEN){message = message.replace(process.env.QUANTIMODO_ACCESS_TOKEN, 'HIDDEN');}
message = qmLog.obfuscateString(message);
return message;
},
isSecretWord: function(propertyName){
var lowerCaseProperty = propertyName.toLowerCase();
return lowerCaseProperty.indexOf('secret') !== -1 ||
lowerCaseProperty.indexOf('password') !== -1 ||
lowerCaseProperty.indexOf('key') !== -1 ||
lowerCaseProperty.indexOf('database') !== -1 ||
lowerCaseProperty.indexOf('token') !== -1;
},
obfuscateString: function(string){
var env = process.env;
for (var propertyName in env) {
if (env.hasOwnProperty(propertyName)) {
if(qmLog.isSecretWord(propertyName)){
string = string.replace(env[propertyName], '[SECURE]');
}
}
}
return string;
},
obfuscateSecrets: function(object){
if(typeof object !== 'object'){return object;}
object = JSON.parse(JSON.stringify(object)); // Decouple so we don't screw up original object
for (var propertyName in object) {
if (object.hasOwnProperty(propertyName)) {
if(qmLog.isSecretWord(propertyName)){
object[propertyName] = "[SECURE]";
} else {
object[propertyName] = qmLog.obfuscateSecrets(object[propertyName]);
}
}
}
return object;
},
getCurrentServerContext: function() {
if(process.env.CIRCLE_BRANCH){return "circleci";}
if(process.env.BUDDYBUILD_BRANCH){return "buddybuild";}
return process.env.HOSTNAME;
},
prettyJSONStringify: function(object) {return JSON.stringify(object, null, '\t');},
slugify: function(str){
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++)
{
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace('.', '-') // replace a dot by a dash
.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by a dash
.replace(/-+/g, '-'); // collapse dashes
return str;
},
logStartOfProcess: function (str){
console.log("STARTING "+str+"\n====================================")
},
logEndOfProcess: function (str){
console.log("====================================\n"+"DONE WITH "+str)
}
};
var bugsnag = require("bugsnag");
bugsnag.register("ae7bc49d1285848342342bb5c321a2cf");
bugsnag.releaseStage = qmLog.getCurrentServerContext();
process.on('unhandledRejection', function (err) {
console.error("Unhandled rejection: " + (err && err.stack || err));
bugsnag.notify(err);
});
bugsnag.onBeforeNotify(function (notification) {
var metaData = notification.events[0].metaData;
metaData = qmLog.addMetaData(metaData);
});
var qmGit = {
branchName: null,
getBranchName: function(){
if(qmGit.branchName){return qmGit.branchName;}
qmLog.info("Branch name not set!");
return null;
},
isMaster: function () {
if(!qmGit.getBranchName()){throw "Branch name not set!";}
return qmGit.getBranchName() === "master";
},
isDevelop: function () {
if(!qmGit.getBranchName()){throw "Branch name not set!";}
return qmGit.getBranchName() === "develop";
},
isFeature: function () {
return qmGit.getBranchName().indexOf("feature") !== -1;
},
getCurrentGitCommitSha: function () {
if(process.env.SOURCE_VERSION){return process.env.SOURCE_VERSION;}
try {
return require('child_process').execSync('git rev-parse HEAD').toString().trim();
} catch (error) {
qmLog.info(error);
}
},
accessToken: process.env.GITHUB_ACCESS_TOKEN,
getCommitMessage: function(callback){
if(process.env.BUILDPACK_LOG_FILE){
qmLog.info("Can't get commit on Heroku");
callback("Can't get commit on Heroku");
return;
}
var commandForGit = 'git log -1 HEAD --pretty=format:%s';
execute(commandForGit, function (error, output) {
var commitMessage = output.trim();
qmLog.info("Commit: "+ commitMessage);
if(callback) {callback(commitMessage);}
});
},
outputCommitMessageAndBranch: function () {
qmGit.getCommitMessage(function (commitMessage) {
qmGit.setBranchName(function () {
qmLog.info("=====\nBuilding\n" + commitMessage + "\non branch: "+ qmGit.getBranchName() + "\n=====");
});
});
},
setBranchName: function (callback) {
if(qmGit.branchName){
qmLog.info("branchName already set to "+qmGit.branchName);
if (callback) {callback();}
return;
}
var git = require('gulp-git');
function setBranch(branch, callback) {
qmGit.branchName = branch.replace('origin/', '');
qmLog.info('current git branch: ' + qmGit.branchName);
if (callback) {callback();}
}
if (qmGit.getBranchEnv()){
setBranch(qmGit.getBranchEnv(), callback);
return;
}
if(process.env.BUILDPACK_LOG_FILE){
console.info("Setting branch to FEATURE because on Heroku and we can't access git repo data");
setBranch("feature", callback);
return;
}
try {
git.revParse({args: '--abbrev-ref HEAD'}, function (err, branch) {
if(err){qmLog.error(err); return;}
setBranch(branch, callback);
});
} catch (e) {
qmLog.info("Could not set branch name because " + e.message);
}
},
getBranchEnv: function () {
function getNameIfNotHead(envName) {
if(process.env[envName] && process.env[envName].indexOf("HEAD") === -1){return process.env[envName];}
return false;
}
if(getNameIfNotHead('CIRCLE_BRANCH')){return process.env.CIRCLE_BRANCH;}
if(getNameIfNotHead('BUDDYBUILD_BRANCH')){return process.env.BUDDYBUILD_BRANCH;}
if(getNameIfNotHead('TRAVIS_BRANCH')){return process.env.TRAVIS_BRANCH;}
if(getNameIfNotHead('GIT_BRANCH')){return process.env.GIT_BRANCH;}
}
};
qmGit.setBranchName();
var majorMinorVersionNumbers = '2.10.';
if(argv.clientSecret){process.env.QUANTIMODO_CLIENT_SECRET = argv.clientSecret;}
process.env.npm_package_licenseText = null; // Pollutes logs
qmLog.debug("Environmental Variables", process.env, 50000);
var qmGulp = {
chcp: {
enabled: false,
loginAndBuild: function(callback){
/** @namespace qm.getAppSettings().additionalSettings.appIds.appleId */
qmGulp.staticData.chcp = {
"name": qmGulp.getAppDisplayName(),
"s3bucket": qmGulp.chcp.getS3Bucket(),
"s3region": "us-east-1",
"s3prefix": qmGulp.chcp.getS3Prefix()+'/',
"ios_identifier": qmGulp.getAppIds().appleId,
"android_identifier": qmGulp.getAppIdentifier(),
"update": "start",
"content_url": qmGulp.chcp.getContentUrl()+'/'
};
writeToFileWithCallback('cordova-hcp.json', qmLog.prettyJSONStringify(qmGulp.staticData.chcp), function(err){
if(err) {return qmLog.error(err);}
var chcpBuildOptions = {
"dev": {"config-file": qmGulp.chcp.getChcpJsonUrl("dev")},
"production": {"config-file": qmGulp.chcp.getChcpJsonUrl("production")},
"QA": {"config-file": qmGulp.chcp.getChcpJsonUrl("qa")}
};
return writeToFileWithCallback('chcpbuild.options', qmLog.prettyJSONStringify(chcpBuildOptions), function(err){
if(err) {return qmLog.error(err);}
qmGulp.chcp.chcpLogin(function(err){
if(err) {return qmLog.error(err);}
qmGulp.chcp.outputCordovaHcpJson();
execute("cordova-hcp build", callback);
});
});
});
},
outputCordovaHcpJson: function() {
outputFileContents('cordova-hcp.json');
},
chcpLogin: function (callback){
if(!checkAwsEnvs()){throw "Cannot upload to S3. Please set environmental variable AWS_SECRET_ACCESS_KEY";}
var string = '{"key": "' + AWS_ACCESS_KEY_ID + ' ", "secret": "' + AWS_SECRET_ACCESS_KEY +'"}';
return writeToFileWithCallback(paths.chcpLogin, string, callback);
},
getS3HostName: function(){
return "https://"+qmGulp.chcp.getS3Bucket()+".s3.amazonaws.com/";
},
getContentUrl: function(releaseStage){
var url;
if(releaseStage){
url = qmGulp.chcp.getS3HostName() + qmGulp.chcp.getAppPath() + "/" + releaseStage;
} else {
url = qmGulp.chcp.getS3HostName() + qmGulp.chcp.getS3Prefix();
}
qmLog.info("ContentUrl is " + url);
return url;
},
getChcpJsonUrl: function(releaseStage){
return qmGulp.chcp.getContentUrl(releaseStage)+"/chcp.json";
},
releaseStagePath: null,
getReleaseStagePath: function () {
if(qmGulp.chcp.releaseStagePath){return qmGulp.chcp.releaseStagePath;}
var path = "dev";
if(qmGit.getBranchName() && qmGit.isMaster()){path = "production";}
if(qmGit.getBranchName() && qmGit.isDevelop()){path = "qa";}
if(qmGulp.buildSettings.buildDebug()){
qmLog.info("qmGulp.buildSettings.buildDebug returns true so using ReleaseStagePath dev");
path = "dev";
}
qmLog.info("CHCP ReleaseStagePath: " + path);
return path;
},
appPath: null,
getAppPath: function(){
if(qmGulp.chcp.appPath){return qmGulp.chcp.appPath;}
return qmGulp.getClientIdFromStaticData();
},
getS3Prefix: function(){
return qmGulp.chcp.getAppPath() + "/"+qmGulp.chcp.getReleaseStagePath();
},
getS3Bucket: function(){
if(process.env.PWD && process.env.PWD.indexOf('workspace/DEPLOY-staging') !== -1){return "qm-staging.quantimo.do";}
if(process.env.PWD && process.env.PWD.indexOf('workspace/DEPLOY-production') !== -1){return "quantimodo.quantimo.do";}
return "qm-cordova-hot-code-push";
},
chcpCleanConfigFiles: function(){
return cleanFiles([
'.chcpenv',
'chcpbuild.options',
'cordova-hcp.json',
'src/chcp.json',
'src/chcp.manifest',
'www/chcp.json',
paths.chcpLogin
]);
}
},
client: {
getClientId: function () {
if(QUANTIMODO_CLIENT_ID){return QUANTIMODO_CLIENT_ID;}
return null;
},
setClientId: function(clientId){
QUANTIMODO_CLIENT_ID = clientId;
},
clientIds: {
medimodo: 'medimodo',
quantimodo: 'quantimodo'
}
},
buildSettings: {
doNotMinify: null,
weShouldMinify: function(){
if(qmPlatform.buildingFor.android()){return false;}
//if(!qmPlatform.buildingFor.web()){return false;} We need to minify on mobile or the app contains huge lib folder and CHCP sync is slow!
if(qmGulp.buildSettings.doNotMinify !== null){return !!qmGulp.buildSettings.doNotMinify;}
if(typeof process.env.MINIFY !== "undefined"){return isTruthy(process.env.MINIFY);}
if(isTruthy(process.env.DO_NOT_MINIFY)){return false;}
if(qmGulp.buildSettings.buildDebug()){
qmLog.info("Copying src instead of minifying because qm.buildSettings.buildDebug returns true");
return false;
}
return true;
},
buildDebug: function () {
if(isTruthy(process.env.BUILD_ANDROID_RELEASE)){return false;}
if(isTruthy(process.env.BUILD_DEBUG) || isTruthy(process.env.DEBUG_BUILD)){
qmLog.info("BUILD_DEBUG or DEBUG_BUILD is true");
return true;
}
if(qmPlatform.buildingFor.chrome()){return false;} // Otherwise we don't minify and extension is huge
// Always building debug when not on master causes unexpected results. Just use BUILD_DEBUG env if necessary
//if(!qmGit.isMaster()){ qmLog.info("Not on master so buildDebug is true"); return true; }
return false;
}
},
buildInfoHelper: {
alreadyMinified: function(){
try {
var files = fs.readdirSync(paths.www.scripts);
if (!files.length) {
qmLog.info("Scripts folder is empty so we need to minify");
return false;
}
} catch (e) {
qmLog.info("No scripts folder so we need to minify");
return false;
}
var previousSha = qmGulp.buildInfoHelper.getPreviousBuildSha();
if(!previousSha){
qmLog.error("Could not get previous git commit SHA!");
return false;
}
var currentSha = qmGit.getCurrentGitCommitSha();
if(!currentSha){
qmLog.error("Could not get current git commit SHA!");
return false;
}
var alreadyMinified = previousSha === currentSha;
if(!alreadyMinified){
qmLog.info("current sha " + currentSha + " and previous commit SHA " + previousSha +
" don't match so we need to minify again");
} else {
qmLog.info("No need to minify again because current sha " + currentSha + " and previous commit SHA " +
previousSha + " match");
}
return alreadyMinified;
},
buildInfo: {
iosCFBundleVersion: null,
builtAt: null,
buildServer: null,
buildLink: null,
versionNumber: null,
versionNumbers: {},
gitBranch: null,
gitCommitShaHash: null
},
getPreviousBuildSha: function(){
var previousBuildInfo = qmGulp.buildInfoHelper.getPreviousBuildInfo();
if(!previousBuildInfo){return false;}
return previousBuildInfo.gitCommitShaHash;
},
getCurrentBuildInfo: function () {
qmGulp.buildInfoHelper.currentBuildInfo = {
iosCFBundleVersion: qmGulp.buildInfoHelper.buildInfo.versionNumbers.iosCFBundleVersion,
builtAt: timeHelper.getUnixTimestampInSeconds(),
builtAtString: new Date().toISOString(),
buildServer: qmLog.getCurrentServerContext(),
buildLink: qmGulp.buildInfoHelper.getBuildLink(),
versionNumber: qmGulp.buildInfoHelper.buildInfo.versionNumbers.ionicApp,
versionNumbers: qmGulp.buildInfoHelper.buildInfo.versionNumbers,
gitBranch: qmGit.getBranchName(),
gitCommitShaHash: qmGit.getCurrentGitCommitSha()
};
return qmGulp.buildInfoHelper.currentBuildInfo;
},
getPreviousBuildInfo: function () {
var previousBuildInfo = readFile(paths.src.buildInfo);
if(!previousBuildInfo){
qmLog.info("No previous BuildInfo file at "+paths.src.buildInfo);
qmGulp.buildInfoHelper.previousBuildInfo = false;
} else {
qmGulp.buildInfoHelper.previousBuildInfo = previousBuildInfo;
}
return qmGulp.buildInfoHelper.previousBuildInfo;
},
previousBuildInfo: null,
writeCommitSha: function () {
writeToFile('www/data/commits/'+qmGit.getCurrentGitCommitSha(), qmGit.getCurrentGitCommitSha());
writeToFile('src/data/commits/'+qmGit.getCurrentGitCommitSha(), qmGit.getCurrentGitCommitSha());
},
getBuildLink: function() {
if(process.env.BUDDYBUILD_APP_ID){return "https://dashboard.buddybuild.com/apps/" + process.env.BUDDYBUILD_APP_ID + "/build/" + process.env.BUDDYBUILD_APP_ID;}
if(process.env.CIRCLE_BUILD_NUM){return "https://circleci.com/gh/QuantiModo/quantimodo-android-chrome-ios-web-app/" + process.env.CIRCLE_BUILD_NUM;}
if(process.env.TRAVIS_BUILD_ID){return "https://travis-ci.org/" + process.env.TRAVIS_REPO_SLUG + "/builds/" + process.env.TRAVIS_BUILD_ID;}
},
setVersionNumbers: function(){
var date = new Date();
function getPatchVersionNumber() {
var monthNumber = (date.getMonth() + 1).toString();
var dayOfMonth = ('0' + date.getDate()).slice(-2);
return monthNumber + dayOfMonth;
}
function getIosMinorVersionNumber() {
return (getMinutesSinceMidnight()).toString();
}
function getMinutesSinceMidnight() {
return date.getHours() * 60 + date.getMinutes();
}
function getAndroidMinorVersionNumber() {
var number = getMinutesSinceMidnight() * 99 / 1440;
number = Math.round(number);
number = appendLeadingZero(number);
return number;
}
function appendLeadingZero(integer) {return ('0' + integer).slice(-2);}
function getLongDateFormat(){return date.getFullYear().toString() + appendLeadingZero(date.getMonth() + 1) + appendLeadingZero(date.getDate());}
qmGulp.buildInfoHelper.buildInfo.versionNumbers = {
iosCFBundleVersion: majorMinorVersionNumbers + getPatchVersionNumber() + '.' + getIosMinorVersionNumber(),
//androidVersionCodes: {armV7: getLongDateFormat() + appendLeadingZero(date.getHours()), x86: getLongDateFormat() + appendLeadingZero(date.getHours() + 1)},
androidVersionCode: getLongDateFormat() + getAndroidMinorVersionNumber(),
ionicApp: majorMinorVersionNumbers + getPatchVersionNumber()
};
qmGulp.buildInfoHelper.buildInfo.versionNumbers.buildVersionNumber = qmGulp.buildInfoHelper.buildInfo.versionNumbers.androidVersionCode;
qmLog.info(JSON.stringify(qmGulp.buildInfoHelper.buildInfo.versionNumbers));
}
},
getAdditionalSettings: function(){
return qmGulp.staticData.appSettings.additionalSettings;
},
getAppDisplayName: function(){
if (!qmGulp.staticData.appSettings.appDisplayName) { throw 'Please export appSettings.appDisplayName';}
return qmGulp.staticData.appSettings.appDisplayName;
},
getAppHostName: function(){
if(process.env.RELEASE_STAGE === "staging"){return "https://staging.quantimo.do";}
if(process.env.APP_HOST_NAME){return process.env.APP_HOST_NAME;}
// We can set utopia as env or in the app when necessary because always using it in build process on develop causes too many problems
//if(qmGulp.buildSettings.buildDebug()){return "https://utopia.quantimo.do";}
return "https://app.quantimo.do";
},
getAppIds: function(){
return qmGulp.getAdditionalSettings().appIds;
},
getAppIdentifier: function(){
return qmGulp.getAppIds().appIdentifier;
},
getAppStatus: function(){
return qmGulp.staticData.appSettings.appStatus;
},
getAppSettings: function(){
return qmGulp.staticData.appSettings;
},
getBuildStatus: function(){
return qmGulp.staticData.appSettings.appStatus.buildStatus;
},
getClientIdFromStaticData: function(){
return qmGulp.staticData.appSettings.clientId;
},
getMonetizationSettings: function(){
return qmGulp.staticData.appSettings.additionalSettings.monetizationSettings;
},
releaseService: {
getReleaseStage: function () {
if(!process.env.RELEASE_STAGE){
qmLog.info("No RELEASE_STAGE set! Assuming development");
return 'development';
}
return process.env.RELEASE_STAGE;
},
isDevelopment: function () {
return qmGulp.releaseService.getReleaseStage() === 'development';
},
isStaging: function () {
return qmGulp.releaseService.getReleaseStage() === 'staging';
},
isProduction: function () {
return qmGulp.releaseService.getReleaseStage() === 'production';
},
getReleaseStageSubDomain: function(){
if(qmGulp.releaseService.isStaging()){return "staging-web";}
if(qmGulp.releaseService.isProduction()){return "web";}
qmLog.error("No RELEASE_STAGE set! Assuming GHPagesSubDomain qm-dev");
return "qm-dev";
}
},
//server: {isHeroku: function(){return process.env.BUILDPACK_LOG_FILE !== null;}}, Not sure why this breaks gulp?
staticData: {
commonVariables: null,
units: null,
variableCategories: null,
connectors: null,
docs: null,
appSettings: null,
privateConfig: null,
chcp: null,
buildInfo: null,
configXml: null,
chromeExtensionManifest: null
},
createStatusToCommit: function(statusOptions, callback){
var github = require('gulp-github');
github.createStatusToCommit(statusOptions, qmGulp.getGithubOptions(), callback);
},
getGithubOptions: function(){
if(!process.env.GITHUB_ACCESS_TOKEN){
throw "Please set GITHUB_ACCESS_TOKEN env in order to update Github statuses";
}
// noinspection JSUnusedLocalSymbols,JSUnusedLocalSymbols
var options = {
// Required options: git_token, git_repo
// refer to https://help.github.com/articles/creating-an-access-token-for-command-line-use/
git_token: process.env.GITHUB_ACCESS_TOKEN,
// comment into this repo, this pr.
git_repo: 'QuantiModo/quantimodo-android-chrome-ios-web-app',
//git_prid: '1',
// create status to this commit, optional
git_sha: qmGit.getCurrentGitCommitSha(),
jshint_status: 'error', // Set status to error when jshint errors, optional
jscs_status: 'failure', // Set git status to failure when jscs errors, optional
eslint_status: 'error', // Set git status to error when eslint errors, optional
// when using github enterprise, optional
git_option: {
// refer to https://www.npmjs.com/package/github for more options
//host: 'github.mycorp.com',
// You may require this when you using Enterprise Github
//pathPrefix: '/api/v3'
},
// Provide your own jshint reporter, optional
jshint_reporter: function (E, file) { // gulp stream file object
// refer to http://jshint.com/docs/reporters/ for E structure.
return 'Error in ' + E.file + '!';
},
// Provide your own jscs reporter, optional
jscs_reporter: function (E, file) { // gulp stream file object
// refer to https://github.com/jscs-dev/node-jscs/wiki/Error-Filters for E structure.
return 'Error in ' + E.filename + '!';
}
};
return options;
},
uploadBuildToS3: function(filePath) {
if(!fs.existsSync(filePath)){
throw filePath+" not found!";
}
if(qmGulp.getAppSettings().apiUrl === "local.quantimo.do"){
qmLog.info("Not uploading because qm.getAppSettings().apiUrl is " + qmGulp.getAppSettings().apiUrl);
return;
}
/** @namespace qm.getAppSettings().appStatus.betaDownloadLinks */
var url = getApkS3DownloadUrl(filePath);
qmLog.info("Download from "+url+ " and test!");
qmGulp.getAppStatus().betaDownloadLinks[convertFilePathToPropertyName(filePath)] = url;
var context = qmGulp.getClientIdFromStaticData() + " " + qmGulp.currentTask.replace('upload-combined-', '').replace('-to-s3', '');
qmGulp.createStatusToCommit({
description: 'Click Details to download and test',
context: context,
target_url: url,
state: 'success'
});
/** @namespace qm.getAppSettings().appStatus.buildStatus */
qmGulp.getBuildStatus()[convertFilePathToPropertyName(filePath)] = "READY";
return uploadToS3(filePath);
}
};
qmGulp.buildInfoHelper.setVersionNumbers();
var Quantimodo = require('quantimodo');
/** @namespace Quantimodo.ApiClient */
var defaultClient = Quantimodo.ApiClient.instance;
var quantimodo_oauth2 = defaultClient.authentications.quantimodo_oauth2;
quantimodo_oauth2.accessToken = process.env.QUANTIMODO_ACCESS_TOKEN;
console.log("process.platform is " + process.platform + " and process.env.OS is " + process.env.OS);
qmGit.outputCommitMessageAndBranch();
function setClientId(callback) {
if (process.env.BUDDYBUILD_SCHEME) {
QUANTIMODO_CLIENT_ID = process.env.BUDDYBUILD_SCHEME.toLowerCase().substr(0, process.env.BUDDYBUILD_SCHEME.indexOf(' '));
}
if(QUANTIMODO_CLIENT_ID){
qmLog.info('Client id already set to ' + QUANTIMODO_CLIENT_ID);
if (callback) {callback();}
return;
}
if(argv.clientId){
QUANTIMODO_CLIENT_ID = argv.clientId;
qmLog.info("Using argv.clientId as client id: " + argv.clientId);
}
if(QUANTIMODO_CLIENT_ID){
QUANTIMODO_CLIENT_ID = QUANTIMODO_CLIENT_ID.replace('apps/', '');
qmLog.info('Stripped apps/ and now client id is ' + QUANTIMODO_CLIENT_ID);
}
if (!QUANTIMODO_CLIENT_ID) {
qmGit.setBranchName(function () {
var fullBranchName = qmGit.getBranchName();
var branch = fullBranchName.replace('apps/', '');
if (!QUANTIMODO_CLIENT_ID) {
if (appIds[branch]) {
qmLog.info('Setting QUANTIMODO_CLIENT_ID using branch name ' + branch);
QUANTIMODO_CLIENT_ID = branch;
} else {
console.warn('No QUANTIMODO_CLIENT_ID set. Falling back to quantimodo client id');
QUANTIMODO_CLIENT_ID = 'quantimodo';
}
}
if (callback) {callback();}
});
} else {
if (callback) {callback();}
}
}
setClientId();
function getChromeExtensionZipFilename() {return QUANTIMODO_CLIENT_ID + '-chrome-extension.zip';}
function getPathToChromeExtensionZip() {return buildPath + '/' + getChromeExtensionZipFilename();}
function getPathToUnzippedChromeExtension() {return buildPath + '/' + QUANTIMODO_CLIENT_ID + '-chrome-extension';}
function readDevCredentials(){
try{
devCredentials = JSON.parse(fs.readFileSync(paths.src.devCredentials));
qmLog.info("Using dev credentials from " + paths.src.devCredentials + ". This file is ignored in .gitignore and should never be committed to any repository.");
} catch (error){
qmLog.debug('No existing dev credentials found');
devCredentials = {};
}
}
function readFile(path){
try {
return JSON.parse(fs.readFileSync(path));
} catch (e) {
qmLog.error("Could not read "+path);
return false;
}
}
function outputFileContents(path){
qmLog.info(path+": "+fs.readFileSync(path));
}
function validateJsonFile(filePath) {
try{
var parsedOutput = JSON.parse(fs.readFileSync(filePath));
qmLog.info(filePath + " is valid json");
qmLog.debug(filePath + ": ", parsedOutput);
} catch (error){
var message = filePath + " is NOT valid json!";
qmLog.error(message, error);
throw(message);
}
}
readDevCredentials();
function convertToCamelCase(string) {
string = string.replace('.', '-');
string = string.replace('_', '-');
if(string.charAt(0) === "-"){string = string.substr(1);}
string = string.replace(/(\_[a-z])/g, function($1){return $1.toUpperCase().replace('_','');});
string = string.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
return string;
}
function getSubStringAfterLastSlash(myString) {
var parts = myString.split('/');
return parts[parts.length - 1];
}
function convertFilePathToPropertyName(filePath) {
var propertyName = getSubStringAfterLastSlash(filePath);
propertyName = propertyName.replace(QUANTIMODO_CLIENT_ID, '');
propertyName = propertyName.replace('.zip', '').replace('.apk', '');
propertyName = convertToCamelCase(propertyName);
return propertyName;
}
function getS3AppUploadsRelativePath(relative_filename) {
var path = 'app_uploads/' + QUANTIMODO_CLIENT_ID + '/' + relative_filename;
// noinspection JSUnusedLocalSymbols
var numbers = qmGulp.buildInfoHelper.buildInfo.versionNumbers;
if(relative_filename.indexOf('.apk') !== -1 && QUANTIMODO_CLIENT_ID === 'quantimodo'){
var slug = qmLog.slugify(qmGit.getBranchName());
slug = slug.replace('renovate-', '');
path = path.replace('app-',
//numbers.buildVersionNumber
slug
+'-app-');
}
return path;
}
function getApkS3DownloadUrl(filePath){
var url = 'https://quantimodo.s3.amazonaws.com/' + getS3AppUploadsRelativePath(filePath);
return url;
}
function uploadAppImagesToS3(filePath) {
//qm.getAdditionalSettings().appImages[convertFilePathToPropertyName(filePath)] = getS3Url(filePath); We can just generate this from client id in PHP constructor
return uploadToS3(filePath);
}
function checkAwsEnvs() {
if(!AWS_ACCESS_KEY_ID){
qmLog.info("Please set environmental variable QM_AWS_ACCESS_KEY_ID");
return false;
}
if(!AWS_SECRET_ACCESS_KEY){
qmLog.info("Please set environmental variable QM_AWS_SECRET_ACCESS_KEY");
return false;
}
return true;
}
function uploadToS3(filePath) {
var s3 = require('gulp-s3-upload')(s3Options);
if(!checkAwsEnvs()){
qmLog.info("No S3 credentials to upload " + filePath);
return;
}
// noinspection JSUnusedLocalSymbols
fs.stat(filePath, function (err, stat) {
if (!err) {
qmLog.info("Uploading " + filePath + " to S3...");
// noinspection JSUnusedLocalSymbols
return gulp.src([filePath]).pipe(s3({
Bucket: 'quantimodo',
ACL: 'public-read',
keyTransform: function(relative_filename) {
var S3AppUploadsRelativePath = getS3AppUploadsRelativePath(filePath);
qmLog.info("S3 path: " + S3AppUploadsRelativePath);
return S3AppUploadsRelativePath;
}
}, {
maxRetries: 5,
logger: console
}));
} else {
qmLog.error('Could not find ' + filePath);
qmLog.error(err);
}
});
}
function execute(command, callback, suppressErrors, lotsOfOutput) {
var exec = require('child_process').exec;
var spawn = require('child_process').spawn; // For commands with lots of output resulting in stdout maxBuffer exceeded error
qmLog.info('executing ' + command);
if(lotsOfOutput){
var args = command.split(" ");
var program = args.shift();
var ps = spawn(program, args);
ps.on('exit', function (code, signal) {
qmLog.info(command + ' exited with ' + 'code '+ code + ' and signal '+ signal);
if(callback){callback();}
});
ps.stdout.on('data', function (data) {qmLog.info(command + ' stdout: ' + data);});
ps.stderr.on('data', function (data) {qmLog.error(command + ' stderr: ' + data);});
ps.on('close', function (code) {if (code !== 0) {qmLog.error(command + ' process exited with code ' + code);}});
} else {
// noinspection JSUnusedLocalSymbols
var my_child_process = exec(command, function (error, stdout, stderr) {
if (error !== null) {if (suppressErrors) {qmLog.info('ERROR: exec ' + error);} else {qmLog.error('ERROR: exec ' + error);}}
callback(error, stdout);
});
my_child_process.stdout.pipe(process.stdout);
my_child_process.stderr.pipe(process.stderr);
}
}
function decryptFile(fileToDecryptPath, decryptedFilePath, callback) {
if (!process.env.ENCRYPTION_SECRET) {
qmLog.error('ERROR: Please set ENCRYPTION_SECRET environmental variable!');
if (callback) {callback();}
return;
}
qmLog.info('DECRYPTING ' + fileToDecryptPath + ' to ' + decryptedFilePath);
var cmd = 'openssl aes-256-cbc -k "' + process.env.ENCRYPTION_SECRET + '" -in "' + fileToDecryptPath + '" -d -a -out "' + decryptedFilePath + '"';
execute(cmd, function (error) {
if (error !== null) {qmLog.error('ERROR: DECRYPTING: ' + error);} else {qmLog.info('DECRYPTED to ' + decryptedFilePath);}
// noinspection JSUnusedLocalSymbols
fs.stat(decryptedFilePath, function (err, stat) {
if (!err) {
qmLog.info(decryptedFilePath + ' exists');
} else {
qmLog.error('Could not decrypt' + fileToDecryptPath);
qmLog.error('Make sure openssl works on your command line and the bin folder is in your PATH env: https://code.google.com/archive/p/openssl-for-windows/downloads');
qmLog.error(err);
}
});
if (callback) {callback();}
//outputSHA1ForAndroidKeystore(decryptedFilePath);
});
}
function encryptFile(fileToEncryptPath, encryptedFilePath, callback) {
if (!process.env.ENCRYPTION_SECRET) {
qmLog.error('ERROR: Please set ENCRYPTION_SECRET environmental variable!');
return;
}
var cmd = 'openssl aes-256-cbc -k "' + process.env.ENCRYPTION_SECRET + '" -in "' + fileToEncryptPath + '" -e -a -out "' + encryptedFilePath + '"';
qmLog.debug('executing ' + cmd);
execute(cmd, callback);
}
function ionicUpload(callback) {
var commandForGit = 'git log -1 HEAD --pretty=format:%s';
execute(commandForGit, function (error, output) {
var commitMessage = output.trim();
var uploadCommand = 'ionic upload --email [email protected] --password ' + process.env.IONIC_PASSWORD +
' --note "' + commitMessage + '" --deploy ' + process.env.RELEASE_STAGE;
qmLog.info('ionic upload --note "' + commitMessage + '" --deploy ' + process.env.RELEASE_STAGE);
qmLog.debug('\n' + uploadCommand);
execute(uploadCommand, callback);
});
}
function zipAFolder(folderPath, zipFileName, destinationFolder) {
var zip = require('gulp-zip');
qmLog.info("Zipping " + folderPath + " to " + destinationFolder + '/' + zipFileName);
qmLog.debug('If this fails, make sure there are no symlinks.');
return gulp.src([folderPath + '/**/*'])
.pipe(zip(zipFileName))
.pipe(gulp.dest(destinationFolder));
}
function zipAndUploadToS3(folderPath, zipFileName) {
var zip = require('gulp-zip');
var s3 = require('gulp-s3-upload')(s3Options);
if(!checkAwsEnvs()){return;}
var s3Path = getS3AppUploadsRelativePath(folderPath + '.zip');
qmLog.info("Zipping " + folderPath + " to " + s3Path);
qmLog.debug('If this fails, make sure there are no symlinks.');