-
Notifications
You must be signed in to change notification settings - Fork 0
/
place-export.js
1029 lines (881 loc) · 32.7 KB
/
place-export.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
DEPLOYMENT_CHOICE = 'personal';
DEPLOYMENTS = {
flitto: 'https://script.google.com/macros/s/AKfycbyv_zSd9V7WPCm9HCB-ZPsuKiFy6zVCqlntulD8U_n9M75nxZ77FwAmGqyWCo4j12h8LQ/exec',
personal: 'https://script.google.com/macros/s/AKfycbwmfCR2ZihT6WWwAVlq-1scEmfKB4JsMGeRHhguedtc-0zQXHsaoAzv0FIHXJJnFplRJA/exec', /* outputs to Flitto account*/
flittobot: 'https://script.google.com/macros/s/AKfycbz63F3xWwLj2sxruue4fFdFzGVfFQN4H-r9bvCN-LV2p93MMaTXWcBFKJ877KufKEiz/exec', /* outputs to folders in own account, for testing (change in Drive if needed)*/
}
DEPLOYMENT_URL = DEPLOYMENTS[DEPLOYMENT_CHOICE]
USER_TOKEN = localStorage.getItem('access_token');
PLACES_FOLDER_URL = 'https://drive.google.com/drive/u/1/folders/1F3Bvh5c5isrsDU9JtQ53kIkKHsY6VagX'; // Always Flitto folder (link shown to user by LameModal)
class LameModal {
static html = `
<div id="lame-ui-header">
<a href="` + `${PLACES_FOLDER_URL}` + `" target="_blank" tabindex="-1">
<i _ngcontent-rvc-c130="" class="fa fa-external-link"></i>
Open HO folder
</a>
<button id="lame-ui-close-btn" type="button" class="btn btn-xs btn-secondary">
<i class="fa fa-times fa-lg"></i>
</button>
</div>
<div id="lame-ui-body">
<span>Input place IDs separated by commas</span>
<input id="lame-input" autocomplete="off" tabindex="1"></input>
<label>
<input id="lame-ckbox" type="checkbox" ${(localStorage.lame_srcOnly && JSON.parse(localStorage.lame_srcOnly)) ? 'checked' : ''}>
Source only
</label>
<div id="lame-ui-main-btn-group">
<button id="btn-horz" onclick="go(1)" class="btn btn-info" disabled>
<i _ngcontent-rvc-c130="" class="fa fa-link"></i>
Horizontal (HO)
</button>
<button id="btn-vert" onclick="go(0)" class="btn btn-primary" disabled>
<i _ngcontent-rvc-c130="" class="fa fa-download"></i>
Vertical (HB)
</button>
</div>
</div>`;
static css = `
#lame-ui {
margin-top: 5rem;
padding: 1em 2em 2em 2em;
min-width:50ch;
max-width:100ch;
max-height: 80vh;
border: 0;
box-shadow: #000 0px 0px 1em;
border-radius: 5px;
}
#lame-ui-header {
display: flex;
align-items: end;
justify-content: space-between;
}
#lame-ui-close-btn {
border-radius: 50%;
transform: translate(50%);
}
#lame-ui-close-btn i {
transform: translate(0, -10%);
}
#lame-ui-body {
padding-top: 2em;
max-height: 60vh;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.5em;
}
#lame-ui-body label {
align-self: start;
display: flex;
align-items: center;
gap:5px;
margin-bottom:0;
user-select: none;
}
#lame-ui-main-btn-group {
padding-top: 1em;
display: flex;
justify-content: space-around;
}
dialog::backdrop {
background: #000;
opacity: 0.5;
transition: opacity .15s linear;
}
`;
constructor() {
// Limit to one instance
if (!LameModal.dialog) {
// Make dialog
LameModal.dialog = Object.assign(document.createElement('dialog'), {
id: 'lame-ui',
open: '',
innerHTML: LameModal.html,
});
document.body.append(LameModal.dialog);
// Add css
const styleSheet = Object.assign(document.createElement('style'), { textContent: LameModal.css });
document.head.appendChild(styleSheet);
// Get references for use in OTHER methods
LameModal.inputField = LameModal.dialog.querySelector('#lame-input');
LameModal.btnClose = LameModal.dialog.querySelector('#lame-ui-close-btn');
LameModal.btnHorz = LameModal.dialog.querySelector('#btn-horz');
LameModal.btnVert = LameModal.dialog.querySelector('#btn-vert');
LameModal.srcOnlyBox = LameModal.dialog.querySelector('#lame-ckbox');
// Add events
LameModal.inputField.addEventListener('input', () => LameModal.validateInput());
LameModal.btnClose.addEventListener('click', () => LameModal.close());
}
// Show if hidden
if (!LameModal.dialog.open) {
LameModal.dialog.showModal();
LameModal.dialog.querySelector('#lame-input').focus();
}
return LameModal.dialog
};
static validateInput () {
let val = LameModal.inputField.value;
//let rx = /^\d+(\s*,\s*\d+)*\s*$/ /* Digits separated by commas an optional spaces (trailing comma not allowed)*/
let rxMulti = /^\s*\d{1,6}(\s*,\s*\d{1,6})*\s*,?\s*$/ /* Digits separated by commas an optional spaces */
let rxSingle = /^\s*\d{1,6}\s*$/; // Not used
let rxGoogleSheetUrl = /^https:\/\/docs\.google\.com\/spreadsheets\/d\/\S+$/ //Not strict
let isMulti = rxMulti.test(val);
let isGoogleSheetUrl = rxGoogleSheetUrl.test(val);
LameModal.btnHorz.disabled = !isMulti;
LameModal.btnVert.disabled = !(isMulti || isGoogleSheetUrl); //!isSingle;
};
static close() {
LameModal.btnHorz.disabled = true;
LameModal.btnVert.disabled = true;
LameModal.inputField.value = '';
LameModal.dialog.close()
}
}
const lameify = () => new LameModal;
class Spinner {
static wrapper;
static templates = {
wrapper: `
<header id="spinners-sticky-header">
<button style=
"
margin-right: auto;
background: none!important;
border: none;
padding: 0!important;
color: #069;
text-decoration: underline;
cursor: pointer;
user-select: none;
"
onclick="Spinner.close('all')"
>Close all</button>
</header>
`,
loading: function (msg = 'Getting ready...') {
return `
<!-- https://loading.io/css/ -->
<div class="lds-ring"><div></div><div></div><div></div><div></div></div>
<p class="progress-msg" style="text-align:center; word-break: break-all;">${msg}</p>
`
},
ho: {
notFound: function (notFoundPlaceId) {
return `
<div style="width: 100%; display: flex; justify-content: space-between;">
<span>No place data found for:</span>
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center;">
<span>${notFoundPlaceId}</span>
</div>
`
},
preexisting: function (values) {
return `
<div style="width: 100%; display: flex; justify-content: end;">
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center; margin-bottom: 1rem;">
<a class="ho-link" href="${values.sheetUrl}" target="_blank" style="text-decoration:underline;">${values.sheetName}</a>
<s style="text-decoration:none;">(기존시트)</s>
</div>
`
},
new: function (values) {
let newUrl = `https://docs.google.com/spreadsheets/d/${values.newSheetId}`;
return `
<div style="width: 100%; display: flex; justify-content: end;">
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center; margin-bottom: 1rem;">
<a class="ho-link" href="${newUrl}" target="_blank" style="text-decoration:underline;">${values.fullPlaceName}</a>
</div>
`
},
project: function(projectSheetUrl) {
return `
<div style="width: 100%; display: flex; justify-content: end;">
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center; margin-bottom: 1rem;">
<a class="ho-link" href="${projectSheetUrl}" target="_blank" style="text-decoration:underline;">Your Project</a>
</div>
</div>
`
},
},
hb: {
success: function (values) {
// response is url to vertical (hb) sheet
return `
<div style="width: 100%; display: flex; justify-content: end;">
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center;">
<a href="${values.res}"
style="text-align: center;word-break: break-all;
margin-bottom:1em">Download HB sheet<br>${(isNaN(values.chosenPlaceId))
? (values.chosenPlaceId)
: ' for place ' + values.chosenPlaceId }</a>
</div>
`
},
formulaError: function (hoSheetUrl) {
// hoSheetUrl's firs 6 chars == '#ERROR'
return `
<div style="width: 100%; display: flex; justify-content: space-between;">
<span></span>
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center; color: indianred">
<span>Formula error(s) found.</span>
<span>Search for <b>"#"</b> in:</span>
<a href="${hoSheetUrl.slice(6, hoSheetUrl.length)}" target="_blank" style="text-decoration:underline; text-align: center; margin-bottom:1em">SOURCE SHEET</a>
</div>
`
},
notFound: function (notFoundPlaceId) {
return `
<div style="width: 100%; display: flex; justify-content: space-between;">
<span>No sheet found for:</span>
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center;">
<span>${notFoundPlaceId}</span>
</div>
`
}
},
exception: function(msg = 'Something went wrong') {
return `
<div style="width: 100%; display: flex; justify-content: space-between;">
<span></span>
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center; color: indianred; word-break: break-all;">
<span style="text-align:center; margin-bottom: 1rem;">${msg}</span>
</div>
`
},
unknownError: function (values) {
return `
<div style="width: 100%; display: flex; justify-content: space-between;">
<span></span>
<button onclick="Spinner.close(this)" style="border:0;background-color:transparent;user-select:none;">x</button>
</div>
<div style="flex-grow: 1; display: grid; place-items: center; color: indianred; word-break: break-all;">
<span>Something went wrong</span>
<span>${(isNaN(values.chosenPlaceId))
? values.chosenPlaceId
: ' with place ' + values.chosenPlaceId + '.' }</span>
<button style=
"
background: none!important;
border: none;
padding: 0!important;
color: #069;
text-decoration: underline;
cursor: pointer;
"
onclick="alert(\`${values.err}\`)"
>See details</button>
</div>
`
},
};
static css = `
#spinners-wrap {
z-index: 3001;
min-width: 200px;
max-width: 300px;
max-height: 90vh;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 5px;
position: fixed;
top: 5px;
right: 5px;
background-color: white;
border: 5px solid lightgray;
padding: 0 5px 5px 5px;
}
#spinners-sticky-header {
z-index: 3002;
position: sticky;
top: 0;
background-color: #fff;
padding-top: 5px;
box-shadow: 0px 15px 10px -10px #fff;
}
.spinner {
position: relative;
display: flex;
flex-direction:column;
align-items:center;
justify-content:center;
background-color: whitesmoke;
padding: 5px;
}
/* https://loading.io/css/ */
.lds-ring {
display: inline-block;
position: relative;
width: 80px;
height: 80px;
}
.lds-ring div {
box-sizing: border-box;
display: block;
position: absolute;
width: 64px;
height: 64px;
margin: 8px;
border: 8px solid steelblue;
border-radius: 50%;
animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
border-color: steelblue transparent transparent transparent;
}
.lds-ring div:nth-child(1) {
animation-delay: -0.45s;
}
.lds-ring div:nth-child(2) {
animation-delay: -0.3s;
}
.lds-ring div:nth-child(3) {
animation-delay: -0.15s;
}
@keyframes lds-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
`;
static close = function (target) {
const wrap = document.getElementById('spinners-wrap');
if (target == 'all') {
wrap.remove();
return
}
else {
target.closest('.spinner').remove();
if (wrap.children.length <= 1) { // child 1 = Close all button
wrap.remove();
}
}
}
setMsg(msg) {
this.element.querySelector('.progress-msg').innerHTML = msg;
}
setInnerHTML(html) {
this.element.innerHTML= html;
}
setTemplate(templatePath, values) {
let template = Spinner.resolveObjPath(templatePath, Spinner.templates);
let filledUpTemplate = template(values);
this.element.innerHTML= filledUpTemplate;
}
static resolveObjPath(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev?.[curr], obj)
}
constructor(initMsg = '') {
//Make wrapper if not exist
if (!document.getElementById('spinners-wrap')) {
Spinner.wrapper = Object.assign(document.createElement('div'), {
id: 'spinners-wrap',
innerHTML: Spinner.templates.wrapper,
onclick: function (e) {
// Remove selection caused by triple click
window.getSelection().removeAllRanges();
// Wait for deselection to be repainted
setTimeout(() => {
if ((e.detail === 3 && e.target.id === 'spinners-wrap')
|| (e.detail === 3 && e.target.id === 'spinners-sticky-header')) {
//On triple click:
if (!document.querySelectorAll('#spinners-wrap a.ho-link').length) return
if (confirm('Combine HO sheets into project sheet?')) {
combineProject()
}
}
}, 0);
},
});
document.body.append(Spinner.wrapper);
}
// Append CSS if not exist
if (!document.getElementById('spinner-styleSheet')) {
let styleSheet = Object.assign(document.createElement('style'), {
id: 'spinner-styleSheet',
textContent: Spinner.css,
});
document.head.appendChild(styleSheet);
}
// Make individual spinner
this.element = Object.assign(document.createElement('div'), {
classList: 'spinner',
innerHTML: Spinner.templates.loading(initMsg),
});
document.getElementById('spinners-wrap').append(this.element);
return this
}
}
function go(isHO) {
//save settings
localStorage.setItem('lame_srcOnly', JSON.stringify(LameModal.srcOnlyBox.checked));
//
let inputStr = LameModal.inputField.value;
if (isNaN(inputStr[0])) {
// Input is URL:
const baseUrlLen = 39;
const idLen = 44;
const id = inputStr.slice(baseUrlLen, baseUrlLen + idLen);
processProjRevert(id) //Sheet URL of combined project
LameModal.close()
return
}
// Input is IDs:
let inputArr = inputStr.split(/\s*,\s*/).filter(item => (item));
let inputSet = new Set(inputArr);
LameModal.close()
let cb = (isHO) ? processHO : processHB;
let delay = 500; // just in case
inputSet.forEach( (id, i) => /* setTimeout( */cb(id)/* , delay * i) */ )
}
async function processProjRevert(sheetId) {
let chosenPlaceId = sheetId; //deconstructed name expected by template
let spinner = new Spinner(`Processing for download...<br>(${sheetId})`);
try {
let res = await fetchGetFromGS('id' + sheetId) // 'id' string used for routing
if (/^http/.test(res)) {
console.log(res);
spinner.setTemplate('hb.success', {chosenPlaceId, res});
return
}
else if (/^#ERROR/.test(res)) {
spinner.setTemplate('hb.formulaError', res);
return
}
}
catch(err) {
console.error(`Error on ${arguments.callee.name} for ${chosenPlaceId}:`, err);
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
}
async function processHB(chosenPlaceId) {
let spinner = new Spinner(`Processing place #${chosenPlaceId}<br>for download...`);
try {
let res = await fetchGetFromGS('v' + chosenPlaceId); //Notice the "v" for vertical!
if (/^http/.test(res)) {
console.log(res);
spinner.setTemplate('hb.success', {chosenPlaceId, res});
return
}
else if (/^#ERROR/.test(res)) {
spinner.setTemplate('hb.formulaError', res);
return
}
else {
spinner.setTemplate('hb.notFound', res);
return
}
}
catch(err) {
console.error(`Error on ${arguments.callee.name} for ${chosenPlaceId}:`, err);
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
}
async function fetchGetFromGS(query) {
let url = DEPLOYMENT_URL + '?' + query;
let sResponse = await fetch(url, {method: 'GET'});
let oResponse = JSON.parse(await sResponse.text());
// Response.ok / Response.status / etc. not available here.
// Because Google Sheets always returns 200.
// (Or redirects to error page, causing some CORS error)
if (oResponse['server-error'] > 0) throw new Error(oResponse.innards)
return oResponse.innards;
}
async function processHO(chosenPlaceId) {
// Check if sheet already exists -----------------------------------------
let spinner = new Spinner('Checking existing files...');
try {
let preexisting = await fetchGetFromGS(chosenPlaceId);
if (preexisting.found) {
let {sheetUrl, sheetName} = preexisting;
spinner.setTemplate('ho.preexisting', {sheetUrl, sheetName});
return
}
}
catch(err) {
console.error(`Error on ${arguments.callee.name} for ${chosenPlaceId}:`, err);
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
// Doesn't already exist, so fetch basic info -----------------------------------
spinner.setMsg('Fetching place details...');
let basicPlaceInfo;
try {
basicPlaceInfo = await fetchBasicPlaceInfo(chosenPlaceId);
if (!basicPlaceInfo) {
spinner.setTemplate('ho.notFound', chosenPlaceId);
return
}
}
catch(err) {
console.error(`Error on ${arguments.callee.name} for ${chosenPlaceId}:`, err);
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
// Now, fetch every page listed in basic info -----------------------------
let promises = [];
let i = 0;
for (let item of basicPlaceInfo.item) {
i++;
spinner.setMsg(`Working on image ${i} / ${basicPlaceInfo.item.length}`);
let promise = await fetchItem(item.item_id);
promises.push(promise);
}
let pages = await Promise.all(promises)
.then(results => { return results } )
.catch(error => {
console.error(`Error in page promises: ${error}`)
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
});
if (!pages.length) {
spinner.setTemplate('exception', `No images found for <br> place ${chosenPlaceId}.`);
return
}
let activePages = pages.filter( p => p.status == 'Y');
let placesBaseURL = 'https://a3.flit.to/#/menu-tr/places/'
if (!activePages.length) {
let link = `<a style="color: indianred; text-decoration: underline;"
href="${placesBaseURL}${chosenPlaceId}/items">${chosenPlaceId}</a>`;
spinner.setTemplate('exception', `Place ${link}<br>has no active images.`);
return
}
console.log(pages)
/*
if (!pages[0].item_org.length) {
let link = `<a style="color: indianred; text-decoration: underline;"
href="${placesBaseURL}${chosenPlaceId}/items">${chosenPlaceId}</a>`;
spinner.setTemplate('exception', `Place ${link}<br>has no translatable text.`);
return
}
*/
// Reshuffle data in preparation to request make sheet
let simplifiedData;
try {
simplifiedData = simplifyData(basicPlaceInfo, activePages);
console.log(simplifiedData);
}
catch(err) {
console.error(`Error on ${arguments.callee.name} for ${chosenPlaceId}:`, err);
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
// Request making of new HO sheet -----------------------------------------
spinner.setMsg('Making spreadsheet...<br>(May take a while)');
try {
let newSheetId = await requestSheet(simplifiedData);
let fullPlaceName = `${basicPlaceInfo.place_id}. ${basicPlaceInfo.place_info.title}`;
spinner.setTemplate('ho.new', {newSheetId, fullPlaceName})
return
}
catch(err) {
console.error(`Error on ${arguments.callee.name} for ${chosenPlaceId}:`, err);
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
async function requestSheet(data) {
let sData = JSON.stringify(data);
let options = {
method: 'POST',
body: sData,
headers: { 'Content-Type': 'text/plain;charset=utf-8' }
};
let sResponse = await fetch(DEPLOYMENT_URL, options)
let oResponse = JSON.parse(await sResponse.text());
// Response.ok / Response.status / etc. not available here.
// Because Google Sheets always returns 200.
// (Or redirects to error page, causing some CORS error)
if (oResponse['server-error'] > 0) throw new Error(oResponse.innards)
return oResponse.innards;
}
async function fetchBasicPlaceInfo(placeId) {
let url = `https://a3-prod.flit.to:1443/v2/qr-place/places/${placeId}?place_id=${placeId}&_method=GET`;
let options = {
method: 'GET',
headers: { Authorization: 'Bearer ' + USER_TOKEN, 'content-type': 'application/json' }
};
let response = await fetch(url, options);
if (!response.ok) {
const message = `Fetching of place ${placeId} details failed w/ status: ${response.status}`;
console.log(message);
throw new Error(message);
}
let responseBody = await response.text();
if (!responseBody) return null; // An empty body means the place doesn't exist
return JSON.parse(responseBody);
}
async function fetchItem(itemId) {
let itemUrl = `https://a3-prod.flit.to:1443/v2/qr-place/items/${itemId}?_method=GET`;
let options = {
method: 'GET',
headers: { Authorization: 'Bearer ' + USER_TOKEN, 'content-type': 'application/json' }
};
let response = await fetch(itemUrl, options);
if (!response.ok) {
const message = `Fetching of item (page) ${itemId} failed w/ status: ${response.status}`;
console.log(message);
throw new Error(message);
}
let json = await response.json();
return json
}
}
async function combineProject() {
let spinner = new Spinner(`Merging sheets... `);
const hoLinkElems = [...document.querySelectorAll('#spinners-wrap a.ho-link')]
const urlArray = hoLinkElems.map(a => a.href)
try{
const projectSheetUrl = await requestMergeProject(urlArray);
spinner.setTemplate('ho.project', projectSheetUrl);
return
}
catch(err) {
console.error(`Error on ${arguments.callee.name}`, err);
let chosenPlaceId = 'when combining files.';
spinner.setTemplate('unknownError', {chosenPlaceId, err});
return
}
async function requestMergeProject(urlArray) {
let sData = JSON.stringify(urlArray);
let options = {
method: 'POST',
body: sData,
headers: { 'Content-Type': 'text/plain;charset=utf-8' }
};
console.log(sData)
let sResponse = await fetch(DEPLOYMENT_URL, options)
let oResponse = JSON.parse(await sResponse.text());
// Response.ok / Response.status / etc. not available here.
// Because Google Sheets always returns 200.
// (Or redirects to error page, causing some CORS error)
if (oResponse['server-error'] > 0) throw new Error(oResponse.innards)
return oResponse.innards;
}
}
function simplifyData(basicPlaceInfo, pages) {
const flittoLangs = {
"1": "Afrikaans(Afrikaans)",
"2": "Albanian(gjuha shqipe)",
"3": "Arabic(العربية)",
"4": "Armenian(Հայերեն)",
"5": "Azerbaijani(azərbaycan dili)",
"6": "Belarusian(беларуская мова)",
"7": "Bengali(বাংলা)",
"8": "Bosnian(bosanski jezik)",
"9": "Bulgarian(български език)",
"10": "Catalan(català, valencià)",
"11": "Chinese (Simplified)(中文(简体))",
"12": "Chinese (Traditional)(中文(繁體))",
"13": "Croatian(hrvatski jezik)",
"14": "Czech(Čeština)",
"15": "Danish(dansk)",
"16": "Dutch(Nederlands)",
"17": "English(English)",
"18": "Estonian(eesti, eesti keel)",
"19": "Finnish(suomi)",
"20": "French(Français)",
"21": "Georgian(ქართული)",
"22": "German(Deutsch)",
"23": "Greek(ελληνικά)",
"24": "Hebrew(עברית)",
"25": "Hindi(हिन्दी, हिंदी)",
"26": "Hungarian(magyar)",
"27": "Indonesian(Bahasa Indonesia)",
"28": "Icelandic(Íslenska)",
"29": "Italian(Italiano)",
"30": "Japanese(日本語)",
"31": "Kazakh(қазақ тілі)",
"32": "Khmer(ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ)",
"33": "Korean(한국어)",
"34": "Lao(ພາສາລາວ)",
"35": "Lithuanian(lietuvių kalba)",
"36": "Latvian(latviešu valoda)",
"37": "Macedonian(македонски јазик)",
"38": "Malay(Bahasa Melayu)",
"39": "Maltese(Malti)",
"40": "Mongolian(монгол)",
"41": "Norwegian Bokmål(Norsk bokmål)",
"42": "Punjabi(ਪੰਜਾਬੀ, پنجابی)",
"43": "Persian(فارسی)",
"44": "Polish(Polski)",
"45": "Portuguese(Português)",
"46": "Romansh(rumantsch grischun)",
"47": "Romanian(limba română, limba moldovenească)",
"48": "Russian(Русский язык)",
"49": "Serbian(српски језик)",
"50": "Slovak(slovenčina, slovenský jazyk)",
"51": "Slovene(slovenski jezik, slovenščina)",
"52": "Spanish(Español)",
"53": "Swedish(Svenska)",
"54": "Tamil(தமிழ்)",
"55": "Tajik(тоҷикӣ, toğikī, تاجیکی)",
"56": "Thai(ไทย)",
"57": "Turkish(Türkçe)",
"58": "Ukrainian(українська мова)",
"59": "Urdu(اردو)",
"60": "Uzbek(O'zbek, Ўзбек, أۇزبېك)",
"61": "Vietnamese(Tiếng Việt)",
"62": "Tagalog(Tagalog)",
"63": "Swahili(Kiswahili)",
"64": "English(British)(English(British))",
"65": "Spanish(Latin America)(Español(Latinoamérica))",
"66": "Portuguese(Brazil)(Português(Brasil))",
"67": "French(Canada)(français(canadien))",
"68": "Burmese(Burmese)",
"69": "Chinese (Cantonese)(中文(廣東話))",
"Afrikaans(Afrikaans)": 1,
"Albanian(gjuha shqipe)": 2,
"Arabic(العربية)": 3,
"Armenian(Հայերեն)": 4,
"Azerbaijani(azərbaycan dili)": 5,
"Belarusian(беларуская мова)": 6,
"Bengali(বাংলা)": 7,
"Bosnian(bosanski jezik)": 8,
"Bulgarian(български език)": 9,
"Catalan(català, valencià)": 10,
"Chinese (Simplified)(中文(简体))": 11,
"Chinese (Traditional)(中文(繁體))": 12,
"Croatian(hrvatski jezik)": 13,
"Czech(Čeština)": 14,
"Danish(dansk)": 15,
"Dutch(Nederlands)": 16,
"English(English)": 17,
"Estonian(eesti, eesti keel)": 18,
"Finnish(suomi)": 19,
"French(Français)": 20,
"Georgian(ქართული)": 21,
"German(Deutsch)": 22,
"Greek(ελληνικά)": 23,
"Hebrew(עברית)": 24,
"Hindi(हिन्दी, हिंदी)": 25,
"Hungarian(magyar)": 26,
"Indonesian(Bahasa Indonesia)": 27,
"Icelandic(Íslenska)": 28,
"Italian(Italiano)": 29,
"Japanese(日本語)": 30,
"Kazakh(қазақ тілі)": 31,
"Khmer(ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ)": 32,
"Korean(한국어)": 33,
"Lao(ພາສາລາວ)": 34,
"Lithuanian(lietuvių kalba)": 35,
"Latvian(latviešu valoda)": 36,
"Macedonian(македонски јазик)": 37,
"Malay(Bahasa Melayu)": 38,
"Maltese(Malti)": 39,
"Mongolian(монгол)": 40,
"Norwegian Bokmål(Norsk bokmål)": 41,
"Punjabi(ਪੰਜਾਬੀ, پنجابی)": 42,
"Persian(فارسی)": 43,
"Polish(Polski)": 44,
"Portuguese(Português)": 45,
"Romansh(rumantsch grischun)": 46,
"Romanian(limba română, limba moldovenească)": 47,
"Russian(Русский язык)": 48,
"Serbian(српски језик)": 49,
"Slovak(slovenčina, slovenský jazyk)": 50,
"Slovene(slovenski jezik, slovenščina)": 51,
"Spanish(Español)": 52,
"Swedish(Svenska)": 53,
"Tamil(தமிழ்)": 54,
"Tajik(тоҷикӣ, toğikī, تاجیکی)": 55,
"Thai(ไทย)": 56,
"Turkish(Türkçe)": 57,
"Ukrainian(українська мова)": 58,
"Urdu(اردو)": 59,
"Uzbek(O'zbek, Ўзбек, أۇزبېك)": 60,
"Vietnamese(Tiếng Việt)": 61,
"Tagalog(Tagalog)": 62,
"Swahili(Kiswahili)": 63,
"English(British)(English(British))": 64,
"Spanish(Latin America)(Español(Latinoamérica))": 65,
"Portuguese(Brazil)(Português(Brasil))": 66,
"French(Canada)(français(canadien))": 67,
"Burmese(Burmese)": 68,
"Chinese (Cantonese)(中文(廣東話))": 69
};
/*
Get target languages from 1st page, 1st segment
DON'T trust laguages set in basic info.
Why not?
Place 1 (basic info):
lang_id: 30 (matches Japanese image)
place_lang_pair: ko(33) → ja(30) //Flipped src/trg
Place 873 (basic info):
lang_id: 17 (does NOT match Korean image)
place_lang_pair: ko(33) → en(17) //Correct pair
*/
let validPage = pages.find(page => page.item_org[0]);
if (!validPage) throw Error('All menu pages are empty');
let targetLangs = validPage.item_org[0].item_tr.map(tr => flittoLangs[tr.lang_id])
/*
//QUICK FIX on 230209 for 776
targetLangs = ['Arabic(العربية)', 'Chinese (Simplified)(中文(简体))', 'Chinese (Traditional)(中文(繁體))', 'English(English)', 'Japanese(日本語)', 'Mongolian(монгол)', 'Russian(Русский язык)', 'Vietnamese(Tiếng Việt)']
//
console.log(targetLangs)
*/
targetLangs.sort();
let sortedLangIds = targetLangs.map( lang => flittoLangs[lang] );
let simple = {
placeName: basicPlaceInfo.place_info.title,
placeId: basicPlaceInfo.place_info.place_id,
mainImageUrl: basicPlaceInfo.place_image[0].image_url,
langs: targetLangs,
};
let simplePages = pages.map(p => {
return {
pageId: p.item_id,
imageUrl: p.image_url,
segments:
/* 1. If segment is empty, wrap in 2d array, as required by Google Sheets */
(!p.item_org.length) ? [['']]
: p.item_org.reduce((prev, seg) => {
/* 2. Filter out 삭제됨 items (status = 'D'), leaving only 사용 가능 (status = 'Y') */
if (seg.status != 'Y') { return prev }
/* 3. Get "id", "source language", and "content" columns */
let sourceInfo = [seg.item_org_id, flittoLangs[seg.lang_id], seg.content];
/* NEW: 3.5 Skip sorting translationg if clicked source-only checkbox*/
if (LameModal.srcOnlyBox.checked) {
return [...prev, sourceInfo];