MTurk HIT Database Mk.II

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

目前為 2015-09-02 提交的版本,檢視 最新版本

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