MTurk HIT Database Mk.II

Keep track of the HITs you've done (and more!). Cross browser compatible.

目前为 2016-04-28 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name MTurk HIT Database Mk.II
  3. // @author feihtality
  4. // @namespace https://greasyfork.org/en/users/12709
  5. // @version 1.1.003
  6. // @description Keep track of the HITs you've done (and more!). Cross browser compatible.
  7. // @include /^https://www\.mturk\.com/mturk/(dash|view|sort|find|prev|search|accept|cont).*/
  8. // @exclude https://www.mturk.com/mturk/findhits?*hit_scraper
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. /**\
  13. **
  14. ** This is a complete rewrite of the MTurk HIT Database script from the ground up, which
  15. ** eliminates obsolete methods, fixes many bugs, and brings this script up-to-date
  16. ** with the modern browser environment.
  17. **
  18. \**/
  19.  
  20.  
  21.  
  22. /*globals self*/
  23.  
  24. const DB_VERSION = 8;
  25. const DB_NAME = 'HITDB';
  26. const MTURK_BASE = 'https://www.mturk.com/mturk/';
  27.  
  28. /*************************** Native code modifications *******************************/
  29. if (!NodeList.prototype[Symbol.iterator]) NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  30. Number.prototype.toPadded = function(length) { // format leading zeros
  31. 'use strict';
  32. length = length || 2;
  33. return ("0000000"+this).substr(-length);
  34. };
  35. Math.decRound = function(v, shift) { // decimal rounding
  36. 'use strict';
  37. v = Math.round(+(v+"e"+shift));
  38. return +(v+"e"+-shift);
  39. };
  40. Date.prototype.toLocalISOString = function() { // ISOString by local timezone
  41. 'use strict';
  42. var pad = function(num) { return Number(num).toPadded(); },
  43. offset = pad(Math.floor(this.getTimezoneOffset()/60)) + pad(this.getTimezoneOffset()%60),
  44. timezone = this.getTimezoneOffset() > 0 ? "-" + offset : "+" + offset;
  45. return this.getFullYear() + "-" + pad(this.getMonth()+1) + "-" + pad(this.getDate()) +
  46. "T" + pad(this.getHours()) + ":" + pad(this.getMinutes()) + ":" + pad(this.getSeconds()) + timezone;
  47. };
  48. if (!('includes' in Array.prototype)) Array.prototype.includes = function(arg) { 'use strict'; return Boolean(~this.indexOf(arg)); };
  49. /***********************************************************************************************/
  50.  
  51. (function() { // simplify strict scoping
  52. 'use strict';
  53.  
  54. var qc = {
  55. //extraDays: !!localStorage.getItem("hitdb_extraDays") || false,
  56. save: function(key, name, isObj) {
  57. if (isObj)
  58. localStorage.setItem(name, JSON.stringify(this[key]));
  59. else
  60. localStorage.setItem(name, this[key]);
  61. }
  62. },
  63. metrics = {};
  64.  
  65. var
  66. HITStorage = { //{{{
  67. data: {}, db: null,
  68. versionChange: function hsversionChange() { //{{{
  69. var db = this.result;
  70. db.onversionchange = function(e) { console.log("detected version change??",console.dir(e)); db.close(); };
  71. var dbo, idx;
  72.  
  73. console.groupCollapsed("HITStorage.versionChange::onupgradeneeded");
  74.  
  75. if (!db.objectStoreNames.contains("HIT")) {
  76. console.log("creating HIT OS");
  77. dbo = db.createObjectStore("HIT", { keyPath: "hitId" });
  78. for (idx of ['date', 'requesterName', 'title', 'reward', 'bonus', 'status', 'requesterId'])
  79. dbo.createIndex(idx, idx, { unique: false });
  80.  
  81. //localStorage.setItem("hitdb_extraDays", true);
  82. //qc.extraDays = true;
  83. } else if (!this.transaction.objectStore('HIT').indexNames.contains('bonus')) {
  84. this.transaction.objectStore('HIT').createIndex('bonus','bonus',{ unique: false });
  85. }
  86. if (!db.objectStoreNames.contains("STATS")) {
  87. console.log("creating STATS OS");
  88. dbo = db.createObjectStore("STATS", { keyPath: "date" });
  89. }
  90. if (this.transaction.objectStore("STATS").indexNames.length < 5) { // new in v5: schema additions
  91. for (idx of ['approved', 'earnings', 'pending', 'rejected', 'submitted'])
  92. this.transaction.objectStore("STATS").createIndex(idx, idx, { unique: false });
  93. }
  94.  
  95. if (db.objectStoreNames.contains("NOTES") && this.transaction.objectStore("NOTES").indexNames.length < 3)
  96. db.deleteObjectStore("NOTES");
  97.  
  98. if (!db.objectStoreNames.contains("NOTES")) { // new in v5; schema change
  99. console.log("creating NOTES OS");
  100. dbo = db.createObjectStore("NOTES", { keyPath: "id", autoIncrement: true });
  101. dbo.createIndex("hitId", "hitId", { unique: false });
  102. dbo.createIndex("requesterId", "requesterId", { unique: false });
  103. dbo.createIndex("tags", "tags", { unique: false, multiEntry: true });
  104. dbo.createIndex("date", "date", { unique: false });
  105. }
  106.  
  107. if (db.objectStoreNames.contains("BLOCKS"))
  108. db.deleteObjectStore("BLOCKS");
  109.  
  110. console.groupEnd();
  111. }, // }}} versionChange
  112. parseDOM: function(doc) {//{{{
  113. Status.color = "black";
  114.  
  115. var errorCheck = doc.querySelector('td[class="error_title"]'),
  116. extraInfo = [];
  117.  
  118. if (doc.title.search(/Status$/) > 0) // status overview
  119. parseStatus();
  120. else if (doc.querySelector('td[colspan="4"]')) // valid status detail, but no data
  121. parseMisc("next");
  122. else if (doc.title.search(/Status Detail/) > 0) // status detail with data
  123. parseDetail();
  124. else if (errorCheck) { // encountered an error page
  125. // hit max request rate
  126. if (~errorCheck.textContent.indexOf("page request rate")) {
  127. var _d = doc.documentURI.match(/\d{8}/)[0],
  128. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  129. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "start");
  130. console.log("exceeded max requests; refetching %sp%s", _d, _p);
  131. Status.node.innerHTML = "Exceeded maximum server requests; retrying "+Utils.ISODate(_d)+" page "+_p+"."+
  132. "<br>Please wait...";
  133. setTimeout(HITStorage.fetch, 3050, doc.documentURI);
  134. return;
  135. }
  136. // no more staus details left in range
  137. else if (qc.extraDays)
  138. parseMisc("end");
  139. else
  140. Utils.errorHandler(new Error("Failed to parse '" + doc.documentURI + "'"));
  141. }
  142. else
  143. Utils.errorHandler(new Error("Unhandled document '" + doc.docuemntURI + "'"));
  144.  
  145. function parseStatus() {//{{{
  146. HITStorage.data = { HIT: [], STATS: [] };
  147. qc.seen = {};
  148. ProjectedEarnings.clear();
  149.  
  150. qc.aat = JSON.parse(localStorage.getItem("hitdb_autoAppTemp") || "{}");
  151. qc.fetchData = JSON.parse(localStorage.getItem("hitdb_fetchData") || "{}");
  152. var _pastDataExists = Boolean(Object.keys(qc.fetchData).length),
  153. timeout = 0, scope = [],
  154. range = _pastDataExists ? Object.keys(qc.fetchData).filter(v => !isNaN(v)) : [],
  155. raw = {
  156. day: doc.querySelectorAll(".statusDateColumnValue"),
  157. sub: doc.querySelectorAll(".statusSubmittedColumnValue"),
  158. app: doc.querySelectorAll(".statusApprovedColumnValue"),
  159. rej: doc.querySelectorAll(".statusRejectedColumnValue"),
  160. pen: doc.querySelectorAll(".statusPendingColumnValue"),
  161. pay: doc.querySelectorAll(".statusEarningsColumnValue")
  162. };
  163. for (var i=0;i<raw.day.length;i++) {
  164. var d = {};
  165. var _date = raw.day[i].childNodes[1].href.substr(53);
  166. d.date = Utils.ISODate(_date);
  167. d.submitted = +raw.sub[i].textContent;
  168. d.approved = +raw.app[i].textContent;
  169. d.rejected = +raw.rej[i].textContent;
  170. d.pending = +raw.pen[i].textContent;
  171. d.earnings = +raw.pay[i].textContent.substr(1);
  172. HITStorage.data.STATS.push(d);
  173.  
  174. // bonus received on date with 0 HITs
  175. if (!d.submitted && !d.pending) { if (_date in qc.fetchData) delete qc.fetchData[_date]; continue; }
  176. // check whether or not we need to get status detail pages for date, then
  177. // fetch status detail pages per date in range and slightly slow
  178. // down GET requests to avoid making too many in too short an interval
  179. var payload = { encodedDate: _date, pageNumber: 1, sortType: "All" };
  180. if (_pastDataExists) {
  181. // date not in range but is new date (or old date but we need updates)
  182. // lastDate stored in ISO format, fetchData date keys stored in mturk's URI ecnodedDate format
  183. if ( (d.date >= qc.fetchData.lastDate) || ~(Object.keys(qc.fetchData).indexOf(_date)) ||
  184. (d.pending && !~Object.keys(qc.fetchData).indexOf(_date))) {
  185. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  186. timeout += 380;
  187.  
  188. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  189. scope.push(_date);
  190. }
  191. } else { // get everything
  192. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  193. timeout += 380;
  194.  
  195. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  196. }
  197. } // for
  198.  
  199. // remove out of range dates to prevent lockup when scanning after a long hiatus
  200. range.filter(v => !scope.includes(v)).forEach(v => delete qc.fetchData[v]);
  201.  
  202. // try for extra days
  203. if (qc.extraDays === true) {
  204. localStorage.removeItem("hitdb_extraDays");
  205. d = _decDate(HITStorage.data.STATS[HITStorage.data.STATS.length-1].date);
  206. qc.extraDays = d; // repurpose extraDays for QC
  207. payload = { encodedDate: d, pageNumber: 1, sortType: "All" };
  208. setTimeout(HITStorage.fetch, 1000, MTURK_BASE+"statusdetail", payload);
  209. }
  210. qc.fetchData.expectedTotal = _calcTotals(qc.fetchData);
  211. qc.fetchData.lastDate = HITStorage.data.STATS[0].date; // most recent date seen
  212. qc.save("fetchData", "hitdb_fetchData", true);
  213.  
  214. }//}}} parseStatus
  215. function parseDetail() {//{{{
  216. var _date = doc.documentURI.replace(/.+(\d{8}).+/, "$1"),
  217. _page = doc.documentURI.replace(/.+ber=(\d+).+/, "$1"),
  218. getExtras = function(entry) {
  219. return new Promise( function(y) {
  220. HITStorage.db.transaction('HIT', 'readonly').objectStore('HIT').get(entry.hitId).onsuccess = function() {
  221. if (this.result && +this.result.bonus)
  222. entry.bonus = +this.result.bonus;
  223. if (this.result && +this.result.autoAppTime)
  224. entry.autoAppTime = this.result.autoAppTime;
  225. HITStorage.data.HIT.push(entry); y(1);
  226. };
  227. });
  228. };
  229.  
  230. metrics.dbupdate.mark("[PRE]"+_date+"p"+_page, "end");
  231. Status.message = "Processing "+Utils.ISODate(_date)+" page "+_page;
  232. var raw = {
  233. req: doc.querySelectorAll(".statusdetailRequesterColumnValue"),
  234. title: doc.querySelectorAll(".statusdetailTitleColumnValue"),
  235. pay: doc.querySelectorAll(".statusdetailAmountColumnValue"),
  236. status: doc.querySelectorAll(".statusdetailStatusColumnValue"),
  237. feedback: doc.querySelectorAll(".statusdetailRequesterFeedbackColumnValue")
  238. };
  239.  
  240. for (var i=0;i<raw.req.length;i++) {
  241. var d = {};
  242. d.date = Utils.ISODate(_date);
  243. d.feedback = raw.feedback[i].textContent.trim().replace(/[\n\t]/g, ' ');
  244. d.hitId = raw.req[i].childNodes[1].href.replace(/.+HIT\+(.+)/, "$1");
  245. d.requesterId = raw.req[i].childNodes[1].href.replace(/.+rId=(.+?)&.+/, "$1");
  246. d.requesterName = raw.req[i].textContent.trim();
  247. d.reward = +raw.pay[i].textContent.substr(1);
  248. d.status = raw.status[i].textContent.replace(/\s/g, " "); // replace char160 spaces with char32 spaces
  249. d.title = raw.title[i].textContent.trim();
  250.  
  251. // mturk apparently never marks $0.00 HITs as 'Paid' so we fix that
  252. if (!d.reward && ~d.status.search(/approved/i)) d.status = "Paid";
  253. // insert autoApproval times
  254. d.autoAppTime = HITStorage.autoApprovals.getTime(_date,d.hitId);
  255.  
  256. extraInfo.push(getExtras(d));
  257.  
  258. if (!qc.seen[_date]) qc.seen[_date] = {};
  259. qc.seen[_date] = {
  260. submitted: qc.seen[_date].submitted + 1 || 1,
  261. pending: ~d.status.search(/pending/i) ?
  262. (qc.seen[_date].pending + 1 || 1) : (qc.seen[_date].pending || 0)
  263. };
  264.  
  265. ProjectedEarnings.updateValues(d);
  266. } //for
  267.  
  268. // additional pages remain; get them
  269. var morePages = doc.querySelector('img[src="/media/right_dbl_arrow.gif"]')/* || doc.querySelector('a[href*="&pageNumber='+(_page+1)+'"]')*/;
  270. if (morePages) {
  271. var payload = { encodedDate: _date, pageNumber: +_page+1, sortType: "All" };
  272. setTimeout(HITStorage.fetch, 380, MTURK_BASE+"statusdetail", payload);
  273. return;
  274. } else if (Utils.ISODate(_date) !== qc.fetchData.lastDate &&
  275. qc.seen[_date].submitted === qc.fetchData[_date].submitted && qc.seen[_date].pending === 0) {
  276. console.log("no more pending hits, removing",_date,"from fetchData");
  277. delete qc.fetchData[_date];
  278. qc.save("fetchData", "hitdb_fetchData", true);
  279. }
  280.  
  281. if (!qc.extraDays) { // not fetching extra days
  282. console.log("date:", _date, "pages:", _page, "totals:", _calcTotals(qc.seen), "of", qc.fetchData.expectedTotal);
  283. Status.message += " [ "+_calcTotals(qc.seen)+"/"+ qc.fetchData.expectedTotal+" ]";
  284. if (_calcTotals(qc.seen) === qc.fetchData.expectedTotal) {
  285. Status.message = "Writing to database...";
  286. HITStorage.autoApprovals.purge();
  287. Promise.all(extraInfo).then(function() { HITStorage.write(HITStorage.data, cbUpdate); });
  288. }
  289. } else if (_date <= qc.extraDays) { // day is older than default range and still fetching extra days
  290. parseMisc("next");
  291. console.log("fetchrequest for", _decDate(Utils.ISODate(_date)));
  292. }
  293. }//}}} parseDetail
  294. function parseMisc(type) {//{{{
  295. var _d = doc.documentURI.match(/\d{8}/)[0],
  296. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  297. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "end");
  298. var payload = { encodedDate: _decDate(Utils.ISODate(_d)), pageNumber: 1, sortType: "All" };
  299.  
  300. if (type === "next" && +qc.extraDays > 1) {
  301. setTimeout(HITStorage.fetch, 250, MTURK_BASE+"statusdetail", payload);
  302. console.log("going to next page", payload.encodedDate);
  303. } else if (type === "end" && +qc.extraDays > 1) {
  304. Status.message = "Writing to database...";
  305. Promise.all(extraInfo).then(function() { HITStorage.write(HITStorage.data, cbUpdate); });
  306. } else
  307. Utils.errorHandler(new TypeError("Failed to execute '"+type+"' in '"+doc.documentURI+"'"));
  308. }//}}}
  309. function _decDate(date) {//{{{
  310. var y = date.substr(0,4);
  311. var m = date.substr(5,2);
  312. var d = date.substr(8,2);
  313. date = new Date(y,m-1,d-1);
  314. return Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded() + date.getFullYear();
  315. }//}}}
  316. function _calcTotals(obj) {//{{{
  317. var sum = 0;
  318. for (var k in obj){
  319. if (obj.hasOwnProperty(k) && !isNaN(+k))
  320. sum += obj[k].submitted;
  321. }
  322. return sum;
  323. }//}}}
  324. },//}}} parseDOM
  325. autoApprovals: {//{{{
  326. getTime : function(date, hitId) {
  327. if (qc.extraDays || !Object.keys(qc.aat).length) return "";
  328. var found = false,
  329. autoApp = "";
  330.  
  331. if (!found && Object.keys(qc.aat).length) {
  332. for (var key in qc.aat) { if (qc.aat.hasOwnProperty(key)) { // for all dates in aat
  333. var id = Object.keys(qc.aat[key]).filter(id => id === hitId)[0];
  334. autoApp = qc.aat[key][id] || "";
  335. if (autoApp) {
  336. found = true;
  337. delete qc.aat[key][id];
  338. qc.save("aat", "hitdb_autoAppTemp", true);
  339. break;
  340. }
  341. }} // for key (dates)
  342. } // if !found && aat not empty
  343. return autoApp;
  344. },// getTime
  345. purge : function() {
  346. if (!Object.keys(qc.aat).length) return; // nothing here
  347. var pad = function(num) { return Number(num).toPadded(); },
  348. _date = Date.parse(new Date().getFullYear() + "-" + pad(new Date().getMonth()+1) + "-" + pad(new Date().getDate()));
  349.  
  350. for (var key of Object.keys(qc.aat)) {
  351. if (_date - key > 169200000) delete qc.aat[key]; // at least 2 days old, no need to keep it around
  352. }
  353. qc.save("aat", "hitdb_autoAppTemp", true);
  354. } // purge
  355. },//}}} autoApprovals
  356. fetch: function(url, payload) { //{{{
  357. //format GET request with query payload
  358. if (payload) {
  359. var args = 0;
  360. url += "?";
  361. for (var k in payload) {
  362. if (payload.hasOwnProperty(k)) {
  363. if (args++) url += "&";
  364. url += k + "=" + payload[k];
  365. }
  366. }
  367. }
  368. // defer XHR to a promise
  369. var fetch = new Promise( function(fulfill, deny) {
  370. var urlreq = new XMLHttpRequest();
  371. urlreq.open("GET", url, true);
  372. urlreq.responseType = "document";
  373. urlreq.send();
  374. urlreq.onload = function() {
  375. if (this.status === 200) {
  376. fulfill(this.response);
  377. } else {
  378. deny(new Error(this.status + " - " + this.statusText));
  379. }
  380. };
  381. urlreq.onerror = function() { deny(new Error(this.status + " - " + this.statusText)); };
  382. urlreq.ontimeout = function() { deny(new Error(this.status + " - " + this.statusText)); };
  383. } );
  384. fetch.then( HITStorage.parseDOM, Utils.errorHandler );
  385.  
  386. }, //}}} fetch
  387. write: function(input, callback) { //{{{
  388. var counts = { requests: 0, total: 0 },
  389. os = Object.keys(input),
  390. dbo = [],
  391. dbt = HITStorage.db.transaction(os, "readwrite");
  392. for (var i=0;i<os.length;i++) { // cycle object stores
  393. dbo[i] = dbt.objectStore(os[i]);
  394. for (var k of input[os[i]]) { // cycle entries to put into object stores
  395. if (typeof k.reward === 'object') { k.bonus = k.reward.bonus; k.reward = k.reward.pay; }
  396. if (typeof callback === 'function' && ++counts.requests)
  397. dbo[i].put(k).onsuccess = callback.bind(counts);
  398. else
  399. dbo[i].put(k);
  400. }
  401. }
  402. }, //}}} write
  403. recall: function(store, options) {//{{{
  404. var _cb = function(cursor) {
  405. try { Status.message = `Retrieving data... [ ${matches} / ${++total} ]`; } catch(e) {}
  406. if (filter(cursor.value)) {
  407. sr.include(cursor.value);
  408. try { Status.message = `Retrieving data... [ ${++matches} / ${total} ]`; } catch(e) {}
  409. }
  410. cursor.continue();
  411. },
  412. o = Object.assign({
  413. index: null, range: null, dir: 'next', limit: Infinity, progress: false, mode: 'readonly', callback: _cb,
  414. status: null, query: null, date: null, reward: null, bonus: null, requesterId: null, requesterName: null
  415. }, options || {});
  416. if (o.status === '*') o.status = null; //if (o.query === '*') o.query = null;
  417. if (o.progress) Progress.show();
  418.  
  419. var sr = new DBResult(), matches = 0, total = 0,
  420. filter = function(obj) {//{{{
  421. var fields = ['status', 'query', 'reward', 'bonus', 'requesterId', 'requesterName'], matches = {};
  422. // out of date range
  423. if (o.date && (obj.date < (o.date[0]) || obj.date > (o.date[1]))) return false;
  424.  
  425. for (var f of fields) {
  426. matches[f] = false;
  427. if (!o[f]) {
  428. matches[f] = true;
  429. } else if (f === 'query') { // general search - title, rname, hitid
  430. if ((obj.title + obj.requesterName + obj.hitId).toLowerCase().includes(o[f])) matches[f] = true;
  431. } else if (!isNaN(obj[f])) {// number
  432. if (+obj[f] >= o[f][0] && +obj[f] <= o[f][1]) matches[f] = true;
  433. } else { // text
  434. if (obj[f].toLowerCase().includes(o[f].toLowerCase())) matches[f] = true;
  435. }
  436. }
  437. return fields.reduce((a,b) => a && matches[b], true);
  438. };//}}}
  439.  
  440. return new Promise( function(resolve) {
  441. var dbo = HITStorage.db.transaction(store, o.mode).objectStore(store), dbq = null;
  442. if (o.index)
  443. dbq = dbo.index(o.index).openCursor(o.range, o.dir);
  444. else
  445. dbq = dbo.openCursor(o.range, o.dir);
  446. dbq.onsuccess = function() {
  447. if (this. result && matches < o.limit)
  448. o.callback(this.result);
  449. else {
  450. try { Status.message = "Done."; } catch(e) {}
  451. resolve(sr);
  452. }
  453. }; // IDBCursor
  454. }); // promise
  455. },//}}} HITStorage::recall
  456. backup: function(internal) {//{{{
  457. var bData = {},
  458. os = ["STATS", "NOTES", "HIT"],
  459. count = 0;
  460.  
  461. Progress.show();
  462. Status.push("Preparing backup...", "black");
  463.  
  464. for (var store of os)
  465. HITStorage.db.transaction(os, "readonly").objectStore(store).openCursor().onsuccess = populateBackup;
  466.  
  467. function populateBackup(e) {
  468. var cursor = e.target.result;
  469. if (cursor) {
  470. if (!bData[cursor.source.name]) bData[cursor.source.name] = [];
  471. bData[cursor.source.name].push(cursor.value);
  472. cursor.continue();
  473. } else
  474. if (++count === 3)
  475. finalizeBackup();
  476. }
  477. function finalizeBackup() {
  478. if (typeof internal === 'function') { qc.merge = bData; internal(true); return; }
  479. var backupblob = new Blob([JSON.stringify(bData)], {type:"application/json"});
  480. var date = new Date();
  481. var dl = document.createElement("A");
  482. date = date.getFullYear() + Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded();
  483. dl.href = URL.createObjectURL(backupblob);
  484. console.log(dl.href);
  485. dl.download = "hitdb_"+date+".bak";
  486. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  487. dl.click(); // so we make it so and click,
  488. dl.remove(); // then immediately remove it
  489. Progress.hide();
  490. Status.push("Done!", "green");
  491. }
  492.  
  493. }//}}} backup
  494. }, //}}} HITStorage
  495.  
  496. Utils = { //{{{
  497. disableButtons: function(arr, status) { //{{{
  498. for (var b of arr) document.getElementById(b).disabled = status;
  499. }, //}}}
  500. ftime : function(t) {//{{{
  501. if (String(t).length && +t === 0) return "0s";
  502. if (!t) return "n/a";
  503. var d = Math.floor(t/86400),
  504. h = Math.floor(t%86400/3600),
  505. m = Math.floor(t%86400%3600/60),
  506. s = t%86400%3600%60;
  507. return ((d>0) ? d+" day"+(d>1 ? "s " : " ") : "") + ((h>0) ? h+"h " : "") + ((m>0) ? m+"m " : "") + ((s>0) ? s+"s" : "");
  508. },//}}}ftime
  509. ISODate: function(date) { //{{{ MMDDYYYY <-> YYYY-MM-DD
  510. if (date.length === 10)
  511. return date.substr(5,2)+date.substr(-2)+date.substr(0,4);
  512. else
  513. return date.substr(4)+"-"+date.substr(0,2)+"-"+date.substr(2,2);
  514. },//}}} ISODate
  515. getPosition: function(element, includeHeight) {//{{{
  516. var offsets = { x: 0, y: includeHeight ? element.offsetHeight : 0 };
  517. do {
  518. offsets.x += element.offsetLeft;
  519. offsets.y += element.offsetTop;
  520. element = element.offsetParent;
  521. } while (element);
  522. return offsets;
  523. },//}}} getPosition
  524. errorHandler: function(err) {//{{{
  525. try { Status.push(err.name + ": " + err.message, "red"); }
  526. catch(e) {}
  527. finally {
  528. console.error(err);
  529. if (err.message.includes('AccessViolation'))
  530. console.warn('HITdb needs to run an internal update.\nPlease close all tabs running HITdb to complete the process. ' +
  531. 'This includes all other MTurk pages and all tabs running HIT Scraper.');
  532. }
  533. }//}}}
  534. }, //}}} Utils
  535.  
  536. ProjectedEarnings = {//{{{
  537. data: JSON.parse(localStorage.getItem("hitdb_projectedEarnings") || "{}"),
  538. updateDate: function() {//{{{
  539. var tableList = document.querySelectorAll(".metrics-table"), el, date;
  540. try {
  541. el = tableList[5].rows[1].cells[0].children[0];
  542. date = el.href.match(/\d{8}/)[0];
  543. } catch(e1) {
  544. try {
  545. el = tableList[3].rows[1].cells[0].children[0];
  546. date = el.href.match(/\d{8}/)[0];
  547. } catch(e2) {
  548. for (var tbl of tableList) {
  549. if (tbl.rows.length < 2 || tbl.rows[1].cells.length < 6) continue;
  550. el = tbl.rows[1].cells[0].children[0];
  551. date = el.href.match(/\d{8}/)[0];
  552. } //for
  553. }//catch
  554. }//catch
  555. var day = el ? el.textContent : null,
  556. isToday = day === "Today",
  557. _date = new Date(),
  558. weekEnd = null,
  559. weekStart = null;
  560.  
  561. _date.setDate(_date.getDate() - _date.getDay()); // sunday
  562. weekStart = Date.parse(_date.toLocalISOString().slice(0,10));
  563. _date.setDate(_date.getDate() + 7); // next sunday
  564. weekEnd = Date.parse(_date.toLocalISOString().slice(0,10));
  565.  
  566. if (!Object.keys(this.data).length) {
  567. this.data = {
  568. today: date, weekStart: weekStart, weekEnd: weekEnd, day: new Date().getDay(), dbUpdated: "n/a",
  569. pending: 0, approved: 0, earnings: {}, target: { day: 0, week: 0 }
  570. };
  571. }
  572.  
  573. if ( (Date.parse(Utils.ISODate(date)) >= this.data.weekEnd) ||
  574. (!isToday && new Date().getDay() < this.data.day) ) { // new week
  575. this.data.earnings = {};
  576. this.data.weekEnd = weekEnd;
  577. this.data.weekStart = weekStart;
  578. }
  579. if ( (this.data.today === null && isToday) || (this.data.today !== null && (date !== this.data.today || !isToday)) ) { // new day
  580. this.data.today = date === this.data.today ? null : date;
  581. this.data.day = new Date().getDay();
  582. }
  583.  
  584. this.saveState();
  585. },//}}} updateDate
  586. draw: function(init) {//{{{
  587. var parentTable = document.querySelector("#total_earnings_amount").offsetParent,
  588. rowPending = init ? parentTable.insertRow(-1) : parentTable.rows[4],
  589. rowProjectedDay = init ? parentTable.insertRow(-1) : parentTable.rows[5],
  590. rowProjectedWeek = init ? parentTable.insertRow(-1) : parentTable.rows[6],
  591. title = "Click to set/change the target value",
  592. weekTotal = this.getWeekTotal(),
  593. dayTotal = this.data.earnings[this.data.today] || 0;
  594.  
  595. if (init) {
  596. rowPending.insertCell(-1);rowPending.insertCell(-1);rowPending.className = "even";
  597. rowProjectedDay.insertCell(-1);rowProjectedDay.insertCell(-1);rowProjectedDay.className = "odd";
  598. rowProjectedWeek.insertCell(-1);rowProjectedWeek.insertCell(-1);rowProjectedWeek.className = "even";
  599. for (var i=0;i<rowPending.cells.length;i++) rowPending.cells[i].style.borderTop = "dotted 1px black";
  600. rowPending.cells[0].className = "metrics-table-first-value";
  601. rowProjectedDay.cells[0].className = "metrics-table-first-value";
  602. rowProjectedWeek.cells[0].className = "metrics-table-first-value";
  603. }
  604.  
  605. rowPending.cells[1].title = "This value includes all earnings that are not yet fully cleared as 'Paid'\n" +
  606. "\n Pending Approval: $" + (this.data.pending - (this.data.approved || 0)).toFixed(2) +
  607. "\n Pending Payment: $" + (this.data.approved || 0).toFixed(2) +
  608. "\n Total Pending: $" + this.data.pending.toFixed(2);
  609. rowPending.cells[0].innerHTML = 'Pending earnings '+
  610. '<span style="font-family:arial;font-size:10px;" title="Timestamp of last database update">[ ' + this.data.dbUpdated + ' ]</span>';
  611. rowPending.cells[1].textContent = "$" + this.data.pending.toFixed(2);
  612. rowProjectedDay.cells[0].innerHTML = 'Projected earnings for the day<br>'+
  613. '<meter id="projectedDayProgress" style="width:220px;" title="'+title+
  614. '" value="'+dayTotal+'" max="'+this.data.target.day+'"></meter>'+
  615. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + (dayTotal-this.data.target.day).toFixed(2) + '</span>';
  616. rowProjectedDay.cells[1].textContent = "$"+ dayTotal.toFixed(2);
  617. rowProjectedWeek.cells[0].innerHTML = 'Projected earnings for the week<br>' +
  618. '<meter id="projectedWeekProgress" style="width:220px;" title="'+title+
  619. '" value="'+weekTotal+'" max="'+this.data.target.week+'"></meter>' +
  620. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + (weekTotal-this.data.target.week).toFixed(2) + '</span>';
  621. rowProjectedWeek.cells[1].textContent = "$" + weekTotal.toFixed(2);
  622. document.querySelector("#projectedDayProgress").onclick = updateTargets.bind(this, "day");
  623. document.querySelector("#projectedWeekProgress").onclick = updateTargets.bind(this, "week");
  624.  
  625. function updateTargets(span, e) {
  626. /*jshint validthis:true*/
  627. var goal = prompt("Set your " + (span === "day" ? "daily" : "weekly") + " target:",
  628. this.data.target[span === "day" ? "day" : "week"]);
  629. if (goal && !isNaN(goal)) {
  630. this.data.target[span === "day" ? "day" : "week"] = goal;
  631. e.target.max = goal;
  632. e.target.nextSibling.textContent = " " + ((span === "day" ? dayTotal : weekTotal) - goal).toFixed(2);
  633. this.saveState();
  634. }
  635. }
  636. },//}}} draw
  637. getWeekTotal: function() {//{{{
  638. var totals = 0;
  639. for (var k of Object.keys(this.data.earnings))
  640. totals += this.data.earnings[k];
  641.  
  642. return Math.decRound(totals, 2);
  643. },//}}}
  644. saveState: function() {//{{{
  645. saveState("hitdb_projectedEarnings", JSON.stringify(this.data));
  646. },//}}}
  647. clear: function() {//{{{
  648. this.data.pending = 0;
  649. this.data.approved = 0;
  650. for (var day of Object.keys(this.data.earnings))
  651. if (day in qc.fetchData || day === this.data.today) this.data.earnings[day] = 0;
  652. },//}}}
  653. updateValues: function(obj) {//{{{
  654. var vDate = Date.parse(obj.date), iDate = Utils.ISODate(obj.date);
  655.  
  656. if (~obj.status.search(/pending/i)) // sum pending earnings (include approved until fully cleared as paid)
  657. this.data.pending = Math.decRound(obj.reward+this.data.pending, 2);
  658. if (~obj.status.search(/approved/i))
  659. this.data.approved = Math.decRound(obj.reward+this.data.approved, 2);
  660. if (vDate < this.data.weekEnd && vDate >= this.data.weekStart && !~obj.status.search(/rejected/i)){ // sum weekly earnings by day
  661. this.data.earnings[iDate] = Math.decRound(obj.reward+(this.data.earnings[iDate] || 0), 2 );
  662. }
  663. }//}}}
  664. },//}}} ProjectedEarnings
  665.  
  666. DBResult = function(resArr, colObj) {//{{{
  667. this.results = resArr || [];
  668. this.collation = colObj || null;
  669. this.formatHTML = function(type, simple) {//{{{
  670. simple = simple || false;
  671. var count = 0, htmlTxt = [], entry = null, _trClass = null;
  672.  
  673. if (this.results.length < 1) return "<h2>No entries found matching your query.</h2>";
  674.  
  675. if (type === "daily") {
  676. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th></th>'+
  677. '<th>Date</th><th>Submitted</th><th>Approved</th><th>Rejected</th><th>Pending</th><th>Earnings</th></tr></thead><tbody>');
  678. var r = this.collate(this.results,"stats");
  679. for (entry of this.results) {
  680. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  681. htmlTxt.push('<tr '+_trClass+' style="text-align:right">' +
  682. '<td><span class="hdbExpandRow">[+]</span></td>'+
  683. '<td style="text-align:center;">' + entry.date + '</td><td>' + entry.submitted + '</td>' +
  684. '<td>' + entry.approved + '</td><td>' + entry.rejected + '</td><td>' + entry.pending + '</td>' +
  685. '<td>' + Number(entry.earnings).toFixed(2) + '</td></tr>');
  686. }
  687. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow" style="text-align:right;"><td>Totals:</td>' +
  688. '<td>' + r.totalEntries + ' days</td><td>' + r.totalSub + '</td>' +
  689. '<td>' + r.totalApp + '</td><td>' + r.totalRej + '</td>' +
  690. '<td>' + r.totalPen + '</td><td>$' +
  691. Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  692. } else if (type === "pending" || type === "requester") {
  693. htmlTxt.push('<thead><tr data-sort="99999" class="hdbHeaderRow"><th width="160">Requester ID</th>' +
  694. '<th>Requester</th><th>' + (type === "pending" ? 'Pending' : 'HITs') + '</th><th>Rewards</th></tr></thead><tbody>');
  695. r = this.collate(this.results,"requesterId");
  696. for (var k in r) {
  697. if (!~k.search(/total/) && r.hasOwnProperty(k)) {
  698. var tr = ['<tr data-sort="'+Math.decRound(r[k].pay,2)+'"><td>' +
  699. '<span class="hdbExpandRow" title="Display all pending HITs from this requester">' +
  700. '[+]</span> ' + r[k][0].requesterId + '</td><td>' + r[k][0].requesterName + '</td>' +
  701. '<td style="text-align:center;">' + r[k].length + '</td><td>' + Number(Math.decRound(r[k].pay,2)).toFixed(2) + '</td></tr>'];
  702.  
  703. for (var hit of r[k]) { // hits in range per requester id
  704. tr.push('<tr data-rid="'+r[k][0].requesterId+'" style="color:#c60000;display:none;"><td style="text-align:right">' +
  705. hit.date + '</td><td width="500" colspan="2" class="nowrap" style="max-width:520" title="'+hit.title+'">' +
  706. '[ <span class="helpSpan" title="Auto-approval time">AA: '+Utils.ftime(hit.autoAppTime).trim()+'</span> ] '+
  707. hit.title + '</td><td style="text-align:right">' + hit.reward.toFixed(2) + '</td></tr>');
  708. }
  709. htmlTxt.push(tr.join(''));
  710. }
  711. }
  712. htmlTxt.sort(function(a,b) { return +b.substr(15,5).match(/\d+\.?\d*/) - +a.substr(15,5).match(/\d+\.?\d*/); });
  713. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td style="text-align:right;">Totals:</td>' +
  714. '<td style="text-align:center;">' + (Object.keys(this.collation || r).length-7) + ' Requesters</td>' +
  715. '<td style="text-align:right;">' + (this.collation || r).totalEntries + '</td>'+
  716. '<td style="text-align:right;">$' + Number(Math.decRound((this.collation || r).totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  717. } else { // default
  718. if (!simple)
  719. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th colspan="3"></th>' +
  720. '<th colspan="2" title="Bonuses must be added in manually.\n\nClick inside' +
  721. 'the cell to edit, click out of the cell to save">Reward</th><th colspan="3"></th></tr>'+
  722. '<tr class="hdbHeaderRow">' +
  723. '<th style="min-width:65">Date</th><th>Requester</th><th>HIT title</th><th style="font-size:10px;">Pay</th>'+
  724. '<th style="font-size:10px;"><span class="helpSpan" title="Click the cell to edit.\nIts value is automatically saved">'+
  725. 'Bonus</span></th><th>Status</th><th>'+
  726. '<span class="helpSpan" title="Auto-approval times">AA</span></th><th>Feedback</th></tr></thead><tbody>');
  727.  
  728. this.results.sort(function(a,b) { return a.date === b.date ?
  729. (a.requesterName.toLowerCase() > b.requesterName.toLowerCase() ? 1 : -1) : a.date < b.date ? -1 : 1; });
  730. for (entry of this.results) {
  731. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  732. var _stColor = ~entry.status.search(/(paid|approved)/i) ? "green" :
  733. entry.status === "Pending Approval" ? "orange" : "red";
  734. var href = MTURK_BASE+'contact?requesterId='+entry.requesterId+'&requesterName='+entry.requesterName+
  735. '&subject=Regarding+Amazon+Mechanical+Turk+HIT+'+entry.hitId;
  736.  
  737. if (!simple)
  738. htmlTxt.push('<tr '+_trClass+' data-id="'+entry.hitId+'">'+
  739. '<td width="74px">' + entry.date + '</td><td style="max-width:145px;">' +
  740. '<a target="_blank" title="Contact this requester" href="'+href+'">' + entry.requesterName + '</a></td>' +
  741. '<td width="375px" title="HIT ID: '+entry.hitId+'">' +
  742. '<span title="Add a note" id="note-'+entry.hitId+'" style="cursor:pointer;">&nbsp;&#128221;&nbsp;</span>' +
  743. entry.title + '</td><td style="text-align:right">' + entry.reward.toFixed(2) + '</td>' +
  744. '<td style="text-align:right" class="bonusCell" title="Click to add/edit" contenteditable="true" data-hitid="'+entry.hitId+'">' +
  745. (entry.bonus ? entry.bonus.toFixed(2) : "") +
  746. '</td><td style="color:'+_stColor+';text-align:center">' + entry.status + '</td>' +
  747. '<td>' + Utils.ftime(entry.autoAppTime) + '</td><td>' + entry.feedback + '</td></tr>');
  748. else
  749. htmlTxt.push('<tr>' + '<td class="nowrap" title="'+entry.requesterName+'" style="max-width:130">'+entry.requesterName+'</td>' +
  750. '<td class="nowrap" title="'+entry.title+'" style="max-width:520">'+entry.title+'</td><td>'+ entry.reward.toFixed(2) +
  751. '</td><td class="nowrap" title="'+entry.status+'" style="max-width:60">'+ entry.status+'</td></tr>');
  752. }
  753.  
  754. if (!simple) {
  755. r = this.collation || this.collate(this.results,"requesterId");
  756. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td></td>' +
  757. '<td style="text-align:right">Totals:</td><td style="text-align:center;">' + r.totalEntries + ' HITs</td>' +
  758. '<td style="text-align:right">$' + Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td>' +
  759. '<td style="text-align:right">$' + Number(Math.decRound(r.totalBonus,2)).toFixed(2) + '</td>' +
  760. '<td colspan="3"></td></tr></tfoot>');
  761. }
  762. }
  763. return htmlTxt.join('');
  764. };//}}} formatHTML
  765. this.formatCSV = function(type) {//{{{
  766. var csvTxt = [], entry = null, delimiter="\t";
  767. if (type === "daily") {
  768. csvTxt.push( ["Date", "Submitted", "Approved", "Rejected", "Pending", "Earnings\n"].join(delimiter) );
  769. for (entry of this.results) {
  770. csvTxt.push( [entry.date, entry.submitted, entry.approved, entry.rejected,
  771. entry.pending, Number(entry.earnings).toFixed(2)+"\n"].join(delimiter) );
  772. }
  773. csvToFile(csvTxt, "hitdb_dailyOverview.csv");
  774. } else if (type === "pending" || type === "requester") {
  775. csvTxt.push( ["RequesterId","Requester", (type === "pending" ? "Pending" : "HITs"), "Rewards\n"].join(delimiter) );
  776. var r = this.collation || this.collate(this.results,"requesterId");
  777. for (var k in r) {
  778. if (!~k.search(/total/) && r.hasOwnProperty(k))
  779. csvTxt.push( [k, r[k][0].requesterName, r[k].length, Number(Math.decRound(r[k].pay,2)).toFixed(2)+"\n"].join(delimiter) );
  780. }
  781. csvToFile(csvTxt, "hitdb_"+type+"Overview.csv");
  782. } else {
  783. csvTxt.push(["hitId","date","requesterName","requesterId","title","pay","bonus","status","autoAppTime","feedback\n"].join(delimiter));
  784. for (entry of this.results) {
  785. csvTxt.push([entry.hitId, entry.date, entry.requesterName, entry.requesterId, entry.title, entry.reward.toFixed(2),
  786. (entry.bonus ? entry.bonus.toFixed(2) : ''), entry.status, entry.autoAppTime,
  787. entry.feedback.replace(/[\t\n]/g,' ')+"\n"].join(delimiter));
  788. }
  789. csvToFile(csvTxt, "hitdb_queryResults.csv");
  790. }
  791.  
  792. return '';//"<pre>"+csvTxt.join('')+"</pre>";
  793.  
  794. function csvToFile(csv, filename) {
  795. var blob = new Blob(csv, {type: "text/csv", endings: "native"}),
  796. dl = document.createElement("A");
  797. dl.href = URL.createObjectURL(blob);
  798. dl.download = filename;
  799. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  800. dl.click(); // so we make it so and click,
  801. dl.remove(); // then immediately remove it
  802. return dl;
  803. }
  804. };//}}} formatCSV
  805. this.include = function(value) {
  806. this.results.push(value);
  807. };
  808. this.collate = function(data, index) {//{{{
  809. var r = {
  810. totalPay: 0, totalBonus: 0, totalEntries: data.length,
  811. totalSub: 0, totalApp: 0, totalRej: 0, totalPen: 0
  812. };
  813. for (var e of data) {
  814. if (!r[e[index]]) {
  815. r[e[index]] = [];
  816. Object.defineProperty(r[e[index]], "pay", {value: 0, enumerable: false, configurable: true, writable: true});
  817. }
  818. r[e[index]].push(e);
  819.  
  820. if (index === "stats") {
  821. r.totalSub += e.submitted;
  822. r.totalApp += e.approved;
  823. r.totalRej += e.rejected;
  824. r.totalPen += e.pending;
  825. r.totalPay += e.earnings;
  826. } else {
  827. r[e[index]].pay += (+e.reward);
  828. r.totalPay += (+e.reward);
  829. r.totalBonus += (+e.bonus);
  830. }
  831. }
  832. return r;
  833. };//}}} _collate
  834.  
  835. },//}}} databaseresult
  836.  
  837. DashboardUI = {//{{{
  838. draw: function() {//{{{
  839. var controlPanel = document.createElement("TABLE"),
  840. insertionNode = document.querySelector(".footer_separator").previousSibling;
  841. document.body.insertBefore(controlPanel, insertionNode);
  842. controlPanel.width = "760";
  843. controlPanel.align = "center";
  844. controlPanel.id = "hdbControlPanel";
  845. controlPanel.cellSpacing = "0";
  846. controlPanel.cellPadding = "0";
  847. controlPanel.innerHTML = '<tr height="25px"><td width="10" bgcolor="#7FB448" style="padding-left: 10px;"></td>' +
  848. '<td class="white_text_14_bold" style="padding-left:10px; background-color:#7FB448;">' +
  849. 'HIT Database Mk. II&nbsp;<a href="https://greasyfork.org/en/scripts/11733-mturk-hit-database-mk-ii#userGuide" '+
  850. 'class="whatis" target="turkPopUp" onclick="customPopup(this, 500, 400)">' +
  851. '(What\'s this?)</a></td></tr>' +
  852. '<tr><td class="container-content" colspan="2">' +
  853. '<div style="text-align:center; position:relative" id="hdbDashboardInterface">' +
  854. '<button id="hdbBackup" title="Export your entire database!\nPerfect for moving between computers or as a periodic backup">Create Backup</button>' +
  855. '<button id="hdbRestore" title="Import data from an external file" style="margin:5px">Import</button>' +
  856. '<button id="hdbUpdate" title="Update... the database" style="color:green;">Update Database</button>' +
  857. '<input id="hdbFileInput" type="file" style="display:none"/>' +
  858. '<br>'+
  859. '<div style="position:absolute; top:0; right:0; text-align:initial">' +
  860. //'<label title="Popout search results in a new window" style="vertical-align:middle;">popout' +
  861. //'<input id="hdbPopout" type="checkbox" style="vertical-align:middle"></label>' +
  862. '<label for="hdbCSVInput" title="Export results as CSV file" style="vertical-align:middle;">export CSV</label>' +
  863. '<input id="hdbCSVInput" title="Export results as CSV file" type="checkbox" style="vertical-align:middle;">' +
  864. '</div>' +
  865. '<button id="hdbPending" title="Summary of all pending HITs\n Can be exported as CSV" style="margin: 0px 5px 5px;">Pending Overview</button>' +
  866. '<button id="hdbRequester" title="Summary of all requesters\n Can be exported as CSV" style="margin: 0px 5px 5px;">Requester Overview</button>' +
  867. '<button id="hdbDaily" title="Summary of each day you\'ve worked\nCan be exported as CSV" style="margin:0px 5px 5px;">Daily Overview</button>' +
  868. '<br>' +
  869. '<label>Find </label>' +
  870. '<select id="hdbStatusSelect" style="width:100px"><option value="*">ALL</option>' +
  871. '<option value="Pending Approval" style="color: orange;">Pending Approval</option>' +
  872. '<option value="Rejected" style="color: red;">Rejected</option>' +
  873. '<option value="Approved - Pending Payment" style="color:green;">Approved - Pending Payment</option>' +
  874. '<option value="Paid" style="color:green;">Paid</option></select>' +
  875. '<label> HITs from </label><input id="hdbMinDate" type="date" size="10" title="Specify a date, or leave blank">' +
  876. '<label> to </label><input id="hdbMaxDate" type="date" size="10" title="Specify a date, or leave blank">' +
  877. '<label> matching </label>'+
  878. '<br>' +
  879. '<input id="hdbSearchInput" style="width:400px" title="Query can be HIT title, HIT ID, or requester name" />' +
  880. '<button id="hdbSearch" style="margin-left:5px">Search</button>' +
  881. '<br>' +
  882. '<label id="hdbStatusText"></label>' +
  883. '<div id="hdbProgressBar">' +
  884. '<div id="hdbB1" class="ball"></div><div id="hdbB2" class="ball"></div>' +
  885. '<div id="hdbB3" class="ball"></div><div id="hdbB4" class="ball"></div>' +
  886. '</div>' +
  887. '</div></td></tr>';
  888.  
  889. var searchResults = document.createElement("DIV");
  890. searchResults.align = "center";
  891. searchResults.id = "hdbSearchResults";
  892. searchResults.style.display = "block";
  893. searchResults.innerHTML =
  894. '<span class="hdbResControl" id="hdbResClear">[ clear results ]</span>' +
  895. '<span class="hdbTablePagination" id="hdbPageTop"></span><br>' +
  896. '<table cellSpacing="0" cellpadding="2" width="760" id="hdbResultsTable"></table>' +
  897. '<span class="hdbResControl" id="hdbVpTop">Back to top</span>' +
  898. '<span class="hdbTablePagination" id="hdbPageBot"></span><br>';
  899. document.body.insertBefore(searchResults, insertionNode);
  900. },//}}} dashboardUI::draw
  901. initClickables: function() {//{{{
  902. var updateBtn = document.getElementById("hdbUpdate"),
  903. backupBtn = document.getElementById("hdbBackup"),
  904. restoreBtn = document.getElementById("hdbRestore"),
  905. fileInput = document.getElementById("hdbFileInput"),
  906. exportCSVInput = document.getElementById("hdbCSVInput"),
  907. searchBtn = document.getElementById("hdbSearch"),
  908. searchInput = document.getElementById("hdbSearchInput"),
  909. pendingBtn = document.getElementById("hdbPending"),
  910. reqBtn = document.getElementById("hdbRequester"),
  911. dailyBtn = document.getElementById("hdbDaily"),
  912. fromdate = document.getElementById("hdbMinDate"),
  913. todate = document.getElementById("hdbMaxDate"),
  914. statusSelect = document.getElementById("hdbStatusSelect"),
  915. searchResults = document.getElementById("hdbSearchResults"),
  916. resultsTable = document.getElementById("hdbResultsTable"),
  917. isGecko = /Gecko\/\d+/.test(navigator.userAgent);
  918.  
  919. searchResults.firstChild.onclick = function() { //{{{ clear results
  920. resultsTable.innerHTML = null; qc.sr = [];
  921. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  922. if (~d.search(/page/i)) searchResults.querySelector('#'+d).innerHTML = "";
  923. document.getElementById(d).style.display = "none";
  924. }
  925. };//}}}
  926. document.getElementById("hdbVpTop").onclick = function() { autoScroll("#hdbControlPanel"); };
  927.  
  928. updateBtn.onclick = function() { //{{{
  929. if (!HITStorage.db) { return Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); }
  930. Utils.disableButtons(['hdbUpdate'], true);
  931. Progress.show();
  932. metrics.dbupdate = new Metrics("database_update");
  933. HITStorage.fetch(MTURK_BASE+"status");
  934. Status.message = "fetching status page....";
  935. };//}}}
  936. exportCSVInput.addEventListener("click", function() {//{{{
  937. var a = document.getElementById('hdbAnalytics');
  938. if (a && a.checked) a.click();
  939. if (exportCSVInput.checked) {
  940. searchBtn.textContent = "Export CSV";
  941. pendingBtn.textContent += " (csv)";
  942. reqBtn.textContent += " (csv)";
  943. dailyBtn.textContent += " (csv)";
  944. }
  945. else {
  946. searchBtn.textContent = "Search";
  947. pendingBtn.textContent = pendingBtn.textContent.replace(" (csv)","");
  948. reqBtn.textContent = reqBtn.textContent.replace(" (csv)","");
  949. dailyBtn.textContent = dailyBtn.textContent.replace(" (csv)", "");
  950. }
  951. });//}}}
  952. if (isGecko) {//{{{
  953. fromdate.addEventListener("focus", function() {
  954. var offsets = Utils.getPosition(this, true);
  955. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  956. });
  957. todate.addEventListener("focus", function() {
  958. var offsets = Utils.getPosition(this, true);
  959. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  960. });
  961. }//}}}
  962.  
  963. backupBtn.onclick = HITStorage.backup;
  964. restoreBtn.onclick = function() { fileInput.value = ''; fileInput.click(); };
  965. fileInput.onchange = FileHandler.delegate;//processFile;
  966. searchInput.onkeydown = function(e) { if (e.keyCode === 13) searchBtn.click(); };
  967.  
  968. searchBtn.addEventListener('click', function(e) {//{{{
  969. if (!/^[se]/i.test(e.target.textContent)) return;
  970. var opt = this.getRange(statusSelect.value, _getFilters(searchInput.value.trim()));
  971. opt.progress = true;
  972. if (opt.query && opt.query.length === 30 && !/\s/.test(opt.query)) {
  973. opt.range = window.IDBKeyRange.only(opt.query.toUpperCase());
  974. opt.index = null;
  975. }
  976. _dbaccess("search", ["HIT", opt], function(r) {
  977. var limiter = 500,
  978. _cb = function(slice) {
  979. for (var _r of slice)
  980. HITStorage.recall("NOTES", { index: "hitId", range: window.IDBKeyRange.only(_r.hitId) }).then(noteHandler.bind(null,"attach"));
  981. var _nodes = [document.querySelectorAll(".bonusCell"), document.querySelectorAll('span[id^="note-"]')];
  982. for (var i=0;i<_nodes[0].length;i++) {
  983. var bonus = _nodes[0][i],
  984. note = _nodes[1][i];
  985. bonus.dataset.initial = bonus.textContent;
  986. bonus.onkeydown = updateBonus;
  987. bonus.onblur = updateBonus;
  988. note.onclick = noteHandler.bind(null,"new");
  989. }
  990. };
  991. if (exportCSVInput.checked)
  992. resultsTable.innerHTML = r.formatCSV();
  993. else if (r.results.length > limiter) {
  994. var collation = r.collate(r.results, "requesterId");
  995. do { qc.sr.push(new DBResult(r.results.splice(0,limiter), collation)) } while (r.results.length);
  996. resultConstrain(qc.sr, 0, "default", _cb);
  997. } else
  998. resultConstrain(r, 0, "default", _cb);
  999. });
  1000. }.bind(this)); //}}} search button click event
  1001. //{{{ overview buttons
  1002. pendingBtn.onclick = function() {
  1003. var opt = this.getRange('pending', _getFilters(searchInput.value.trim())),
  1004. _opt = { index:'status', dir:'prev', range:window.IDBKeyRange.only('Pending Approval'), progress:true };
  1005.  
  1006. opt = Object.assign(opt, _opt);
  1007. _dbaccess("pending", ["HIT", opt], function(r) {
  1008. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("pending") : r.formatHTML("pending");
  1009. var expands = document.querySelectorAll(".hdbExpandRow");
  1010. for (var el of expands)
  1011. el.onclick = showHiddenRows;
  1012. });
  1013. }.bind(this); //pending overview click event
  1014. reqBtn.onclick = function() {
  1015. var opt = this.getRange(statusSelect.value, _getFilters(searchInput.value.trim()));
  1016. opt.progress = true;
  1017.  
  1018. _dbaccess("requester", ["HIT", opt], function(r) {
  1019. var limiter = 100,
  1020. _cb = function() {
  1021. var expands = document.querySelectorAll(".hdbExpandRow");
  1022. for (var el of expands)
  1023. el.onclick = showHiddenRows;
  1024. };
  1025. if (exportCSVInput.checked)
  1026. resultsTable.innerHTML = r.formatCSV("requester");
  1027. else if (r.results.length > limiter) {
  1028. var collation = r.collate(r.results, "requesterId"), _r = [], count = 0;
  1029. var keys = Object.keys(collation)
  1030. .filter(function(e) { return !/total/.test(e); })
  1031. .sort(function(a,b) { return collation[b].pay - collation[a].pay; });
  1032. keys.forEach(function(key){
  1033. if (++count > limiter) {
  1034. qc.sr.push(new DBResult(_r, collation));
  1035. count = 0; _r = [];
  1036. } else _r = _r.concat(collation[key]);
  1037. });
  1038. qc.sr.push(new DBResult(_r, collation));
  1039. resultConstrain(qc.sr, 0, "requester", _cb);
  1040. } else
  1041. resultConstrain(r, 0, "requester", _cb);
  1042. });
  1043. }.bind(this); //requester overview click event
  1044. dailyBtn.onclick = function() {
  1045. var opt = Object.assign(this.getRange("*"), { index:null, dir:'prev', progress:true });
  1046. _dbaccess("daily", ["STATS", opt], function(r) {
  1047. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("daily") : r.formatHTML("daily");
  1048. var expands = document.querySelectorAll(".hdbExpandRow");
  1049. for (var el of expands)
  1050. el.onclick = showHitsByDate;
  1051. });
  1052. }.bind(this); //daily overview click event
  1053. //}}}
  1054. function _getFilters(str) {//{{{
  1055. var re = /(?:[rh][equstri]*(?:id|name)|bonus|reward|pay|req|id):[^;]+/ig,
  1056. matches = str.match(re),
  1057. filters = { query: str },
  1058. _setRange = function(str) {
  1059. var rng = str.split(/[><,]/).filter(v => v).sort(); rng.forEach((v,i,a) => a[i] = +v);
  1060. if (rng.length === 1) {
  1061. if (str.startsWith('<')) {
  1062. rng[0] -= 0.01;
  1063. rng.unshift(0.01);
  1064. } else if (str.startsWith('>')) {
  1065. rng[0] += 0.01;
  1066. rng.push(Infinity);
  1067. } else rng.push(rng[0]);
  1068. }
  1069. return rng;
  1070. };
  1071.  
  1072. if (!matches) return filters;
  1073. filters.query = str.slice(0,str.indexOf(matches[0])).trim();
  1074. if (!filters.query.length) filters.query = null;
  1075. for (var m of matches) {
  1076. var _m = m.split(':');
  1077. if (/(^req$|r[eqstr]*name)/i.test(_m[0])) filters.requesterName = _m[1].trimLeft();
  1078. else if (/(^id$|hitid)/i.test(_m[0])) filters.hitId = _m[1].toUpperCase().trimLeft();
  1079. else if (/r[eqstr]*id/i.test(_m[0])) filters.requesterId = _m[1].toUpperCase().trimLeft();
  1080. else if (/(reward|pay)/i.test(_m[0])) filters.reward = _setRange(_m[1]);
  1081. else if (_m[0].toLowerCase() === 'bonus') filters.bonus = _setRange(_m[1]);
  1082. }
  1083. return filters;
  1084. }//}}}
  1085. function _dbaccess(method, rargs, tfn) {//{{{
  1086. if (!HITStorage.db) { Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); return; }
  1087. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], true);
  1088. searchResults.firstChild.click();
  1089. Status.push("Preparing database...", "black");
  1090. metrics.dbrecall = new Metrics("database_recall::"+method);
  1091. metrics.dbrecall.mark("data retrieval", "start");
  1092.  
  1093. HITStorage.recall(rargs[0],rargs[1]).then(function(r) {
  1094. metrics.dbrecall.mark("data retrieval", "end");
  1095. Status.message = "Building HTML...";
  1096. try {
  1097. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  1098. if (exportCSVInput.checked || (~d.search(/page/i) && !/^[sr]/.test(method))) continue;
  1099. document.getElementById(d).style.display = "initial";
  1100. }
  1101. metrics.dbrecall.mark("HTML construction", "start");
  1102. tfn(r);
  1103. metrics.dbrecall.mark("HTML construction", "end");
  1104. } catch(e) {
  1105. Utils.errorHandler(e);
  1106. } finally {
  1107. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], false);
  1108. autoScroll("#hdbSearchResults");
  1109. Status.push("Done!", "green");
  1110. Progress.hide();
  1111. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1112. }
  1113. });
  1114. }//}}} _dbaccess
  1115. },//}}} dashboardUI::initClickables
  1116. getRange: function(status, filters) {//{{{
  1117. var fromdate = document.getElementById("hdbMinDate"),
  1118. todate = document.getElementById("hdbMaxDate"),
  1119. statusSelect = document.getElementById("hdbStatusSelect"),
  1120. obj = Object.assign({}, filters || {}), r = window.IDBKeyRange;
  1121. obj.status = status || statusSelect.value;
  1122. obj.date = [ (fromdate.value || '0000'), (todate.value || '9999') ];
  1123. obj.index = obj.date[0] !== '0000' || obj.date[1] !== '9999' ? 'date' : 'status';
  1124. if (filters) {
  1125. var indexPriority = { hitId:100, bonus:80, date:70, status:60, requesterId:50, requesterName:40, reward:30, },
  1126. indices = Object.keys(filters);
  1127. indices.push(obj.index);
  1128. obj.index = indices.reduce((a,b) => indexPriority[a] || 0 > indexPriority[b] || 0 ? a : b);
  1129. }
  1130. obj.range = (function(i) {
  1131. if (['date','reward','pay','bonus'].includes(i))
  1132. return r.bound(obj[i][0], obj[i][1]);
  1133. else if (i === 'status' && status.length > 1)
  1134. return r.only(status);
  1135. else if (['hitId','requesterName','requesterId'].includes(i))
  1136. return r.bound(obj[i], obj[i].slice(0,-1) + String.fromCharCode(obj[i].slice(-1).charCodeAt()+1));
  1137. })(obj.index);
  1138. if (obj.index === 'hitId' || (obj.index === 'status' && status.length === 1)) obj.index = null;
  1139. return obj;
  1140. }//}}} dashboardUI::getRange
  1141. },//}}} dashboard
  1142. FileHandler = { //{{{
  1143. //
  1144. // TODO: JSON integrity check
  1145. //
  1146. delegate: function(e) {//{{{
  1147. var f = e.target.files;
  1148. if (f.length && ~f[0].name.search(/\.(bak|csv|json)$/i)/* && ~f[0].type.search(/(text|json)/)*/) {
  1149. var reader = new FileReader(), testing = true, isCsv = false;
  1150. metrics.dbimport = new Metrics("file_import");
  1151.  
  1152. reader.readAsText(f[0].slice(0,10));
  1153. reader.onload = function(e) {
  1154. var r = e.target.result;
  1155. if (testing && !~r.search(/(STATS|NOTES|HIT)/)) { // failed json check, test if csv
  1156. console.log("failed json integrity:", r, "\nchecking csv schema...");
  1157. if (!~r.search(/hitId/)) { // failed csv check, return error
  1158. console.log("failed csv integrity:", r, "\naborting");
  1159. return Utils.errorHandler(new TypeError("Invalid data structure"));
  1160. } else { // passed initial csv check, parse full file
  1161. console.log("deferring to csv parser");
  1162. isCsv = true;
  1163. testing = false;
  1164. Progress.show();
  1165. reader.readAsText(f[0]);
  1166. }
  1167. } else if (testing) {
  1168. testing = false;
  1169. Progress.show();
  1170. reader.readAsText(f[0]);
  1171. } else {
  1172. if (isCsv) this.csv.fromFile(r);
  1173. else HITStorage.write(JSON.parse(r), cbImport);
  1174. }
  1175. }.bind(FileHandler); // reader.onload
  1176. } else if (f.length)
  1177. Utils.errorHandler(new TypeError("Unsupported file format"));
  1178. },//}}}
  1179. csv: {//{{{
  1180. fromFile: function(r) {//{{{
  1181. var validKeys = ["autoAppTime","date","feedback","hitId","requesterId","requesterName","reward","pay","bonus","status","title"],
  1182. //lines = r.replace(/\r?\n^(?!"?[A-Z0-9]{30})/gm,' ').split(/\r?\n/);
  1183. lines = r.split(/\r?\n(?="?[A-Z0-9]{30})/);
  1184. this.delimiter = /^"/.test(lines[0]) ? r.substr(7,1) : r.substr(5,1);
  1185. this.header = lines.splice(0,1)[0].replace(new RegExp(`([" ]|${this.delimiter}$)`,'g'),'').split(this.delimiter);
  1186. this.data = { HIT:[] };
  1187.  
  1188. console.log('delimiter:',this.delimiter==='\t'?'tab':this.delimiter,'\nlines:',lines.length,'\nheader:',this.header);
  1189. if (!lines.length) return Utils.errorHandler(new Error("CSV file must contain at least one record"));
  1190. // make sure header keys are valid
  1191. for (var key of this.header)
  1192. if (!~validKeys.indexOf(key)) {
  1193. Progress.hide();
  1194. return Utils.errorHandler(new TypeError("Invalid key '"+key+"' found in column header"));
  1195. }
  1196. this.core(lines);
  1197. },//}}}
  1198. core: function(lr, syn) {//{{{
  1199. syn = syn || false;
  1200. var badLines = [],
  1201. deq = function(str) { if (/^"/.test(str) && /"$/.test(str)) return str.replace(/(^"|"$)/g,''); else return str;},
  1202. qfix = arr => arr.reduce((a,b) => {
  1203. if (a.length && /^".+[^"]$/.test(a[a.length-1])) {
  1204. a[a.length-1] = a[a.length-1] + this.delimiter + b;
  1205. return a;
  1206. } else return a.concat(b);
  1207. }, []);
  1208. for (var line of lr) {
  1209. var record = {};
  1210. line = line.split(this.delimiter);
  1211. if (line.length <= 1) continue;
  1212. if (line.length !== this.header.length) {
  1213. // attempt to resolve delimiter conflicts within field values
  1214. line = qfix(line);
  1215. while (line.length > this.header.length) {
  1216. var datum = line.pop();
  1217. if (/\S/.test(deq(datum))) { line.push(datum); break; }
  1218. }
  1219. if (line.length !== this.header.length) {
  1220. badLines.push({record: line, reason: "SyntaxError: Number of field do not match number of columns"}); continue; }
  1221. }
  1222. // convert into usable JSON
  1223. for (var i=0;i<line.length;i++) {
  1224. if (/(pay|bonus|reward|autoAppTime)/.test(this.header[i]) && isNaN(+line[i])) {
  1225. badLines.push({record: line, reason: `TypeError: Value in '${this.header[i]}' is not a number.`}); break; }
  1226. if (this.header[i] === 'hitId' && (/\W/.test(deq(line[i])) || deq(line[i]).length !== 30)) {
  1227. badLines.push({record: line, reason: "TypeError: Invalid hitId."}); break; }
  1228. if (this.header[i] === 'date' && !/\d{4}-\d{2}-\d{2}/.test(line[i])) {
  1229. badLines.push({record: line, reason: "TypeError: Invalid date. Dates must be in ISO format (YYYY-MM-DD)."}); break; }
  1230.  
  1231. if (this.header[i] === 'pay' || this.header[i] === 'reward')
  1232. record.reward = +line[i];
  1233. else if (this.header[i] === 'bonus')
  1234. record.bonus = +line[i];
  1235. else
  1236. record[this.header[i]] = deq(line[i]);
  1237. } // for each field
  1238. if (!syn && !badLines.find(v => v.record === line)) this.data.HIT.push(record);
  1239. } // for each record
  1240. if (syn) return !badLines.length;
  1241. else if (badLines.length) { console.warn('SyntaxError'); console.dir(badLines); this.manualFix(badLines); }
  1242. else HITStorage.write(this.data, cbImport);
  1243. },//}}}
  1244. manualFix: function(lr) {//{{{
  1245. var div = document.body.appendChild(document.createElement('DIV')),
  1246. title = div.appendChild(document.createElement('P')),
  1247. divInner = div.appendChild(document.createElement('DIV')),
  1248. buttons = div.appendChild(document.createElement('P')),
  1249. trimSansTab = function(str) {
  1250. var c = "[ \f\n\r\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+";
  1251. return str.replace(new RegExp("^"+c),'').replace(new RegExp(c+"$"),'');
  1252. },
  1253. kdFn = function(e) {
  1254. if (e.keyCode === 9) {// tab
  1255. e.preventDefault();
  1256. var zs = e.target.selectionStart,
  1257. ze = e.target.selectionEnd;
  1258. e.target.value = e.target.value.substr(0,zs) + '\t' + e.target.value.substr(ze);
  1259. }
  1260. e.target.style.height = '1px';
  1261. e.target.style.height = e.target.scrollHeight + 10 +'px';
  1262. },
  1263. blurFn = function(e) {
  1264. var check = this.core([trimSansTab(e.target.value)],true);
  1265. if (check) e.target.style.background = '#9EFF9E'; else e.target.style.background = 'white';
  1266. }.bind(this);
  1267. title.outerHTML = '<p style="margin:0;text-align:center;font-weight:bold;font-size:1.2em">Failed lines</p>' +
  1268. '<p style="text-align:center;font-weight:bold;font-size:0.9em;margin:1%">' + this.header.join(this.delimiter)+'</p>';
  1269. div.style.cssText = "z-index:5; position:fixed; top:50%;left:50%; padding:0.7%; width:650px; resize:both; overflow:auto;" +
  1270. "background:rgba(204,204,204,0.88); box-shadow: 0px 0px 15px 2px #000; margin-right:-50%; transform:translate(-50%, -50%);";
  1271. divInner.style.cssText = "position:relative; max-height:350px; overflow:auto;";
  1272. for (var v of lr) {
  1273. divInner.appendChild(document.createTextNode(v.reason));
  1274. var ta = divInner.appendChild(document.createElement('TEXTAREA'));
  1275. ta.style.cssText = "resize:none; overflow:hidden; width:100%; display:block";
  1276. ta.onkeydown = kdFn;
  1277. ta.onblur = blurFn;
  1278. ta.value = v.record.join(this.delimiter);
  1279. ta.style.height = ta.scrollHeight + 10 + 'px';
  1280. }
  1281. buttons.style.cssText = "margin:1% auto; text-align:center;";
  1282. buttons.innerHTML = '<button id="fretry" title="Retry failed lines.")">Retry</button> ' +
  1283. '<button id="fskip" title="Skip these failed lines and import the rest to the database.">Skip</button> ' +
  1284. '<button id="fcancel" title="Cancel the entire import process">Cancel</button><br>' +
  1285. 'Modify the above entries and retry, or skip them, or cancel the entire import.';
  1286. buttons.querySelector('#fretry').onclick = function() {
  1287. var l = [];
  1288. for (var el of div.querySelectorAll('textarea')) l.push(trimSansTab(el.value));
  1289. this.core(l);
  1290. div.remove();
  1291. }.bind(this);
  1292. buttons.querySelector('#fskip').onclick = function() { div.remove(); HITStorage.write(this.data, cbImport); }.bind(this);
  1293. buttons.querySelector('#fcancel').onclick = function() { div.remove(); this.data = null; Progress.hide();}.bind(this);
  1294. }//}}}
  1295. }//}}} FileHandler::csv
  1296. };//}}}
  1297.  
  1298. /*
  1299. *
  1300. *
  1301. *
  1302. *
  1303. *///{{{
  1304. console.log('hdb hook');
  1305. if (document.location.pathname === "/mturk/dashboard") {
  1306. DashboardUI.draw();
  1307. DashboardUI.initClickables();
  1308. ProjectedEarnings.updateDate();
  1309. ProjectedEarnings.draw(true);
  1310.  
  1311. var Status = {
  1312. node: document.getElementById("hdbStatusText"),
  1313. get message() { return this.node.textContent; },
  1314. set message(str) { this.node.textContent = str; },
  1315. get color() { return this.node.style.color; },
  1316. set color(c) { this.node.style.color = c; },
  1317. push: function(m,c) { c = c || "black"; this.message = m; this.color = c; }
  1318. }, Progress = {
  1319. node: document.getElementById("hdbProgressBar"),
  1320. hide: function() { this.node.style.display = "none"; },
  1321. show: function() { this.node.style.display = "block"; }
  1322. };
  1323.  
  1324. var dbh = window.indexedDB.open(DB_NAME, DB_VERSION);
  1325. dbh.onerror = function(e) { Utils.errorHandler(e.target.error); };
  1326. dbh.onupgradeneeded = HITStorage.versionChange;
  1327. dbh.onsuccess = INITDB;
  1328.  
  1329. // export some variables for external extensions
  1330. self.Status = Status; self.Progress = Progress; self.Metrics = Metrics; self.Math.decRound = Math.decRound;
  1331. } else { // page is not dashboard
  1332. window.indexedDB.open(DB_NAME).onsuccess = function() { HITStorage.db = this.result; beenThereDoneThat(); };
  1333. }
  1334. /*}}}
  1335. *
  1336. *
  1337. *
  1338. *
  1339. */
  1340.  
  1341. function saveState(key, value) {//{{{
  1342. try {
  1343. localStorage.setItem(key,value);
  1344. } catch(err) {
  1345. if (err.name !== 'QuotaExceededError') return Utils.errorHandler(err);
  1346. try {
  1347. localStorage.removeItem(key);
  1348. localStorage.setItem(key, value);
  1349. } catch(errr) {
  1350. return Utils.errorHandler(errr);
  1351. }
  1352. }
  1353. }//}}}
  1354.  
  1355. // {{{ css injection
  1356. var css = "<style type='text/css'>" +
  1357. "#hdbProgressBar {margin:auto; width:250px; height:15px; position:relative; display:none;}" +
  1358. ".ball {position:absolute; left:0; width:12px; height:12px; border-radius:5px;" +
  1359. "animation:kfpballs 2s cubic-bezier(0.24,0.77,0.68,1) infinite;" +
  1360. "background:linear-gradient(222deg, rgba(208,69,247,0), rgba(208,69,247,1), rgba(69,197,247,1), rgba(69,197,247,0))}" +
  1361. "#hdbB2{animation-delay:.19s} #hdbB3{animation-delay:.38s} #hdbB4{animation-delay:.55s}" +
  1362. "@keyframes kfpballs {0% {left:0%;opacity:1} 50% {left:98%;opacity:0.2} 100% {left:0%;opacity:1}}" +
  1363. ".hitdbRTButtons {border:1px solid; font-size: 10px; height: 18px; padding-left: 5px; padding-right: 5px; background: pink;}" +
  1364. ".hitdbRTButtons-green {background: lightgreen;}" +
  1365. ".hitdbRTButtons-large {width:80px;}" +
  1366. ".hdbCalControls {cursor:pointer;} .hdbCalControls:hover {color:#c27fcf;}" +
  1367. ".hdbCalCells {background:#f0f6f9; height:19px}" +
  1368. ".hdbCalDays {cursor:pointer; text-align:center;} .hdbCalDays:hover {background:#7fb4cf; color:white;}" +
  1369. ".hdbDayHeader {width:26px; text-align:center; font-weight:bold; font-size:12px; background:#f0f6f9;}" +
  1370. ".hdbCalHeader {background:#7fb4cf; color:white; font-weight:bold; text-align:center; font-size:11px; padding:3px 0px;}" +
  1371. "#hdbCalendarPanel {position:absolute; z-index:10; box-shadow:-2px 3px 5px 0px rgba(0,0,0,0.68);}" +
  1372. ".hdbExpandRow {cursor:pointer; color:blue;}" +
  1373. ".hdbTotalsRow {background:#CCC; color:#369; font-weight:bold;}" +
  1374. ".hdbHeaderRow {background:#7FB448; font-size:12px; color:white;}" +
  1375. ".helpSpan {border-bottom:1px dotted; cursor:help;}" +
  1376. ".hdbResControl {border-bottom:1px solid; color:#c60; cursor:pointer; display:none;}" +
  1377. ".hdbTablePagination {margin-left:15em; color:#c60; display:none;}" +
  1378. ".spin {animation: kfspin 0.7s infinite linear; font-weight:bold;}" +
  1379. "@keyframes kfspin { 0% { transform: rotate(0deg) } 100% { transform: rotate(359deg) } }" +
  1380. ".spin:before{content:'*'}" +
  1381. ".nowrap {white-space:nowrap; overflow:hidden; text-overflow:ellipsis}" +
  1382. "</style>";
  1383. document.head.innerHTML += css;
  1384. // }}}
  1385.  
  1386. function resultConstrain(data, index, type, callback) {//{{{
  1387. data = data || qc.sr;
  1388.  
  1389. var table = document.getElementById("hdbResultsTable"),
  1390. rslice = data.length ? data[index].results : data.results,
  1391. pager = [document.getElementById("hdbPageTop"), document.getElementById("hdbPageBot")],
  1392. sopt = [],
  1393. _f = function(e) { resultConstrain(null,e.target.value,type,callback); };
  1394. pager[0].innerHTML = ''; pager[1].innerHTML = '';
  1395.  
  1396. if (data instanceof DBResult)
  1397. table.innerHTML = data.formatHTML(type);
  1398. else {
  1399. table.innerHTML = data[index].formatHTML(type);
  1400. pager[0].innerHTML = '<span style="cursor:pointer;">' + (index > 0 ? '&#9664; Prev' : '') + '</span> ' +
  1401. '<span style="cursor:pointer;">' + (+index+1 === data.length ? '' : 'Next &#9654;') + '</span> &nbsp; || &nbsp; '+
  1402. '<label>Select page: </label><select></select>';
  1403. for (var i=0;i<data.length;i++) {
  1404. if (i === +index)
  1405. sopt.push('<option value="' + i + '" selected="selected">' + (i+1) + '</option>');
  1406. else
  1407. sopt.push('<option value="' + i + '">' + (i+1) + '</option>');
  1408. }
  1409. pager[0].lastChild.innerHTML = sopt.join('');
  1410. pager[2] = pager[0].cloneNode(true);
  1411. pager[2].id = "hdbPageBot";
  1412. for (i of [0,2]) {
  1413. pager[i].children[0].onclick = resultConstrain.bind(null,null,+index-1,type,callback);
  1414. pager[i].children[1].onclick = resultConstrain.bind(null,null,+index+1,type,callback);
  1415. pager[i].children[3].onchange = _f;
  1416. }
  1417. pager[0].parentNode.replaceChild(pager[2], pager[1]);
  1418. }
  1419.  
  1420. callback(rslice);
  1421. }//}}} resultConstrain
  1422.  
  1423. function beenThereDoneThat() {//{{{
  1424. if (~document.location.pathname.search(/(accept|continue)/)) {
  1425. if (!document.querySelector('input[name="hitAutoAppDelayInSeconds"]')) return;
  1426.  
  1427. // capture autoapproval times
  1428. var _aa = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  1429. _hid = document.querySelectorAll('input[name="hitId"]')[1].value,
  1430. pad = function(num) { return Number(num).toPadded(); },
  1431. _d = Date.parse(new Date().getFullYear() + "-" + pad(new Date().getMonth()+1) + "-" + pad(new Date().getDate()));
  1432. qc.aat = JSON.parse(localStorage.getItem("hitdb_autoAppTemp") || "{}");
  1433.  
  1434. if (!qc.aat[_d]) qc.aat[_d] = {};
  1435. qc.aat[_d][_hid] = _aa;
  1436. qc.save("aat", "hitdb_autoAppTemp", true);
  1437. return;
  1438. }
  1439. var qualNode = document.querySelector('td[colspan="11"]');
  1440. if (qualNode) { // we're on the preview page!
  1441. var requesterid = document.querySelector('input[name="requesterId"]').value,
  1442. requestername = document.querySelector('input[name="prevRequester"]').value,
  1443. autoApproval = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  1444. hitTitle = document.querySelector('div[style*="ellipsis"]').textContent.trim(),
  1445. insertionNode = qualNode.parentNode.parentNode;
  1446. var row = document.createElement("TR"), cellL = document.createElement("TD"), cellR = document.createElement("TD");
  1447. var resultsTableR = document.createElement("TABLE"),
  1448. resultsTableT = document.createElement("TABLE");
  1449. resultsTableR.dataset.rid = requesterid;
  1450. resultsTableT.dataset.title = hitTitle;
  1451. insertionNode.parentNode.parentNode.appendChild(resultsTableR);
  1452. insertionNode.parentNode.parentNode.appendChild(resultsTableT);
  1453.  
  1454. cellR.innerHTML = '<span class="capsule_field_title">Auto-Approval:</span>&nbsp;&nbsp;'+Utils.ftime(autoApproval);
  1455. var rbutton = document.createElement("BUTTON");
  1456. rbutton.classList.add("hitdbRTButtons","hitdbRTButtons-large");
  1457. rbutton.textContent = "Requester";
  1458. rbutton.onclick = function(e) { e.preventDefault(); showResults.call(resultsTableR, "req", hitTitle); };
  1459. var tbutton = rbutton.cloneNode(false);
  1460. rbutton.title = "Show HITs completed from this requester";
  1461. tbutton.textContent = "HIT Title";
  1462. tbutton.onclick = function(e) { e.preventDefault(); showResults.call(resultsTableT, "title", requestername) };
  1463. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(requesterid), limit: 1})
  1464. .then(processResults.bind(rbutton,resultsTableR));
  1465. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(hitTitle), limit: 1})
  1466. .then(processResults.bind(tbutton,resultsTableT));
  1467. row.appendChild(cellL);
  1468. row.appendChild(cellR);
  1469. cellL.appendChild(rbutton);
  1470. cellL.appendChild(tbutton);
  1471. cellL.colSpan = "3";
  1472. cellR.colSpan = "8";
  1473. insertionNode.appendChild(row);
  1474. } else { // browsing HITs n sutff
  1475. var titleNodes = document.querySelectorAll('a[class="capsulelink"]');
  1476. if (titleNodes.length < 1) return; // nothing left to do here!
  1477. var requesterNodes = document.querySelectorAll('a[href*="hitgroups&requester"]');
  1478. var insertionNodes = [];
  1479.  
  1480. for (var i=0;i<titleNodes.length;i++) {
  1481. var _title = titleNodes[i].textContent.trim();
  1482. var _tbutton = document.createElement("BUTTON");
  1483. var _id = requesterNodes[i].href.replace(/.+Id=(.+)/, "$1");
  1484. var _name = requesterNodes[i].textContent;
  1485. var _rbutton = document.createElement("BUTTON");
  1486. var _div = document.createElement("DIV"), _tr = document.createElement("TR");
  1487. resultsTableR = document.createElement("TABLE");
  1488. resultsTableR.dataset.rid = _id;
  1489. resultsTableT = document.createElement("TABLE");
  1490. resultsTableT.dataset.title = _title;
  1491. insertionNodes.push(requesterNodes[i].parentNode.parentNode.parentNode);
  1492. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(resultsTableR);
  1493. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(resultsTableT);
  1494.  
  1495. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(_title), limit: 1} )
  1496. .then(processResults.bind(_tbutton,resultsTableT));
  1497. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(_id), limit: 1} )
  1498. .then(processResults.bind(_rbutton,resultsTableR));
  1499.  
  1500. _tr.appendChild(_div);
  1501. _div.id = "hitdbRTInjection-"+i;
  1502. _div.appendChild(_rbutton);
  1503. _rbutton.textContent = 'R';
  1504. _rbutton.classList.add("hitdbRTButtons");
  1505. _rbutton.onclick = showResults.bind(resultsTableR, "req", _title);
  1506. _rbutton.title = "Show HITs completed from this requester";
  1507. _div.appendChild(_tbutton);
  1508. _tbutton.textContent = 'T';
  1509. _tbutton.classList.add("hitdbRTButtons");
  1510. _tbutton.onclick = showResults.bind(resultsTableT, "title", _name);
  1511. insertionNodes[i].appendChild(_tr);
  1512. }
  1513. } // else
  1514.  
  1515. function showResults(type, match) {//{{{
  1516. /*jshint validthis: true*/
  1517. if (!this.dataset.hasResults) return;
  1518. if (this.children.length) // table is populated
  1519. this.innerHTML = '';
  1520. else { // need to populate table
  1521. var head = this.createTHead(),
  1522. body = this.createTBody(),
  1523. capt = this.createCaption(),
  1524. style= "font-size:10px;font-weight:bold;text-align:center",
  1525. validKeys = function(obj) { return Object.keys(obj).filter(function(v) { return !~v.search(/total[A-Z]/); }); };
  1526.  
  1527. capt.innerHTML = '<span style="'+style+'">Loading...<label class="spin"></label></span>';
  1528.  
  1529. if (type === "req") {
  1530. HITStorage.recall("HIT", {index:"requesterId", range:window.IDBKeyRange.only(this.dataset.rid)})
  1531. .then( function(r) {
  1532. var cbydate = r.collate(r.results, "date"),
  1533. kbydate = validKeys(cbydate),
  1534. cbydatextitle, kbytitle, bodyHTML = [];
  1535. kbydate.forEach(function(date) {
  1536. cbydatextitle = r.collate(cbydate[date], "title");
  1537. kbytitle = validKeys(cbydatextitle);
  1538. kbytitle.forEach(function(title) {
  1539. bodyHTML.push('<tr style="text-align:center;"><td>'+date+'</td>' +
  1540. '<td style="text-align:left">'+title.trim()+'</td><td>'+cbydatextitle[title].length+'</td>' +
  1541. '<td>'+Number(Math.decRound(cbydatextitle[title].pay,2)).toFixed(2)+'</td></tr>');
  1542. });
  1543. });
  1544. var help = "Total number of HITs submitted for a given date with the same title\n" +
  1545. "(aggregates results with the same title to simplify the table and reduce unnecessary spam for batch workers)";
  1546. head.innerHTML = '<tr style="'+style+'"><th>Date</th><th>Title</th>' +
  1547. '<th><span class="helpSpan" title="'+help+'">#HITs</span></th><th>Total Rewards</th></tr>';
  1548. body.innerHTML = bodyHTML.sort(function(a,b) {
  1549. return a.match(/\d{4}-\d{2}-\d{2}/)[0] < b.match(/\d{4}-\d{2}-\d{2}/)[0] ? 1 : -1;
  1550. }).join('');
  1551. capt.innerHTML = '<label style="'+style+'">HITs Matching This Requester</label>';
  1552.  
  1553. var mrows = Array.prototype.filter.call(body.rows, function(v) {return v.cells[1].textContent === match});
  1554. for (var row of mrows)
  1555. row.style.background = "lightgreen";
  1556. });
  1557. }
  1558. else if (type === "title") {
  1559. HITStorage.recall("HIT", {index:"title", range:window.IDBKeyRange.only(this.dataset.title)})
  1560. .then( function(r) {
  1561. var cbyreq = r.collate(r.results, "requesterName"),
  1562. kbyreq = validKeys(cbyreq),
  1563. bodyHTML = [];
  1564. for (var key of kbyreq)
  1565. bodyHTML.push('<tr style="text-align:center;"><td>'+key+'</td><td>'+cbyreq[key].length+'</td>' +
  1566. '<td>'+Number(Math.decRound(cbyreq[key].pay,2)).toFixed(2)+'</td></tr>');
  1567. var help = "Total number of HITs matching this title submitted for a given requester\n" +
  1568. "(aggregates results with the same requester name to simplify the table and reduce unnecessary spam for batch workers)";
  1569. head.innerHTML = '<tr style="'+style+'"><th>Requester Name</th>' +
  1570. '<th><span class="helpSpan" title="'+help+'">#HITs</span></th><th>Total Rewards</th></tr>';
  1571. body.innerHTML = bodyHTML.join('');
  1572. capt.innerHTML = '<label style="'+style+'">Reqesters With HITs Matching This Title</label>';
  1573.  
  1574. var mrows = Array.prototype.filter.call(body.rows, function(v) {return v.cells[0].textContent === match});
  1575. for (var row of mrows)
  1576. row.style.background = "lightgreen";
  1577. });
  1578. } //if type === 'title'
  1579. }//populate table
  1580. }//}}} showResults
  1581.  
  1582. function processResults(table, r) {
  1583. /*jshint validthis: true*/
  1584. if (r.results.length) {
  1585. table.dataset.hasResults = "true";
  1586. this.classList.add("hitdbRTButtons-green");
  1587. }
  1588. }
  1589. }//}}} btdt
  1590.  
  1591. function showHiddenRows(e) {//{{{
  1592. var rid = e.target.parentNode.textContent.substr(4);
  1593. var nodes = document.querySelectorAll('tr[data-rid="'+rid+'"]'), el = null;
  1594. if (e.target.textContent === "[+]") {
  1595. for (el of nodes)
  1596. el.style.display="table-row";
  1597. e.target.textContent = "[-]";
  1598. } else {
  1599. for (el of nodes)
  1600. el.style.display="none";
  1601. e.target.textContent = "[+]";
  1602. }
  1603. }//}}}
  1604.  
  1605. function showHitsByDate(e) {//{{{
  1606. var date = e.target.parentNode.nextSibling.textContent,
  1607. row = e.target.parentNode.parentNode,
  1608. table= row.parentNode;
  1609.  
  1610. if (e.target.textContent === "[+]") {
  1611. e.target.textContent = "[-]";
  1612. var nrow = table.insertBefore(document.createElement("TR"), row.nextSibling);
  1613. nrow.className = row.className;
  1614. nrow.innerHTML = '<td><b>Loading...<label class="spin"></label></b></td>';
  1615. HITStorage.recall("HIT", {index: "date", range: window.IDBKeyRange.only(date)}).then( function(r) {
  1616. nrow.innerHTML = '<td colspan="7"><table style="width:760;color:#c60;">' + r.formatHTML(null,true) + '</table></td>';
  1617. });
  1618. } else {
  1619. e.target.textContent = "[+]";
  1620. table.removeChild(row.nextSibling);
  1621. }
  1622. }//}}} showHitsByDate
  1623.  
  1624. function updateBonus(e) {//{{{
  1625. if (e instanceof window.KeyboardEvent && e.keyCode === 13) {
  1626. e.target.blur();
  1627. return false;
  1628. } else if (e instanceof window.FocusEvent) {
  1629. var _bonus = +e.target.textContent.replace(/[^\d.]/g,""),
  1630. _tBonusCell = e.target.offsetParent.tFoot.rows[0].cells[4],
  1631. _tBonus = +_tBonusCell.textContent.replace(/\$/,"");
  1632. e.target.textContent = Number(_bonus).toFixed(2);
  1633. _tBonusCell.textContent = '$'+Number(_tBonus-e.target.dataset.initial+_bonus).toFixed(2);
  1634. if (_bonus !== +e.target.dataset.initial) {
  1635. console.log("updating bonus to",_bonus,"from",e.target.dataset.initial,"("+e.target.dataset.hitid+")");
  1636. e.target.dataset.initial = _bonus;
  1637. var _range = window.IDBKeyRange.only(e.target.dataset.hitid);
  1638.  
  1639. HITStorage.db.transaction("HIT", "readwrite").objectStore("HIT").openCursor(_range).onsuccess = function() {
  1640. var c = this.result;
  1641. if (c) {
  1642. c.value.bonus = _bonus;
  1643. c.update(c.value);
  1644. }
  1645. }; // idbcursor
  1646. } // bonus is new value
  1647. } // keycode
  1648. } //}}} updateBonus
  1649.  
  1650. function noteHandler(type, e) {//{{{
  1651. //
  1652. // TODO restructure event handling/logic tree
  1653. // combine save and delete; it's ugly :(
  1654. // actually this whole thing is messy and in need of refactoring
  1655. //
  1656. if (e instanceof window.KeyboardEvent) {
  1657. if (e.keyCode === 13) {
  1658. e.target.blur();
  1659. return false;
  1660. }
  1661. return;
  1662. }
  1663.  
  1664. if (e instanceof window.FocusEvent) {
  1665. if (e.target.textContent.trim() !== e.target.dataset.initial) {
  1666. if (!e.target.textContent.trim()) { e.target.previousSibling.previousSibling.firstChild.click(); return; }
  1667. var note = e.target.textContent.trim(),
  1668. _range = window.IDBKeyRange.only(e.target.dataset.id),
  1669. inote = e.target.dataset.initial,
  1670. hitId = e.target.dataset.id,
  1671. date = e.target.previousSibling.textContent;
  1672.  
  1673. e.target.dataset.initial = note;
  1674. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1675. if (this.result) {
  1676. var r = this.result.value;
  1677. if (r.note === inote) { // note already exists in database, so we update its value
  1678. r.note = note;
  1679. this.result.update(r);
  1680. return;
  1681. }
  1682. this.result.continue();
  1683. } else {
  1684. if (this.source instanceof window.IDBObjectStore)
  1685. this.source.put({ note:note, date:date, hitId:hitId });
  1686. else
  1687. this.source.objectStore.put({ note:note, date:date, hitId:hitId });
  1688. }
  1689. };
  1690. }
  1691. return; // end of save event; no need to proceed
  1692. }
  1693.  
  1694. if (type === "delete") {
  1695. var tr = e.target.parentNode.parentNode,
  1696. noteCell = tr.lastChild;
  1697. _range = window.IDBKeyRange.only(noteCell.dataset.id);
  1698. if (!noteCell.dataset.initial) tr.remove();
  1699. else {
  1700. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1701. if (this.result) {
  1702. if (this.result.value.note === noteCell.dataset.initial) {
  1703. this.result.delete();
  1704. tr.remove();
  1705. return;
  1706. }
  1707. this.result.continue();
  1708. }
  1709. };
  1710. }
  1711. return; // end of deletion event; no need to proceed
  1712. } else {
  1713. if (type === "attach" && !e.results.length) return;
  1714.  
  1715. var trow = e instanceof window.MouseEvent ? e.target.parentNode.parentNode : null,
  1716. tbody = trow ? trow.parentNode : null,
  1717. row = document.createElement("TR"),
  1718. c1 = row.insertCell(0),
  1719. c2 = row.insertCell(1),
  1720. c3 = row.insertCell(2);
  1721. date = new Date();
  1722. hitId = e instanceof window.MouseEvent ? e.target.id.substr(5) : null;
  1723.  
  1724. c1.innerHTML = '<span class="removeNote" title="Delete this note" style="cursor:pointer;color:crimson;">[x]</span>';
  1725. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1726. c1.style.textAlign = "right";
  1727. c2.title = "Date on which the note was added";
  1728. c3.style.color = "crimson";
  1729. c3.colSpan = "6";
  1730. c3.contentEditable = "true";
  1731. c3.onblur = noteHandler.bind(null,"blur");
  1732. c3.onkeydown = noteHandler.bind(null, "kb");
  1733. if (type === "new") {
  1734. row.classList.add(trow.classList);
  1735. tbody.insertBefore(row, trow.nextSibling);
  1736. c2.textContent = date.getFullYear()+"-"+Number(date.getMonth()+1).toPadded()+"-"+Number(date.getDate()).toPadded();
  1737. c3.dataset.initial = "";
  1738. c3.dataset.id = hitId;
  1739. c3.focus();
  1740. return;
  1741. }
  1742.  
  1743. for (var entry of e.results) {
  1744. trow = document.querySelector('tr[data-id="'+entry.hitId+'"]');
  1745. tbody = trow.parentNode;
  1746. row = row.cloneNode(true);
  1747. c1 = row.firstChild;
  1748. c2 = c1.nextSibling;
  1749. c3 = row.lastChild;
  1750. row.classList.add(trow.classList);
  1751. tbody.insertBefore(row, trow.nextSibling);
  1752.  
  1753. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1754. c2.textContent = entry.date;
  1755. c3.textContent = entry.note;
  1756. c3.dataset.initial = entry.note;
  1757. c3.dataset.id = entry.hitId;
  1758. c3.onblur = noteHandler.bind(null,"blur");
  1759. c3.onkeydown = noteHandler.bind(null, "kb");
  1760. }
  1761. } // new/attach
  1762. }//}}} noteHandler
  1763.  
  1764. // writing callback functions {{{
  1765. function cbImport() {
  1766. /*jshint validthis:true*/
  1767. Status.push("Importing " + this.total + " entries");
  1768. if (++this.total !== this.requests) return;
  1769. Status.push("Importing " + this.total + " entries... Done!", "green");
  1770. try { Progress.hide(); metrics.dbimport.stop(); metrics.dbimport.report(); } catch(err) {}
  1771. }
  1772. function cbUpdate() {
  1773. /*jshint validthis:true*/
  1774. if (++this.total !== this.requests) return;
  1775. if (qc.extraDays) qc.extraDays = false;
  1776. Status.push("Update Complete!", "green");
  1777. ProjectedEarnings.data.dbUpdated = new Date().toLocalISOString();
  1778. ProjectedEarnings.saveState();
  1779. ProjectedEarnings.draw(false);
  1780. Utils.disableButtons(['hdbUpdate'], false);
  1781. Progress.hide(); metrics.dbupdate.stop(); metrics.dbupdate.report();
  1782. }
  1783. //}}}
  1784.  
  1785. function autoScroll(location, dt) {//{{{
  1786. var target = document.querySelector(location).offsetTop,
  1787. pos = window.scrollY,
  1788. dpos = Math.ceil((target - pos)/3);
  1789. dt = dt ? dt-1 : 25; // time step/max recursions
  1790.  
  1791. if (target === pos || dpos === 0 || dt === 0) return;
  1792.  
  1793. window.scrollBy(0, dpos);
  1794. setTimeout(function() { autoScroll(location, dt); }, dt);
  1795. }//}}}
  1796.  
  1797. function Calendar(offsetX, offsetY, caller) {//{{{
  1798. this.date = new Date();
  1799. this.offsetX = offsetX;
  1800. this.offsetY = offsetY;
  1801. this.caller = caller;
  1802. this.drawCalendar = function(year,month,day) {//{{{
  1803. year = year || this.date.getFullYear();
  1804. month = month || this.date.getMonth()+1;
  1805. day = day || this.date.getDate();
  1806. var longMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  1807. var date = new Date(year,month-1,day);
  1808. var anchors = _getAnchors(date);
  1809.  
  1810. //make new container if one doesn't already exist
  1811. var container = null;
  1812. if (document.querySelector("#hdbCalendarPanel")) {
  1813. container = document.querySelector("#hdbCalendarPanel");
  1814. container.removeChild( container.getElementsByTagName("TABLE")[0] );
  1815. }
  1816. else {
  1817. container = document.createElement("DIV");
  1818. container.id = "hdbCalendarPanel";
  1819. document.body.appendChild(container);
  1820. }
  1821. container.style.left = this.offsetX;
  1822. container.style.top = this.offsetY;
  1823. var cal = document.createElement("TABLE");
  1824. cal.cellSpacing = "0";
  1825. cal.cellPadding = "0";
  1826. cal.border = "0";
  1827. container.appendChild(cal);
  1828. cal.innerHTML = '<tr>' +
  1829. '<th class="hdbCalHeader hdbCalControls" title="Previous month" style="text-align:right;"><span>&lt;</span></th>' +
  1830. '<th class="hdbCalHeader hdbCalControls" title="Previous year" style="text-align:center;"><span>&#8810;</span></th>' +
  1831. '<th colspan="3" id="hdbCalTableTitle" class="hdbCalHeader">'+date.getFullYear()+'<br>'+longMonths[date.getMonth()]+'</th>' +
  1832. '<th class="hdbCalHeader hdbCalControls" title="Next year" style="text-align:center;"><span>&#8811;</span></th>' +
  1833. '<th class="hdbCalHeader hdbCalControls" title="Next month" style="text-align:left;"><span>&gt;</span></th>' +
  1834. '</tr><tr><th class="hdbDayHeader" style="color:red;">S</th><th class="hdbDayHeader">M</th>' +
  1835. '<th class="hdbDayHeader">T</th><th class="hdbDayHeader">W</th><th class="hdbDayHeader">T</th>' +
  1836. '<th class="hdbDayHeader">F</th><th class="hdbDayHeader">S</th></tr>';
  1837. document.querySelector('th[title="Previous month"]').addEventListener( "click", function() {
  1838. this.drawCalendar(date.getFullYear(), date.getMonth(), 1);
  1839. }.bind(this) );
  1840. document.querySelector('th[title="Previous year"]').addEventListener( "click", function() {
  1841. this.drawCalendar(date.getFullYear()-1, date.getMonth()+1, 1);
  1842. }.bind(this) );
  1843. document.querySelector('th[title="Next month"]').addEventListener( "click", function() {
  1844. this.drawCalendar(date.getFullYear(), date.getMonth()+2, 1);
  1845. }.bind(this) );
  1846. document.querySelector('th[title="Next year"]').addEventListener( "click", function() {
  1847. this.drawCalendar(date.getFullYear()+1, date.getMonth()+1, 1);
  1848. }.bind(this) );
  1849.  
  1850. var hasDay = false, thisDay = 1;
  1851. for (var i=0;i<6;i++) { // cycle weeks
  1852. var row = document.createElement("TR");
  1853. for (var j=0;j<7;j++) { // cycle days
  1854. if (!hasDay && j === anchors.first && thisDay < anchors.total)
  1855. hasDay = true;
  1856. else if (hasDay && thisDay > anchors.total)
  1857. hasDay = false;
  1858.  
  1859. var cell = document.createElement("TD");
  1860. cell.classList.add("hdbCalCells");
  1861. row.appendChild(cell);
  1862. if (hasDay) {
  1863. cell.classList.add("hdbCalDays");
  1864. cell.textContent = thisDay;
  1865. cell.addEventListener("click", _clickHandler.bind(this));
  1866. cell.dataset.year = date.getFullYear();
  1867. cell.dataset.month = date.getMonth()+1;
  1868. cell.dataset.day = thisDay++;
  1869. }
  1870. } // for j
  1871. cal.appendChild(row);
  1872. } // for i
  1873. var controls = cal.insertRow(-1);
  1874. controls.insertCell(0);
  1875. controls.cells[0].colSpan = "7";
  1876. controls.cells[0].classList.add("hdbCalCells");
  1877. controls.cells[0].innerHTML = ' &nbsp; &nbsp; <a href="javascript:void(0)" style="font-weight:bold;text-decoration:none;">Clear</a>' +
  1878. ' &nbsp; <a href="javascript:void(0)" style="font-weight:bold;text-decoration:none;">Close</a>';
  1879. controls.cells[0].children[0].onclick = function() { this.caller.value = ""; }.bind(this);
  1880. controls.cells[0].children[1].onclick = this.die;
  1881.  
  1882. function _clickHandler(e) {
  1883. /*jshint validthis:true*/
  1884.  
  1885. var y = e.target.dataset.year;
  1886. var m = Number(e.target.dataset.month).toPadded();
  1887. var d = Number(e.target.dataset.day).toPadded();
  1888. this.caller.value = y+"-"+m+"-"+d;
  1889. this.die();
  1890. }
  1891.  
  1892. function _getAnchors(date) {
  1893. var _anchors = {};
  1894. date.setMonth(date.getMonth()+1);
  1895. date.setDate(0);
  1896. _anchors.total = date.getDate();
  1897. date.setDate(1);
  1898. _anchors.first = date.getDay();
  1899. return _anchors;
  1900. }
  1901. };//}}} drawCalendar
  1902.  
  1903. this.die = function() { document.getElementById('hdbCalendarPanel').remove(); };
  1904.  
  1905. }//}}} Calendar
  1906.  
  1907. // instance metrics apart from window scoped PerformanceTiming API
  1908. function Metrics(name) {//{{{
  1909. this.name = name || "undefined";
  1910. this.marks = {};
  1911. this.start = window.performance.now();
  1912. this.end = null;
  1913. this.stop = function(){
  1914. if (!this.end)
  1915. this.end = window.performance.now();
  1916. else
  1917. Utils.errorHandler(new Error("Metrics::AccessViolation - end point cannot be overwritten"));
  1918. };
  1919. this.mark = function(name,position) {
  1920. if (position === "end" && !this.marks[name]) return;
  1921.  
  1922. if (!this.marks[name])
  1923. this.marks[name] = {};
  1924. if (!this.marks[name][position])
  1925. this.marks[name][position] = window.performance.now();
  1926. };
  1927. this.report = function() {
  1928. console.group("Metrics for",this.name.toUpperCase());
  1929. console.log("Process completed in",+Number((this.end-this.start)/1000).toFixed(3),"seconds");
  1930. for (var k in this.marks) {
  1931. if (this.marks.hasOwnProperty(k)) {
  1932. console.log(k,"occurred after",+Number((this.marks[k].start-this.start)/1000).toFixed(3),"seconds,",
  1933. "resolving in", +Number((this.marks[k].end-this.marks[k].start)/1000).toFixed(3), "seconds");
  1934. }
  1935. }
  1936. console.groupEnd();
  1937. };
  1938. }//}}}
  1939.  
  1940. function INITDB() {//{{{
  1941. HITStorage.db = this.result;
  1942. self.HITStorage = {db: this.result};
  1943. if (localStorage.getItem('hitdb_ridx') === 'true') return;
  1944.  
  1945. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], true);
  1946. var count = 0;
  1947. this.result.transaction('HIT', 'readwrite').objectStore('HIT').openCursor().onsuccess = function() {
  1948. if (!this.result) {
  1949. Status.push('Done.');
  1950. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], false);
  1951. return localStorage.setItem('hitdb_ridx', 'true');
  1952. }
  1953. Status.push('Performing integrity check... ' + (++count));
  1954. var r = this.result.value;
  1955. if (typeof r.reward === 'object') {
  1956. r.bonus = r.reward.bonus;
  1957. r.reward = r.reward.pay;
  1958. this.result.update(r);
  1959. }
  1960. this.result.continue();
  1961. }
  1962. }//}}}
  1963. })(); //scoping
  1964.  
  1965. // vim: ts=2:sw=2:et:fdm=marker:noai