Greasy Fork 还支持 简体中文。

MTurk HIT Database Mk.II

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

目前為 2015-10-14 提交的版本,檢視 最新版本

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