MTurk HIT Database Mk.II

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

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

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