-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathosdi.js
882 lines (702 loc) · 19.5 KB
/
osdi.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
// TODO
// addresses are now inline
// restructure data
// person->data
// person->tags ['tag','tag']
// person->self
// person->tags
// detect if not chrome and alert
// add tagging support
// misc refactoring
//
// deal with non-json error response? or fix on server to always report json
// bump
"use strict";
var _data;
var _people;
var _sample = {
first_name: 'Josh',
last_name: 'Cohen',
email: '[email protected]'
}
function selectDefaultAEP(){
var hostname = window.location.hostname;
var aep;
switch (hostname) {
case "canvasser.opensupporter.org":
aep="http://api.opensupporter.org/api/v1";
break;
case "az-canvasser.opensupporter.org":
aep="https://az-osdi.herokuapp.com/proxy/salsa";
break;
case "localhost":
aep="http://localhost:3000/proxy/salsa";
break;
default:
aep="http://localhost:3000/proxy/salsa";
}
return aep;
}
var _ls = window.localStorage;
var _counter_idx;
var _counter_count;
osdiLogClear();
var container = document.getElementById('container');
var viewport = document.getElementById('viewport');
$( document ).delegate("#localstore", "pageinit", function() {
showLocal();
});
$( document ).ready(function() {
consoleLog( "Document Ready!" );
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if ( ! is_chrome ) {
// alert('Please use Chrome');
}
if (_ls['osdi_aep'] == undefined || _ls['osdi_aep'] == "") {
$("#osdi_server").val(selectDefaultAEP());
setServerAEP();
} else {
updateServerUI();
}
swizzleCounter();
});
function updateServerUI() {
$('#osdi_server').val(_ls['osdi_aep']);
$('#api_key').val(_ls['api_key']);
$('#people_uri').text(_ls['osdi_people_uri']);
$('#logger_uri').text(_ls['logger_uri']);
$('#logo').attr('src',_ls['brand_logo']);
$('#person_signup_uri').text(_ls['person_signup_uri']);
$('#logo_uri').text(_ls['brand_logo']);
if ( present(_ls['brand_logo'])) {
$('#logo').attr('src',_ls['brand_logo']);
} else {
$('#logo').attr('src',null);
}
$('#canvasser_email').val(_ls['canvasser_email']);
}
// if ( _ls['osdi_aep'] == undefined || _ls['osdi_aep'] == "") {
// _ls['osdi_aep'] = $('#osdi_server').val();
// var uri = getPeopleURI();
// _ls['osdi_people_uri'] = uri;
// osdiLog('Set empty aep to ' + _ls['osdi_aep'] + ' PURI ' + uri);
// }
// $('#osdi_server').val(_ls['osdi_aep']);
// $('#people_uri').text(_ls['osdi_people_uri']);
// $('#logo').attr('src',_ls['brand_logo']);
/*
$( "a" ).on( "click", function( event ){
// Prevent the usual navigation behavior
event.preventDefault();
// grab new URL
var newUrl = $(this).attr( "href" );
osdiLog('going to ' + newUrl);
// Alter the url according to the anchor's href attribute, and
// store the data-foo attribute information with the url
$.mobile.navigate( newUrl );
});
*/
//getPeople();
// form buttons
$('#btnProcess').click(function (event) {
event.preventDefault();
uploadForm();
});
$('#btnClearHTML5').click(function (event) {
event.preventDefault();
var r=confirm("Delete HTML5 Store?");
if (r==true) {
localStorage.clear();
alert("Cleared!");
$.mobile.changePage('#upload');
window.location.reload();
}
});
$('#btnDefaultAEP').click(function (event) {
$("#osdi_server").val(selectDefaultAEP());
setServerAEPUI();
});
$('#btnReset').click(function (event) {
// clearButton('#btnReset');
$("#myForm")[0].reset()
consoleLog('Clicked Reset');
});
$('#btnSave').click(function (event) {
event.preventDefault();
consoleLog('Save Clicked');
// we need to allow blank email.
// if ( $('#email').val() == "" ) {
// alert('Email must not be blank');
// } else {
if ( saveForm() != null ) {
saveConfirmation();
swizzleCounter();
} else {
alert("Missing Required Fields");
}
// }
});
function saveConfirmation() {
if ( $('#save_confirmation').prop('checked')) {
$.mobile.changePage('#saved');
setTimeout(function() {
$.mobile.changePage('#newrecord');
},1000);
}
}
function showLogs()
{
$("#log-messages").html( osdiLogMessages().join("<br/>"));
$.mobile.changePage('#logger');
}
function showSavedScreen() {
window.location = '#saved';
setTimeout(function() {
window.location = '#newrecord';
},1000);
}
// upload button
$('#btnUpload').click(uploadPeople);
$('#btnClearLocal').click(clearLocal);
$('#btnUpdateServer').click(setServerAEPUI);
$('#btnShowLogs').click(showLogs);
$('.local-refresh').click(showLocal);
function clearButton(btnStringId) {
$(btnStringId).parent().removeClass('ui-btn-active');
}
function doImage() {
var image= new Image();
image.src="http://my.washingtonunitedformarriage.org/assets/web/avatar-face-wa.png";
return image;
}
function setBusy(status) {
if (status) {
$('#status').text('Busy');
} else {
$('#status').text('Ready');
}
}
function uploadForm() {
var p=processForm();
uploadPerson(p);
}
function saveForm() {
var p=processForm();
if ( p != null ) {
savePerson(p);
}
return p;
}
// people stuff
function uploadPeople() {
var _counter_count = countPeople();
if ( _counter_count == 0 ) {
alert('No records to upload!');
return;
}
if ( ! present(_ls['person_signup_uri'])) {
alert('Invalid OSDI Server. Update AEP');
return;
}
busy(true);
window.setTimeout( processUploads, 100);
}
function busy(yes) {
if ( yes ) {
$('#status').html('<span style="color: red">Busy Working...</span>');
$.mobile.loading('show');
} else {
$('#status').html('Ready...');
$.mobile.loading('hide');
}
}
function counter(idx,count) {
$('#counter').html( idx + ' / ' + count);
}
function clearCounter() {
$('#counter').html('');
}
function countPeople() {
var people=loadPeople();
var count = Object.keys(people).length;
return count;
}
function updateCounter() {
var count = countPeople();
$(".store-count").text( "(" + count + ")");
}
function swizzleCounter() {
updateCounter();
$(".store-count").effect("pulsate",{times:4},1000)
}
function verifyUpload(prune) {
var people=loadPeople();
var status;
_ls['failures'] = 0;
var failures = 0;
for (var key in people) {
status = people[key]['status_code']
if (status != 200) {
// there was an error
osdiLog("Error " + status + " uploading " + key);
failures++
} else {
if (prune == true) {
osdiLog("OK to remove " + key);
deletePerson(key);
}
}
}
_ls['failures'] = failures;
return failures
}
function uploadLogs(logger_uri,status) {
var json = JSON.stringify(_ls);
var res=exec_ajax(json,logger_uri + "?status=" + status + "&email=" + _ls['canvasser_email']);
return res;
}
function postProcess() {
// are there failures?
var failures = verifyUpload(false);
var res;
var msgs = [];
if ( present(_ls['logger_uri'])) {
// upload logs
if ( failures > 0 ) {
msgs.push("There were " + failures + " errors, logs uploaded");
res=uploadLogs(_ls['logger_uri'],901);
} else if ( $("#always_log").prop('checked') ) {
msgs.push("No errors. Logging transmitted")
res=uploadLogs(_ls['logger_uri'],900);
}
if ( res.status == 200 ) {
// logs uploaded successfully
if ( $("#auto_clean").prop('checked') && failures == 0 ) {
//clean
msgs.push('Clearing local store')
clearLocalInner();
osdiLogClear();
}
} else {
msgs.push('Could not send logs!')
}
} else {
// no logging so just prune
verifyUpload(true);
}
var log_messages = osdiLogMessages();
$("#log-messages").html(msgs.join("<br/>") + "<br/><br/>" + log_messages.join("<br/>"));
window.location = "#logger";
}
function uploadPeopleInner() {
var resourceUrl = _ls['osdi_people_uri'];
var people = loadPeople();
_counter_count = countObjectProperties(people);
_counter_idx = 0;
for(var key in people) {
_counter_idx++;
counter(_counter_idx,_counter_count);
window.setTimeout(function () {
uploadPerson(people[key], resourceUrl)}, 300);
}
busy(false);
}
function processUploads() {
var resourceUrl = _ls['person_signup_uri'];
var people = loadPeople();
var kys = Object.keys(people);
var mykey;
_counter_count = countObjectProperties(people);
_counter_idx = 0;
osdiLog("Preparing to upload " + _counter_count + " items");
function doChunk() {
mykey=kys[_counter_idx];
osdiLog("Processing " + mykey + " idx " + _counter_idx);
counter(_counter_idx +1 ,_counter_count);
uploadPerson(people[mykey],resourceUrl);
//tagPerson(people[mykey]);
_counter_idx++;
if (_counter_idx < _counter_count) {
setTimeout(doChunk,100);
} else {
clearCounter();
postProcess();
busy(false)
}
}
doChunk();
// busy(false);
}
function clearLocal() {
var r=confirm('Delete: Are you sure?');
if ( r == true) {
clearLocalInner();
}
}
function clearLocalInner() {
_ls.removeItem('people');
swizzleCounter();
}
function showLocal() {
consoleLog('In showLocal');
$('#record-list').empty();
var people = loadPeople();
for(var key in people) {
consoleLog('Adding ' + key);
var fn = people[key]['data']['person']['given_name'] + ' ' + people[key]['data']['person']['family_name'];
$('#record-list').append('<li>' + fn + ' <' + key + '></li>');
$('#record-list').listview('refresh');
// $('body').append(localStorage.getItem(key));
}
}
function loadPeople(){
var peopleRaw = _ls['people'];
if ( peopleRaw == "" || peopleRaw == undefined) {
// it's empty so send back an empty hash
return {};
}
var people = JSON.parse(peopleRaw);
return people;
}
function xloadPerson(email){
var peopleRaw = _ls['people'];
if ( peopleRaw == "" || peopleRaw == undefined) {
// it's empty so send back an empty hash
return {};
}
var people = JSON.parse(peopleRaw);
return people[email];
}
function deletePerson(key) {
var people = loadPeople();
delete people[key]
var json=JSON.stringify(people);
_ls['people'] = json;
}
function savePerson(p) {
consoleLog(this);
var people = loadPeople();
var email = p.data.person.email_addresses[0].address
var hkey;
var name = p.data.given_name + p.data.family_name;
if (email) {
hkey=email;
} else {
hkey = name;
}
people[hkey] = p;
var json=JSON.stringify(people);
_ls['people'] = json;
$('#btnReset').click();
}
function processForm() {
if ( ! present($('#first_name').val())
&& !present($('#last_name').val())
&& ! present($('#email').val())
) {
return null;
}
var msg={};
msg['data'] = {};
var data = msg['data'];
data['add_tags'] = []
data['person'] = {};
var tags = data['add_tags'];
var p = data['person'];
data['originating_system'] = "canvasser.opensupporter.org";
p['given_name']=$('#first_name').val();
p['family_name']=$('#last_name').val();
p['email_addresses']= [ {
"address" : $('#email').val(),
"primary" : true
}];
p['phone_numbers'] = [];
p['phone_numbers'][0] = {
'number' : $('#phone_number').val(),
'sms_permission' : $('#sms_permission').val()
}
var a={
"address_lines": [ $('#address1').val(),$('#address2').val() ],
"locality": $('#city').val(),
"region": $('#state').val(),
"postal_code": $('#postal_code').val()
}
p['postal_addresses'] = [ a ];
// // handle checkboxes for tags
// if ( $('#volunteer').prop('checked') ){
// tags.push('volunteer');
// }
$( ".tags" ).each(function() {
if ( $( this ).prop('checked') ) {
tags.push( $(this).val() );
}
});
consoleLog('Generated person ');
consoleLog(msg);
return msg;
}
// Server stuff
function setServerAEPUI() {
if ( ! present( $('#canvasser_email').val() )) {
alert("Please enter canvasser email");
return;
} else {
_ls['canvasser_email'] = $('#canvasser_email').val();
}
// always save it so it can be cleared
_ls['api_key'] = $('#api_key').val();
busy(true);
setTimeout(setServerAEP,300);
}
function setServerAEP() {
var aep = $('#osdi_server').val();
_ls['osdi_aep'] = aep;
var peopleUrl = getPeopleURI();
_ls['osdi_people_uri'] = peopleUrl;
consoleLog('Set AEP: ' + aep);
updateServerUI();
busy(false);
}
function nav(obj, expression) {
var ret=undefined;
try {
ret = eval(expression);
} catch (e) {
ret = undefined;
}
return ret;
}
function getOSDIStatus(json) {
var obj;
var str;
try {
obj = JSON.parse(json);
str = obj['osdi:status']['status'] + ' ' + obj['osdi:status']['description'];
} catch (e) {
str = "Undetermined";
}
return str;
}
function present(obj) {
if ( obj != undefined && obj != null && obj != ""
&& obj != "undefined" && obj != "null"){
return true;
} else {
return false;
}
}
function getPeopleURI() {
var aep=getAEP();
var peopleUrl = nav(aep,"obj['_links']['osdi:people']['href']");
//aep['_links']['osdi:people']['href'];
consoleLog('People URL: ' + peopleUrl);
try {
_ls['person_signup_uri'] = aep['_links']['osdi:person_signup_helper']['href'];
} catch (e) {
alert("Cannot find OSDI Server");
}
if ( ! present(_ls['person_signup_uri'])) {
alert('Invalid OSDI Server');
}
// optional
_ls['brand_logo'] = nav(aep,"obj['_links']['canvasser:brand_logo']['href']" ) ;
_ls['logger_uri'] = nav(aep, "obj['_links']['canvasser:logger']['href']" ) ;
consoleLog("Got here");
return peopleUrl;
}
function getOSDILinkURI(rel) {
var aep=getAEP();
var linkUri = aep['_links'][rel]['href'];
return linkUri;
}
function getAEP() {
var response;
consoleLog('Get AEP');
var myheaders = {};
if (present(_ls['api_key']) ) {
myheaders['OSDI-API-Token'] = _ls['api_key'];
}
var ajaxSettings = {
// The url to flickrs api
url: _ls['osdi_aep'],
async: false,
type: "GET",
headers: myheaders,
// The function to execute when the api has finished loading
//success: apiSuccessOSDI,
};
// Pass all the settings to being fetching the data
response = $.ajax(ajaxSettings);
consoleLog(response);
var aep = JSON.parse(response.responseText);
return aep;
}
function uploadPerson(person, resourceUrl) {
// serialize to JSON
var json = JSON.stringify(person['data']);
var response;
var response_json;
// busy on
// do POST to server synchronous
// Settings to pass to jquery to fetch the data
osdiLog('Uploading person ' + personEmail(person));
response = exec_ajax(json,resourceUrl);
response_json = response.responseText;
person['save_response'] = response_json;
person['status_code'] = response.status;
person['request_id'] = response.getResponseHeader('OSDI-Request-ID');
savePerson(person);
if ( response.status > 299) {
osdiLog("Upload Error " + personEmail(person) + " status " + response.status);
osdiLog(getOSDIStatus(response.responseText));
} else {
osdiLog("Upload Success " + personEmail(person) + " status " + response.status);
}
consoleLog(response);
// busy off
}
function tagPerson(person) {
var save_response=JSON.parse(person['save_response']);
var tagUrl =save_response['_links']['osdi:tags']['href'];
var json;
person['tags'].map( function (tagName) {
consoleLog ("Tagging [" + tagName + "] " + personEmail(person) );
tagObject(tagName,tagUrl);
});
}
function personEmail(person) {
var pe = person['data']['person']['email_addresses'][0]['address'];
return pe;
}
function tagObject(tagName, tagUrl) {
var tagHash = {
"name" : tagName
};
var json = JSON.stringify(tagHash);
var response = exec_ajax(json,tagUrl);
}
function exec_ajax(json,resourceUrl) {
var response;
var myheaders = {};
if (present(_ls['api_key']) ) {
myheaders['OSDI-API-Token'] = _ls['api_key'];
}
var ajaxSettings = {
// The url to flickrs api
url: resourceUrl,
// The format we want it in
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
type: "POST",
data: json,
headers: myheaders,
// The function to execute when the api has finished loading
//success: apiSuccessOSDI,
};
// Pass all the settings to being fetching the data
response = $.ajax(ajaxSettings);
consoleLog(response.status + ' POST ' + resourceUrl );
return response;
}
function apiSuccessOSDI(data) {
_data=data;
_people = _data['_embedded']['people'];
consoleLog(data);
renderPeople(_people);
}
// This function is to be called when reddits api responds
function apiSuccess(data){
console.info('flickr response', data);
// Reddit returns a lot of data, find the bit we actually want
var whiteMeat = data['items'];
// Loop through the reddit posts
for (var i = whiteMeat.length - 1; i >= 0; i--) {
// Assign the post to a variable for neatness
var data = whiteMeat[i];
// Generate the image for the post
var postImage = new Image();
// *on* the images load event, execute the imageload function
postImage.onload = imageLoad;
// Set the image source to the url we got from flickr
postImage.src = data['media']['m'].replace('_m', '_b');
// Disable the browser default behaviour, can interfere with swiping
postImage.draggable = false;
};
}
function renderPeople(data) {
for (var i=0;i<data.length;i++) {
var p=data[i];
consoleLog('Person: ' + p);
$('#people').append("<h2>" + p.first_name + ' ' + p.last_name + "</h2>");
$('#people').append("<p>" + p.email + '</p>');
}
}
function getPosts(){
// Settings to pass to jquery to fetch the data
var ajaxSettings = {
// The url to flickrs api
url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?',
// The format we want it in
dataType: 'jsonp',
// The function to execute when the api has finished loading
success: apiSuccess,
};
// Pass all the settings to being fetching the data
$.ajax(ajaxSettings);
}
function getPeople(){
// Settings to pass to jquery to fetch the data
var ajaxSettings = {
// The url to flickrs api
url: 'http://192.168.40.1:3000/api/v1/people/',
// The format we want it in
dataType: 'json',
// The function to execute when the api has finished loading
success: apiSuccessOSDI,
};
// Pass all the settings to being fetching the data
$.ajax(ajaxSettings);
}
// count of items in an object
function countObjectProperties(obj)
{
var count = 0;
for(var i in obj)
if(obj.hasOwnProperty(i))
count++;
return count;
}
function osdiLog(msg)
{
console.log(msg);
var log_messages = JSON.parse(_ls['log_messages']);
log_messages.unshift(msg);
_ls['log_messages']= JSON.stringify(log_messages);
}
function consoleLog(msg)
{
osdiLog(msg);
}
function osdiLogClear()
{
_ls['log_messages'] = "[]";
}
function osdiLogMessages() {
var log_messages = JSON.parse(_ls['log_messages']);
return log_messages;
}
// app cache stuff
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);