MTurk HIT Database Mk.II

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

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

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