-
Notifications
You must be signed in to change notification settings - Fork 1
/
oracle.js
2485 lines (2362 loc) · 85.7 KB
/
oracle.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
//TODO
// TODO: selectable change operations on text: regexp/match/etc
// TODO: loading symbol on fetchcard (since it's ajax)
// TODO: active card name in dipslay ( like results returned)
// TODO: # cards in list in display (like numresults)
// See: oracle.api for api documentation currently
$.views.settings.allowCode(true);
$.views.tags("printingidfromset",templateprintingidfromset);
$.views.tags("imagehashfromset",templateimagehashfromset);
$.views.tags("imagefromset",templateimagefromset);
$.views.tags("setfromset",templatesetfromset);
$.views.tags("printingfromid",templateprintingfromid);
$.views.tags("fetchimage",templatefetchimage);
$.views.tags("fetchdata",templatefetchdata);
$.views.tags("fetchfull",templatefetch);
$.views.helpers("concatarrays",templateconcatarrays);
function formatdate(val) {
return (new Date(val)).toLocaleDateString('en-US', {
day: 'numeric',
month: 'long',
year: 'numeric'
});
}
$.views.converters("formatDate", function(val) {return formatdate(val);});
function filenamecleaner(val) {
return val.replace(/[^\-a-z0-9]/gi,'_').toLowerCase().replace(/_{2,}/,'_');
}
$.views.converters("filenamecleaner", function(val) {return filenamecleaner(val);});
var listtypes = {'deck':'Deck',
'collection':'Collection',
'have':'Have',
'want':'Want',
'other':'Other'};
$.views.converters("listTypeSelect",function(type) {
var sel='';
for (ltype in listtypes) {
sel += '<option value="'+ltype+'"'+(ltype==type?' selected':'')+'>'+listtypes[ltype]+'</option>';
}
return sel;
});
function addslashes(str) {
if(str) {
if(Array.isArray(str)) {
return str.map(addslashes);
} else {
return str.replace(/\\/g, '\\\\').replace(/\'/g, '\\\'').replace(/\"/g, '\\"').replace(/\0/g, '\\0');
}
} else {
return str;
}
}
function chunkArrayInGroups(arr, size) {
var myArray = [];
for(var i = 0; i < arr.length; i += size) {
myArray.push(arr.slice(i, i+size));
}
return myArray;
}
function escapequotes(str) {
return str.replace('"','"');
}
function htmlEncode(value){
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
function htmlDecode(value) {
if (value) {
return $('<div />').html(value).text();
} else {
return '';
}
}
/**
* Deep diff between two object, using lodash
* @param {Object} object Object compared
* @param {Object} base Object to compare with
* @return {Object} Return a new object who represent the diff
*/
function jsondiff(object, base) {
function changes(object, base) {
return _.transform(object, function(result, value, key) {
if (!_.isEqual(value, base[key])) {
result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
}
});
}
return changes(object, base);
}
function loadtest() {
console.log("load test template");
$("#all_template").append('<script src="templates/test.js"></script>');
addgametolist('test');
}
$.views.converters("addslashes",addslashes);
var apiuri = "https://api.oracleofthevoid.com";
// https://sweve5sd4d.execute-api.us-east-1.amazonaws.com
var searchcache = {};
// potential for language stuff:
const searcherror = {'empty': '<div class="error"><img src="res/splatout-150.png"><br>No cards found.</div>',
'error': '<div class="error"><img src="res/splatout-150.png"><br>Something went wrong with the search.</div>',
'more': '<div class="more">More Results (Click to load)</div>',
'moreloading': '<div class="moreloading">Loading <img width=20 src="res/shuriken-150x150.png-animated.gif" /></div>',
'loading': '<img src="res/shuriken-150x150.png-animated.gif" />',
'numresults': 'XXX cards found',
'searchmiddle': 'Loading more search terms <img width=25 src="res/shuriken-150x150.png-animated.gif" />'
};
var oraclelayout;
var nolocalstore = {};
var searchables = {};
var searchselectload = {};
var templates = {'loaded':{}};
var templateactive = {};
var updates = {};
var updatepending = {};
var updatecallback = {};
var database = 'l5r';
var outputheaders = true;
if(found = window.location.href.match(/(\w+)\.html/)) {
if(found && found[1] != 'index') {
database = found[1];
console.log("database: "+database);
}
}
if(cache_session("database")) {
database = cache_session("database");
}
var labels = {};
var populatecallback = [];
var auth;
var databasesort = {};
var headerize = {};
var refreshauthvar;
var dbinfo = {};
var searchsorts = {'':{}};
searchsorts[''][JSON.stringify([{'title.keyword':{'order': 'asc'}}])] = 'Title';
// 'random': 'Random'
searchsorts[database] = searchsorts[''];
var activelists = [];
var savetimeout = '';
var missingimage = {"select": '/res/missing-stamp-rot150.png',
"details": '/res/missing-stamp-rot150.png',
"master": '/res/missing-stamp-rot150.png'
};
// ************************* AUTHENTICATION *******************************
function dologin() {
auth.getSession();
}
function dologout() {
auth.signOut();
localStorage.clear();
}
function logoutcallback() {
console.log("Not logged in");
$('#loginfo').html("");
$('.loginfo').hide()
$('#loginbutton').show();
$('.showonlogin').hide();
$('.hideonlogin').show();
}
function logincallback(session) {
if (session) {
console.log("Logged in");
$('.loginfo').css({display:'block'});
$('#loginbutton').hide();
$('.loginfo').show();
$('.showonlogin').show();
$('.hideonlogin').hide();
}
if(window.location.href.includes("#access_token") || window.location.href.includes("?code=")) {
window.location = location.protocol + '//' + location.host + location.pathname;
}
refreshauthvar = setTimeout(refreshauth,45*60*1000); // refresh every 45 min... tokens last 1h
if(cache_thing("user","data")) {
userinfocallback();
} else {
userinfo();
}
if (cache_thing("user","data") && ("oracle" in cache_thing("user","data")) && ("groups" in cache_thing("user","data").oracle[0])) {
if(!cache_thing("structuretemplate",database)) {
$.ajax({
type: 'GET',
url: apiuri+"/structure?database="+database+"&key=template",
contentType: 'application/json',
dataType: 'json',
responseType: 'application/json',
success: function(data) {
cache_thing("structuretemplate",database,data);
console.log(["structures loaded",data]);
},
error: function(error) { console.log("Structure Fetch Fail: "+JSON.stringify(error)); }
});
}
}
}
function initCognitoSDK() {
var authData = {
ClientId : '2l3lsebipenkm36upk6e02uh7n',
AppWebDomain : 'login.oracleofthevoid.com',
TokenScopesArray : ['openid','email','profile'],
RedirectUriSignIn : location.protocol + '//' + location.host + location.pathname,
RedirectUriSignOut : location.protocol + '//' + location.host + location.pathname,
UserPoolId : 'us-east-1_aIvSiSZy5',
AdvancedSecurityDataCollectionFlag : false
};
var auth = new AmazonCognitoIdentity.CognitoAuth(authData);
// You can also set state parameter // auth.setState(<state parameter>);
auth.userhandler = {
onSuccess: function(result) {
logincallback(result);
},
onFailure: function(err) {
console.log("initcognito failure - logging out");
dologout();
logoutcallback();
// alert("Error!" + err);
}
};
auth.useCodeGrantFlow()
return auth;
}
function refreshauth() {
clearTimeout(refreshauthvar);
let user = auth.getCachedSession();
auth.refreshSession(user.getRefreshToken().getToken());
console.log("Session refreshed");
refreshauthvar = setTimeout(refreshauth,45*60*1000); // refresh every 45 min... tokens last 1h
}
function getidtoken() {
return auth.getCachedSession().idToken.jwtToken;
}
//**********************88 ACCOUNT STUFFF ****************88
function userinfo() {
$.ajax({
type: 'GET',
url: apiuri+"/user",
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(data) {
console.log(data);
cache_thing("user","data",data);
userinfocallback();
},
error: function(error) { console.log("Epic Fail: "+JSON.stringify(error)); }
});
}
function userinfocallback() {
var info = cache_thing("user","data");
$('#loginfo').html(info.cognito.name);
// $('#userinfo-id').html("Uid: "+info.oracle[0].uid);
// $('#userinfo-email').html(info.oracle[0].emails.join("<br />"));
// $('#userinfo-joined').html(info.oracle[0].insert_date);
// $('#userinfo-lists').html(info.oracle[0].deckcount);
hellotemplate = $.templates("#template-hello");
$('#userinfo-drop').html(hellotemplate.render({cognito: info.cognito, oracle: info.oracle[0]}));
// $(".helloplace").replaceWith(hellotemplate.render({cognito: info.cognito, oracle: info.oracle[0]}));
// $(".infoplace:first-child").before(hellotemplate.render({cognito: data.cognito, oracle: data.oracle[0]}));
listinfo(); // TODO: more intelligently decide if we need to do listinfo or just the callback
}
function getuid() {
return cache_thing("user","data").oracle[0].uid;
}
//**********************88 LIST STUFFF ****************
// TODO: cache this better...
function listinfo(listid=null,switchview=true,listoutput=null) {
console.log(["listinfo",listid,switchview,listoutput]);
if(listid && cache_thing("list",listid) != null) {
console.log("cached");
$("#lastlistid").val(listid);
renderlist(cache_thing("list",listid).list.Items[0],switchview,listoutput+(outputheaders?'':',noheaders'));
} else {
$.ajax({
type: 'GET',
url: apiuri+"/list?uid="+getuid()+"&database="+database+(listid?"&listid="+listid:""),
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(data) {
console.log(data);
if(listid) {
if(data.list.Items[0].sort == undefined) {
console.log('nosort set');
if(data.list.Items[0].type == 'deck') {
data.list.Items[0].sort = 'deck';
console.log('setting deck');
} else {
data.list.Items[0].sort = '';
}
}
cache_thing("list",listid,data);
$("#lastlistid").val(listid);
renderlist(data.list.Items[0],switchview,listoutput+(outputheaders?'':',noheaders'));
renderlisteditarea();
/* console.log('here');
if(data.list.Items[0].list.length > 0 && typeof(data.list.Items[0].totalcount) == "undefined") {
console.log('fixing');
// fix the counts if they don't exist by adding 0 of first card.
addlistitem(listid,data.list.Items[0].list[0].cardid,data.list.Items[0].list[0].printing,0);
renderlist(data.list.Items[0],false,listoutput);
} */
} else {
cache_thing("list","data",data);
listinfocallback();
}
},
error: function(error) { console.log("Epic Fail: "+JSON.stringify(error)); }
});
}
}
function listinfoupdate(listid,field,value) {
// valid fields:
// name=text, notes=text, public=t/f, type=short text, list = JSON.stringify(data)
// for the first 4, just do on change
// for the list, periodically do an update if stuff has changed to decrease traffic (have some sort of unsaved/saving/saved area)
// TODO: rethink calling listinfo.. that might overwrite pending stuff? or wait.. that's not the actual list.. might be ok
// either way, we need to trap pulling new list info if we have pending updates.
// TODO: when listinfoupdate is called, and lastmod is newer than what we have and we have a list, force update or dump cache
var message_status = $('#list_modified\\:'+listid);
var url = apiuri+"/list?uid="+getuid()+"&database="+database+"&listid="+listid+"&updatefield="+field+"&updatevalue="+encodeURI(value);
console.log(url);
$.ajax({
type: "GET",
url: url,
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(status) {
//message_status.show();
message_status.text("List Updated");
//hide the message
setTimeout(function(){message_status.text(formatdate(new Date()))},3000);
// setTimeout(function(){message_status.hide()},3000);
$("#list_prev_"+field).text(value);
if($("#importlistid").length) {
var listid = $("#importlistid").val();
erasemodal();
cache_thing("list",listid,null,true); //TODO we might seed the cache.. but we get no verification that it took. DynamoDB has no guarantee it's fresh, so might blow cache here.
listinfo(listid);
}
},
error: function(status) {
console.log(status);
}
});
}
function listinfocallback() {
cache_thing("list","datareverse",cache_thing("list","data").lists.Items.reduce((hsh,list,index) => { hsh[list.listid]=index; return hsh;},{}));
listertemplate = $.templates("#template-lists");
$(".directorylistitem").remove();
$(listertemplate.render(cache_thing("list","data").lists.Items)).insertAfter(".directorylistheader");
//acknowledgement message
$('.listitem div[contenteditable=true][id^="list_"]').blur(function(){
var field_userid = $(this).attr("id").split(/:/) ;
var value = $(this).text() ;
//TODO: update value
if($("#list_prev_"+field_userid[0].replace('list_','')+'\\:'+field_userid[1]).text() != value) {
//console.log($("#list_prev_"+field_userid[0].replace('list_','')+'\\:'+field_userid[1]).text());
console.log(field_userid);
listinfoupdate(field_userid[1],field_userid[0].replace('list_',''),value);
}
});
// $(".infoplace:first-child").before(hellotemplate.render({cognito: data.cognito, oracle: data.oracle[0]}));
}
function toggleheaders() {
if(outputheaders) {
$(".toggleheaderson").hide();
$(".toggleheadersoff").show();
} else {
$(".toggleheaderson").show();
$(".toggleheadersoff").hide();
}
outputheaders = !outputheaders;
}
// *********************** list edits **************
function renderlisteditarea() {
if(activelists.length < 1) {
$("#deckarea").html(Object.keys(updatepending).length >0 ? '<div class="randarea"><span style="background-color:red;" onclick="savecallback();">Updates Pending</span></div>' :'');
} else {
listactivetemplate = $.templates("#template-listactive");
$("#deckarea").html(
'<div class="randarea">Active Lists:<br />'+
(Object.keys(updatepending).length >0 ? '<span style="background-color:red;" onclick="savecallback();">Updates Pending</span>' :'')+
listactivetemplate.render(activelists.map(function(listid) {
var list=cache_thing("list","data").lists.Items[cache_thing("list","datareverse")[listid]];
if(cache_thing("list",listid)) {
list.listdata = cache_thing("list",listid);
}
return list;
}))+
'</div><br /><br />'
);
}
}
function activatelist(listid) {
listinfo(listid,false);
var index = activelists.indexOf(listid);
if (index > -1) {
activelists.splice(index, 1);
}
activelists.unshift(listid);
$("#listinactive"+listid).hide();
$("#listactive"+listid).show();
renderlisteditarea();
}
function deactivatelist(listid) {
var index = activelists.indexOf(listid);
if (index > -1) {
activelists.splice(index, 1);
}
$("#listactive"+listid).hide();
$("#listinactive"+listid).show();
renderlisteditarea();
}
function newlist(json=null) {
/*
Create new list. json example:
{
"name": "new list name", // default: "New List"
"list": [ { cardid: 6974, printing: 0, quantity: 3 }, // default: empty list
{ cardid: 123, printing: 2, quanity: 1}
],
"public": true, // default false
"type": "collection" // default 'deck'
}
game is set from queryString
owner is set from authentication information and matching queryString
createdate, modified are automatically set and non-modifiable currently
*/
$.ajax({
type: 'GET',
url: apiuri+"/list?uid="+getuid()+"&database="+database+"&listid=new"+(json?encodeURIComponent(JSON.stringify(json)):''),
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(data) {
console.log(data);
var oldlists = cache_thing("list","data");
oldlists.lists.Items.unshift(data.list.Item);
cache_thing("list","data",oldlists);
listinfocallback();
},
error: function(error) { console.log("Epic Fail: "+JSON.stringify(error)); }
});
}
function removelist(listid) {
if(confirm("Really remove list: "+listid+"?")) {
$.ajax({
type: 'GET',
url: apiuri+"/list?uid="+getuid()+"&database="+database+"&listid="+listid+"&action=remove",
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(data) {
console.log(data);
},
error: function(error) { console.log("Epic Fail: "+JSON.stringify(error)); }
});
var oldlists = cache_thing("list","data");
var ind = $("#listitem_"+listid).index();
oldlists.lists.Items.splice(ind-1,1);
cache_thing("list","data",oldlists);
$("#listitem_"+listid).remove();
listinfocallback();
}
}
function savecallback() {
console.log("Saving....");
for(listid in updatepending) {
listinfoupdate(listid,'list',JSON.stringify(cache_thing("list",listid).list.Items[0].list));
delete updatepending[listid];
}
renderlisteditarea(); // update card counts
clearTimeout(savetimeout);
}
function addlistitem(listid,cardid,prid=0,n=1,abs=false,sort=null) {
//var list=cache_thing("list","data").lists.Items[cache_thing("list","datareverse")[listid]];
// listinfoupdate(listid,'list',JSON.stringify(cache_thing("list",listid).list.Items[0].list));
var list = cache_thing("list",listid);
var ind = list.list.Items[0].list.findIndex(function(ele) { return ele.cardid == cardid && ele.printing == prid; });
if(ind<0 && n != null) {
list.list.Items[0].list.push({'cardid':cardid,'printing':prid,'quantity':n});
} else {
if(n == null) {
list.list.Items[0].list.splice(ind,1);
} else {
if(abs) {
list.list.Items[0].list[ind].quantity = n;
} else {
list.list.Items[0].list[ind].quantity += n;
}
}
}
list.list.Items[0].distinctcount = list.list.Items[0].list.length;
list.list.Items[0].totalcount = list.list.Items[0].list.reduce(function (total,card) {
return total + parseInt(card['quantity']);
},0);
cache_thing("list",listid,list);
$("#lastlistid").val(listid);
renderlist(cache_thing("list",$("#lastlistid").val()).list.Items[0],false);
if(Object.keys(updatepending).length < 1) {
savetimeout = setTimeout(savecallback,60*1000);
}
updatepending[listid]=1;
renderlisteditarea(); // update card counts
}
function importlist(listid=null,name=null) {
// this will initiate a file dialog to upload a file to a list
var title = "Import a file from disk into: "+name;
var importtemplate = $.templates("#template-import");
modal(title,importtemplate.render({"listid": listid, "database": database}));
}
function deletecard(cardid=null,printid=null) {
if(cardid&&printid) {
var carddata = cache_card_fetch(cardid);
modalconfirm("Delete instance "+printid+" from: "+carddata.title[0],
"Are you sure you want to delete this instance:<br><br>"+
"Card: "+carddata.title[0]+"<br>"+
(carddata.printing[carddata.printingreverse.printingid[printid]].set ? "Set: "+carddata.printing[carddata.printingreverse.printingid[printid]].set : '')+"<br>"+
(carddata.printing[carddata.printingreverse.printingid[printid]].rarity ? "Rarity: "+carddata.printing[carddata.printingreverse.printingid[printid]].rarity : '')+"<br>"+
"<br><br>",
"deletecardtrigger('"+database+"',"+cardid+","+printid+");"
);
} else if(cardid) {
var carddata = cache_card_fetch(cardid);
modalconfirm("Delete: "+carddata.title[0],
"Are you sure you want to delete this card:<br><br>"+
"Card: "+carddata.title[0]+"<br>"+
"<br><br>",
"deletecardtrigger('"+database+"',"+cardid+",null);"
);
}
}
function deletecardtrigger(database=null,cardid=null,printid=null) {
var url = apiuri+"/update";
var requestdata = {
"uid": getuid(),
"database": database,
"cardid": cardid,
"data": {"remove":true} // dummy data
};
if(cardid&&printid) {
requestdata['printingid'] = printid;
requestdata['operation'] = 'removeinstance';
} else if(cardid) {
requestdata['operation'] = 'remove';
}
var request = {
type: "POST",
url: url,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(requestdata),
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(status) {
console.log(["update ret",status]);
nomodal();
if(requestdata.cardid) {
cache_card_remove(requestdata.cardid);
$('#modal-content').html('<div id="submitafter" class="error">REMOVED</div>');
$('#resultcard').html('');
}
},
error: function(status) {
$('#modal-content').append('<div id="submitafter" class="error">Error</div><br /> '+status.responseText);
console.log(status);
}
};
console.log(["posting",request]);
$.ajax(request);
}
function editcard(cardid=null,printid=null) {
if(cardid&&printid) {
var carddata = cache_card_fetch(cardid);
var title;
var printing;
if(printid == Number.MAX_SAFE_INTEGER) {
title = "Add instance to: "+carddata.title[0];
// new printing version
var structure = cache_thing("structuretemplate",database);
printing = structure.template.printing[0];
} else {
title = "Edit card information for: "+carddata.title[0]+' - instance '+printid;
// edit just a printing version
printing = carddata.printing[carddata.printingreverse.printingid[printid]];
delete printing.printingid;
}
var editcardtemplate = $.templates("#template-editcard");
modal(title,editcardtemplate.render({"cardid": cardid, "printid": printid, "carddata": JSON.stringify(printing,null,2), "database": database}));
} else if(cardid) {
// This edits just the main card data, no instance info
var carddata = cache_card_fetch(cardid);
delete carddata.printing;
delete carddata.printingreverse;
delete carddata.printingprimary;
delete carddata.cardid;
delete carddata.updatelog;
delete carddata['@timestamp'];
delete carddata['@SequenceNumber'];
var title = "Edit card information for: "+carddata.title[0];
var editcardtemplate = $.templates("#template-editcard");
modal(title,editcardtemplate.render({"cardid": cardid, "carddata": htmlEncode(JSON.stringify(carddata,null,2)), "database": database}));
} else {
var structure = cache_thing("structuretemplate",database);
var title = "Insert new card";
var editcardtemplate = $.templates("#template-editcard");
modal(title,editcardtemplate.render({"cardid": "", "carddata": htmlEncode(JSON.stringify(structure.template,null,2)), "database": database}));
}
}
function editcardtrigger() {
// https://github.com/Oracle-of-the-Void/ootv-client/blob/master/docs/API.md#update
// authenticated: /update
// Header, uid
// cardid, database, data
// operation: update (hash of keys to update) - replace contents
// printingid + operation: updateinstance (hash of keys to update for printing) - replace contents
// new / newinstance laterz
// remove / removeinstance laterz
// Note, this one is just doing an edit on main card (so just update)
var printid = $('#editcardprint').val();
var cardid = $('#editcardid').val();
var url = apiuri+"/update";
var requestdata = {
"uid": getuid(),
"database": $('#editcarddb').val(),
"cardid": cardid,
"operation": "update",
"printingid": printid,
"data": {}
};
var newdata;
var changedata = {};
try {
newdata = JSON.parse($('#editcard').val());
} catch(e) {
$('#editcardbuttonafter').replaceWith('<div id="editcardbuttonafter" class="error">Failed to parse</div>');
return;
}
// TODO: enforce requirements
if (printid) {
if(printid == Number.MAX_SAFE_INTEGER) {
// new instance
requestdata.operation = "newinstance";
var structure = cache_thing("structuretemplate",database);
for (let def in structure.operation.new.defaultprinting) {
if(!newdata[def]) {
newdata[def] = structure.operation.new.defaultprinting[def];
}
}
delete newdata.printingid;
requestdata.data = newdata;
console.log(["NEW",requestdata]);
// TODO HERE
} else {
// update instance
requestdata.operation = "updateinstance";
carddata = cache_card_fetch(cardid);
printing = carddata.printing[carddata.printingreverse.printingid[printid]];
console.log(printing);
delete printing.printingid;
if(_.isEqual(newdata,printing)) {
$('#editcardbuttonafter').replaceWith('<div id="editcardbuttonafter" class="error">No Change</div>');
return;
}
console.log(["differences",jsondiff(newdata,printing)]);
for (key in newdata) {
if(!_.isEqual(newdata[key],printing[key])) {
changedata[key] = newdata[key];
}
}
for (key in printing) {
if(!(key in newdata)) {
changedata[key] = null;
}
}
requestdata.data = changedata;
}
} else if(cardid) {
// update card main
// kill things managed in different ways
carddata = cache_card_fetch(cardid);
delete carddata.printing;
delete carddata.printingreverse;
delete carddata.printingprimary;
delete carddata.cardid;
delete carddata.updatelog;
delete carddata['@timestamp'];
delete carddata['@SequenceNumber'];
// make sure nobody "adds" anything restricted.
delete newdata.printing;
delete newdata.printingreverse;
delete newdata.printingprimary;
delete newdata.cardid;
delete newdata.updatelog;
delete newdata['@timestamp'];
delete newdata['@SequenceNumber'];
if(_.isEqual(newdata,carddata)) {
$('#editcardbuttonafter').replaceWith('<div id="editcardbuttonafter" class="error">No Change</div>');
return;
}
console.log(["differences",jsondiff(newdata,carddata)]);
for (key in newdata) {
if(!_.isEqual(newdata[key],carddata[key])) {
changedata[key] = newdata[key];
}
}
for (key in carddata) {
if(!(key in newdata)) {
changedata[key] = null;
}
}
requestdata.data = changedata;
} else {
// NEW
requestdata.operation = "new";
delete requestdata.cardid;
delete requestdata.printingid;
// TODO: enforce "required" things
var structure = cache_thing("structuretemplate",database);
for (let rem of structure.operation.new.remove) {
delete newdata[rem];
}
for (let def in structure.operation.new.default) {
if(!newdata[def]) {
newdata[def] = structure.operation.new.default[def];
}
}
for (let i = 0; i< newdata.printing.length ; i++) {
for (let def in structure.operation.new.defaultprinting) {
if(!newdata.printing[i][def]) {
newdata.printing[i][def] = structure.operation.new.defaultprinting[def];
}
}
}
requestdata.data = [newdata];
console.log(["NEW",requestdata]);
}
$('#editcardbuttonafter').replaceWith('<div id="editcardbuttonafter" class="error">Updating</div>');
$('#editcardbutton').hide();
console.log(["updating card data",requestdata]);
var request = {
type: "POST",
url: url,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(requestdata),
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(status) {
$('#editcardbuttonafter').replaceWith('<div id="editcardbuttonafter" class="error">Updated Successfully</div>');
console.log(["update ret",status]);
if(requestdata.cardid) {
cardfetch(requestdata.cardid,status.olddata.printingid?status.olddata.printingid:null,$('#lastsearchquery').val(),nomodal);
} else if(status.cardids) {
cardfetch(status.cardids[0],null,$('#lastsearchquery').val(),nomodal);
}
},
error: function(status) {
$('#editcardbuttonafter').replaceWith('<div id="editcardbuttonafter" class="error">Error</div><br /> '+status.responseText);
console.log(status);
}
};
console.log(["posting",request]);
$.ajax(request);
}
function setprimary(cardid,printid) {
if(cardid&&printid) {
var url = apiuri+"/update";
var requestdata = {
"uid": getuid(),
"database": database,
"cardid": cardid,
"operation": "update",
"data": {"printingprimary":printid}
};
console.log(["updating card data",requestdata]);
var request = {
type: "POST",
url: url,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(requestdata),
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', getidtoken());},
responseType: 'application/json',
success: function(status) {
console.log(["update ret",status]);
cardfetch(requestdata.cardid,printid,$('#lastsearchquery').val(),nomodal);
},
error: function(status) {
alert('Error: '+status.responseText);
console.log(status);
}
};
console.log(["posting",request]);
$.ajax(request);
}
}
function importlisttrigger() {
$("#importprogress").show();
$("#importform").hide();
$("#importstatus").html("");
$.ajax({
// Your server script to process the upload
url: 'https://api.oracleofthevoid.com/import',
type: 'POST',
// Form data
data: new FormData($('#importform')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('importprogress', function (e) {
if (e.lengthComputable) {
$('#importprogress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
},
success: function(data) {
console.log("success");
console.log(data);
$("#importprogress").hide();
var importsuccess = $.templates("#template-importsuccess");
$("#importfailedval").val(data.failed.join("\n"));
$("#importdataval").val(JSON.stringify(data.list));
$("#importstatus").html(importsuccess.render({"numresults":data.list.length,"numfailed":data.failed.length,"failed":data.failed.join("\n")}));
},
error: function(data) {
console.log("error");
console.log(data);
$("#importprogress").hide();
$("#importstatus").html('<div class="error">Error</div><br /><br />'+(data.message ? data.message : (data.statusText ? data.statusText : print_r(data,1))));
}
});
}
function importlistfinalize() {
listinfoupdate($("#importlistid").val(),'list',$("#importdataval").val());
nomodal();
}
// ********************************* fetching / querying the api ******************8
// TODO: sometimes this fails if I do a card not primed from c/p
// e.g: https://dev.oracleofthevoid.com/#cardid=999
function cardfetch(cardid,prid=null,qs=null,handler=null) {
$.ajax({
type: 'GET',
url: apiuri+"/oracle-fetch?table="+database+"&cardid="+cardid,
contentType: 'application/json',
dataType: 'json',
responseType: 'application/json',
success: function(data) {
data = imagehashtourl(data);
cache_card(data);
docard(data,prid,qs);
if(handler) { handler(); }
},
error: function(error) { console.log("Epic Fail: "+JSON.stringify(error)); }
});
}
function listprefetch(listids,callback=null) {
console.log(['listprefetch',listids,callback]);
$.ajax({
type: 'GET',
url: apiuri+"/oracle-fetch?table="+database+"&cardid="+listids.join(),
contentType: 'application/json',
dataType: 'json',
responseType: 'application/json',
success: function(data) {
console.log(data);
if(Array.isArray(data)) {
data.forEach(function(c) { cache_card(imagehashtourl(c)); });
} else if(typeof data == 'object') {
cache_card(imagehashtourl(data));
}
if(callback) {
callback[0](callback[1],callback[2],callback[3],callback[4],callback[5]);
}
},
error: function(error) { console.log("Epic Fail: "+JSON.stringify(error)); }
});
}
function imagehashtourl(card) {
//dbinfo[database].imageuri +
if(card.imagehash) {
card.icon = dbinfo[database].imageuri + card.imagehash+'/card_'+card.cardid+'__icon.jpg';
card.imageurl = dbinfo[database].imageuri + card.imagehash+'/printing_'+card.cardid+'_'+card.printingprimary+'_'; // then you can add details, select, etc
}
for(var p = 0; p < card.printing.length; p++) {
if(!card.printing[p].images) {
card.printing[p].images = [];
stub = 'printing_';
if(card.printing[p].printimagehash) {
for(var h = 0; h < card.printing[p].printimagehash.length; h++) {
card.printing[p].images[h] = dbinfo[database].imageuri + card.printing[p].printimagehash[h] + '/'+stub+card.cardid+'_'+
card.printing[p].printingid+'_'; // then you add details, etc
}
} else {
console.log("Card missing a printimagehash: "+JSON.stringify(card));
}
}
}
//printing: {{if ~datarequest.field_printing_edition}}{{imagehashfromset ~datarequest.field_printing_edition printing /}}/printing_{{:cardid}}_{{printingidfromset ~datarequest.field_printing_edition printing /}}_select.jpg{{else}}{{:imagehash}}/card_{{:cardid}}__icon.jpg{{/if}}
card.printingreverse = {printingid: {}};
for(var p = 0; p < card.printing.length; p++) {
card.printingreverse.printingid[card.printing[p].printingid] = p;
}
for(seakey in searchables[database]) {
sea = searchables[database][seakey];
if((typeof sea === 'object') && ('reverse' in sea)) {
card.printingreverse[seakey.replace("printing.","")] = {};
for(var p = 0; p < card.printing.length; p++) {
if(seakey.replace("printing.","") in card.printing[p]) {
card.printingreverse[seakey.replace("printing.","")][card.printing[p][seakey.replace("printing.","")][0]] = p;
}
}
if(jQuery.isEmptyObject(card.printingreverse[seakey.replace("printing.","")])) {
delete card.printingreverse[seakey.replace("printing.","")];
}
}
}
return card;
}
function updateselect(select) {
// creates an array consisting of the sorted elements of that field
$.ajax({
type: 'POST',
url: apiuri+"/attributes",
data: {
table: database,
lookup: select,
optgroup: 1
},
contentType: 'application/json',
dataType: 'json',
responseType: 'application/json',
success: function(raw) {
console.log(["select lookup results: ",select,raw]);