MTurk HIT Database Mk.II

Keep track of the HITs you've done (and more!)

目前为 2015-09-15 提交的版本。查看 最新版本

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