MTurk HIT Database Mk.II

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

当前为 2015-10-16 提交的版本,查看 最新版本

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