-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1078 lines (906 loc) · 36.8 KB
/
Copy pathindex.html
File metadata and controls
1078 lines (906 loc) · 36.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thingiverse Upload Editor</title>
<script src="https://cdn.jsdelivr.net/gh/MicroContent/ThingiverseUploadEditor@main/seamlessjs/seamless.child.min.js"></script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.2.1/dist/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css">
<style>
body {
background-color: whitesmoke;
border-bottom: 0 solid black;
display: flex;
justify-content: center;
align-items: center;
}
/* === Wrapper Styles === */
.container {
margin: 3em 4em 3em 4em;
}
#FileUpload {
justify-content: center;
}
.wrapper {
padding: 0.5em;
box-shadow: 0 1em 2em rgba(0, 0, 0, 0.30), 0 0.6em 0.5em rgba(0, 0, 0, 0.22);
border-radius: 0.5em;
background-color: white;
max-height: 35em;
overflow: auto;
margin-bottom: 1em;
}
.title-section {
display: flex;
justify-content: center;
align-content: flex-start;
flex-wrap: wrap;
}
/* === Text Input Box === */
.title {
letter-spacing: 0.1em;
text-align: center;
}
#helpTitle {
font-weight: bold;
}
.form-control {
margin-top: 1em;
}
label {
margin-bottom: 0 !important;
}
.custom-file-label {
margin-bottom: 0.5em;
cursor: pointer;
}
#inputGroupFile {
margin-bottom: 0.5em;
}
small {
float: right;
}
.info-icon {
cursor: pointer;
}
.break {
flex-basis: 100%;
height: 0;
}
.tool-tip {
flex-basis: 100%;
display: none;
z-index: 2;
}
.tooltiptext {
max-width: 30em;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 0.5em;
position: absolute;
}
.tooltiptext::after {
content: "";
position: absolute;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
#close-txt {
text-decoration: underline;
cursor: pointer;
}
/* === Upload Box === */
.upload {
margin: 0.5em;
height: auto;
border: 0.5em dashed #EDEDED;
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
border-radius: 0.3em;
}
.upload p {
margin-top: 0.5em;
line-height: 0;
font-size: 1.3rem;
color: #0c3214;
letter-spacing: 0.1em;
}
.hint-formats {
text-align: center;
width: 80%;
margin-bottom: 0.5em;
}
.upload-button {
height: 2.3em;
background-color: #EDEDED;
box-shadow: 0 0.3em 0.5em rgba(0, 0, 0, 0.22);
border: 0;
border-radius: 0.5em;
padding: 0 0.3em 0 0.5em;
}
.upload-button:hover {
cursor: pointer;
opacity: 0.8;
}
/* === Uploaded Files === */
.uploaded {
width: 96%;
margin: 0.5em;
padding: 0.5em;
background-color: #EDEDED;
border-radius: 0.5em;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
}
.file {
display: flex;
width: 100%;
flex-direction: column;
}
.file-name {
display: flex;
flex-direction: row;
align-items: baseline;
width: 100%;
line-height: 0;
color: #0c3214;
font-size: 1.1rem;
letter-spacing: 0.1em;
}
.file-name p {
flex-grow: 2;
}
.fa-info-circle {
margin-right: 0.5em;
}
.fa-times:hover {
cursor: pointer;
opacity: 0.8;
}
.fa-file {
padding: 0.3em;
font-size: 1em;
color: #0c3214;
}
.fa-redo {
padding: 0.3em;
font-size: 1.4em;
}
.fa-redo:hover {
cursor: pointer;
opacity: 0.9;
}
.error {
margin: 0.5em;
color: red;
}
#selectFile {
display: none;
}
.btn {
width: 6em;
float: right;
}
.fa-exclamation-triangle {
color: red;
}
</style>
</head>
<body>
<!-- Connection establishment and communication -->
<script>
var parent = window.seamless.connect({
url: window.location.url,
allowStyleInjection: true
});
parent.receive(function (data) {
switch (data.type) {
case 'setContent':
window.data = data.main[0];
init(window.data);
break;
case 'getContent':
sendToParent();
}
});
window.sendToParent = function (event) {
if (event) {
event.preventDefault();
}
dataGetter().then(data => {
parent.send(data);
updateLayout();
});
}
function updateLayout() {
parent.send({
type: 'updateLayout'
});
}
async function dataGetter() {
const previewImgUrl = await readFileAsUrl(titleImage);
let cloudinaryFilesUrl = await readAllFilesAsUrl(cloudinaryFiles);
const fileNames = fileList.map(file => file.name ? file.name : file);
return {
type: 'updateData',
title: title,
thingUrl: thingiverseItemUrl,
imageUrl: previewImgUrl,
altDescription: altDescription,
description: description,
mediaUrlArray: cloudinaryFilesUrl,
fileNames: fileNames,
thingiverseIdMap: thingiverseIdMap
}
}
async function init(data) {
await fetch("https://res.cloudinary.com/dowxznli2/raw/upload/v1685973374/test_vmgndw.json")
.then(response => response.json())
.then(data => {
thingiverse = Object.values(data)[0];
});
if (data) {
if (data.thingUrl) {
isEdit = true;
thingiverseItemUrl = data.thingUrl;
}
title = data.title ? data.title : ""
description = data.description ? data.description : "";
instructions = data.instructions ? data.instructions : "";
fileList = data.fileNames ? data.fileNames : [];
cloudinaryFiles = data.mediaUrlArray ? data.mediaUrlArray : [];
titleImage = data.imageUrl ? data.imageUrl : "";
thingiverseIdMap = data.thingiverseIdMap ? data.thingiverseIdMap : [];
for (const filename of fileList) {
const isAlreadyUploaded = true;
renderUploadItem(filename, isAlreadyUploaded)
}
updateNrOfFilesString();
document.getElementById('inputTitle').value = title;
document.getElementById('inputDescription').value = description;
document.getElementById('inputInstructions').value = instructions;
}
}
</script>
<!-- UI -->
<div class="container">
<div class="wrapper form-group">
<div class="title-section">
<h3 class="title">Upload Files </h3>
<div class="bi bi-info-circle info-icon " onclick="toggleTooltip()"></div>
<div class="tool-tip" id="tooltip">
<span class="tooltiptext">This plugin helps you upload 3D printing files and all associated data.
The files will be uploaded to the <a href="https://www.thingiverse.com/tatabooks/designs"
target="_blank">tatabooks</a> account by default,
if you would like to upload files to your own account, please upload them to <a
href="https://www.thingiverse.com/" target="_blank">Thingiverse</a> directly.
<br><span id="close-txt" onclick="toggleTooltip()">Dismiss</span></span>
</div>
</div>
<form class="needs-validation" id="form">
<input id="inputTitle" class="form-control" maxlength="100" aria-labelledby="helpTitle" placeholder="Title*"
type="text" required>
<label class="hint" id="helpTitle" for="inputTitle">Enter a title for the Thing (max. 100 characters)</label>
<small>*required</small>
<div class="invalid-feedback">
Please add a title!
</div>
<div class="input-group form-control">
<input type="file" accept="image/*" id="inputGroupFile">
<label class="custom-file-label" for="inputGroupFile" id="inputGroupFileLabel">Choose Preview
Image</label>
</div>
<input id="inputAltDesc" class="form-control" placeholder="alt. description" type="text">
<label class="hint" id="helpAlt" for="inputAltDesc">Please add an alt. description for your title
image</label>
<textarea id="inputDescription" maxlength="2000" rows="3"
class="form-control" aria-labelledby="labelDescription"
placeholder="Add a text to describe the Thing you want to upload to Thingiverse*"
required></textarea>
<label id="labelDescription" for="inputDescription">Description</label>
<small>*required</small>
<div class="invalid-feedback">
Please add a description!
</div>
<textarea id="inputInstructions" maxlength="200" rows="3"
class="form-control" aria-labelledby="labelDescription"
placeholder="Add instructions for printing to the Thing you want to upload to Thingiverse"></textarea>
<label id="labelInstructions" for="inputInstructions">Instructions</label>
</form>
</div>
<div id="FileUpload">
<div class="wrapper">
<div class="upload" id="uploadZone">
<p>Drag files here or </p>
<div class="break"></div>
<button class="upload-button" onclick="openFileExplorer()">Browse</button>
<input type="file" id="selectFile" multiple>
<div class="break"></div>
<small class="hint-formats">Allowed file formats:<br>stl, obj, thing, scad, amf, dae, 3ds, x3d, blend,
ply, dxf, ai, cdr, ps, eps, epsi, sch, brd, jpg, png, gif, svg, txt, doc, docx, mp3, wav,
mp4</small>
</div>
<div class="error" id="errorMaxFile" style="display: none"></div>
<div class="error" id="errorFileFormat" style="display: none"></div>
<p>No. of files: <strong id="nrFiles">0</strong></p>
<div id="divUploadItems"></div>
</div>
</div>
<button type="submit" class="btn btn-success" onclick="uploadFiles(fileList)">Upload</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete this file?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="btn-delete">Delete</button>
</div>
</div>
</div>
</div>
</div>
<!-- == Plugin Logic == -->
<script>
/* === Event Listeners on UI === */
document.getElementById('inputGroupFile').addEventListener('change', (e) => {
if (!e.target.files[0]) return;
titleImage = e.target.files[0];
document.getElementById('inputGroupFileLabel').innerText = titleImage.name;
});
document.getElementById('inputAltDesc').addEventListener('change', (e) => {
altDescription = e.target.value;
});
document.getElementById('inputTitle').addEventListener('change', (e) => {
title = e.target.value;
});
document.getElementById('inputDescription').addEventListener('change', (e) => {
description = e.target.value;
});
document.getElementById('inputInstructions').addEventListener('change', (e) => {
instructions = e.target.value;
});
document.getElementById('uploadZone').addEventListener('drop', (e) => {
e.preventDefault();
let files = e.dataTransfer.files;
addFiles(files);
});
document.getElementById('uploadZone').addEventListener('dragover', (e) => {
e.preventDefault();
document.getElementById('uploadZone').style.borderColor = '#A9A9A9';
});
document.getElementById('uploadZone').addEventListener('dragleave', (e) => {
e.preventDefault();
document.getElementById('uploadZone').style.borderColor = '#EDEDED';
});
function openFileExplorer() {
const inputFile = document.getElementById('selectFile');
inputFile.click();
inputFile.onchange = function () {
let files = document.getElementById('selectFile').files;
addFiles(files);
};
}
function addFiles(files) {
resetErrors();
for (const file of files) {
if (validateFile(file)) {
fileList.push(file);
renderUploadItem(file.name);
if (!checkIfThingiverseFile(file.name)) {
cloudinaryFiles.push(file);
}
}
}
updateNrOfFilesString();
}
$(document).on('click', '.fa-times', function () {
let filename = $(this).attr("id").replace('icon-close-', "");
$("#exampleModal").attr("caller-id", "uploaded-" + filename);
});
$(document).on('click', '#btn-delete', () => {
let caller = $("#btn-delete").closest(".modal").attr("caller-id");
removeFile(caller);
$('#exampleModal').modal('hide');
});
function handleRemoveClick(documentId, filename) {
if (isEdit) {
$('#exampleModal').modal('show');
} else {
removeFile(documentId, filename);
}
}
function removeFile(documentId, filename) {
if (!filename) {
filename = documentId.replace('uploaded-', '');
}
const thingiverseId = thingiverseIdMap.filter(elem => elem.name === filename).map(elem => elem.id);
if (thingiverseId.length > 0 && thingiverseItemUrl !== "") {
const itemId = getItemId();
const isImage = checkIfImage(filename);
deleteThingiverseFileById(thingiverseId, itemId, isImage);
}
document.getElementById(documentId).remove();
fileList = fileList.filter(file => file.name !== filename && file !== filename);
updateNrOfFilesString();
}
function validateFile(file) {
if (!file) {
setErrorMaxFile("Oops! Something went wrong.")
return false;
} else if (fileList.length >= 80) {
setErrorMaxFile("You can only upload a maximum of 80 files!")
return false;
} else if (!checkIfValidFileFormat(file.name)) {
setErrorMsgFormat(`${file.name}: not a valid file format\n`)
return false;
} else if (!checkIfThingiverseFile(file.name) && !checkIfValidFileSize(file)) {
setErrorMaxFile("File size cannot exceed 10MB!")
return false;
}
return true;
}
/**
* Checks if a given filename has a valid format for upload at thingiverse
* @param filename name (incl. extension) of the file to check
* @return {boolean}
*/
function checkIfThingiverseFile(filename) {
const regex = new RegExp(/[^\s]+(.*?).(stl|obj|thing|scad|amf|dae|3ds|x3d|blend|ply|dxf|ai|cdr|ps|eps|epsi|sch|brd|jpe?g|png|gif|svg|txt|doc|docx|gcode)$/)
return regex.test(filename.toLowerCase());
}
function checkIfValidFileFormat(filename) {
const regex = new RegExp(/[^\s]+(.*?).(stl|obj|thing|scad|amf|dae|3ds|x3d|blend|ply|dxf|ai|cdr|ps|eps|epsi|sch|brd|jpe?g|png|gif|svg|txt|doc|docx|gcode|mp3|mp4|wav)$/)
return regex.test(filename.toLowerCase())
}
function checkIfImage(filename) {
const regex = new RegExp(/[^\s]+(.*?).(jpe?g|png|gif|svg)$/)
return regex.test(filename.toLowerCase());
}
function checkIfValidFileSize(file) {
return file.size < 10485760;
}
function uploadFiles(files) {
if (!validateTitle()) return; // Guard: no title
if (isEdit || thingiverseItemId != null) {
const urlComps = thingiverseItemUrl.split(":")
thingiverseItemId = urlComps[urlComps.length - 1];
patchThingiverseItem(itemId);
} else {
thingiverseItemId = createThingiverseItem();
}
if (!thingiverseItemId) return; // Guard: could not create item
for (const file of files) {
if (isEdit && !file.name) continue; // file already uploaded
if (checkIfThingiverseFile(file.name)) {
uploadFile(file, thingiverseItemId)
}
}
setTimeout(() => publishThingiverseItem(thingiverseItemId), 2000);
}
async function uploadFile(file, itemId) {
const progressbar = document.getElementById(`progress-${file.name}`);
progressbar.style.width = `7%`; // default progress to indicate background action to user
const awsInfo = informThingiversePreUpload(file, itemId);
if (!awsInfo) return; // Guard: could not upload file
await createFileAws(awsInfo, file);
}
function readFileAsUrl(file) {
if (!file) {
return;
} else if (!(file instanceof Blob)) {
return file;
}
const fileReader = new FileReader();
return new Promise((resolve, reject) => {
fileReader.onload = _ => {
resolve(fileReader.result);
}
fileReader.onerror = _ => {
reject("Could not Read");
}
fileReader.readAsDataURL(file);
});
}
async function readAllFilesAsUrl(files) {
return Promise.all(files.map(readFileAsUrl))
}
/* === API calls === */
/**
* Synchronous function to create a new item at Thingiverse
*
* @return {string|undefined} Returns the itemId when successful and undefined if the response status was not 200
*/
function createThingiverseItem() {
if (thingiverse === undefined || thingiverse === null || thingiverse === "") {
setErrorMaxFile("Status 401: Upload can not be completed at this moment. Please inform your system administrator.");
console.log("Missing credentials");
return;
}
const url = "https://api.thingiverse.com/things";
const item = {
"name": title,
"category": category,
"tags": ["tatabooks"],
"description": description,
"instructions": instructions,
"is_wip": false,
"license": "cc"
}
let xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.setRequestHeader('Authorization', 'Bearer ' + thingiverse);
xhr.send(JSON.stringify(item))
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const response = JSON.parse(xhr.response);
console.log(response);
thingiverseItemUrl = response.public_url;
return response.id;
} else {
setErrorMaxFile("Oops! Something went wrong, please try again later.")
console.log("An issue occurred during the creation of the item");
console.log(xhr.response);
return undefined;
}
}
function publishThingiverseItem(itemId) {
if (thingiverse === undefined || thingiverse === null || thingiverse === "") {
setErrorMaxFile("Status 401: Upload can not be completed at this moment. Please inform your system administrator.");
console.log("Missing credentials");
return;
} else if (!itemId) {
console.log("no Item ID provided.");
return;
}
const url = `https://api.thingiverse.com/things/${itemId}/publish`;
let xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.setRequestHeader('Authorization', 'Bearer ' + thingiverse);
xhr.send();
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("thing published: " + itemId);
} else {
console.log("An issue occurred during publishing of a thing:");
console.log(xhr.response)
}
}
function patchThingiverseItem(itemId) {
if (thingiverse === undefined || thingiverse === null || thingiverse === "") {
setErrorMaxFile("Status 401: Upload can not be completed at this moment. Please inform your system administrator.");
console.log("Missing credentials");
return;
} else if (!itemId) {
console.log("no Item ID provided.");
return;
}
const url = `https://api.thingiverse.com/things/${itemId}`;
const item = {
"name": title,
"category": category,
"tags": [], // todo tags = keywords?
"description": description,
"instructions": instructions,
}
let xhr = new XMLHttpRequest();
xhr.open('PATCH', url, false);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.setRequestHeader('Authorization', 'Bearer ' + thingiverse);
xhr.send(JSON.stringify(item))
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const response = JSON.parse(xhr.response);
console.log(response);
} else {
setErrorMaxFile("Oops! Something went wrong, please try again later.")
console.log("An issue occurred during the creation of the item");
console.log(xhr.response);
}
}
function deleteThingiverseFileById(id, itemId, isImage) {
const url = isImage ? `https://api.thingiverse.com/things/${itemId}/images/${id}` : `https://api.thingiverse.com/things/${itemId}/files/${id}`
let xhr = new XMLHttpRequest();
xhr.open('DELETE', url, true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.setRequestHeader('Authorization', 'Bearer ' + thingiverse);
xhr.send()
xhr.onload = () => {
thingiverseIdMap = thingiverseIdMap.filter(elem => elem.id !== id)
}
}
/**
* Synchronous function to inform Thingiverse that you want to attach a file to an item.
* @param file File object that should be uploaded.
* @param itemId String which identifies the item to which the file should be attached.
*
* @return {any|undefined} returns the metadata needed to access the bucket if successful and undefined if status not 200.
*/
function informThingiversePreUpload(file, itemId) {
if (thingiverse === undefined || thingiverse === null || thingiverse === "") {
console.log("Missing credentials");
return;
}
const url = `https://api.thingiverse.com/things/${itemId}/files`;
const body = {"filename": file.name};
const xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.setRequestHeader('Authorization', 'Bearer ' + thingiverse);
xhr.send(JSON.stringify(body));
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
return JSON.parse(xhr.response);
} else {
console.log("An issue occurred during informing thingiverse preupload:");
console.log(xhr.response);
return undefined;
}
}
/**
* Asynchronous function to upload a given file to the corresponding AWS Bucket.
* @param awsInfo Metadata needed to access the AWS bucket
* @param file File object that should be uploaded
*/
async function createFileAws(awsInfo, file) {
const url = awsInfo.action;
const corsUrl = 'https://api.codetabs.com/v1/proxy?quest=' + encodeURIComponent(url)
let formData = new FormData();
formData.append('AWSAccessKeyId', awsInfo.fields.AWSAccessKeyId);
formData.append('bucket', awsInfo.fields.bucket);
formData.append('key', awsInfo.fields.key);
formData.append('acl', awsInfo.fields.acl);
formData.append('success_action_redirect', awsInfo.fields.success_action_redirect);
formData.append('policy', awsInfo.fields.policy);
formData.append('signature', awsInfo.fields.signature);
formData.append('Content-Type', awsInfo.fields["Content-Type"]);
formData.append('Content-Disposition', awsInfo.fields["Content-Disposition"]);
formData.append('file', file);
let xhr = new XMLHttpRequest();
xhr.open('POST', corsUrl, true);
xhr.upload.onprogress = (evt) => {
if (evt.lengthComputable) {
const progressbar = document.getElementById(`progress-${file.name}`);
let percentComplete = parseInt((evt.loaded / file.size) * 100);
if (percentComplete > 7) { // account for default progress when starting the upload
progressbar.style.width = `${percentComplete}%`;
}
}
}
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && (xhr.status === 200 || xhr.status === 401)) {
informThingiversePostUpload(awsInfo.fields.success_action_redirect, file.name);
} else if (xhr.readyState === XMLHttpRequest.DONE) {
handleFileUploadError(file, xhr.response);
}
}
xhr.send(formData);
}
/**
* Asynchronous function to inform Thingiverse that a file has been attached to an item
* @param redirectUrl url provided by Thingiverse to finalize the fileupload
* @param filename name of the file that was just uploaded
*/
function informThingiversePostUpload(redirectUrl, filename) {
let xhr = new XMLHttpRequest();
xhr.open("POST", redirectUrl, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + thingiverse);
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const res = JSON.parse(xhr.response);
const progressbar = document.getElementById(`progress-${filename}`);
setProgressbarStyleComplete(progressbar);
console.log(res);
thingiverseIdMap.push({id: res.id, name: filename});
} else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status !== 200) {
console.log("Error occurred:");
console.log(xhr.response)
}
}
xhr.send();
}
/**
* Function to handle an error during file upload
* Removes the failed file from the fileList and gives UI feedback to the user.
* @param file File object for which the upload failed
* @param response Response returned from the API.
*/
function handleFileUploadError(file, response) {
const index = fileList.indexOf(file);
fileList.splice(index, 1);
failedUploads.push(file);
const iconRedo = document.getElementById(`icon-${file.name}`);
iconRedo.className = "";
iconRedo.classList.add('fas', 'fa-redo');
iconRedo.onclick = () => retryUpload(file);
const iconError = document.createElement('i');
iconError.classList.add('fas', 'fa-exclamation-triangle');
iconError.id = 'icon-error-' + file.name;
document.getElementById(`div-file-${file.name}`).appendChild(iconError);
setProgressbarStyleError(document.getElementById(`progress-${file.name}`))
setErrorMaxFile("Oops! Something went wrong, some files could not be uploaded.");
console.log("Error occurred during upload to AWS:");
console.log(response);
}
function retryUpload(file) {
const itemId = getItemId()
resetUploadItem(file);
uploadFile(file, itemId)
}
/* === HTML and CSS updates === */
/**
* Renders HTML elements for a given file
* @example
* <div class="uploaded uploaded--one">
* <i class="far fa-file"></i>
* <div class="file">
* <div class="file-name">
* <p>lorem_ipsum.txt</p>
* <i class="fas fa-times"></i>
* </div>
* <div class="progress">
* <div class="progress-bar bg-success progress-bar-striped progress-bar-animated" style="width:100%"></div>
* </div>
* </div>
* </div>
*/
function renderUploadItem(filename, isAlreadyUploaded) {
let shortenedName = shortenFilename(filename, 13);
let isThingiverse = checkIfThingiverseFile(filename);
let divUploaded = document.createElement('div');
divUploaded.classList.add('uploaded')
divUploaded.id = 'uploaded-' + filename;
let icon = document.createElement('i');
icon.classList.add('far', 'fa-file');
icon.id = 'icon-' + filename;
let divFile = document.createElement('div');
divFile.classList.add('file');
let divFileName = document.createElement('div');
divFileName.classList.add('file-name');
divFileName.id = 'div-file-' + filename;
let pName = document.createElement('p');
pName.innerText = shortenedName;
let iconClose = document.createElement('i');
iconClose.id = 'icon-close-' + filename;
iconClose.classList.add('fas', 'fa-times');
iconClose.onclick = () => handleRemoveClick(divUploaded.id, filename);
if (!isThingiverse) {
let iconInfo = document.createElement('i');
iconInfo.classList.add('fas', 'fa-info-circle');
iconInfo.id = 'icon-info-' + filename;
iconInfo.title = "This file will ne uploaded using another service when you save the card."
divFileName.append(pName, iconInfo, iconClose);
} else {
divFileName.append(pName, iconClose)
}
let divProgress = document.createElement('div');
divProgress.classList.add('progress');
let divProgressbar = document.createElement('div');
if (isAlreadyUploaded) {
divProgressbar.classList.add("progress-bar", "bg-success")
divProgressbar.style.width = "100%"
divProgressbar.id = "progress-" + filename;
} else {
divProgressbar.classList.add("progress-bar", "bg-success", "progress-bar-striped", "progress-bar-animated")
divProgressbar.style.width = "1%"
divProgressbar.id = "progress-" + filename;
}
divProgress.appendChild(divProgressbar);
let pError = document.createElement('p');
pError.classList.add('error');
pError.id = 'error-' + filename;
divFile.append(divFileName, divProgress, pError)
divUploaded.append(icon, divFile);
document.getElementById('divUploadItems').append(divUploaded);
}
function resetUploadItem(file) {
const icon = document.getElementById(`icon-${file.name}`)
icon.className = "";
icon.classList.add('far', 'fa-file');
icon.onclick = undefined;
const iconError = document.getElementById(`icon-error-${file.name}`);
document.getElementById(`div-file-${file.name}`).removeChild(iconError);
const progressbar = document.getElementById(`progress-${file.name}`);
progressbar.className = "";
progressbar.classList.add('progress-bar', 'bg-success');
fileList.push(file);
}
function shortenFilename(filename, length) {
let split = filename.split('.');
let extension = split[split.length - 1];
let shortenedName = split[0].substring(0, length);
return shortenedName + "... ." + extension;
}
function setProgressbarStyleComplete(progressbar) {
progressbar.classList.remove('progress-bar-striped', 'progress-bar-animated');
progressbar.style.width = "100%"
}
function setProgressbarStyleError(progressbar) {
progressbar.className = ""
progressbar.classList.add('progress-bar', 'bg-danger');
progressbar.style.width = "1%"
}