-
Notifications
You must be signed in to change notification settings - Fork 0
/
turkerview.user.js
4649 lines (4026 loc) · 248 KB
/
turkerview.user.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
// ==UserScript==
// @name TurkerViewJS
// @namespace https://turkerview.com/mturk-scripts/
// @version 11.0.4
// @updateURL https://raw.githubusercontent.com/0x7C2f/UserScripts/main/turkerview.user.js
// @downloadURL https://raw.githubusercontent.com/0x7C2f/UserScripts/main/turkerview.user.js
// @description Imports Turkerview.com functionality into mTurk.
// @author ChrisTurk
// @contrib Kadauchi - hijacked coloring functions that I then mangled, his were clean.
// @contrib Slothbear - tons of bugfixes when I fail to test stuff in the real-world
// @contrib SalemBeats - this jerk demands proper coding design structure.. pfft
// @include /^http(s)?://worker\.mturk\.com/
// @exclude https://worker.mturk.com/direct_deposit*
// @exclude https://worker.mturk.com/payment_schedule*
// @exclude https://worker.mturk.com/?finder_beta
// @exclude https://worker.mturk.com/?hit_forker
// @exclude https://worker.mturk.com/requesters/PandaCrazy/projects
// @exclude https://worker.mturk.com/?filters[search_term]=pandacrazy=on
// @grant GM_log
// @grant GM_addStyle
// @grant GM_getResourceText
// @require https://code.jquery.com/jquery-3.1.0.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @require https://use.fontawesome.com/fd61435f75.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone.min.js
// @require https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js
// @resource customCSS https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css
// @run-at document-end
// ==/UserScript==
let settings = {};
var settingsDB;
function initTVDB(){
try {
if (mturksuite) return;
}
catch (e) {}
const request = indexedDB.open(`turkerview`, 1);
request.onerror = function(event){
console.log(`TVJS could not open indexedDB`, event.target.errorCode);
}
request.onsuccess = function(event){
settingsDB = event.target.result;
var transaction = settingsDB.transaction([`turkerview`]);
var objectStore = transaction.objectStore(`turkerview`);
var request = objectStore.get(`settings`);
request.onsuccess = function(evented){
if (!request.result){
let check_old_api_key = localStorage.getItem(`turkerview_api_key`) || null;
var settings = {
key: `settings`,
api_key: check_old_api_key
}
var apiObjectStore = settingsDB.transaction(`turkerview`, `readwrite`).objectStore(`turkerview`);
apiObjectStore.add(settings);
initSetting();
return;
}
if (request.result['api_key'] != null) initSetting(request.result['api_key']);
else initSetting()
}
};
request.onupgradeneeded = function(event){
var db = event.target.result;
var objectStore = db.createObjectStore(`turkerview`, { keyPath: `key` });
objectStore.transaction.oncomplete = function(event){
let check_old_api_key = localStorage.getItem(`turkerview_api_key`) || null;
var settings = {
key: `settings`,
api_key: check_old_api_key
}
var apiObjectStore = db.transaction(`turkerview`, `readwrite`).objectStore(`turkerview`);
apiObjectStore.add(settings);
}
};
}
function initSetting(db_info = null){
ls_tv_api_key = localStorage.getItem('turkerview_api_key') || null;
settings = JSON.parse(localStorage.getItem('tv-settings')) || null;
if (settings === null){
settings = {
version: 2,
titlebar_wage_display: true,
display_requester_ratings: true,
display_hit_ratings: true,
disable_return_reviews: false,
show_return_favicon: true,
tv_api_key: (db_info != null) ? db_info : ls_tv_api_key,
return_warning_levels: {
underpaid: 'high',
broken: 'high',
screener: 'high',
tos: 'high',
writing: 'high',
downloads: 'high',
extraordinary_measures: 'high'
},
last_sync: null
}
commitSettings();
} else if (settings.version === undefined){
settings.version = 2;
settings.show_return_favicon = true;
settings.display_requester_ratings = true;
settings.display_hit_ratings = true;
settings.disable_return_reviews = false;
settings.tv_api_key = (db_info != null) ? db_info : ls_tv_api_key,
settings.return_warning_levels = {};
settings.return_warning_levels.underpaid = 'high';
settings.return_warning_levels.broken = 'high';
settings.return_warning_levels.screener = 'high';
settings.return_warning_levels.tos = 'high';
settings.return_warning_levels.writing = 'high';
settings.return_warning_levels.downloads = 'high';
settings.return_warning_levels.extraordinary_measures = 'high';
settings.last_sync = null;
} else if (db_info != null){
settings.tv_api_key = db_info
} else if (ls_tv_api_key != null){
settings.tv_api_key = ls_tv_api_key
}
ViewHeaders = new Headers([
['X-VIEW-KEY', settings.tv_api_key],
['X-APP-KEY', 'TurkerViewJS'],
['X-APP-VER', ver] //SemVer
]);
//settings are loaded, its safe to start the script
initTVJS();
}
function changeSettings(){
let the_api_key = $('input[name=tv_api_key]').val();
if (settings.tv_api_key != the_api_key && the_api_key != null && the_api_key != '' && the_api_key.length == 40){
var store_settings = {
key: `settings`,
api_key: the_api_key
}
var transaction = settingsDB.transaction([`turkerview`], `readwrite`);
var objectStore = transaction.objectStore(`turkerview`);
var request = objectStore.put(store_settings);
request.onsuccess = function(event){
//console.log('put settings:', request.result);
}
$('#api_connect').show(500);
ViewHeaders = new Headers([
['X-VIEW-KEY', $('input[name=tv_api_key]').val()],
['X-APP-KEY', 'TurkerViewJS'],
['X-APP-VER', ver] //SemVer
]);
}
settings.titlebar_wage_display = $('input[name=display_titlebar_wage]').is(':checked') ? true : false;
settings.show_return_favicon = $('input[name=show_return_favicon]').is(':checked') ? true : false;
settings.display_mturk_ratings = $('input[name=display_mturk_ratings]').is(':checked') ? true : false;
settings.display_requester_ratings = $('input[name=display_requester_ratings]').is(':checked') ? true : false;
settings.display_hit_ratings = $('input[name=display_hit_ratings]').is(':checked') ? true : false;
settings.enable_quick_reviews = $('input[name=enable_quick_reviews]').is(':checked') ? true : false;
settings.disable_return_reviews = $('input[name=disable_return_reviews]').is(':checked') ? true : false;
settings.tv_api_key = !$('input[name=tv_api_key]').val() ? null : $('input[name=tv_api_key]').val();
settings.return_warning_levels = {}
settings.exp_returners = $('input[name=exp_returners]').is(':checked') ? true : false;
settings.rr_screener_min = $('select[name=rr_screener_min]').val();
settings.return_warning_levels.underpaid = $('select[name=return_underpaid_warn_lvl]').val();
settings.return_warning_levels.broken = $('select[name=return_broken_warn_lvl]').val();
settings.return_warning_levels.screener = $('select[name=return_screener_warn_lvl]').val();
settings.return_warning_levels.tos = $('select[name=return_tos_warn_lvl]').val();
settings.return_warning_levels.writing = $('select[name=return_writing_warn_lvl]').val();
settings.return_warning_levels.downloads = $('select[name=return_downloads_warn_lvl]').val();
settings.return_warning_levels.extraordinary_measures = $('select[name=return_extraordinary_warn_lvl]').val();
settings.last_sync = settings.last_sync ? settings.last_sync : null;
commitSettings()
}
function commitSettings(){
localStorage.setItem('tv-settings', JSON.stringify(settings));
localStorage.setItem('ztv-settings', JSON.stringify(settings)); //duplicate for testing exporting
localStorage.setItem('turkerview_api_key', settings.tv_api_key);
}
let tvAgreement = (localStorage.getItem('tv-agree') == 'true') || false;
let tvQualified = (localStorage.getItem('tv-qual-2') == 'true') ? true : (localStorage.getItem('tv-qual-2') == 'false') ? false : null;
let hideReviewedFromTable = (localStorage.getItem('tv-hide-reviewed') == 'true') || false;
let viewData = [];
let hitData = [];
let react = [];
moment.tz.add("America/Los_Angeles|PST PDT PWT PPT|80 70 70 70|010102301010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010|-261q0 1nX0 11B0 1nX0 SgN0 8x10 iy0 5Wp1 1VaX 3dA0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1a00 1fA0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1cN0 1cL0 1cN0 1cL0 s10 1Vz0 LB0 1BX0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|15e6");
const today = moment.tz('America/Los_Angeles').format('YYYY-MM-DD');
const queue = new RegExp('/worker\.mturk\.com\/tasks');
const windowHREF = window.location.href;
const ver = GM_info.scriptMetaStr.match(/version.*?(\d+.*)/)[1];
let ViewHeaders = new Headers([
['X-VIEW-KEY', settings.tv_api_key],
['X-APP-KEY', 'TurkerViewJS'],
['X-APP-VER', ver] //SemVer
]);
const hourlyFormat = (hourly) => {
let color = 'rgba(255, 0, 0, ';
if (hourly >= 10.00) { color = 'rgba(0, 128, 0, '; }
else if (hourly >= 7.25) { color = 'rgba(255, 165, 0, '; }
else if (hourly === '<i class="fa fa-minus"></i>') { color = 'rgba(128, 128, 128, '; }
return color;
};
const iconImage = (hourly) => {
let url = 'https://turkerview.com/assets/images/tv-unrated.png'
if (hourly == null) url = 'https://turkerview.com/assets/images/tv-unrated.png';
else if (hourly < 7.25) url = 'https://turkerview.com/assets/images/tv-red.png';
else if (hourly < 10.50) url = 'https://turkerview.com/assets/images/tv-orange.png';
else url = 'https://turkerview.com/assets/images/tv-green.png';
return url;
};
const confidence = (ratings_count) => {
let cOpacity = '0.5';
if (ratings_count >= 10) { cOpacity = '1'; }
else if (ratings_count >= 5) { cOpacity = '0.75'; }
else if (ratings_count >= 1) { cOpacity = '0.5'; }
return cOpacity;
};
const payFormat = (pay) => {
let payFA = '<i class="fa fa-thumbs-o-down" style="color: red;"></i> Very bad';
if (pay >= 4.25) { payFA = '<i class="fa fa-thumbs-o-up" style="color: green;"></i> Generous'; }
else if (pay >= 3.5) { payFA = '<i class="fa fa-thumbs-o-up" style="color: green;"></i> Good'; }
else if (pay >= 2.5) { payFA = '<i class="fa fa-handshake-o" style="color: orange;"></i> Fair'; }
else if (pay >= 1.5) { payFA = '<i class="fa fa-thumbs-o-down" style="color: red;"></i> Low'; }
else if (pay === null) { payFA = '<i class="fa fa-minus" style="color: grey;"></i> Unrated'; }
return payFA;
};
const classMap = total_reports => total_reports == 0 ? 'text-muted' :
total_reports < 3 ? 'text-warning' : 'text-danger';
$(document).ready(function(){
initTVDB();
});
let syncing = false;
function initTVJS(){
if (!settings.install_date) settings.install_date = moment.tz('America/Los_Angeles');
commitSettings();
if (tvQualified == null) checkQual('get');
if ($('ol.hit-set-table').length) {
if ($('.mturk-alert-content:contains(something is not right)').length > 0){
$('.mturk-alert-content:contains(something is not right)').append(`<p class="p-b-0 m-b-0" style="margin-top: 0.5rem;"><strong>If you just came from contacting a requester using TurkerView or a manual contact link you can ignore this warning, your message went through just fine!</strong></p>`)
}
waitForKeyElements ( '.requester-column:eq(0)', getRIDs);
}
let api_announcement = (!settings.tv_api_key || settings.tv_api_key === "" || settings.tv_api_key.length != 40) ? `<i class="fa fa-warning" style="color: #f39c12;"></i> ` : `<img src="https://turkerview.com/assets/images/tv-green.png" style="max-width: 16px; max-height: 16px; display: none;">`;
if ($('ul.nav.navbar-nav').length){
$('ul.nav.navbar-nav:first').find('.nav-item:last').after(`<li class="nav-item"><a id="nav-tv" class="nav-link" href="#">${api_announcement}TurkerView</a></li>`);
} else {
$('a:contains(HIT Details)')
$('a.navbar-brand').after(`<div class="navbar-divider hidden-xs-down"></div><ul class="nav navbar-nav hidden-xs-down"><li class="nav-item"><a id="nav-tv" class="nav-link" href="#">${api_announcement}TurkerView</a></li></ul>`);
}
$('body').on('click', '#nav-tv', function(){
//don't call the modal unless we need it
if (settings.last_sync){
let diff = moment.tz('America/Los_Angeles').diff(moment(settings.last_sync), 'seconds');
if (diff > 1800 && !/projects.*assignment_id/.test(windowHREF)){
if (diff > 129600) settings.install_date = moment.tz('America/Los_Angeles');
else cycleAASync();
}
}
if (!$('#tvDashModal').length){
initTurkerView();
initReviews();
$('input[name=display_titlebar_wage], input[name=display_mturk_ratings], input[name=display_requester_ratings], input[name=disable_return_reviews], input[name=display_hit_ratings], input[name=show_return_favicon], input[name=tv_api_key], input[name=exp_returners], select[name=rr_screener_min], select[name*=return_]').on('change keyup', function(){
changeSettings();
});
$('input[name=enable_quick_reviews]').on('change', function(){
changeSettings();
fillTable();
})
fillTable();
}
else {
$('#tv-table').find('tbody').html('');
fillTable();
$('body').addClass('global-modal-open modal-open');
$('#tvDashModal, #tv-dash-modal-backdrop').show();
}
});
if (/https:\/\/worker\.mturk\.com\/tasks/.test(windowHREF)){
getRIDs();
} else if (/https:\/\/worker\.mturk\.com\/contact_requester/.test(windowHREF)){
contactPage();
} else if (/projects.*assignment_id/.test(windowHREF)){
trackingTask();
} else if (/projects.*\/tasks/.test(windowHREF)){
let assignmentData = $('.project-detail-bar').find('[data-react-class="require(\'reactComponents/common/ShowModal\')[\'default\']"]').data('react-props').modalOptions;
let assignableHitsCount = assignmentData.assignableHitsCount;
let hit_set_id = document.querySelectorAll('form[action*="projects/')[0].action.match(/projects\/([A-Z0-9]+)\/tasks/)[1];
let rid = assignmentData['contactRequesterUrl'].match(/requester_id%5D=(.*?)&/)[1];
let title = assignmentData['projectTitle'];
let reward = assignmentData['monetaryReward']['amountInDollars'];
getHitReturnData(hit_set_id, assignableHitsCount);
getDetailedHitData(rid, reward, title, assignableHitsCount, hit_set_id);
} else if (/dashboard/.test(windowHREF)){
/* Let's get some stats */
let surveyWorkTime = 0;
let surveyPE = 0;
let batchWorkTime = 0;
let batchPE = 0;
let totalPE = 0;
let trackedWorkTime = 0;
let requesterBreakdownTableHtml = ``;
Object.keys(localStorage)
.forEach(function(key){
if (/^tv_/.test(key)) {
let json = JSON.parse(localStorage.getItem(key));
if (json['date'] != today) return;
let reviewButton = ``;
if (json['reviewId'] == null){
reviewButton = `<a class="btn btn-primary btn-sm btn-review" data-toggle="tooltip" data-title="Leave a review on TurkerView!" data-hitKey="${escape(key)}">Review</a>`;
} else if (json['reviewId'] != null){
reviewButton = `<a href="https://turkerview.com/reviews/edit.php?id=${json['reviewId']}" target="_blank" class="btn btn-default btn-sm" data-hitKey="${escape(key)}" data-toggle="tooltip" data-title="Edit Review (Takes you to TurkerView)">Edit</a>`;
}
if (json['times'].length == 1){
surveyWorkTime += json['completionTime'];
surveyPE += json['reward'];
trackedWorkTime += json['completionTime'];
requesterBreakdownTableHtml += `
<div class="col-xs-4" style="overflow: hidden; white-space: nowrap;">${json['requester']}</div>
<div class="col-xs-2 text-xs-right">${json['times'].length}</div>
<div class="col-xs-2 text-xs-right">${moment().startOf('day').seconds((json['completionTime']/1000)).format('H:mm:ss')}</div>
<div class="col-xs-2 text-xs-right">$${((3600/(json['completionTime']/1000))*json['reward']).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}/hr</div>
<div class="col-xs-2 text-xs-right">$${json['reward'].toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
<div class="col-xs-1" style="display: none;">${reviewButton}</div>`;
return;
}
/* Use Median Values on Batches */
let mind;
let arr = json['times'];
mind = Math.floor(median(filterOutliers(arr))/1000);
if (!mind) mind = Math.floor(median(arr)/1000);
//batchWorkTime += mind*(arr.length);
batchPE += json['reward']*(arr.length);
let batch_work_time = 0;
let batch_earned = 0;
json['times'].forEach(time => {
batchWorkTime += time/1000;
trackedWorkTime += time;
batch_work_time += time;
batch_earned += json['reward'];
});
requesterBreakdownTableHtml += `
<div class="col-xs-4" style="overflow: hidden; white-space: nowrap;">${json['requester']}</div>
<div class="col-xs-2 text-xs-right">${json['times'].length}</div>
<div class="col-xs-2 text-xs-right">${moment().startOf('day').seconds((batch_work_time/1000)).format('H:mm:ss')}</div>
<div class="col-xs-2 text-xs-right">$${((3600/(batch_work_time/1000))*batch_earned).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}/hr</div>
<div class="col-xs-2 text-xs-right">$${batch_earned.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
<div class="col-xs-1" style="display: none;">${reviewButton}</div>`;
/* Calculate the hourly based on every single individual HIT */
/* We're not going to use this for now, I think overall it'll be less accurate since wild swings in completion times will throw things off
json['times'].forEach(function(time){
workTime += time;
pe += json['reward'];
});
*/
}
});
totalPE = surveyPE+batchPE;
let overall_wages = ((3600/(trackedWorkTime/1000))*totalPE).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
overall_wages = Number(overall_wages) ? `$${overall_wages}/hr` : `-`;
let trackedFormatted = moment().startOf('day').seconds(Math.floor(trackedWorkTime/1000)).format('H:mm:ss');
let daily_survey_hourly = ((3600/(surveyWorkTime/1000))*surveyPE).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
daily_survey_hourly = Number(daily_survey_hourly) ? `$${daily_survey_hourly}/hr` : `-`;
let daily_batch_hourly = ((3600/(batchWorkTime))*batchPE).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
daily_batch_hourly = Number(daily_batch_hourly) ? `$${daily_batch_hourly}/hr` : `-`;
if ($('.row.m-b-sm:contains(Projected Earnings)').length){
//Dashboard Enhancer present, just append
$('.row.m-b-sm:contains(Projected Earnings)').after(`
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Tracked Time</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${trackedFormatted}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Overall Wages</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${overall_wages.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Batch Wages</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${daily_batch_hourly}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Survey Wages</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${daily_survey_hourly}</div>
</div>`);
} else{
/* Rebuild the entire PE dash >.> Y U NO HAVE DASH ENHANCER??? */
$('.col-xs-12.col-md-4.col-md-push-8').prepend(`
<div class="row m-b-xl">
<div class="col-xs-12">
<h2 class="m-b-md">Today's Activity</h2>
<div class="row">
<div class="col-xs-12">
<div class="border-gray-lightest p-a-sm">
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Tracked Earnings</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">$${totalPE.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Tracked Time</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${trackedFormatted}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Overall Wages</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${overall_wages.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Batch Wages</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${daily_batch_hourly}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7"><strong>Survey Wages</strong></div>
<div class="col-xs-5 col-sm-6 col-lg-5 text-xs-right">${daily_survey_hourly}</div>
</div>
<div class="row m-b-sm">
<div class="col-xs-7 col-sm-6 col-lg-7">
<span class="expand-requester-breakdown-button">
<a class="table-expand-collapse-button" href="#" style="display: block; text-align: center;"><i class="fa fa-plus-circle"></i>
<span class="button-text">Show Requesters</span>
</a>
</span>
</div>
<div class="col-xs-5 col-sm-6 col-lg-5">
<span class="collapse-requester-breakdown-button">
<a class="table-expand-collapse-button" href="#" style="display: block; text-align: center;"><i class="fa fa-minus-circle"></i>
<span class="button-text">Hide Requesters</span>
</a>
</span>
</div>
</div>
<!-- Requester Breakdown Table -->
<div id="requester-breakdown" class="row m-b-sm" style="display: none;">
<div class="col-xs-4"><strong>Requester</strong></div>
<div class="col-xs-2 text-xs-right"><strong>Submitted</strong></div>
<div class="col-xs-2 text-xs-right"><strong>Time</strong></div>
<div class="col-xs-2 text-xs-right"><strong>Wages</strong></div>
<div class="col-xs-2 text-xs-right"><strong>Earned</strong></div>
<div class="col-xs-1 text-xs-right" style="display: none;"><strong>Review</strong></div>
${requesterBreakdownTableHtml}
</div>
</div>
</div>
</div>
</div>
</div>
`)
$('.expand-requester-breakdown-button').click(function(){
$('#requester-breakdown').slideDown(250);
});
$('.collapse-requester-breakdown-button').click(function(){
$('#requester-breakdown').slideUp(250);
});
/*
initTurkerView();
initReviews();
$('input[name=display_titlebar_wage], input[name=display_requester_ratings], input[name=disable_return_reviews], input[name=display_hit_ratings], input[name=show_return_favicon], input[name=tv_api_key], select[name*=return_]').on('change keyup', function(){
changeSettings();
});
fillTable();
*/
}
$('.result-count-info').append(`<span id="tv-aa-sync" style="cursor: pointer; margin-left: 5px;"><i class="fa fa-refresh"></i> Sync TV Review Approvals</span>`);
$('#tv-aa-sync').click(function(){
if (syncing) return;
syncing = true;
$('#tv-aa-sync').addClass('text-muted').html(`<i class="fa fa-refresh fa-spin"></i> Syncing`);
cycleAASync();
})
setInterval(dashWatcher, 900000);
function dashWatcher(){
let diff = moment.tz('America/Los_Angeles').diff(moment(settings.last_sync), 'seconds');
if (diff > 7200 || !settings.last_sync){
if (diff > 129600) {
settings.install_date = moment.tz('America/Los_Angeles');
settings.last_sync = moment.tz('America/Los_Angeles');
commitSettings();
cycleAASync();
}
else cycleAASync();
}
}
let diff = moment.tz('America/Los_Angeles').diff(moment(settings.last_sync), 'seconds');
if (diff > 900 || !settings.last_sync){
if (diff > 129600) {
settings.install_date = moment.tz('America/Los_Angeles');
settings.last_sync = moment.tz('America/Los_Angeles');
commitSettings();
cycleAASync();
}
else cycleAASync();
} //else console.log('we wont send another hit status request for '+(900 - diff)+' seconds..');
$(document).on('click', '.btn-update-rejection', function(){
$(this).attr('disabled', true);
let json = JSON.parse(localStorage.getItem($(this).attr('id')));
let postObject = {
fast_rating_5: [], fast_rating_4: [], fast_rating_3: [], fast_rating_2: [], fast_rating_1: [],
rejection_ids: [{ review_id: json.reviewId, requester_feedback: json.feedback, requester_name: json.requester }]
}
let postData = new FormData();
postData.append('data', JSON.stringify(postObject));
fetch(`https://turkerview.com/api/v2/reviews/update/status/`, {
method: 'POST',
body: postData,
headers: ViewHeaders
}).then(res => {
if (!res.ok) throw res;
return res.json()
}).then(res => {
if ($('#rejection-thanks').length == 0) $(this).closest('table').before(`<p>Thank you!</p><p>Thank you for sharing your experience with this requester. If you need help getting the rejections overturned please drop by the current <a href='https://forum.turkerview.com/forums/daily-mturk-hits-threads.2/' target='_blank'>Daily Thread</a></p>`);
}).catch(ex => {
console.log(ex);
alert(`Sorry, TVJS couldn't communicate your rejection to TV! Let CT know we saw this exception: ${ex} - also available in console (F12)`)
});
});
checkQual('react');
if (settings.tv_api_key == null || settings.tv_api_key == '' || settings.tv_api_key.length != 40){
$('h1:contains(Overview)').before(tvApiAlert());
}
}
/* TurkerView Bridge */
if (/status_details/.test(windowHREF)){
console.log(`bridge status page`);
waitForKeyElements('.hit-status-details:eq(0)', bridgeStatusPage);
}
}
let lastDay = '';
function cycleAASync(){
if (!settings.tv_api_key || settings.tv_api_key.length != 40) {
settings.last_sync = moment.tz('America/Los_Angeles');
syncing = false;
commitSettings();
return;
}
let newtoday = moment(today).tz('America/Los_Angeles', true);
let installdate = moment(settings.install_date).tz('America/Los_Angeles', true);
let installDiff = newtoday.startOf('day').diff(installdate.startOf('day'), 'days');
let datesWithReviews = [];
Object.keys(localStorage)
.forEach(function(key){
if (/^tv_/.test(key)) {
let json = JSON.parse(localStorage.getItem(key));
let sizeEst = (JSON.stringify(json).length*16)/(8*1024);
/* Let's clean up old data or data we no longer have use for so we can keep localstorage clean for the user */
/*
Single record HITs are <400 len, ~.75kb in size so we could store up to 6,000 without overflowing localstorage, we should never get close to that.
A massive Forker / Overwatch / etc install complicates this immensely, so lets be stingy with what TV is storing to avoid any possible complications while still getting good AA data
*/
let days = moment(today).tz('America/Los_Angeles', true).diff(moment(json['date']).tz('America/Los_Angeles', true), 'days');
if (days > 7 && !json.reviewId){
//This record is too old to be reviewed & doesn't have a review id, its safe to remove it
localStorage.removeItem(key);
return;
} else if (days > 3 && json.reviewId && ( (json.hit_status == 1 && json.task_count == 1) || json.approved == json.task_count ) ){
//This record is too old to be edited from TVJS, it has been reviewed & we already uploaded the approval time no need to keep it
localStorage.removeItem(key);
return;
} else if (days > 10 && json.reviewId && sizeEst > 5){
//This record is simply too big to keep longer than 10 days, this should be incredibly rare to invoke, but adds a very important safety net around the user's limited local storage length
localStorage.removeItem(key);
return;
} else if (days > 4 && !json.times){
//This record is from prior to TVJS10, we should remove it
localStorage.removeItem(key);
return;
} else if (days > 31){
//Its been too long, lets move on with our lives.
localStorage.removeItem(key);
return;
}
if (json.hit_stauts == 1 && json.task_count == 1) return; //filter out hits we already know the AA time of. don't filter rejections, we need to know if they overturn
if (json.fast && json.approved == json.task_count) return; //only count approvals here, if there are rejections we should check to see if they overturn
if (!datesWithReviews.includes(json['date'])) datesWithReviews.push(json['date']);
}
});
datesWithReviews.sort(function(a,b){return new Date(a).getTime() - new Date(b).getTime()}).reverse();
let yesterday = moment(today).tz('America/Los_Angeles', true).subtract(1, 'days').format('YYYY-MM-DD');
let startSubtract = 1;
let startCooldown = 0;
let installWait = -1;
let days_scanned = 0;
/* we'll always check the last two days IF(!) there are reviews, just in case */
if (datesWithReviews.includes(today)) {
days_scanned++;
startCooldown += 1500;
checkHitStatus(today, 50);
lastDay = today;
}
if (datesWithReviews.includes(yesterday)) {
days_scanned++;
startCooldown += 1500;
setTimeout(function(){ checkHitStatus(yesterday); }, startCooldown);
lastDay = yesterday
}
for (let i = 0; i < 32; i++){
startSubtract++;
installWait++;
let dateFormatted = moment(today).tz('America/Los_Angeles', true).subtract(startSubtract, 'days').format('YYYY-MM-DD');
if (!datesWithReviews.includes(dateFormatted)) continue;
days_scanned++;
lastDay = dateFormatted;
startCooldown += 1500;
setTimeout(function(){ checkHitStatus(dateFormatted); }, startCooldown);
}
if (days_scanned == 0){
syncing = false;
if ($('#tv-aa-sync').hasClass('text-muted')) $('#tv-aa-sync').removeClass('text-muted').html(`<i class="fa fa-refresh"></i> Done!`);
settings.last_sync = moment.tz('America/Los_Angeles');
commitSettings();
}
if (datesWithReviews.length === 0){
console.log('no reviews');
syncing = false;
settings.last_sync = moment.tz('America/Los_Angeles');
commitSettings();
$('#tv-aa-sync').removeClass('text-muted').html(`<i class="fa fa-refresh"></i> Done!`);
}
}
async function checkHitStatus(date, page_limit = 50){
//console.log('checking...',date);
let statusHits = [];
let paidPages = 1;
let approvedPages = 1;
let rejectedPages = 1;
let ps = [];
const workHistory = await Promise.all([
fetch(`https://worker.mturk.com/status_details/${date}?utf8=✓&assignment_state=Approved&format=json`).then(res => res.json()).then(res => {
approvedPages = Math.ceil(res.total_num_results/20);
res.results.forEach(hit => {
statusHits.push(hit)
});
for (i = 2; i < page_limit; i++){
if (i > approvedPages) break;
let x = fetch(`https://worker.mturk.com/status_details/${date}?utf8=✓&assignment_state=Approved&format=json&page_number=${i}`).then(res => res.json()).then(res => {
res.results.forEach(hit => {
statusHits.push(hit)
})
});
ps.push(x)
}
}),
fetch(`https://worker.mturk.com/status_details/${date}?utf8=✓&assignment_state=Paid&format=json`).then(res => res.json()).then(res => {
paidPages = Math.ceil(res.total_num_results/20);
res.results.forEach(hit => {
statusHits.push(hit)
});
for (i = 2; i < page_limit; i++){
if (i > paidPages) break;
let x = fetch(`https://worker.mturk.com/status_details/${date}?utf8=✓&assignment_state=Paid&format=json&page_number=${i}`).then(res => res.json()).then(res => {
res.results.forEach(hit => {
statusHits.push(hit)
})
});
ps.push(x)
}
}),
fetch(`https://worker.mturk.com/status_details/${date}?utf8=✓&assignment_state=Rejected&format=json`).then(res => res.json()).then(res => {
rejectedPages = Math.ceil(res.total_num_results/20);
res.results.forEach(hit => {
statusHits.push(hit)
});
for (i = 2; i < page_limit; i++){
if (i > rejectedPages) break;
let x = fetch(`https://worker.mturk.com/status_details/${date}?utf8=✓&assignment_state=Rejected&format=json&page_number=${i}`).then(res => res.json()).then(res => {
res.results.forEach(hit => {
statusHits.push(hit)
})
});
ps.push(x)
}
})
]);
const pageHistory = await Promise.all(ps);
let diff = moment(today).diff(date, 'days');
let newtoday = moment(today).tz('America/Los_Angeles', true);
let installdate = moment(settings.install_date).tz('America/Los_Angeles', true);
let installDiff = newtoday.startOf('day').diff(installdate.startOf('day'), 'days');
let submitday = moment(date).tz('America/Los_angeles', true);
let submitDiff = newtoday.startOf('day').diff(submitday.startOf('day'), 'days'); //# of days since hit was submitted
let syncDate = moment(settings.last_sync).tz('America/Los_Angeles', true);
let syncDiff = newtoday.startOf('day').diff(syncDate.startOf('day'), 'days'); //# of days since last sync
//console.log(`Installed: ${installDiff} days ago, submitted: ${submitDiff} days ago, synced ${syncDiff} days ago`);
/* Rules:
1) Install diff should be less than days since HIT was submitted (if we submit a HIT 7 days ago, but only installed for 2 days, we don't know when it approved, don't mark fast)
2) Sync diff should be less than 1,5 days to reliably track fast approval
3) Use checkDiff to mark fast according to the old rules
*/
let str = `tv_${date}`;
let keyTest = new RegExp("^"+str);
// 5 == good (~1day AA), 1 == bad (15-30 day)
let fast_rating_5 = [];
let fast_rating_4 = [];
let fast_rating_3 = [];
let fast_rating_2 = [];
let fast_rating_1 = [];
let approved_ids = [];
let rejected_reviews = [];
let new_rejections = [];
let new_overturned_rejections = [];
let temp_object = {fast5: [], fast4: [], fast3: [], fast2: [], fast1: []};
let batches = [];
Object.keys(localStorage).forEach(function(key){
if (keyTest.test(key)) {
let json = JSON.parse(localStorage.getItem(key));
/* The only thing this does is upload a copy of a record we already have, we only do this if we're not confident our server will process the original request, look to remove. */
if (json.reviewId && json.fast){
if (json.fast == 5) temp_object.fast5.push(json.reviewId);
else if (json.fast == 4) temp_object.fast4.push(json.reviewId);
else if (json.fast == 3) temp_object.fast3.push(json.reviewId);
else if (json.fast == 2) temp_object.fast2.push(json.reviewId);
else if (json.fast == 1) temp_object.fast1.push(json.reviewId);
return; //don't need to look for this, we've already marked it for AA
}
//we need to keep track of:
// total task_count that we're scraping, as well as the max we should get to for a particular review
//when task_count == 1 make sure the assignment_id matches up
statusHits.forEach(function(hitResult){
/* We use this since status pages don't store group_id but we still group reviews by that string, ugh */
if (hitResult.requester_id != json.rid) return;
if (hitResult.title != json.title) return;
if (hitResult.reward.amount_in_dollars != json.reward) return;
/* Process Batch Records */
if (json.task_count > 1 && json.assignment_id == hitResult.assignment_id){
//we want to handle these differently, we'll update the approved/rejected count and if it equals the total submitted we'll let TV know we're done w/ this record
let t_approved = 0;
let t_rejected = 0;
let rejection_feedback = [];
let one_feedback = null;
statusHits.forEach(function(hit){
//loop through them all, see if we can get an approved/rejected count == task_count [ie, no pending left]
if (hit.requester_id != json.rid) return;
if (hit.title != json.title) return;
if (hit.reward.amount_in_dollars != json.reward) return;
if (hit.state == "Rejected") {
t_rejected++;
json.feedback = hit.requester_feedback;
if (!rejection_feedback.includes(hit.requester_feedback)) rejection_feedback.push(hit.requester_feedback);
one_feedback = hit.requester_feedback;
}
else if (hit.state == "Approved" || hit.state == "Paid") t_approved++;
});
//if (t_rejected > 0 && t_approved > 0) json.hit_status = null;
if (json.approved >= 1 && !json.fast){
if (installDiff <= submitDiff && syncDiff <= 2 && submitDiff < 2) {
json.fast = 5;
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 4) {
json.fast = 4;
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 8) {
json.fast = 3;
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 15) {
json.fast = 2;
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 32) {
json.fast = 1;
}
}
let mind;
/* Batch results*/
if (json['multi'] == true && json['times']){
let arr = json['times'];
mind = Math.floor(median(filterOutliers(arr))/1000);
if (!mind) mind = Math.floor(median(arr)/1000);
} else mind = Math.floor(json['completionTime'] / 1000);
if ((t_approved + t_rejected) >= json.task_count && (t_approved != json.approved && t_rejected == 0) ){
//the rejections might overturn, so we'll need to keep syncing this
json.task_count = (t_approved + t_rejected);
json.approved = t_approved;
json.rejected = t_rejected;
let record = {
requester_id: json.rid,
task_count: json.task_count,
approved: json.approved,
rejected: json.rejected,
feedback: one_feedback,
tracked_completion: mind,
fast: json.fast ? json.fast : null,
review_id: json.reviewId
};
if (json.reviewId) batches.push(record);
}
localStorage.setItem(key, JSON.stringify(json));
return;
}
/* End Batch Processing */
/* For one-off HITs, since we're matching title/rid/reward, we need to check the assignment_id here to make sure it's correct */
/* This prevents issues with requesters who use the same title/etc for two different surveys [Andy's $5 HITs w/ multiple in one day] */
if (hitResult.assignment_id != json.assignment_id) return; //make sure we only update the correct record for 1-off HITs
//if the hit_status is already set, don't overwrite it.
if (json.fast) return;
if (json.fast) return; //we've already handled this, should never get here tbh
if (json.hit_status == -1 && hitResult.state == "Rejected") return; //we know this is rejected, only way we'll do anything more w/ it is if it overturns
if (json.hit_status == 1) return; //we've already marked this as approved
if (hitResult.state == "Rejected"){
//change the state to rejected, then return so we don't update _fast rating
json.hit_status = -1;
json.feedback = hitResult.requester_feedback;
if (json.reviewId) rejected_reviews.push(json.reviewId);
localStorage.setItem(key, JSON.stringify(json));
if(json.reviewId) new_rejections.push({key: key, date: json.date, requester_name: json.requester, tasks: json.task_count, title: json.title, reviewId: json.reviewId, feedback: json.feedback})
return;
}
/* This was previously marked as rejected & is no longer rejected [we would have returned earlier if it was], safe to mark as overturned */
if (json.hit_status == -1) {
if(json.reviewId) new_overturned_rejections.push({key: key, date: json.date, requester_name: json.requester, tasks: json.task_count, title: json.title, reviewId: json.reviewId, feedback: json.feedback})
}
/* We know this is approved for sure, we only retrieve approved/paid/rejected results from the status pages */
json.hit_status = 1;
if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff < 2) {
json.fast = 5;
if (json.reviewId) fast_rating_5.push(json.reviewId);
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 4) {
json.fast = 4;
if (json.reviewId) fast_rating_4.push(json.reviewId);
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 8) {
json.fast = 3;
if (json.reviewId) fast_rating_3.push(json.reviewId);
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 15) {
json.fast = 2;
if (json.reviewId) fast_rating_2.push(json.reviewId);
}
else if (installDiff >= submitDiff && syncDiff <= 2 && submitDiff <= 32) {
json.fast = 1;
if (json.reviewId) fast_rating_1.push(json.reviewId);
} else {
//we don't know the AA time, just upload the approval info
if (json.reviewId) approved_ids.push(json.reviewId);
}
localStorage.setItem(key, JSON.stringify(json));
})
}
});
if (batches.length > 0) {
let batch_uploads = {
batches: batches
};
let batchData = new FormData();
batchData.append('data', JSON.stringify(batch_uploads));
fetch(`https://turkerview.com/api/v2/reviews/update/batch/`, {
method: 'POST',
body: batchData,
headers: ViewHeaders
}).then(res => {
if (!res.ok) throw res;
//console.log(res);
return res.json();
}).then(res => {
//we actually don't need to do anything with this, relic from testing
//console.log(res);
}).catch(ex => {
console.log('ex: '+ex);
});
}