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.008
  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.  
  149. qc.aat = JSON.parse(localStorage.getItem("hitdb_autoAppTemp") || "{}");
  150. qc.fetchData = JSON.parse(localStorage.getItem("hitdb_fetchData") || "{}");
  151. ProjectedEarnings.clear();
  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].toLowerCase())) 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] && 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. var _m = 'HITdb probably 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. span = str => '<span style="color:#c60;margin-top:6px;width:400px;display:block;position:relative;left:50%;transform:translateX(-50%)">' + str + '</span>';
  533. console.warn(_m);
  534. try { Status.html = Status.html + span(_m); } catch(err) {}
  535. }
  536. }
  537. }//}}}
  538. }, //}}} Utils
  539.  
  540. ProjectedEarnings = {//{{{
  541. data: JSON.parse(localStorage.getItem("hitdb_projectedEarnings") || "{}"),
  542. updateDate: function() {//{{{
  543. var tableList = document.querySelectorAll(".metrics-table"), el, date;
  544. try {
  545. el = tableList[5].rows[1].cells[0].children[0];
  546. date = el.href.match(/\d{8}/)[0];
  547. } catch(e1) {
  548. try {
  549. el = tableList[3].rows[1].cells[0].children[0];
  550. date = el.href.match(/\d{8}/)[0];
  551. } catch(e2) {
  552. for (var tbl of tableList) {
  553. if (tbl.rows.length < 2 || tbl.rows[1].cells.length < 6) continue;
  554. el = tbl.rows[1].cells[0].children[0];
  555. date = el.href.match(/\d{8}/)[0];
  556. } //for
  557. }//catch
  558. }//catch
  559. var day = el ? el.textContent : null,
  560. isToday = day === "Today",
  561. _date = new Date(),
  562. weekEnd = null,
  563. weekStart = null;
  564.  
  565. _date.setDate(_date.getDate() - _date.getDay()); // sunday
  566. weekStart = Date.parse(_date.toLocalISOString().slice(0,10));
  567. _date.setDate(_date.getDate() + 7); // next sunday
  568. weekEnd = Date.parse(_date.toLocalISOString().slice(0,10));
  569.  
  570. if (!Object.keys(this.data).length) {
  571. this.data = {
  572. today: date, weekStart: weekStart, weekEnd: weekEnd, day: new Date().getDay(), dbUpdated: "n/a",
  573. pending: 0, approved: 0, earnings: {}, target: { day: 0, week: 0 }
  574. };
  575. }
  576.  
  577. if ( (Date.parse(Utils.ISODate(date)) >= this.data.weekEnd) ||
  578. (!isToday && new Date().getDay() < this.data.day) ) { // new week
  579. this.data.earnings = {};
  580. this.data.weekEnd = weekEnd;
  581. this.data.weekStart = weekStart;
  582. }
  583. if ( (this.data.today === null && isToday) || (this.data.today !== null && (date !== this.data.today || !isToday)) ) { // new day
  584. this.data.today = date === this.data.today ? null : date;
  585. this.data.day = new Date().getDay();
  586. }
  587.  
  588. this.saveState();
  589. },//}}} updateDate
  590. draw: function(init) {//{{{
  591. var parentTable = document.querySelector("#total_earnings_amount").offsetParent,
  592. rowPending = init ? parentTable.insertRow(-1) : parentTable.rows[4],
  593. rowProjectedDay = init ? parentTable.insertRow(-1) : parentTable.rows[5],
  594. rowProjectedWeek = init ? parentTable.insertRow(-1) : parentTable.rows[6],
  595. title = "Click to set/change the target value",
  596. weekTotal = this.getWeekTotal(),
  597. dayTotal = this.data.earnings[this.data.today] || 0;
  598.  
  599. if (init) {
  600. rowPending.insertCell(-1);rowPending.insertCell(-1);rowPending.className = "even";
  601. rowProjectedDay.insertCell(-1);rowProjectedDay.insertCell(-1);rowProjectedDay.className = "odd";
  602. rowProjectedWeek.insertCell(-1);rowProjectedWeek.insertCell(-1);rowProjectedWeek.className = "even";
  603. for (var i=0;i<rowPending.cells.length;i++) rowPending.cells[i].style.borderTop = "dotted 1px black";
  604. rowPending.cells[0].className = "metrics-table-first-value";
  605. rowProjectedDay.cells[0].className = "metrics-table-first-value";
  606. rowProjectedWeek.cells[0].className = "metrics-table-first-value";
  607. }
  608.  
  609. rowPending.cells[1].title = "This value includes all earnings that are not yet fully cleared as 'Paid'\n" +
  610. "\n Pending Approval: $" + (this.data.pending - (this.data.approved || 0)).toFixed(2) +
  611. "\n Pending Payment: $" + (this.data.approved || 0).toFixed(2) +
  612. "\n Total Pending: $" + this.data.pending.toFixed(2);
  613. rowPending.cells[0].innerHTML = 'Pending earnings '+
  614. '<span style="font-family:arial;font-size:10px;" title="Timestamp of last database update">[ ' + this.data.dbUpdated + ' ]</span>';
  615. rowPending.cells[1].textContent = "$" + this.data.pending.toFixed(2);
  616. rowProjectedDay.cells[0].innerHTML = 'Projected earnings for the day<br>'+
  617. '<meter id="projectedDayProgress" style="width:220px;" title="'+title+
  618. '" value="'+dayTotal+'" max="'+this.data.target.day+'"></meter>'+
  619. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + (dayTotal-this.data.target.day).toFixed(2) + '</span>';
  620. rowProjectedDay.cells[1].textContent = "$"+ dayTotal.toFixed(2);
  621. rowProjectedWeek.cells[0].innerHTML = 'Projected earnings for the week<br>' +
  622. '<meter id="projectedWeekProgress" style="width:220px;" title="'+title+
  623. '" value="'+weekTotal+'" max="'+this.data.target.week+'"></meter>' +
  624. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + (weekTotal-this.data.target.week).toFixed(2) + '</span>';
  625. rowProjectedWeek.cells[1].textContent = "$" + weekTotal.toFixed(2);
  626. document.querySelector("#projectedDayProgress").onclick = updateTargets.bind(this, "day");
  627. document.querySelector("#projectedWeekProgress").onclick = updateTargets.bind(this, "week");
  628.  
  629. function updateTargets(span, e) {
  630. /*jshint validthis:true*/
  631. var goal = prompt("Set your " + (span === "day" ? "daily" : "weekly") + " target:",
  632. this.data.target[span === "day" ? "day" : "week"]);
  633. if (goal && !isNaN(goal)) {
  634. this.data.target[span === "day" ? "day" : "week"] = goal;
  635. e.target.max = goal;
  636. e.target.nextSibling.textContent = " " + ((span === "day" ? dayTotal : weekTotal) - goal).toFixed(2);
  637. this.saveState();
  638. }
  639. }
  640. },//}}} draw
  641. getWeekTotal: function() {//{{{
  642. var totals = 0;
  643. for (var k of Object.keys(this.data.earnings))
  644. totals += this.data.earnings[k];
  645.  
  646. return Math.decRound(totals, 2);
  647. },//}}}
  648. saveState: function() {//{{{
  649. saveState("hitdb_projectedEarnings", JSON.stringify(this.data));
  650. },//}}}
  651. clear: function() {//{{{
  652. this.data.pending = 0;
  653. this.data.approved = 0;
  654. for (var day of Object.keys(this.data.earnings))
  655. if (day in qc.fetchData || day === this.data.today) this.data.earnings[day] = 0;
  656. },//}}}
  657. updateValues: function(obj) {//{{{
  658. var vDate = Date.parse(obj.date), iDate = Utils.ISODate(obj.date);
  659.  
  660. if (~obj.status.search(/pending/i)) // sum pending earnings (include approved until fully cleared as paid)
  661. this.data.pending = Math.decRound(obj.reward+this.data.pending, 2);
  662. if (~obj.status.search(/approved/i))
  663. this.data.approved = Math.decRound(obj.reward+this.data.approved, 2);
  664. if (vDate < this.data.weekEnd && vDate >= this.data.weekStart && !~obj.status.search(/rejected/i)){ // sum weekly earnings by day
  665. this.data.earnings[iDate] = Math.decRound(obj.reward+(this.data.earnings[iDate] || 0), 2 );
  666. }
  667. }//}}}
  668. },//}}} ProjectedEarnings
  669.  
  670. DBResult = function(resArr, colObj) {//{{{
  671. this.results = resArr || [];
  672. this.collation = colObj || null;
  673. this.formatHTML = function(type, simple) {//{{{
  674. simple = simple || false;
  675. var count = 0, htmlTxt = [], entry = null, _trClass = null;
  676.  
  677. if (this.results.length < 1) return "<h2>No entries found matching your query.</h2>";
  678.  
  679. if (type === "daily") {
  680. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th></th>'+
  681. '<th>Date</th><th>Submitted</th><th>Approved</th><th>Rejected</th><th>Pending</th><th>Earnings</th></tr></thead><tbody>');
  682. var r = this.collate(this.results,"stats");
  683. for (entry of this.results) {
  684. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  685. htmlTxt.push('<tr '+_trClass+' style="text-align:right">' +
  686. '<td><span class="hdbExpandRow">[+]</span></td>'+
  687. '<td style="text-align:center;">' + entry.date + '</td><td>' + entry.submitted + '</td>' +
  688. '<td>' + entry.approved + '</td><td>' + entry.rejected + '</td><td>' + entry.pending + '</td>' +
  689. '<td>' + Number(entry.earnings).toFixed(2) + '</td></tr>');
  690. }
  691. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow" style="text-align:right;"><td>Totals:</td>' +
  692. '<td>' + r.totalEntries + ' days</td><td>' + r.totalSub + '</td>' +
  693. '<td>' + r.totalApp + '</td><td>' + r.totalRej + '</td>' +
  694. '<td>' + r.totalPen + '</td><td>$' +
  695. Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  696. } else if (type === "pending" || type === "requester") {
  697. htmlTxt.push('<thead><tr data-sort="99999" class="hdbHeaderRow"><th width="160">Requester ID</th>' +
  698. '<th>Requester</th><th>' + (type === "pending" ? 'Pending' : 'HITs') + '</th><th>Rewards</th></tr></thead><tbody>');
  699. r = this.collate(this.results,"requesterId");
  700. for (var k in r) {
  701. if (!~k.search(/total/) && r.hasOwnProperty(k)) {
  702. var tr = ['<tr data-sort="'+Math.decRound(r[k].pay,2)+'"><td>' +
  703. '<span class="hdbExpandRow" title="Display all pending HITs from this requester">' +
  704. '[+]</span> ' + r[k][0].requesterId + '</td><td>' + r[k][0].requesterName + '</td>' +
  705. '<td style="text-align:center;">' + r[k].length + '</td><td>' + Number(Math.decRound(r[k].pay,2)).toFixed(2) + '</td></tr>'];
  706.  
  707. for (var hit of r[k]) { // hits in range per requester id
  708. tr.push('<tr data-rid="'+r[k][0].requesterId+'" style="color:#c60000;display:none;"><td style="text-align:right">' +
  709. hit.date + '</td><td width="500" colspan="2" class="nowrap" style="max-width:520" title="'+hit.title+'">' +
  710. '[ <span class="helpSpan" title="Auto-approval time">AA: '+Utils.ftime(hit.autoAppTime).trim()+'</span> ] '+
  711. hit.title + '</td><td style="text-align:right">' + hit.reward.toFixed(2) + '</td></tr>');
  712. }
  713. htmlTxt.push(tr.join(''));
  714. }
  715. }
  716. htmlTxt.sort(function(a,b) { return +b.substr(15,5).match(/\d+\.?\d*/) - +a.substr(15,5).match(/\d+\.?\d*/); });
  717. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td style="text-align:right;">Totals:</td>' +
  718. '<td style="text-align:center;">' + (Object.keys(this.collation || r).length-7) + ' Requesters</td>' +
  719. '<td style="text-align:right;">' + (this.collation || r).totalEntries + '</td>'+
  720. '<td style="text-align:right;">$' + Number(Math.decRound((this.collation || r).totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  721. } else { // default
  722. if (!simple)
  723. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th colspan="3"></th>' +
  724. '<th colspan="2" title="Bonuses must be added in manually.\n\nClick inside' +
  725. 'the cell to edit, click out of the cell to save">Reward</th><th colspan="3"></th></tr>'+
  726. '<tr class="hdbHeaderRow">' +
  727. '<th style="min-width:65">Date</th><th>Requester</th><th>HIT title</th><th style="font-size:10px;">Pay</th>'+
  728. '<th style="font-size:10px;"><span class="helpSpan" title="Click the cell to edit.\nIts value is automatically saved">'+
  729. 'Bonus</span></th><th>Status</th><th>'+
  730. '<span class="helpSpan" title="Auto-approval times">AA</span></th><th>Feedback</th></tr></thead><tbody>');
  731.  
  732. this.results.sort(function(a,b) { return a.date === b.date ?
  733. (a.requesterName.toLowerCase() > b.requesterName.toLowerCase() ? 1 : -1) : a.date < b.date ? -1 : 1; });
  734. for (entry of this.results) {
  735. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  736. var _stColor = ~entry.status.search(/(paid|approved)/i) ? "green" :
  737. entry.status === "Pending Approval" ? "orange" : "red";
  738. var href = MTURK_BASE+'contact?requesterId='+entry.requesterId+'&requesterName='+entry.requesterName+
  739. '&subject=Regarding+Amazon+Mechanical+Turk+HIT+'+entry.hitId;
  740.  
  741. if (!simple)
  742. htmlTxt.push('<tr '+_trClass+' data-id="'+entry.hitId+'">'+
  743. '<td width="74px">' + entry.date + '</td><td style="max-width:145px;">' +
  744. '<a target="_blank" title="Contact this requester" href="'+href+'">' + entry.requesterName + '</a></td>' +
  745. '<td width="375px" title="HIT ID: '+entry.hitId+'">' +
  746. '<span title="Add a note" id="note-'+entry.hitId+'" style="cursor:pointer;">&nbsp;&#128221;&nbsp;</span>' +
  747. entry.title + '</td><td style="text-align:right">' + entry.reward.toFixed(2) + '</td>' +
  748. '<td style="text-align:right" class="bonusCell" title="Click to add/edit" contenteditable="true" data-hitid="'+entry.hitId+'">' +
  749. (entry.bonus ? entry.bonus.toFixed(2) : "") +
  750. '</td><td style="color:'+_stColor+';text-align:center">' + entry.status + '</td>' +
  751. '<td>' + Utils.ftime(entry.autoAppTime) + '</td><td>' + entry.feedback + '</td></tr>');
  752. else
  753. htmlTxt.push('<tr>' + '<td class="nowrap" title="'+entry.requesterName+'" style="max-width:130">'+entry.requesterName+'</td>' +
  754. '<td class="nowrap" title="'+entry.title+'" style="max-width:520">'+entry.title+'</td><td>'+ entry.reward.toFixed(2) +
  755. '</td><td class="nowrap" title="'+entry.status+'" style="max-width:60">'+ entry.status+'</td></tr>');
  756. }
  757.  
  758. if (!simple) {
  759. r = this.collation || this.collate(this.results,"requesterId");
  760. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td></td>' +
  761. '<td style="text-align:right">Totals:</td><td style="text-align:center;">' + r.totalEntries + ' HITs</td>' +
  762. '<td style="text-align:right">$' + (+Math.decRound(r.totalPay,2)).toFixed(2) + '</td>' +
  763. '<td style="text-align:right">$' + (+Math.decRound(r.totalBonus,2) || 0).toFixed(2) + '</td>' +
  764. '<td colspan="3"></td></tr></tfoot>');
  765. }
  766. }
  767. return htmlTxt.join('');
  768. };//}}} formatHTML
  769. this.formatCSV = function(type) {//{{{
  770. var csvTxt = [], entry = null, delimiter="\t";
  771. if (type === "daily") {
  772. csvTxt.push( ["Date", "Submitted", "Approved", "Rejected", "Pending", "Earnings\n"].join(delimiter) );
  773. for (entry of this.results) {
  774. csvTxt.push( [entry.date, entry.submitted, entry.approved, entry.rejected,
  775. entry.pending, Number(entry.earnings).toFixed(2)+"\n"].join(delimiter) );
  776. }
  777. csvToFile(csvTxt, "hitdb_dailyOverview.csv");
  778. } else if (type === "pending" || type === "requester") {
  779. csvTxt.push( ["RequesterId","Requester", (type === "pending" ? "Pending" : "HITs"), "Rewards\n"].join(delimiter) );
  780. var r = this.collation || this.collate(this.results,"requesterId");
  781. for (var k in r) {
  782. if (!~k.search(/total/) && r.hasOwnProperty(k))
  783. csvTxt.push( [k, r[k][0].requesterName, r[k].length, Number(Math.decRound(r[k].pay,2)).toFixed(2)+"\n"].join(delimiter) );
  784. }
  785. csvToFile(csvTxt, "hitdb_"+type+"Overview.csv");
  786. } else {
  787. csvTxt.push(["hitId","date","requesterName","requesterId","title","pay","bonus","status","autoAppTime","feedback\n"].join(delimiter));
  788. for (entry of this.results) {
  789. csvTxt.push([entry.hitId, entry.date, entry.requesterName, entry.requesterId, entry.title, entry.reward.toFixed(2),
  790. (entry.bonus ? entry.bonus.toFixed(2) : ''), entry.status, entry.autoAppTime,
  791. entry.feedback.replace(/[\t\n]/g,' ')+"\n"].join(delimiter));
  792. }
  793. csvToFile(csvTxt, "hitdb_queryResults.csv");
  794. }
  795.  
  796. return '';//"<pre>"+csvTxt.join('')+"</pre>";
  797.  
  798. function csvToFile(csv, filename) {
  799. var blob = new Blob(csv, {type: "text/csv", endings: "native"}),
  800. dl = document.createElement("A");
  801. dl.href = URL.createObjectURL(blob);
  802. dl.download = filename;
  803. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  804. dl.click(); // so we make it so and click,
  805. dl.remove(); // then immediately remove it
  806. return dl;
  807. }
  808. };//}}} formatCSV
  809. this.include = function(value) {
  810. this.results.push(value);
  811. };
  812. this.collate = function(data, index) {//{{{
  813. var r = {
  814. totalPay: 0, totalBonus: 0, totalEntries: data.length,
  815. totalSub: 0, totalApp: 0, totalRej: 0, totalPen: 0
  816. };
  817. for (var e of data) {
  818. if (!r[e[index]]) {
  819. r[e[index]] = [];
  820. Object.defineProperty(r[e[index]], "pay", {value: 0, enumerable: false, configurable: true, writable: true});
  821. }
  822. r[e[index]].push(e);
  823.  
  824. if (index === "stats") {
  825. r.totalSub += e.submitted;
  826. r.totalApp += e.approved;
  827. r.totalRej += e.rejected;
  828. r.totalPen += e.pending;
  829. r.totalPay += e.earnings;
  830. } else {
  831. r[e[index]].pay += (+e.reward);
  832. r.totalPay += (+e.reward);
  833. r.totalBonus += (+e.bonus);
  834. }
  835. }
  836. return r;
  837. };//}}} _collate
  838.  
  839. },//}}} databaseresult
  840.  
  841. DashboardUI = {//{{{
  842. draw: function() {//{{{
  843. var controlPanel = document.createElement("TABLE"),
  844. insertionNode = document.querySelector(".footer_separator").previousSibling;
  845. document.body.insertBefore(controlPanel, insertionNode);
  846. controlPanel.width = "760";
  847. controlPanel.align = "center";
  848. controlPanel.id = "hdbControlPanel";
  849. controlPanel.cellSpacing = "0";
  850. controlPanel.cellPadding = "0";
  851. controlPanel.innerHTML = '<tr height="25px"><td width="10" bgcolor="#7FB448" style="padding-left: 10px;"></td>' +
  852. '<td class="white_text_14_bold" style="padding-left:10px; background-color:#7FB448;">' +
  853. 'HIT Database Mk. II&nbsp;<a href="https://greasyfork.org/en/scripts/11733-mturk-hit-database-mk-ii#userGuide" '+
  854. 'class="whatis" target="turkPopUp" onclick="customPopup(this, 500, 400)">' +
  855. '(What\'s this?)</a></td></tr>' +
  856. '<tr><td class="container-content" colspan="2">' +
  857. '<div style="text-align:center; position:relative" id="hdbDashboardInterface">' +
  858. '<button id="hdbBackup" title="Export your entire database!\nPerfect for moving between computers or as a periodic backup">Create Backup</button>' +
  859. '<button id="hdbRestore" title="Import data from an external file" style="margin:5px">Import</button>' +
  860. '<button id="hdbUpdate" title="Update... the database" style="color:green;">Update Database</button>' +
  861. '<input id="hdbFileInput" type="file" style="display:none"/>' +
  862. '<br>'+
  863. '<div style="position:absolute; top:0; right:0; text-align:initial">' +
  864. //'<label title="Popout search results in a new window" style="vertical-align:middle;">popout' +
  865. //'<input id="hdbPopout" type="checkbox" style="vertical-align:middle"></label>' +
  866. '<label for="hdbCSVInput" title="Export results as CSV file" style="vertical-align:middle;">export CSV</label>' +
  867. '<input id="hdbCSVInput" title="Export results as CSV file" type="checkbox" style="vertical-align:middle;">' +
  868. '</div>' +
  869. '<button id="hdbPending" title="Summary of all pending HITs\n Can be exported as CSV" style="margin: 0px 5px 5px;">Pending Overview</button>' +
  870. '<button id="hdbRequester" title="Summary of all requesters\n Can be exported as CSV" style="margin: 0px 5px 5px;">Requester Overview</button>' +
  871. '<button id="hdbDaily" title="Summary of each day you\'ve worked\nCan be exported as CSV" style="margin:0px 5px 5px;">Daily Overview</button>' +
  872. '<br>' +
  873. '<label>Find </label>' +
  874. '<select id="hdbStatusSelect" style="width:100px"><option value="*">ALL</option>' +
  875. '<option value="Pending Approval" style="color: orange;">Pending Approval</option>' +
  876. '<option value="Rejected" style="color: red;">Rejected</option>' +
  877. '<option value="Approved - Pending Payment" style="color:green;">Approved - Pending Payment</option>' +
  878. '<option value="Paid" style="color:green;">Paid</option></select>' +
  879. '<label> HITs from </label><input id="hdbMinDate" type="date" size="10" title="Specify a date, or leave blank">' +
  880. '<label> to </label><input id="hdbMaxDate" type="date" size="10" title="Specify a date, or leave blank">' +
  881. '<label> matching </label>'+
  882. '<br>' +
  883. '<input id="hdbSearchInput" style="width:400px" title="Query can be HIT title, HIT ID, or requester name" />' +
  884. '<button id="hdbSearch" style="margin-left:5px">Search</button>' +
  885. '<br>' +
  886. '<label id="hdbStatusText"></label>' +
  887. '<div id="hdbProgressBar">' +
  888. '<div id="hdbB1" class="ball"></div><div id="hdbB2" class="ball"></div>' +
  889. '<div id="hdbB3" class="ball"></div><div id="hdbB4" class="ball"></div>' +
  890. '</div>' +
  891. '</div></td></tr>';
  892.  
  893. var searchResults = document.createElement("DIV");
  894. searchResults.align = "center";
  895. searchResults.id = "hdbSearchResults";
  896. searchResults.style.display = "block";
  897. searchResults.innerHTML =
  898. '<span class="hdbResControl" id="hdbResClear">[ clear results ]</span>' +
  899. '<span class="hdbTablePagination" id="hdbPageTop"></span><br>' +
  900. '<table cellSpacing="0" cellpadding="2" width="760" id="hdbResultsTable"></table>' +
  901. '<span class="hdbResControl" id="hdbVpTop">Back to top</span>' +
  902. '<span class="hdbTablePagination" id="hdbPageBot"></span><br>';
  903. document.body.insertBefore(searchResults, insertionNode);
  904. },//}}} dashboardUI::draw
  905. initClickables: function() {//{{{
  906. var updateBtn = document.getElementById("hdbUpdate"),
  907. backupBtn = document.getElementById("hdbBackup"),
  908. restoreBtn = document.getElementById("hdbRestore"),
  909. fileInput = document.getElementById("hdbFileInput"),
  910. exportCSVInput = document.getElementById("hdbCSVInput"),
  911. searchBtn = document.getElementById("hdbSearch"),
  912. searchInput = document.getElementById("hdbSearchInput"),
  913. pendingBtn = document.getElementById("hdbPending"),
  914. reqBtn = document.getElementById("hdbRequester"),
  915. dailyBtn = document.getElementById("hdbDaily"),
  916. fromdate = document.getElementById("hdbMinDate"),
  917. todate = document.getElementById("hdbMaxDate"),
  918. statusSelect = document.getElementById("hdbStatusSelect"),
  919. searchResults = document.getElementById("hdbSearchResults"),
  920. resultsTable = document.getElementById("hdbResultsTable"),
  921. isGecko = /Gecko\/\d+/.test(navigator.userAgent);
  922.  
  923. searchResults.firstChild.onclick = function() { //{{{ clear results
  924. resultsTable.innerHTML = null; qc.sr = [];
  925. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  926. if (~d.search(/page/i)) searchResults.querySelector('#'+d).innerHTML = "";
  927. document.getElementById(d).style.display = "none";
  928. }
  929. };//}}}
  930. document.getElementById("hdbVpTop").onclick = function() { autoScroll("#hdbControlPanel"); };
  931.  
  932. updateBtn.onclick = function() { //{{{
  933. if (!HITStorage.db) { return Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); }
  934. Utils.disableButtons(['hdbUpdate'], true);
  935. Progress.show();
  936. metrics.dbupdate = new Metrics("database_update");
  937. HITStorage.fetch(MTURK_BASE+"status");
  938. Status.message = "fetching status page....";
  939. };//}}}
  940. exportCSVInput.addEventListener("click", function() {//{{{
  941. var a = document.getElementById('hdbAnalytics');
  942. if (a && a.checked) a.click();
  943. if (exportCSVInput.checked) {
  944. searchBtn.textContent = "Export CSV";
  945. pendingBtn.textContent += " (csv)";
  946. reqBtn.textContent += " (csv)";
  947. dailyBtn.textContent += " (csv)";
  948. }
  949. else {
  950. searchBtn.textContent = "Search";
  951. pendingBtn.textContent = pendingBtn.textContent.replace(" (csv)","");
  952. reqBtn.textContent = reqBtn.textContent.replace(" (csv)","");
  953. dailyBtn.textContent = dailyBtn.textContent.replace(" (csv)", "");
  954. }
  955. });//}}}
  956. if (isGecko) {//{{{
  957. fromdate.addEventListener("focus", function() {
  958. var offsets = Utils.getPosition(this, true);
  959. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  960. });
  961. todate.addEventListener("focus", function() {
  962. var offsets = Utils.getPosition(this, true);
  963. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  964. });
  965. }//}}}
  966.  
  967. backupBtn.onclick = HITStorage.backup;
  968. restoreBtn.onclick = function() { fileInput.value = ''; fileInput.click(); };
  969. fileInput.onchange = FileHandler.delegate;//processFile;
  970. searchInput.onkeydown = function(e) { if (e.keyCode === 13) searchBtn.click(); };
  971.  
  972. searchBtn.addEventListener('click', function(e) {//{{{
  973. if (!/^[se]/i.test(e.target.textContent)) return;
  974. var opt = this.getRange(statusSelect.value, _getFilters(searchInput.value.trim()));
  975. opt.progress = true;
  976. if (opt.query && opt.query.length === 30 && !/\s/.test(opt.query)) {
  977. opt.range = window.IDBKeyRange.only(opt.query.toUpperCase());
  978. opt.index = null;
  979. }
  980. _dbaccess("search", ["HIT", opt], function(r) {
  981. var limiter = 500,
  982. _cb = function(slice) {
  983. for (var _r of slice)
  984. HITStorage.recall("NOTES", { index: "hitId", range: window.IDBKeyRange.only(_r.hitId) }).then(noteHandler.bind(null,"attach"));
  985. var _nodes = [document.querySelectorAll(".bonusCell"), document.querySelectorAll('span[id^="note-"]')];
  986. for (var i=0;i<_nodes[0].length;i++) {
  987. var bonus = _nodes[0][i],
  988. note = _nodes[1][i];
  989. bonus.dataset.initial = bonus.textContent;
  990. bonus.onkeydown = updateBonus;
  991. bonus.onblur = updateBonus;
  992. note.onclick = noteHandler.bind(null,"new");
  993. }
  994. };
  995. if (exportCSVInput.checked)
  996. resultsTable.innerHTML = r.formatCSV();
  997. else if (r.results.length > limiter) {
  998. var collation = r.collate(r.results, "requesterId");
  999. do { qc.sr.push(new DBResult(r.results.splice(0,limiter), collation)) } while (r.results.length);
  1000. resultConstrain(qc.sr, 0, "default", _cb);
  1001. } else
  1002. resultConstrain(r, 0, "default", _cb);
  1003. });
  1004. }.bind(this)); //}}} search button click event
  1005. //{{{ overview buttons
  1006. pendingBtn.onclick = function() {
  1007. var opt = this.getRange('pending', _getFilters(searchInput.value.trim())),
  1008. _opt = { index:'status', dir:'prev', range:window.IDBKeyRange.only('Pending Approval'), progress:true };
  1009.  
  1010. opt = Object.assign(opt, _opt);
  1011. _dbaccess("pending", ["HIT", opt], function(r) {
  1012. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("pending") : r.formatHTML("pending");
  1013. var expands = document.querySelectorAll(".hdbExpandRow");
  1014. for (var el of expands)
  1015. el.onclick = showHiddenRows;
  1016. });
  1017. }.bind(this); //pending overview click event
  1018. reqBtn.onclick = function() {
  1019. var opt = this.getRange(statusSelect.value, _getFilters(searchInput.value.trim()));
  1020. opt.progress = true;
  1021.  
  1022. _dbaccess("requester", ["HIT", opt], function(r) {
  1023. var limiter = 100,
  1024. _cb = function() {
  1025. var expands = document.querySelectorAll(".hdbExpandRow");
  1026. for (var el of expands)
  1027. el.onclick = showHiddenRows;
  1028. };
  1029. if (exportCSVInput.checked)
  1030. resultsTable.innerHTML = r.formatCSV("requester");
  1031. else if (r.results.length > limiter) {
  1032. var collation = r.collate(r.results, "requesterId"), _r = [], count = 0;
  1033. var keys = Object.keys(collation)
  1034. .filter(function(e) { return !/total/.test(e); })
  1035. .sort(function(a,b) { return collation[b].pay - collation[a].pay; });
  1036. keys.forEach(function(key){
  1037. if (++count > limiter) {
  1038. qc.sr.push(new DBResult(_r, collation));
  1039. count = 0; _r = [];
  1040. } else _r = _r.concat(collation[key]);
  1041. });
  1042. qc.sr.push(new DBResult(_r, collation));
  1043. resultConstrain(qc.sr, 0, "requester", _cb);
  1044. } else
  1045. resultConstrain(r, 0, "requester", _cb);
  1046. });
  1047. }.bind(this); //requester overview click event
  1048. dailyBtn.onclick = function() {
  1049. var opt = Object.assign(this.getRange("*"), { index:null, dir:'prev', progress:true });
  1050. _dbaccess("daily", ["STATS", opt], function(r) {
  1051. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("daily") : r.formatHTML("daily");
  1052. var expands = document.querySelectorAll(".hdbExpandRow");
  1053. for (var el of expands)
  1054. el.onclick = showHitsByDate;
  1055. });
  1056. }.bind(this); //daily overview click event
  1057. //}}}
  1058. function _getFilters(str) {//{{{
  1059. var re = /(?:[rh][equstri]*(?:id|name)|bonus|reward|pay|req|id):[^;]+/ig,
  1060. matches = str.match(re),
  1061. filters = { query: str },
  1062. _setRange = function(str) {
  1063. var rng = str.split(/[><,]/).filter(v => v).sort(); rng.forEach((v,i,a) => a[i] = +v);
  1064. if (rng.length === 1) {
  1065. if (str.startsWith('<')) {
  1066. rng[0] -= 0.01;
  1067. rng.unshift(0.01);
  1068. } else if (str.startsWith('>')) {
  1069. rng[0] += 0.01;
  1070. rng.push(Infinity);
  1071. } else rng.push(rng[0]);
  1072. }
  1073. return rng;
  1074. };
  1075.  
  1076. if (!matches) return filters;
  1077. filters.query = str.slice(0,str.indexOf(matches[0])).trim();
  1078. if (!filters.query.length) filters.query = null;
  1079. for (var m of matches) {
  1080. var _m = m.split(':');
  1081. if (/(^req$|r[eqstr]*name)/i.test(_m[0])) filters.requesterName = _m[1].trimLeft();
  1082. else if (/(^id$|hitid)/i.test(_m[0])) filters.hitId = _m[1].toUpperCase().trimLeft();
  1083. else if (/r[eqstr]*id/i.test(_m[0])) filters.requesterId = _m[1].toUpperCase().trimLeft();
  1084. else if (/(reward|pay)/i.test(_m[0])) filters.reward = _setRange(_m[1]);
  1085. else if (_m[0].toLowerCase() === 'bonus') filters.bonus = _setRange(_m[1]);
  1086. }
  1087. return filters;
  1088. }//}}}
  1089. function _dbaccess(method, rargs, tfn) {//{{{
  1090. if (!HITStorage.db) { Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); return; }
  1091. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], true);
  1092. searchResults.firstChild.click();
  1093. Status.push("Preparing database...", "black");
  1094. metrics.dbrecall = new Metrics("database_recall::"+method);
  1095. metrics.dbrecall.mark("data retrieval", "start");
  1096.  
  1097. HITStorage.recall(rargs[0],rargs[1]).then(function(r) {
  1098. metrics.dbrecall.mark("data retrieval", "end");
  1099. Status.message = "Building HTML...";
  1100. try {
  1101. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  1102. if (exportCSVInput.checked || (~d.search(/page/i) && !/^[sr]/.test(method))) continue;
  1103. document.getElementById(d).style.display = "initial";
  1104. }
  1105. metrics.dbrecall.mark("HTML construction", "start");
  1106. tfn(r);
  1107. metrics.dbrecall.mark("HTML construction", "end");
  1108. } catch(e) {
  1109. Utils.errorHandler(e);
  1110. } finally {
  1111. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], false);
  1112. autoScroll("#hdbSearchResults");
  1113. Status.push("Done!", "green");
  1114. Progress.hide();
  1115. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1116. }
  1117. });
  1118. }//}}} _dbaccess
  1119. },//}}} dashboardUI::initClickables
  1120. getRange: function(status, filters) {//{{{
  1121. var fromdate = document.getElementById("hdbMinDate"),
  1122. todate = document.getElementById("hdbMaxDate"),
  1123. statusSelect = document.getElementById("hdbStatusSelect"),
  1124. obj = Object.assign({}, filters || {}), r = window.IDBKeyRange;
  1125. obj.status = status || statusSelect.value;
  1126. obj.date = [ (fromdate.value || '0000'), (todate.value || '9999') ];
  1127. obj.index = obj.date[0] !== '0000' || obj.date[1] !== '9999' ? 'date' : 'status';
  1128. if (filters) {
  1129. var indexPriority = { hitId:100, bonus:80, date:70, status:60, requesterId:50, requesterName:40, reward:30, },
  1130. indices = Object.keys(filters);
  1131. indices.push(obj.index);
  1132. obj.index = indices.reduce((a,b) => indexPriority[a] || 0 > indexPriority[b] || 0 ? a : b);
  1133. }
  1134. obj.range = (function(i) {
  1135. if (['date','reward','pay','bonus'].includes(i))
  1136. return (obj[i] = obj[i].sort()) && r.bound(obj[i][0], obj[i][1]);
  1137. else if (i === 'status' && status.length > 1)
  1138. return r.only(status);
  1139. else if (['hitId','requesterName','requesterId'].includes(i))
  1140. return r.bound(obj[i], obj[i].slice(0,-1) + String.fromCharCode(obj[i].slice(-1).charCodeAt()+1));
  1141. })(obj.index);
  1142. if (obj.index === 'hitId' || (obj.index === 'status' && status.length === 1)) obj.index = null;
  1143. return obj;
  1144. }//}}} dashboardUI::getRange
  1145. },//}}} dashboard
  1146. FileHandler = { //{{{
  1147. //
  1148. // TODO: JSON integrity check
  1149. //
  1150. delegate: function(e) {//{{{
  1151. var f = e.target.files;
  1152. if (f.length && ~f[0].name.search(/\.(bak|csv|json)$/i)/* && ~f[0].type.search(/(text|json)/)*/) {
  1153. var reader = new FileReader(), testing = true, isCsv = false;
  1154. metrics.dbimport = new Metrics("file_import");
  1155.  
  1156. reader.readAsText(f[0].slice(0,10));
  1157. reader.onload = function(e) {
  1158. var r = e.target.result;
  1159. if (testing && !~r.search(/(STATS|NOTES|HIT)/)) { // failed json check, test if csv
  1160. console.log("failed json integrity:", r, "\nchecking csv schema...");
  1161. if (!~r.search(/hitId/)) { // failed csv check, return error
  1162. console.log("failed csv integrity:", r, "\naborting");
  1163. return Utils.errorHandler(new TypeError("Invalid data structure"));
  1164. } else { // passed initial csv check, parse full file
  1165. console.log("deferring to csv parser");
  1166. isCsv = true;
  1167. testing = false;
  1168. Progress.show();
  1169. reader.readAsText(f[0]);
  1170. }
  1171. } else if (testing) {
  1172. testing = false;
  1173. Progress.show();
  1174. reader.readAsText(f[0]);
  1175. } else {
  1176. if (isCsv) this.csv.fromFile(r);
  1177. else HITStorage.write(JSON.parse(r), cbImport);
  1178. }
  1179. }.bind(FileHandler); // reader.onload
  1180. } else if (f.length)
  1181. Utils.errorHandler(new TypeError("Unsupported file format"));
  1182. },//}}}
  1183. csv: {//{{{
  1184. fromFile: function(r) {//{{{
  1185. var validKeys = ["autoAppTime","date","feedback","hitId","requesterId","requesterName","reward","pay","bonus","status","title"],
  1186. //lines = r.replace(/\r?\n^(?!"?[A-Z0-9]{30})/gm,' ').split(/\r?\n/);
  1187. lines = r.split(/\r?\n(?="?[A-Z0-9]{30})/);
  1188. this.delimiter = /^"/.test(lines[0]) ? r.substr(7,1) : r.substr(5,1);
  1189. this.header = lines.splice(0,1)[0].replace(new RegExp(`([" ]|${this.delimiter}$)`,'g'),'').split(this.delimiter);
  1190. this.data = { HIT:[] };
  1191.  
  1192. console.log('delimiter:',this.delimiter==='\t'?'tab':this.delimiter,'\nlines:',lines.length,'\nheader:',this.header);
  1193. if (!lines.length) return Utils.errorHandler(new Error("CSV file must contain at least one record"));
  1194. // make sure header keys are valid
  1195. for (var key of this.header)
  1196. if (!~validKeys.indexOf(key)) {
  1197. Progress.hide();
  1198. return Utils.errorHandler(new TypeError("Invalid key '"+key+"' found in column header"));
  1199. }
  1200. this.core(lines);
  1201. },//}}}
  1202. core: function(lr, syn) {//{{{
  1203. syn = syn || false;
  1204. var badLines = [],
  1205. deq = function(str) { if (/^"/.test(str) && /"$/.test(str)) return str.replace(/(^"|"$)/g,''); else return str;},
  1206. qfix = arr => arr.reduce((a,b) => {
  1207. if (a.length && /^".+[^"]$/.test(a[a.length-1])) {
  1208. a[a.length-1] = a[a.length-1] + this.delimiter + b;
  1209. return a;
  1210. } else return a.concat(b);
  1211. }, []);
  1212. for (var line of lr) {
  1213. var record = {};
  1214. line = line.split(this.delimiter);
  1215. if (line.length <= 1) continue;
  1216. if (line.length !== this.header.length) {
  1217. // attempt to resolve delimiter conflicts within field values
  1218. line = qfix(line);
  1219. while (line.length > this.header.length) {
  1220. var datum = line.pop();
  1221. if (/\S/.test(deq(datum))) { line.push(datum); break; }
  1222. }
  1223. if (line.length !== this.header.length) {
  1224. badLines.push({record: line, reason: "SyntaxError: Number of field do not match number of columns"}); continue; }
  1225. }
  1226. // convert into usable JSON
  1227. for (var i=0;i<line.length;i++) {
  1228. if (/(pay|bonus|reward|autoAppTime)/.test(this.header[i]) && isNaN(+line[i])) {
  1229. badLines.push({record: line, reason: `TypeError: Value in '${this.header[i]}' is not a number.`}); break; }
  1230. if (this.header[i] === 'hitId' && (/\W/.test(deq(line[i])) || deq(line[i]).length !== 30)) {
  1231. badLines.push({record: line, reason: "TypeError: Invalid hitId."}); break; }
  1232. if (this.header[i] === 'date' && !/\d{4}-\d{2}-\d{2}/.test(line[i])) {
  1233. badLines.push({record: line, reason: "TypeError: Invalid date. Dates must be in ISO format (YYYY-MM-DD)."}); break; }
  1234.  
  1235. if (this.header[i] === 'pay' || this.header[i] === 'reward')
  1236. record.reward = +line[i];
  1237. else if (this.header[i] === 'bonus')
  1238. record.bonus = +line[i];
  1239. else
  1240. record[this.header[i]] = deq(line[i]);
  1241. } // for each field
  1242. if (!syn && !badLines.find(v => v.record === line)) this.data.HIT.push(record);
  1243. } // for each record
  1244. if (syn) return !badLines.length;
  1245. else if (badLines.length) { console.warn('SyntaxError'); console.dir(badLines); this.manualFix(badLines); }
  1246. else HITStorage.write(this.data, cbImport);
  1247. },//}}}
  1248. manualFix: function(lr) {//{{{
  1249. var div = document.body.appendChild(document.createElement('DIV')),
  1250. title = div.appendChild(document.createElement('P')),
  1251. divInner = div.appendChild(document.createElement('DIV')),
  1252. buttons = div.appendChild(document.createElement('P')),
  1253. trimSansTab = function(str) {
  1254. var c = "[ \f\n\r\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+";
  1255. return str.replace(new RegExp("^"+c),'').replace(new RegExp(c+"$"),'');
  1256. },
  1257. kdFn = function(e) {
  1258. if (e.keyCode === 9) {// tab
  1259. e.preventDefault();
  1260. var zs = e.target.selectionStart,
  1261. ze = e.target.selectionEnd;
  1262. e.target.value = e.target.value.substr(0,zs) + '\t' + e.target.value.substr(ze);
  1263. }
  1264. e.target.style.height = '1px';
  1265. e.target.style.height = e.target.scrollHeight + 10 +'px';
  1266. },
  1267. blurFn = function(e) {
  1268. var check = this.core([trimSansTab(e.target.value)],true);
  1269. if (check) e.target.style.background = '#9EFF9E'; else e.target.style.background = 'white';
  1270. }.bind(this);
  1271. title.outerHTML = '<p style="margin:0;text-align:center;font-weight:bold;font-size:1.2em">Failed lines</p>' +
  1272. '<p style="text-align:center;font-weight:bold;font-size:0.9em;margin:1%">' + this.header.join(this.delimiter)+'</p>';
  1273. div.style.cssText = "z-index:5; position:fixed; top:50%;left:50%; padding:0.7%; width:650px; resize:both; overflow:auto;" +
  1274. "background:rgba(204,204,204,0.88); box-shadow: 0px 0px 15px 2px #000; margin-right:-50%; transform:translate(-50%, -50%);";
  1275. divInner.style.cssText = "position:relative; max-height:350px; overflow:auto;";
  1276. for (var v of lr) {
  1277. divInner.appendChild(document.createTextNode(v.reason));
  1278. var ta = divInner.appendChild(document.createElement('TEXTAREA'));
  1279. ta.style.cssText = "resize:none; overflow:hidden; width:100%; display:block";
  1280. ta.onkeydown = kdFn;
  1281. ta.onblur = blurFn;
  1282. ta.value = v.record.join(this.delimiter);
  1283. ta.style.height = ta.scrollHeight + 10 + 'px';
  1284. }
  1285. buttons.style.cssText = "margin:1% auto; text-align:center;";
  1286. buttons.innerHTML = '<button id="fretry" title="Retry failed lines.")">Retry</button> ' +
  1287. '<button id="fskip" title="Skip these failed lines and import the rest to the database.">Skip</button> ' +
  1288. '<button id="fcancel" title="Cancel the entire import process">Cancel</button><br>' +
  1289. 'Modify the above entries and retry, or skip them, or cancel the entire import.';
  1290. buttons.querySelector('#fretry').onclick = function() {
  1291. var l = [];
  1292. for (var el of div.querySelectorAll('textarea')) l.push(trimSansTab(el.value));
  1293. this.core(l);
  1294. div.remove();
  1295. }.bind(this);
  1296. buttons.querySelector('#fskip').onclick = function() { div.remove(); HITStorage.write(this.data, cbImport); }.bind(this);
  1297. buttons.querySelector('#fcancel').onclick = function() { div.remove(); this.data = null; Progress.hide();}.bind(this);
  1298. }//}}}
  1299. }//}}} FileHandler::csv
  1300. };//}}}
  1301.  
  1302. /*
  1303. *
  1304. *
  1305. *
  1306. *
  1307. *///{{{
  1308. console.log('hdb hook');
  1309. if (document.location.pathname === "/mturk/dashboard") {
  1310. DashboardUI.draw();
  1311. DashboardUI.initClickables();
  1312. ProjectedEarnings.updateDate();
  1313. ProjectedEarnings.draw(true);
  1314.  
  1315. var Status = {
  1316. node: document.getElementById("hdbStatusText"),
  1317. get message() { return this.node.textContent; },
  1318. set message(str) { this.node.textContent = str; },
  1319. get color() { return this.node.style.color; },
  1320. set color(c) { this.node.style.color = c; },
  1321. push: function(m,c) { c = c || "black"; this.message = m; this.color = c; },
  1322. get html() { return this.node.innerHTML },
  1323. set html(str) { this.node.innerHTML = str; }
  1324. }, Progress = {
  1325. node: document.getElementById("hdbProgressBar"),
  1326. hide: function() { this.node.style.display = "none"; },
  1327. show: function() { this.node.style.display = "block"; }
  1328. };
  1329.  
  1330. var dbh = window.indexedDB.open(DB_NAME, DB_VERSION);
  1331. dbh.onerror = function(e) { Utils.errorHandler(e.target.error); };
  1332. dbh.onupgradeneeded = HITStorage.versionChange;
  1333. dbh.onsuccess = INITDB;
  1334.  
  1335. // export some variables for external extensions
  1336. self.Status = Status; self.Progress = Progress; self.Metrics = Metrics; self.Math.decRound = Math.decRound;
  1337. } else { // page is not dashboard
  1338. window.indexedDB.open(DB_NAME).onsuccess = function() { HITStorage.db = this.result; beenThereDoneThat(); };
  1339. }
  1340. /*}}}
  1341. *
  1342. *
  1343. *
  1344. *
  1345. */
  1346.  
  1347. function saveState(key, value) {//{{{
  1348. try {
  1349. localStorage.setItem(key,value);
  1350. } catch(err) {
  1351. if (err.name !== 'QuotaExceededError') return Utils.errorHandler(err);
  1352. try {
  1353. localStorage.removeItem(key);
  1354. localStorage.setItem(key, value);
  1355. } catch(errr) {
  1356. return Utils.errorHandler(errr);
  1357. }
  1358. }
  1359. }//}}}
  1360.  
  1361. // {{{ css injection
  1362. var css = "<style type='text/css'>" +
  1363. "#hdbProgressBar {margin:auto; width:250px; height:15px; position:relative; display:none;}" +
  1364. ".ball {position:absolute; left:0; width:12px; height:12px; border-radius:5px;" +
  1365. "animation:kfpballs 2s cubic-bezier(0.24,0.77,0.68,1) infinite;" +
  1366. "background:linear-gradient(222deg, rgba(208,69,247,0), rgba(208,69,247,1), rgba(69,197,247,1), rgba(69,197,247,0))}" +
  1367. "#hdbB2{animation-delay:.19s} #hdbB3{animation-delay:.38s} #hdbB4{animation-delay:.55s}" +
  1368. "@keyframes kfpballs {0% {left:0%;opacity:1} 50% {left:98%;opacity:0.2} 100% {left:0%;opacity:1}}" +
  1369. ".hitdbRTButtons {border:1px solid; font-size: 10px; height: 18px; padding-left: 5px; padding-right: 5px; background: pink;}" +
  1370. ".hitdbRTButtons-green {background: lightgreen;}" +
  1371. ".hitdbRTButtons-large {width:80px;}" +
  1372. ".hdbCalControls {cursor:pointer;} .hdbCalControls:hover {color:#c27fcf;}" +
  1373. ".hdbCalCells {background:#f0f6f9; height:19px}" +
  1374. ".hdbCalDays {cursor:pointer; text-align:center;} .hdbCalDays:hover {background:#7fb4cf; color:white;}" +
  1375. ".hdbDayHeader {width:26px; text-align:center; font-weight:bold; font-size:12px; background:#f0f6f9;}" +
  1376. ".hdbCalHeader {background:#7fb4cf; color:white; font-weight:bold; text-align:center; font-size:11px; padding:3px 0px;}" +
  1377. "#hdbCalendarPanel {position:absolute; z-index:10; box-shadow:-2px 3px 5px 0px rgba(0,0,0,0.68);}" +
  1378. ".hdbExpandRow {cursor:pointer; color:blue;}" +
  1379. ".hdbTotalsRow {background:#CCC; color:#369; font-weight:bold;}" +
  1380. ".hdbHeaderRow {background:#7FB448; font-size:12px; color:white;}" +
  1381. ".helpSpan {border-bottom:1px dotted; cursor:help;}" +
  1382. ".hdbResControl {border-bottom:1px solid; color:#c60; cursor:pointer; display:none;}" +
  1383. ".hdbTablePagination {margin-left:15em; color:#c60; display:none;}" +
  1384. ".spin {animation: kfspin 0.7s infinite linear; font-weight:bold;}" +
  1385. "@keyframes kfspin { 0% { transform: rotate(0deg) } 100% { transform: rotate(359deg) } }" +
  1386. ".spin:before{content:'*'}" +
  1387. ".nowrap {white-space:nowrap; overflow:hidden; text-overflow:ellipsis}" +
  1388. "</style>";
  1389. document.head.innerHTML += css;
  1390. // }}}
  1391.  
  1392. function resultConstrain(data, index, type, callback) {//{{{
  1393. data = data || qc.sr;
  1394.  
  1395. var table = document.getElementById("hdbResultsTable"),
  1396. rslice = data.length ? data[index].results : data.results,
  1397. pager = [document.getElementById("hdbPageTop"), document.getElementById("hdbPageBot")],
  1398. sopt = [],
  1399. _f = function(e) { resultConstrain(null,e.target.value,type,callback); };
  1400. pager[0].innerHTML = ''; pager[1].innerHTML = '';
  1401.  
  1402. if (data instanceof DBResult)
  1403. table.innerHTML = data.formatHTML(type);
  1404. else {
  1405. table.innerHTML = data[index].formatHTML(type);
  1406. pager[0].innerHTML = '<span style="cursor:pointer;">' + (index > 0 ? '&#9664; Prev' : '') + '</span> ' +
  1407. '<span style="cursor:pointer;">' + (+index+1 === data.length ? '' : 'Next &#9654;') + '</span> &nbsp; || &nbsp; '+
  1408. '<label>Select page: </label><select></select>';
  1409. for (var i=0;i<data.length;i++) {
  1410. if (i === +index)
  1411. sopt.push('<option value="' + i + '" selected="selected">' + (i+1) + '</option>');
  1412. else
  1413. sopt.push('<option value="' + i + '">' + (i+1) + '</option>');
  1414. }
  1415. pager[0].lastChild.innerHTML = sopt.join('');
  1416. pager[2] = pager[0].cloneNode(true);
  1417. pager[2].id = "hdbPageBot";
  1418. for (i of [0,2]) {
  1419. pager[i].children[0].onclick = resultConstrain.bind(null,null,+index-1,type,callback);
  1420. pager[i].children[1].onclick = resultConstrain.bind(null,null,+index+1,type,callback);
  1421. pager[i].children[3].onchange = _f;
  1422. }
  1423. pager[0].parentNode.replaceChild(pager[2], pager[1]);
  1424. }
  1425.  
  1426. callback(rslice);
  1427. }//}}} resultConstrain
  1428.  
  1429. function beenThereDoneThat() {//{{{
  1430. if (~document.location.pathname.search(/(accept|continue)/)) {
  1431. if (!document.querySelector('input[name="hitAutoAppDelayInSeconds"]')) return;
  1432.  
  1433. // capture autoapproval times
  1434. var _aa = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  1435. _hid = document.querySelectorAll('input[name="hitId"]')[1].value,
  1436. pad = function(num) { return Number(num).toPadded(); },
  1437. _d = Date.parse(new Date().getFullYear() + "-" + pad(new Date().getMonth()+1) + "-" + pad(new Date().getDate()));
  1438. qc.aat = JSON.parse(localStorage.getItem("hitdb_autoAppTemp") || "{}");
  1439.  
  1440. if (!qc.aat[_d]) qc.aat[_d] = {};
  1441. qc.aat[_d][_hid] = _aa;
  1442. qc.save("aat", "hitdb_autoAppTemp", true);
  1443. return;
  1444. }
  1445. var qualNode = document.querySelector('td[colspan="11"]');
  1446. if (qualNode) { // we're on the preview page!
  1447. var requesterid = document.querySelector('input[name="requesterId"]').value,
  1448. requestername = document.querySelector('input[name="prevRequester"]').value,
  1449. autoApproval = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  1450. hitTitle = document.querySelector('div[style*="ellipsis"]').textContent.trim(),
  1451. insertionNode = qualNode.parentNode.parentNode;
  1452. var row = document.createElement("TR"), cellL = document.createElement("TD"), cellR = document.createElement("TD");
  1453. var resultsTableR = document.createElement("TABLE"),
  1454. resultsTableT = document.createElement("TABLE");
  1455. resultsTableR.dataset.rid = requesterid;
  1456. resultsTableT.dataset.title = hitTitle;
  1457. insertionNode.parentNode.parentNode.appendChild(resultsTableR);
  1458. insertionNode.parentNode.parentNode.appendChild(resultsTableT);
  1459.  
  1460. cellR.innerHTML = '<span class="capsule_field_title">Auto-Approval:</span>&nbsp;&nbsp;'+Utils.ftime(autoApproval);
  1461. var rbutton = document.createElement("BUTTON");
  1462. rbutton.classList.add("hitdbRTButtons","hitdbRTButtons-large");
  1463. rbutton.textContent = "Requester";
  1464. rbutton.onclick = function(e) { e.preventDefault(); showResults.call(resultsTableR, "req", hitTitle); };
  1465. var tbutton = rbutton.cloneNode(false);
  1466. rbutton.title = "Show HITs completed from this requester";
  1467. tbutton.textContent = "HIT Title";
  1468. tbutton.onclick = function(e) { e.preventDefault(); showResults.call(resultsTableT, "title", requestername) };
  1469. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(requesterid), limit: 1})
  1470. .then(processResults.bind(rbutton,resultsTableR));
  1471. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(hitTitle), limit: 1})
  1472. .then(processResults.bind(tbutton,resultsTableT));
  1473. row.appendChild(cellL);
  1474. row.appendChild(cellR);
  1475. cellL.appendChild(rbutton);
  1476. cellL.appendChild(tbutton);
  1477. cellL.colSpan = "3";
  1478. cellR.colSpan = "8";
  1479. insertionNode.appendChild(row);
  1480. } else { // browsing HITs n sutff
  1481. var titleNodes = document.querySelectorAll('a[class="capsulelink"]');
  1482. if (titleNodes.length < 1) return; // nothing left to do here!
  1483. var requesterNodes = document.querySelectorAll('a[href*="hitgroups&requester"]');
  1484. var insertionNodes = [];
  1485.  
  1486. for (var i=0;i<titleNodes.length;i++) {
  1487. var _title = titleNodes[i].textContent.trim();
  1488. var _tbutton = document.createElement("BUTTON");
  1489. var _id = requesterNodes[i].href.replace(/.+Id=(.+)/, "$1");
  1490. var _name = requesterNodes[i].textContent;
  1491. var _rbutton = document.createElement("BUTTON");
  1492. var _div = document.createElement("DIV"), _tr = document.createElement("TR");
  1493. resultsTableR = document.createElement("TABLE");
  1494. resultsTableR.dataset.rid = _id;
  1495. resultsTableT = document.createElement("TABLE");
  1496. resultsTableT.dataset.title = _title;
  1497. insertionNodes.push(requesterNodes[i].parentNode.parentNode.parentNode);
  1498. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(resultsTableR);
  1499. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(resultsTableT);
  1500.  
  1501. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(_title), limit: 1} )
  1502. .then(processResults.bind(_tbutton,resultsTableT));
  1503. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(_id), limit: 1} )
  1504. .then(processResults.bind(_rbutton,resultsTableR));
  1505.  
  1506. _tr.appendChild(_div);
  1507. _div.id = "hitdbRTInjection-"+i;
  1508. _div.appendChild(_rbutton);
  1509. _rbutton.textContent = 'R';
  1510. _rbutton.classList.add("hitdbRTButtons");
  1511. _rbutton.onclick = showResults.bind(resultsTableR, "req", _title);
  1512. _rbutton.title = "Show HITs completed from this requester";
  1513. _div.appendChild(_tbutton);
  1514. _tbutton.textContent = 'T';
  1515. _tbutton.classList.add("hitdbRTButtons");
  1516. _tbutton.onclick = showResults.bind(resultsTableT, "title", _name);
  1517. insertionNodes[i].appendChild(_tr);
  1518. }
  1519. } // else
  1520.  
  1521. function showResults(type, match) {//{{{
  1522. /*jshint validthis: true*/
  1523. if (!this.dataset.hasResults) return;
  1524. if (this.children.length) // table is populated
  1525. this.innerHTML = '';
  1526. else { // need to populate table
  1527. var head = this.createTHead(),
  1528. body = this.createTBody(),
  1529. capt = this.createCaption(),
  1530. style= "font-size:10px;font-weight:bold;text-align:center",
  1531. validKeys = function(obj) { return Object.keys(obj).filter(function(v) { return !~v.search(/total[A-Z]/); }); };
  1532.  
  1533. capt.innerHTML = '<span style="'+style+'">Loading...<label class="spin"></label></span>';
  1534.  
  1535. if (type === "req") {
  1536. HITStorage.recall("HIT", {index:"requesterId", range:window.IDBKeyRange.only(this.dataset.rid)})
  1537. .then( function(r) {
  1538. var cbydate = r.collate(r.results, "date"),
  1539. kbydate = validKeys(cbydate),
  1540. cbydatextitle, kbytitle, bodyHTML = [];
  1541. kbydate.forEach(function(date) {
  1542. cbydatextitle = r.collate(cbydate[date], "title");
  1543. kbytitle = validKeys(cbydatextitle);
  1544. kbytitle.forEach(function(title) {
  1545. bodyHTML.push('<tr style="text-align:center;"><td>'+date+'</td>' +
  1546. '<td style="text-align:left">'+title.trim()+'</td><td>'+cbydatextitle[title].length+'</td>' +
  1547. '<td>'+Number(Math.decRound(cbydatextitle[title].pay,2)).toFixed(2)+'</td></tr>');
  1548. });
  1549. });
  1550. var help = "Total number of HITs submitted for a given date with the same title\n" +
  1551. "(aggregates results with the same title to simplify the table and reduce unnecessary spam for batch workers)";
  1552. head.innerHTML = '<tr style="'+style+'"><th>Date</th><th>Title</th>' +
  1553. '<th><span class="helpSpan" title="'+help+'">#HITs</span></th><th>Total Rewards</th></tr>';
  1554. body.innerHTML = bodyHTML.sort(function(a,b) {
  1555. return a.match(/\d{4}-\d{2}-\d{2}/)[0] < b.match(/\d{4}-\d{2}-\d{2}/)[0] ? 1 : -1;
  1556. }).join('');
  1557. capt.innerHTML = '<label style="'+style+'">HITs Matching This Requester</label>';
  1558.  
  1559. var mrows = Array.prototype.filter.call(body.rows, function(v) {return v.cells[1].textContent === match});
  1560. for (var row of mrows)
  1561. row.style.background = "lightgreen";
  1562. });
  1563. }
  1564. else if (type === "title") {
  1565. HITStorage.recall("HIT", {index:"title", range:window.IDBKeyRange.only(this.dataset.title)})
  1566. .then( function(r) {
  1567. var cbyreq = r.collate(r.results, "requesterName"),
  1568. kbyreq = validKeys(cbyreq),
  1569. bodyHTML = [];
  1570. for (var key of kbyreq)
  1571. bodyHTML.push('<tr style="text-align:center;"><td>'+key+'</td><td>'+cbyreq[key].length+'</td>' +
  1572. '<td>'+Number(Math.decRound(cbyreq[key].pay,2)).toFixed(2)+'</td></tr>');
  1573. var help = "Total number of HITs matching this title submitted for a given requester\n" +
  1574. "(aggregates results with the same requester name to simplify the table and reduce unnecessary spam for batch workers)";
  1575. head.innerHTML = '<tr style="'+style+'"><th>Requester Name</th>' +
  1576. '<th><span class="helpSpan" title="'+help+'">#HITs</span></th><th>Total Rewards</th></tr>';
  1577. body.innerHTML = bodyHTML.join('');
  1578. capt.innerHTML = '<label style="'+style+'">Reqesters With HITs Matching This Title</label>';
  1579.  
  1580. var mrows = Array.prototype.filter.call(body.rows, function(v) {return v.cells[0].textContent === match});
  1581. for (var row of mrows)
  1582. row.style.background = "lightgreen";
  1583. });
  1584. } //if type === 'title'
  1585. }//populate table
  1586. }//}}} showResults
  1587.  
  1588. function processResults(table, r) {
  1589. /*jshint validthis: true*/
  1590. if (r.results.length) {
  1591. table.dataset.hasResults = "true";
  1592. this.classList.add("hitdbRTButtons-green");
  1593. }
  1594. }
  1595. }//}}} btdt
  1596.  
  1597. function showHiddenRows(e) {//{{{
  1598. var rid = e.target.parentNode.textContent.substr(4);
  1599. var nodes = document.querySelectorAll('tr[data-rid="'+rid+'"]'), el = null;
  1600. if (e.target.textContent === "[+]") {
  1601. for (el of nodes)
  1602. el.style.display="table-row";
  1603. e.target.textContent = "[-]";
  1604. } else {
  1605. for (el of nodes)
  1606. el.style.display="none";
  1607. e.target.textContent = "[+]";
  1608. }
  1609. }//}}}
  1610.  
  1611. function showHitsByDate(e) {//{{{
  1612. var date = e.target.parentNode.nextSibling.textContent,
  1613. row = e.target.parentNode.parentNode,
  1614. table= row.parentNode;
  1615.  
  1616. if (e.target.textContent === "[+]") {
  1617. e.target.textContent = "[-]";
  1618. var nrow = table.insertBefore(document.createElement("TR"), row.nextSibling);
  1619. nrow.className = row.className;
  1620. nrow.innerHTML = '<td><b>Loading...<label class="spin"></label></b></td>';
  1621. HITStorage.recall("HIT", {index: "date", range: window.IDBKeyRange.only(date)}).then( function(r) {
  1622. nrow.innerHTML = '<td colspan="7"><table style="width:760;color:#c60;">' + r.formatHTML(null,true) + '</table></td>';
  1623. });
  1624. } else {
  1625. e.target.textContent = "[+]";
  1626. table.removeChild(row.nextSibling);
  1627. }
  1628. }//}}} showHitsByDate
  1629.  
  1630. function updateBonus(e) {//{{{
  1631. if (e instanceof window.KeyboardEvent && e.keyCode === 13) {
  1632. e.target.blur();
  1633. return false;
  1634. } else if (e instanceof window.FocusEvent) {
  1635. var _bonus = +e.target.textContent.replace(/[^\d.]/g,""),
  1636. _tBonusCell = e.target.offsetParent.tFoot.rows[0].cells[4],
  1637. _tBonus = +_tBonusCell.textContent.replace(/\$/,"");
  1638. e.target.textContent = Number(_bonus).toFixed(2);
  1639. _tBonusCell.textContent = '$'+Number(_tBonus-e.target.dataset.initial+_bonus).toFixed(2);
  1640. if (_bonus !== +e.target.dataset.initial) {
  1641. console.log("updating bonus to",_bonus,"from",e.target.dataset.initial,"("+e.target.dataset.hitid+")");
  1642. e.target.dataset.initial = _bonus;
  1643. var _range = window.IDBKeyRange.only(e.target.dataset.hitid);
  1644.  
  1645. HITStorage.db.transaction("HIT", "readwrite").objectStore("HIT").openCursor(_range).onsuccess = function() {
  1646. var c = this.result;
  1647. if (c) {
  1648. c.value.bonus = _bonus;
  1649. c.update(c.value);
  1650. }
  1651. }; // idbcursor
  1652. } // bonus is new value
  1653. } // keycode
  1654. } //}}} updateBonus
  1655.  
  1656. function noteHandler(type, e) {//{{{
  1657. //
  1658. // TODO restructure event handling/logic tree
  1659. // combine save and delete; it's ugly :(
  1660. // actually this whole thing is messy and in need of refactoring
  1661. //
  1662. if (e instanceof window.KeyboardEvent) {
  1663. if (e.keyCode === 13) {
  1664. e.target.blur();
  1665. return false;
  1666. }
  1667. return;
  1668. }
  1669.  
  1670. if (e instanceof window.FocusEvent) {
  1671. if (e.target.textContent.trim() !== e.target.dataset.initial) {
  1672. if (!e.target.textContent.trim()) { e.target.previousSibling.previousSibling.firstChild.click(); return; }
  1673. var note = e.target.textContent.trim(),
  1674. _range = window.IDBKeyRange.only(e.target.dataset.id),
  1675. inote = e.target.dataset.initial,
  1676. hitId = e.target.dataset.id,
  1677. date = e.target.previousSibling.textContent;
  1678.  
  1679. e.target.dataset.initial = note;
  1680. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1681. if (this.result) {
  1682. var r = this.result.value;
  1683. if (r.note === inote) { // note already exists in database, so we update its value
  1684. r.note = note;
  1685. this.result.update(r);
  1686. return;
  1687. }
  1688. this.result.continue();
  1689. } else {
  1690. if (this.source instanceof window.IDBObjectStore)
  1691. this.source.put({ note:note, date:date, hitId:hitId });
  1692. else
  1693. this.source.objectStore.put({ note:note, date:date, hitId:hitId });
  1694. }
  1695. };
  1696. }
  1697. return; // end of save event; no need to proceed
  1698. }
  1699.  
  1700. if (type === "delete") {
  1701. var tr = e.target.parentNode.parentNode,
  1702. noteCell = tr.lastChild;
  1703. _range = window.IDBKeyRange.only(noteCell.dataset.id);
  1704. if (!noteCell.dataset.initial) tr.remove();
  1705. else {
  1706. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1707. if (this.result) {
  1708. if (this.result.value.note === noteCell.dataset.initial) {
  1709. this.result.delete();
  1710. tr.remove();
  1711. return;
  1712. }
  1713. this.result.continue();
  1714. }
  1715. };
  1716. }
  1717. return; // end of deletion event; no need to proceed
  1718. } else {
  1719. if (type === "attach" && !e.results.length) return;
  1720.  
  1721. var trow = e instanceof window.MouseEvent ? e.target.parentNode.parentNode : null,
  1722. tbody = trow ? trow.parentNode : null,
  1723. row = document.createElement("TR"),
  1724. c1 = row.insertCell(0),
  1725. c2 = row.insertCell(1),
  1726. c3 = row.insertCell(2);
  1727. date = new Date();
  1728. hitId = e instanceof window.MouseEvent ? e.target.id.substr(5) : null;
  1729.  
  1730. c1.innerHTML = '<span class="removeNote" title="Delete this note" style="cursor:pointer;color:crimson;">[x]</span>';
  1731. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1732. c1.style.textAlign = "right";
  1733. c2.title = "Date on which the note was added";
  1734. c3.style.color = "crimson";
  1735. c3.colSpan = "6";
  1736. c3.contentEditable = "true";
  1737. c3.onblur = noteHandler.bind(null,"blur");
  1738. c3.onkeydown = noteHandler.bind(null, "kb");
  1739. if (type === "new") {
  1740. row.classList.add(trow.classList);
  1741. tbody.insertBefore(row, trow.nextSibling);
  1742. c2.textContent = date.getFullYear()+"-"+Number(date.getMonth()+1).toPadded()+"-"+Number(date.getDate()).toPadded();
  1743. c3.dataset.initial = "";
  1744. c3.dataset.id = hitId;
  1745. c3.focus();
  1746. return;
  1747. }
  1748.  
  1749. for (var entry of e.results) {
  1750. trow = document.querySelector('tr[data-id="'+entry.hitId+'"]');
  1751. tbody = trow.parentNode;
  1752. row = row.cloneNode(true);
  1753. c1 = row.firstChild;
  1754. c2 = c1.nextSibling;
  1755. c3 = row.lastChild;
  1756. row.classList.add(trow.classList);
  1757. tbody.insertBefore(row, trow.nextSibling);
  1758.  
  1759. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1760. c2.textContent = entry.date;
  1761. c3.textContent = entry.note;
  1762. c3.dataset.initial = entry.note;
  1763. c3.dataset.id = entry.hitId;
  1764. c3.onblur = noteHandler.bind(null,"blur");
  1765. c3.onkeydown = noteHandler.bind(null, "kb");
  1766. }
  1767. } // new/attach
  1768. }//}}} noteHandler
  1769.  
  1770. // writing callback functions {{{
  1771. function cbImport() {
  1772. /*jshint validthis:true*/
  1773. Status.push("Importing " + this.total + " entries");
  1774. if (++this.total !== this.requests) return;
  1775. Status.push("Importing " + this.total + " entries... Done!", "green");
  1776. try { Progress.hide(); metrics.dbimport.stop(); metrics.dbimport.report(); } catch(err) {}
  1777. }
  1778. function cbUpdate() {
  1779. /*jshint validthis:true*/
  1780. if (++this.total !== this.requests) return;
  1781. if (qc.extraDays) qc.extraDays = false;
  1782. Status.push("Update Complete!", "green");
  1783. ProjectedEarnings.data.dbUpdated = new Date().toLocalISOString();
  1784. ProjectedEarnings.saveState();
  1785. ProjectedEarnings.draw(false);
  1786. Utils.disableButtons(['hdbUpdate'], false);
  1787. Progress.hide(); metrics.dbupdate.stop(); metrics.dbupdate.report();
  1788. }
  1789. //}}}
  1790.  
  1791. function autoScroll(location, dt) {//{{{
  1792. var target = document.querySelector(location).offsetTop,
  1793. pos = window.scrollY,
  1794. dpos = Math.ceil((target - pos)/3);
  1795. dt = dt ? dt-1 : 25; // time step/max recursions
  1796.  
  1797. if (target === pos || dpos === 0 || dt === 0) return;
  1798.  
  1799. window.scrollBy(0, dpos);
  1800. setTimeout(function() { autoScroll(location, dt); }, dt);
  1801. }//}}}
  1802.  
  1803. function Calendar(offsetX, offsetY, caller) {//{{{
  1804. this.date = new Date();
  1805. this.offsetX = offsetX;
  1806. this.offsetY = offsetY;
  1807. this.caller = caller;
  1808. this.drawCalendar = function(year,month,day) {//{{{
  1809. year = year || this.date.getFullYear();
  1810. month = month || this.date.getMonth()+1;
  1811. day = day || this.date.getDate();
  1812. var longMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  1813. var date = new Date(year,month-1,day);
  1814. var anchors = _getAnchors(date);
  1815.  
  1816. //make new container if one doesn't already exist
  1817. var container = null;
  1818. if (document.querySelector("#hdbCalendarPanel")) {
  1819. container = document.querySelector("#hdbCalendarPanel");
  1820. container.removeChild( container.getElementsByTagName("TABLE")[0] );
  1821. }
  1822. else {
  1823. container = document.createElement("DIV");
  1824. container.id = "hdbCalendarPanel";
  1825. document.body.appendChild(container);
  1826. }
  1827. container.style.left = this.offsetX;
  1828. container.style.top = this.offsetY;
  1829. var cal = document.createElement("TABLE");
  1830. cal.cellSpacing = "0";
  1831. cal.cellPadding = "0";
  1832. cal.border = "0";
  1833. container.appendChild(cal);
  1834. cal.innerHTML = '<tr>' +
  1835. '<th class="hdbCalHeader hdbCalControls" title="Previous month" style="text-align:right;"><span>&lt;</span></th>' +
  1836. '<th class="hdbCalHeader hdbCalControls" title="Previous year" style="text-align:center;"><span>&#8810;</span></th>' +
  1837. '<th colspan="3" id="hdbCalTableTitle" class="hdbCalHeader">'+date.getFullYear()+'<br>'+longMonths[date.getMonth()]+'</th>' +
  1838. '<th class="hdbCalHeader hdbCalControls" title="Next year" style="text-align:center;"><span>&#8811;</span></th>' +
  1839. '<th class="hdbCalHeader hdbCalControls" title="Next month" style="text-align:left;"><span>&gt;</span></th>' +
  1840. '</tr><tr><th class="hdbDayHeader" style="color:red;">S</th><th class="hdbDayHeader">M</th>' +
  1841. '<th class="hdbDayHeader">T</th><th class="hdbDayHeader">W</th><th class="hdbDayHeader">T</th>' +
  1842. '<th class="hdbDayHeader">F</th><th class="hdbDayHeader">S</th></tr>';
  1843. document.querySelector('th[title="Previous month"]').addEventListener( "click", function() {
  1844. this.drawCalendar(date.getFullYear(), date.getMonth(), 1);
  1845. }.bind(this) );
  1846. document.querySelector('th[title="Previous year"]').addEventListener( "click", function() {
  1847. this.drawCalendar(date.getFullYear()-1, date.getMonth()+1, 1);
  1848. }.bind(this) );
  1849. document.querySelector('th[title="Next month"]').addEventListener( "click", function() {
  1850. this.drawCalendar(date.getFullYear(), date.getMonth()+2, 1);
  1851. }.bind(this) );
  1852. document.querySelector('th[title="Next year"]').addEventListener( "click", function() {
  1853. this.drawCalendar(date.getFullYear()+1, date.getMonth()+1, 1);
  1854. }.bind(this) );
  1855.  
  1856. var hasDay = false, thisDay = 1;
  1857. for (var i=0;i<6;i++) { // cycle weeks
  1858. var row = document.createElement("TR");
  1859. for (var j=0;j<7;j++) { // cycle days
  1860. if (!hasDay && j === anchors.first && thisDay < anchors.total)
  1861. hasDay = true;
  1862. else if (hasDay && thisDay > anchors.total)
  1863. hasDay = false;
  1864.  
  1865. var cell = document.createElement("TD");
  1866. cell.classList.add("hdbCalCells");
  1867. row.appendChild(cell);
  1868. if (hasDay) {
  1869. cell.classList.add("hdbCalDays");
  1870. cell.textContent = thisDay;
  1871. cell.addEventListener("click", _clickHandler.bind(this));
  1872. cell.dataset.year = date.getFullYear();
  1873. cell.dataset.month = date.getMonth()+1;
  1874. cell.dataset.day = thisDay++;
  1875. }
  1876. } // for j
  1877. cal.appendChild(row);
  1878. } // for i
  1879. var controls = cal.insertRow(-1);
  1880. controls.insertCell(0);
  1881. controls.cells[0].colSpan = "7";
  1882. controls.cells[0].classList.add("hdbCalCells");
  1883. controls.cells[0].innerHTML = ' &nbsp; &nbsp; <a href="javascript:void(0)" style="font-weight:bold;text-decoration:none;">Clear</a>' +
  1884. ' &nbsp; <a href="javascript:void(0)" style="font-weight:bold;text-decoration:none;">Close</a>';
  1885. controls.cells[0].children[0].onclick = function() { this.caller.value = ""; }.bind(this);
  1886. controls.cells[0].children[1].onclick = this.die;
  1887.  
  1888. function _clickHandler(e) {
  1889. /*jshint validthis:true*/
  1890.  
  1891. var y = e.target.dataset.year;
  1892. var m = Number(e.target.dataset.month).toPadded();
  1893. var d = Number(e.target.dataset.day).toPadded();
  1894. this.caller.value = y+"-"+m+"-"+d;
  1895. this.die();
  1896. }
  1897.  
  1898. function _getAnchors(date) {
  1899. var _anchors = {};
  1900. date.setMonth(date.getMonth()+1);
  1901. date.setDate(0);
  1902. _anchors.total = date.getDate();
  1903. date.setDate(1);
  1904. _anchors.first = date.getDay();
  1905. return _anchors;
  1906. }
  1907. };//}}} drawCalendar
  1908.  
  1909. this.die = function() { document.getElementById('hdbCalendarPanel').remove(); };
  1910.  
  1911. }//}}} Calendar
  1912.  
  1913. // instance metrics apart from window scoped PerformanceTiming API
  1914. function Metrics(name) {//{{{
  1915. this.name = name || "undefined";
  1916. this.marks = {};
  1917. this.start = window.performance.now();
  1918. this.end = null;
  1919. this.stop = function(){
  1920. if (!this.end)
  1921. this.end = window.performance.now();
  1922. else
  1923. Utils.errorHandler(new Error("Metrics::AccessViolation - end point cannot be overwritten"));
  1924. };
  1925. this.mark = function(name,position) {
  1926. if (position === "end" && !this.marks[name]) return;
  1927.  
  1928. if (!this.marks[name])
  1929. this.marks[name] = {};
  1930. if (!this.marks[name][position])
  1931. this.marks[name][position] = window.performance.now();
  1932. };
  1933. this.report = function() {
  1934. console.group("Metrics for",this.name.toUpperCase());
  1935. console.log("Process completed in",+Number((this.end-this.start)/1000).toFixed(3),"seconds");
  1936. for (var k in this.marks) {
  1937. if (this.marks.hasOwnProperty(k)) {
  1938. console.log(k,"occurred after",+Number((this.marks[k].start-this.start)/1000).toFixed(3),"seconds,",
  1939. "resolving in", +Number((this.marks[k].end-this.marks[k].start)/1000).toFixed(3), "seconds");
  1940. }
  1941. }
  1942. console.groupEnd();
  1943. };
  1944. }//}}}
  1945.  
  1946. function INITDB() {//{{{
  1947. HITStorage.db = this.result;
  1948. self.HITStorage = {db: this.result};
  1949. if (localStorage.getItem('hitdb_ridx') === 'true') return;
  1950.  
  1951. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], true);
  1952. var count = 0;
  1953. this.result.transaction('HIT', 'readwrite').objectStore('HIT').openCursor().onsuccess = function() {
  1954. if (!this.result) {
  1955. Status.push('Done.');
  1956. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], false);
  1957. return localStorage.setItem('hitdb_ridx', 'true');
  1958. }
  1959. Status.push('Performing integrity check... ' + (++count));
  1960. var r = this.result.value;
  1961. if (typeof r.reward === 'object') {
  1962. r.bonus = r.reward.bonus;
  1963. r.reward = r.reward.pay;
  1964. this.result.update(r);
  1965. }
  1966. this.result.continue();
  1967. }
  1968. }//}}}
  1969. })(); //scoping
  1970.  
  1971. // vim: ts=2:sw=2:et:fdm=marker:noai