MTurk HIT Database Mk.II

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

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

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