-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
1656 lines (1211 loc) · 55.6 KB
/
app.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
// Ringo Core Build Server
// Copyright 2015 Gautam Mittal under MIT License
// Dependencies: NODE.JS + Xcode
// You will also need to populate the .env file with the necessary environment variables in order for this script to run effectively
var dotenv = require('dotenv');
dotenv.load();
var bodyParser = require('body-parser');
var colors = require('colors');
var express = require('express');
var fs = require('fs');
var getIP = require('external-ip')();
var Keen = require("keen.io");
var request = require('request');
var satelize = require('satelize');
var serialNumber = require('serial-number');
serialNumber.preferUUID = true;
require('shelljs/global');
var sendgrid;
if (process.env.REPORT_TO && process.env.SEND_REPORTS == "YES") {
sendgrid = require('sendgrid')(process.env.SENDGRID_KEY);
}
var client;
if (process.env.KEEN_PROJECT_ID) {
console.log("Keen analytics starting up...".magenta);
client = Keen.configure({
projectId: process.env.KEEN_PROJECT_ID,
writeKey: process.env.KEEN_WRITE_KEY
});
}
var reportBalancerTimer;
var exec = require('child_process').exec;
//var ngrok = require('ngrok');
var app = express();
app.use(bodyParser.json({limit: '50mb', extended: true}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(express.static(__dirname + '/build-projects')); // serve the files within build-projects
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var port = 3000;
var server = app.listen(port, function () {
var host = server.address().address;
var port = server.address().port;
console.log(('Ringo core server listening at http://0.0.0.0:'+ port).blue);
});
var build_serverURL = process.env.HOSTNAME;
var secure_serverURL = process.env.SECURE_HOSTNAME;
getIP(function (err, ip) {
if (err) {
console.log(err);
}
if (typeof client != "undefined") {
// satelize.satelize({ip:ip}, function(err, geoData) {
if (err) {
// do something
} else {
var obj = JSON.parse(geoData);
var location = obj.city + ", " + obj.region_code + ", " + obj.country_code3;
var isp = obj.isp;
var country = obj.country;
var timezone = obj.timezone;
client.addEvent("on_start_server", {"location": location, "isp": isp, "country": country, "timezone": timezone});
}
}
});
//ngrok.connect(port, function (err, url) {
// console.log("Tunnel open: " + (url).red + " at "+ new Date());
// process.env["SECURE_HOSTNAME"] = url;
// process.env["HOSTNAME"] = url.replace('https', 'http');
// build_serverURL = process.env.HOSTNAME;
// secure_serverURL = process.env.SECURE_HOSTNAME;
reportBalancerTimer = setInterval(reportToLoadBalancer, 1000); // send data to load balancer
//});
function reportToLoadBalancer() {
if (process.env.LOAD_BALANCER_URL) {
serialNumber(function (err, value) {
if (err) {
console.log('Error getting the server unique ID, will have difficulty registering with the load balancer'.red);
}
// get the amount of stress on the server
getServerLoad(function (server_load) {
request({
url: process.env.LOAD_BALANCER_URL + '/register-server/', //URL to hit
method: 'POST',
json: {
server_id: value,
tunnel: process.env.HOSTNAME,
load:server_load,
key: process.env.BALANCER_AUTH_KEY
}
}, function(error, response, body){
if(error) {
// console.log(error);
}
});
});
});
}
}
// Get the ngrok tunnel url
// GET (no parameters)
app.get('/get-secure-tunnel', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send({"tunnel_url": process.env.HOSTNAME});
});
// Run an Xcode Swift sandbox
// POST {'code':string}
app.post('/build-sandbox', function (req, res) {
cd(buildProjects_path);
if (req.body.code && (req.body.code).length != 0) {
var ip = req.connection.remoteAddress;
if (typeof client != "undefined") { // only run if the user has set up analytics
satelize.satelize({ip:ip}, function(err, geoData) {
// if data is JSON, we may wrap it in js object
if (err) {
// console.log("There was an error getting the user's location.");
} else {
// console.log(geoData);
var obj = JSON.parse(geoData);
var location = obj.city + ", " + obj.region_code + ", " + obj.country_code3;
var isp = obj.isp;
var country = obj.country;
var timezone = obj.timezone;
var lengthOfCode = (req.body.code).length
client.addEvent("built_sandbox", {"location": location, "isp": isp, "country": country, "timezone": timezone, "code_length": lengthOfCode});
} // end error handling
}); // end satelize
}
console.log('Sandbox executed at '+ new Date());
fs.writeFile("code.swift", req.body.code, function(err) {
if(err) {
return console.log(err);
}
exec("swift code.swift", function (err, out, stderror) {
if (stderror) { // if user has buggy code, tell them what they did wrong
res.send(stderror);
} else { // if user doesn't, show them the given output
res.send(out);
}
});
});
} else {
res.send("Nothing to compile.");
}
});
var buildProjects_path = "";
exec('cd build-projects', function (err, out, stderror) {
// set the build-projects path
process.env["BUILD_PROJECTS_PATH"] = pwd() + "/build-projects";
buildProjects_path = process.env.BUILD_PROJECTS_PATH;
if (err) { // if error, assume that the directory is non-existent
console.log('build-projects directory does not exist! creating one instead.'.red);
console.log('downloading renameXcodeProject.sh...'.cyan);
console.log('downloading XcodeProjAdder...'.cyan)
exec('mkdir build-projects', function (err, out, stderror) {
cd('build-projects');
// download the great
exec('wget http://cdn.rawgit.com/gmittal/ringoPeripherals/master/cli-helpers/renameXcodeProject.sh && wget http://cdn.rawgit.com/gmittal/ringoPeripherals/master/cli-helpers/XcodeProjAdder', function (err, out, stderror) {
console.log(out);
exec('chmod 755 renameXcodeProject.sh && chmod a+x XcodeProjAdder', function (err, out, stderror) {
console.log(('Successfully downloaded renameXcodeProject.sh at ' + new Date()).green);
console.log(('Successfully downloaded XcodeProjAdder at ' + new Date()).green);
cleanBuildProjects();
setInterval(cleanBuildProjects, 60000); // clean the build-projects directory every minute
});
});
});
} else {
console.log('build-projects directory was found.'.green);
cleanBuildProjects();
setInterval(cleanBuildProjects, 60000); // clean the build-projects directory every one minute
} // end if err
});
// Destroy any projects that haven't been touched for more than 48 hours
function cleanBuildProjects() {
cd(buildProjects_path);
// console.log("Checking the build-projects directory");
var projects = ls();
var i = 0;
loopProjects();
function loopProjects() {
if (projects[i] != "XcodeProjAdder") {
if (projects[i] != "renameXcodeProject.sh") {
fs.stat(projects[i], function (err, stats) {
// console.log(stats);
var lastModifiedTime = (new Date(stats.mtime)).getTime();
var currentTime = (new Date()).getTime();
// if the time since now and the time when the file was last modified is greater than 172800s (48h) -> destroy!
if (currentTime - lastModifiedTime > 172800000) {
console.log((projects[i] + " is too old. Destroying now.").red);
// destroy the directory
rm('-rf', projects[i]);
}
if (i < projects.length) {
i++;
loopProjects();
}
});
} // end if not renameXcodeProject.sh
} // end if not XcodeProjAdder
} // end loopFiles()
} // end cleanBuildProjects
// Request to make a new Xcode project
// POST {'projectName':string, 'template':string}
app.post('/create-project', function(req, res) {
cd(buildProjects_path);
// only execute if they specify the required parameters
if (req.body.projectName) {
// analytics
var ip = req.connection.remoteAddress;
// console.log("Request made from: " + ip);
if (typeof client != "undefined") {
satelize.satelize({ip:ip}, function(err, geoData) {
// if data is JSON, we may wrap it in js object
if (err) {
// console.log("There was an error getting the user's location.");
} else {
// console.log(geoData);
var obj = JSON.parse(geoData);
var location = obj.city + ", " + obj.region_code + ", " + obj.country_code3;
var isp = obj.isp;
var country = obj.country;
var timezone = obj.timezone;
// console.log(location);
var project_nomen = req.body.projectName
client.addEvent("project_created", {"location": location, "isp": isp, "country": country, "timezone": timezone, "name": project_nomen}, function(err, res) {
// if (err) {
// // console.log("Oh no, an error logging project_created".red);
// } else {
// // console.log("Event project_created logged".green);
// }
}); // end client addEvent
} // end error handling
}); // end satelize
}
var projectName = req.body.projectName;
var project_uid = generatePushID();
project_uid = project_uid.substr(1, project_uid.length);
res.setHeader('Content-Type', 'application/json');
// Using node's child_process.exec causes asynchronous issues... callbacks are my friend
exec('mkdir '+ project_uid, function (err, out, stderror) {
cd(project_uid);
var template = req.body.template;
var exec_cmd = ''; // there is a different command that needs to be executed based on the template the user chooses
if (template == "game") { // generate a SpriteKit game
exec_cmd = 'git clone https://github.com/gmittal/ringoTemplate && .././renameXcodeProject.sh ringoTemplate "'+ projectName +'" && rm -rf ringoTemplate';
} else if (template == "mda") { // generates a Master-Detail application
exec_cmd = 'git clone https://github.com/gmittal/ringoMDATemplate && .././renameXcodeProject.sh ringoMDATemplate "'+ projectName +'" && rm -rf ringoMDATemplate';
} else if (template == "sva") { // generates a Single View application
exec_cmd = 'git clone https://github.com/gmittal/ringoSVATemplate && .././renameXcodeProject.sh ringoSVATemplate "'+ projectName +'" && rm -rf ringoSVATemplate';
} else if (template == "pba") { // generates a Page-based application
exec_cmd = 'git clone https://github.com/gmittal/ringoPBATemplate && .././renameXcodeProject.sh ringoPBATemplate "'+ projectName +'" && rm -rf ringoPBATemplate';
} else if (template == "ta") { // generates a Tabbed application
exec_cmd = 'git clone https://github.com/gmittal/ringoTATemplate && .././renameXcodeProject.sh ringoTATemplate "'+ projectName +'" && rm -rf ringoTATemplate';
}
exec(exec_cmd, function (err, out, stderror) {
// console.log(out);
// console.log(err);
console.log('Successfully created '+(project_uid).magenta+' at ' + new Date() + '\n');
// don't send back the code until its actually done
res.send({"uid": project_uid});
});
});
} else {
res.statusCode = 500;
res.send({"Error": "Invalid parameters."});
}
});
// download your project code in a ZIP file
// GET /download/project/{ID_STRING}
app.get('/download-project/:id', function (req, res) {
cd(buildProjects_path);
// analytics
var ip = req.connection.remoteAddress;
// console.log("Request made from: " + ip);
if (typeof client != "undefined") {
satelize.satelize({ip:ip}, function(err, geoData) {
// if data is JSON, we may wrap it in js object
if (err) {
// console.log("There was an error getting the user's location.");
} else {
// console.log(geoData);
var obj = JSON.parse(geoData);
var location = obj.city + ", " + obj.region_code + ", " + obj.country_code3;
var isp = obj.isp;
var country = obj.country;
var timezone = obj.timezone;
// console.log(location);
client.addEvent("project_code_downloaded", {"location": location, "isp": isp, "country": country, "timezone": timezone, "project_id": req.params.id}, function(err, res) {
// if (err) {
// console.log("Oh no, an error logging project_code_downloaded".red);
// } else {
// console.log("Event project_code_downloaded logged".green);
// }
}); // end client addEvent
} // end error handling
}); // end satelize
} // end if undefined
cd(req.params.id);
var name = ls()[0];
// before the user can download their file, you have to wipe the project's build directory
cd(name);
// console.log(pwd());
// console.log(ls())
exec('rm -rf build', function (err, out, stderror) {
// console.log(out);
console.log('Successfully cleaned up the build directory from the project that will be downloaded.');
// now that we've removed the build projects directory, we need to move back up to the ID directory
cd(buildProjects_path + '/' + req.params.id);
exec('zip -r "'+name+'" "'+name+'"', function (err, out, stderror) {
// console.log(out.cyan);
res.sendFile(buildProjects_path+"/"+req.params.id+"/"+name+".zip");
});
});
});
// Upload an Xcode project to be edited
// POST {'file':base64_file_string}
app.post('/upload-project-zip', function (req, res) {
cd(buildProjects_path);
res.setHeader('Content-Type', 'application/json');
if (req.body.file) {
// analytics
var ip = req.connection.remoteAddress;
console.log("Request made from: " + ip);
if (typeof client != "undefined") {
satelize.satelize({ip:ip}, function(err, geoData) {
// if data is JSON, we may wrap it in js object
if (err) {
console.log("There was an error getting the user's location.");
} else {
// console.log(geoData);
var obj = JSON.parse(geoData);
var location = obj.city + ", " + obj.region_code + ", " + obj.country_code3;
var isp = obj.isp;
var country = obj.country;
var timezone = obj.timezone;
// console.log(location);
var fileSize = ((req.body.file.length*3)/4)/1000000;
fileSize = Math.round(fileSize*2)/2;
// console.log(fileSize + "MB");
client.addEvent("upload_project_zip", {"location": location, "isp": isp, "country": country, "timezone": timezone, "size_mb": fileSize}, function(err, res) {
if (err) {
console.log("Oh no, an error logging upload_project_zip".red);
} else {
console.log("Event upload_project_zip logged".green);
}
}); // end client addEvent
} // end error handling
}); // end satelize
} // end if undefined
cd(buildProjects_path);
// create a unique ID where this awesome project will live
var project_uid = generatePushID();
project_uid = project_uid.substr(1, project_uid.length);
console.log(project_uid);
// console.log(req.body.file);
exec('mkdir '+ project_uid, function (err, out, stderror) {
cd(project_uid);
var base64Data = req.body.file.replace(/^data:application\/zip;base64,/, "");
require("fs").writeFile("anonymous_project.zip", base64Data, 'base64', function(err) {
if (err) {
console.log(err);
}
console.log('User ZIP project successfully received.'.magenta);
exec('unzip anonymous_project.zip && rm -rf anonymous_project.zip', function (err, out, stderror) {
console.log('Took out the garbage.'.yellow);
console.log('Verifying that the project file tree is compliant with Xcode standards...'.yellow);
cd(buildProjects_path);
// sometimes operating systems like OS X generate a __MACOSX directory which confuses the system
rm('-rf', project_uid + "/__MACOSX");
var id_dir = ls(project_uid)[0];
var xc_projName = ""; // suprisingly enough, people like to name their repository name differently than their .xcodeproj name
for (var z = 0; z < ls(project_uid + "/" + id_dir).length; z++) {
if (ls(project_uid + "/" + id_dir)[z].indexOf('.xcodeproj') > -1) {
xc_projName = ls(project_uid + "/" + id_dir)[z].replace('.xcodeproj', '');
}
}
if (xc_projName.length !== 0) {
res.send({"id": project_uid});
} else {
console.log("Does not comply with the standard Xcode project file tree...".red);
res.statusCode = 500;
res.send({"Error": "Invalid parameters"});
}
});
}); // end write ZIP file
}); // end create project directory
} else {
res.statusCode = 500;
res.send({"Error": "Invalid parameters"});
}
});
// Clone a git project to edited
// POST {'url':string}
app.post('/clone-git-project', function (req, res) {
cd(buildProjects_path);
res.setHeader('Content-Type', 'application/json');
if (req.body.url) {
console.log('Received request to git clone a file.');
// analytics
var ip = req.connection.remoteAddress;
console.log("Request made from: " + ip);
if (typeof client != "undefined") {
satelize.satelize({ip:ip}, function(err, geoData) {
// if data is JSON, we may wrap it in js object
if (err) {
console.log("There was an error getting the user's location.");
} else {
var obj = JSON.parse(geoData);
var location = obj.city + ", " + obj.region_code + ", " + obj.country_code3;
var isp = obj.isp;
var country = obj.country;
var timezone = obj.timezone;
var source = "unknown";
if ((req.body.url).substr(0, 4) == "http") {
source = (req.body.url).split("/")[2];
}
// console.log(source);
client.addEvent("clone_git_project", {"location": location, "isp": isp, "country": country, "timezone": timezone, "source": source}, function(err, res) {
if (err) {
// console.log("Oh no, an error logging clone_git_project".red);
} else {
// console.log("Event clone_git_project logged".green);
}
}); // end client addEvent
} // end error handling
}); // end satelize
} // end if undefined
// create a unique ID where this awesome project will live
var project_uid = generatePushID();
project_uid = project_uid.substr(1, project_uid.length);
console.log(project_uid);
exec('mkdir '+ project_uid, function (err, out, stderror) {
cd(project_uid);
// clone the repository
exec('git clone ' + req.body.url, function (err, out, stderror) {
if (out !== undefined) {
console.log(out.cyan);
}
if (err) {
console.log(err.red);
res.statusCode = 500;
res.send({"Error":"Something did not go as expected."});
} else {
res.send({"uid": project_uid});
}
});
}); // end $ mkdir project_uid
} else {
res.statusCode = 500;
res.send({"Error" : "Invalid parameters"});
}
});
// Save the files with updated content -- assumes end user has already made a request to /get-project-contents
// POST {'id':string, 'files':object_array}
app.post('/update-project-contents', function (req, res) {
cd(buildProjects_path);
var project_id = req.body.id;
var files = req.body.files;
console.log(files.length + " files need to be saved for "+ project_id.magenta);
cd(buildProjects_path);
var id_dir = ls(project_id)[0];
var xc_projName = ""; // suprisingly enough, people like to name their repository name differently than their .xcodeproj name
for (var z = 0; z < ls(project_id + "/" + id_dir).length; z++) {
if (ls(project_id + "/" + id_dir)[z].indexOf('.xcodeproj') > -1) {
xc_projName = ls(project_id + "/" + id_dir)[z].replace('.xcodeproj', '');
}
}
var j = 0;
writeFiles();
function writeFiles() {
var file = files[j];
fs.writeFile(project_id+"/"+id_dir+"/"+xc_projName+"/"+file.name, file.data, function (err) {
if (err) {
return console.log(err);
}
// console.log(file.name +" was saved at "+ new Date());
if (j < files.length-1) {
j++;
writeFiles();
} else {
res.send("Complete");
}
});
} // end writeFiles()
});
// Get all of the files and their contents within an Xcode project
// POST {'id':string}
app.post('/get-project-contents', function(req, res) {
cd(buildProjects_path);
var project_id = req.body.id;
var id_dir = ls(project_id)[0];
var xc_projName = ""; // suprisingly enough, people like to name their repository name differently than their .xcodeproj name
for (var z = 0; z < ls(project_id + "/" + id_dir).length; z++) {
if (ls(project_id + "/" + id_dir)[z].indexOf('.xcodeproj') > -1) {
xc_projName = ls(project_id + "/" + id_dir)[z].replace('.xcodeproj', '');
}
}
// console.log(('Xcode Project File Name: ' + xc_projName).red);
// crawl the file tree
walk(buildProjects_path + "/" + project_id+"/"+id_dir+"/"+xc_projName, function(err, results) {
if (err) throw err;
var filtered = [];
// filter out all the stuff that is useless
for (var i = 0; i < results.length; i++) {
var tmp = results[i];
tmp = tmp.split("/");
// find all of the unnecessary top level directories
var dirCount = 0;
for (var k = 0; k < tmp.length; k++) {
if (tmp[k] == project_id) {
break;
} else {
dirCount++;
}
}
// console.log(dirCount+3) // should be the number of directories that need to be removed
for (var j = 0; j < dirCount+3; j++) { // remove the parent directories of the file
tmp.shift();
}
tmp = tmp.join("/");
if (!(tmp.indexOf(".xcassets") > -1)) {
if (!(tmp.indexOf(".DS_Store") > -1)) {
if (!(tmp.indexOf(".sks") > -1)) {
if (!(tmp.indexOf(".playground") > -1)) {
if (!(tmp.indexOf(".png") > -1)) {
filtered.push(tmp);
}
}
}
}
} // end filters
} // end for loop
var files = filtered;
res.setHeader('Content-Type', 'application/json');
var i = 0;
loopFiles();
res.write("[");
// uses file streams to grab contents of each file without maxing out RAM
function loopFiles() {
var file = files[i];
var contentForFile = {};
contentForFile["name"] = file;
contentForFile["data"] = "";
var fileChunks = fs.createReadStream(project_id+"/"+id_dir+"/"+xc_projName+"/"+file, {encoding: 'utf-8'});
fileChunks.on('data', function (chunk) {
contentForFile["data"] += chunk;
});
fileChunks.on('end', function() {
console.log(contentForFile.name);
if (i < files.length-1) {
res.write(JSON.stringify(contentForFile)+", ");
i++;
loopFiles();
} else {
res.write(JSON.stringify(contentForFile));
res.write(', {"count": '+ files.length + '}]');
res.send();
cd(buildProjects_path);
}
});
}
});
});
// allows you to add a new Xcode image asset to the project asset catalog (requires PNG file)
// POST {'id':string, 'assetName':string, 'file':base64_file_string}
app.post('/add-image-xcasset', function (req, res) {
cd(buildProjects_path); // always need this
if (req.body.id) {
var project_id = req.body.id;
var newImage = req.body.file;
var xcassetName = req.body.assetName;
var id_dir = ls(project_id)[0];
var xc_projName = ""; // suprisingly enough, people like to name their repository name differently than their .xcodeproj name
for (var z = 0; z < ls(project_id + "/" + id_dir).length; z++) {
if (ls(project_id + "/" + id_dir)[z].indexOf('.xcodeproj') > -1) {
xc_projName = ls(project_id + "/" + id_dir)[z].replace('.xcodeproj', '');
}
}
// console.log(('Xcode Project File Name: ' + xc_projName).red);
var xcassetsDirName = "";
// contents of the xcode project files directory (one level below the .xcodeproj file's directory)
var xcProjDirectory = ls(project_id + "/" + id_dir + "/" + xc_projName);
for (var z = 0; z < xcProjDirectory.length; z++) {
if (xcProjDirectory[z].indexOf('.xcassets') > -1) {
xcassetsDirName = xcProjDirectory[z];
}
}
// console.log(('.xcassets Directory Name: ' + xcassetsDirName).cyan);
var base64Data = req.body.file.replace(/^data:image\/png;base64,/, "");
cd(project_id + "/" + id_dir + "/" + xc_projName + "/" + xcassetsDirName);
exec('mkdir "'+xcassetName+'.imageset"', function (err, out, stderror) {
if (err) {
console.log(err);
}
cd(buildProjects_path + "/"+project_id + "/" + id_dir + "/" + xc_projName + "/" + xcassetsDirName); // lets take it from the top
fs.writeFile(xcassetName + ".imageset/"+xcassetName+".png", base64Data, 'base64', function (err) {
// console.log(ls());
if (err) {
console.log(err);
res.statusCode = 500;
res.send({"Error": "There was an error creating your xcasset"});
} else {
var imageSetJSON = '{\n\
"images" : [\n\
{\n\
"idiom" : "universal",\n\
"scale" : "1x",\n\
"filename" : "'+ xcassetName +'.png"\n\
},\n\
{\n\
"idiom" : "universal",\n\
"scale" : "2x"\n\
},\n\
{\n\
"idiom" : "universal",\n\
"scale" : "3x"\n\
}\n\
],\n\
"info" : {\n\
"version" : 1,\n\
"author" : "xcode"\n\
}\n\
}';
fs.writeFile(xcassetName + ".imageset/Contents.json", imageSetJSON, function(err) {
if (err) {
console.log(err);
res.statusCode = 500;
res.send({"Error": "There was an error creating your xcasset"});
} else {
res.send({"Success":"Image xcasset successfully added."});
}
}); // end writeFile JSON
}
}); // end writeFile PNG
}); // end exec mkdir
} else {
res.statusCode = 500;
res.send({"Error": "Invalid parameters"});
} // end if req.body.id
});
// get the xcasset files
// POST {'id':string}
app.post('/get-image-xcassets', function (req, res) {
cd(buildProjects_path);
if (req.body.id) {
var project_id = req.body.id;
var id_dir = ls(project_id)[0];
var xc_projName = ""; // suprisingly enough, people like to name their repository name differently than their .xcodeproj name
for (var z = 0; z < ls(project_id + "/" + id_dir).length; z++) {
if (ls(project_id + "/" + id_dir)[z].indexOf('.xcodeproj') > -1) {
xc_projName = ls(project_id + "/" + id_dir)[z].replace('.xcodeproj', '');
}
}
// console.log(('Xcode Project File Name: ' + xc_projName).red);
// crawl the file tree
walk(buildProjects_path + "/" + project_id+"/"+id_dir+"/"+xc_projName, function(err, results) {
if (err) throw err;
var filtered = [];
// filter out all the stuff that is useless
for (var i = 0; i < results.length; i++) {
var tmp = results[i];
tmp = tmp.split("/");
// find all of the unnecessary top level directories
var dirCount = 0;
for (var k = 0; k < tmp.length; k++) {
if (tmp[k] == project_id) {
break;
} else {
dirCount++;
}
}
for (var j = 0; j < dirCount+3; j++) { // remove the parent directories
tmp.shift();
}
tmp = tmp.join("/");
// filter through all of the stuff that we don't want
if (!(tmp.indexOf(".swift") > -1)) {
if (!(tmp.indexOf(".lproj") > -1)) {
if (!(tmp.indexOf(".sks") > -1)) {
if (!(tmp.indexOf(".playground") > -1)) {
if (!(tmp.indexOf(".plist") > -1)) {
if (!(tmp.indexOf(".m") > -1)) {
if (!(tmp.indexOf(".h") > -1)) {
if (!(tmp.indexOf(".json") > -1)) {
if (!(tmp.indexOf(".DS_Store") > -1)) {
filtered.push(tmp);
}
}
}
}
}
}
}
}
} // end filters
} // end for loop
var files = [];
for (var n = 0; n < filtered.length; n++) {
var t = filtered[n];
// push the un-altered copy to the files array
files.push(t);
var imageSetPathSplit = t.split("/");
var imageSetName = imageSetPathSplit[1]; // usually the second folder's name in the path hierarchy