MTurk HIT Database Mk.II

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

当前为 2015-09-14 提交的版本,查看 最新版本

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