MTurk HIT Database Mk.II

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

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

  1. // ==UserScript==
  2. // @name MTurk HIT Database Mk.II
  3. // @author feihtality
  4. // @namespace https://greasyfork.org/en/users/12709
  5. // @version 1.0.006
  6. // @description Keep track of the HITs you've done (and more!). Cross browser compatible.
  7. // @include /^https://www\.mturk\.com/mturk/(dash|view|sort|find|prev|search|accept|cont).*/
  8. // @exclude https://www.mturk.com/mturk/findhits?*hit_scraper
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. /**\
  13. **
  14. ** This is a complete rewrite of the MTurk HIT Database script from the ground up, which
  15. ** eliminates obsolete methods, fixes many bugs, and brings this script up-to-date
  16. ** with the modern browser environment.
  17. **
  18. \**/
  19.  
  20.  
  21.  
  22.  
  23. const DB_VERSION = 7;
  24. const DB_NAME = 'HITDB';
  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. // bonus received on date with 0 HITs
  183. if (!d.submitted && !d.pending) { if (_date in qc.fetchData) delete qc.fetchData[_date]; continue; }
  184. // check whether or not we need to get status detail pages for date, then
  185. // fetch status detail pages per date in range and slightly slow
  186. // down GET requests to avoid making too many in too short an interval
  187. var payload = { encodedDate: _date, pageNumber: 1, sortType: "All" };
  188. if (_pastDataExists) {
  189. // date not in range but is new date (or old date but we need updates)
  190. // lastDate stored in ISO format, fetchData date keys stored in mturk's URI ecnodedDate format
  191. if ( (d.date > qc.fetchData.lastDate) || ~(Object.keys(qc.fetchData).indexOf(_date)) ) {
  192. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  193. timeout += 380;
  194.  
  195. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  196. }
  197. } else { // get everything
  198. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  199. timeout += 380;
  200.  
  201. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  202. }
  203. } // for
  204. qc.fetchData.expectedTotal = _calcTotals(qc.fetchData);
  205.  
  206. // try for extra days
  207. if (qc.extraDays === true) {
  208. localStorage.removeItem("hitdb_extraDays");
  209. d = _decDate(HITStorage.data.STATS[HITStorage.data.STATS.length-1].date);
  210. qc.extraDays = d; // repurpose extraDays for QC
  211. payload = { encodedDate: d, pageNumber: 1, sortType: "All" };
  212. setTimeout(HITStorage.fetch, 1000, MTURK_BASE+"statusdetail", payload);
  213. }
  214. qc.fetchData.lastDate = HITStorage.data.STATS[0].date; // most recent date seen
  215. qc.save("fetchData", "hitdb_fetchData", true);
  216.  
  217. }//}}} parseStatus
  218.  
  219. function parseDetail() {//{{{
  220. var _date = doc.documentURI.replace(/.+(\d{8}).+/, "$1"),
  221. _page = doc.documentURI.replace(/.+ber=(\d+).+/, "$1"),
  222. getBonuses = function(entry) {
  223. return new Promise( function(y) {
  224. HITStorage.db.transaction('HIT', 'readonly').objectStore('HIT').get(entry.hitId).onsuccess = function() {
  225. if (this.result && isNaN(this.result.reward))
  226. entry.reward = { pay: entry.reward, bonus: this.result.reward.bonus };
  227. HITStorage.data.HIT.push(entry); y(1);
  228. };
  229. });
  230. };
  231.  
  232. metrics.dbupdate.mark("[PRE]"+_date+"p"+_page, "end");
  233. Status.message = "Processing "+Utils.ISODate(_date)+" page "+_page;
  234. var raw = {
  235. req: doc.querySelectorAll(".statusdetailRequesterColumnValue"),
  236. title: doc.querySelectorAll(".statusdetailTitleColumnValue"),
  237. pay: doc.querySelectorAll(".statusdetailAmountColumnValue"),
  238. status: doc.querySelectorAll(".statusdetailStatusColumnValue"),
  239. feedback: doc.querySelectorAll(".statusdetailRequesterFeedbackColumnValue")
  240. };
  241.  
  242. for (var i=0;i<raw.req.length;i++) {
  243. var d = {};
  244. d.date = Utils.ISODate(_date);
  245. d.feedback = raw.feedback[i].textContent.trim();
  246. d.hitId = raw.req[i].childNodes[1].href.replace(/.+HIT\+(.+)/, "$1");
  247. d.requesterId = raw.req[i].childNodes[1].href.replace(/.+rId=(.+?)&.+/, "$1");
  248. d.requesterName = raw.req[i].textContent.trim();
  249. d.reward = +raw.pay[i].textContent.substr(1);
  250. d.status = raw.status[i].textContent.replace(/\s/g, " "); // replace char160 spaces with char32 spaces
  251. d.title = raw.title[i].textContent.trim();
  252.  
  253. // mturk apparently never marks $0.00 HITs as 'Paid' so we fix that
  254. if (!d.reward && ~d.status.search(/approved/i)) d.status = "Paid";
  255. // insert autoApproval times
  256. d.autoAppTime = HITStorage.autoApprovals.getTime(_date,d.hitId);
  257.  
  258. bonusSearch.push(getBonuses(d));
  259.  
  260. if (!qc.seen[_date]) qc.seen[_date] = {};
  261. qc.seen[_date] = {
  262. submitted: qc.seen[_date].submitted + 1 || 1,
  263. pending: ~d.status.search(/pending/i) ?
  264. (qc.seen[_date].pending + 1 || 1) : (qc.seen[_date].pending || 0)
  265. };
  266.  
  267. ProjectedEarnings.updateValues(d);
  268. }
  269.  
  270. // additional pages remain; get them
  271. if (doc.querySelector('img[src="/media/right_dbl_arrow.gif"]')) {
  272. var payload = { encodedDate: _date, pageNumber: +_page+1, sortType: "All" };
  273. setTimeout(HITStorage.fetch, 250, MTURK_BASE+"statusdetail", payload);
  274. return;
  275. }
  276.  
  277. if (!qc.extraDays) { // not fetching extra days
  278. //no longer any more useful data here, don't need to keep rechecking this date
  279. if (Utils.ISODate(_date) !== qc.fetchData.lastDate &&
  280. qc.seen[_date].submitted === qc.fetchData[_date].submitted &&
  281. qc.seen[_date].pending === 0) {
  282. console.log("no more pending hits, removing",_date,"from fetchData");
  283. delete qc.fetchData[_date];
  284. qc.save("fetchData", "hitdb_fetchData", true);
  285. HITStorage.autoApprovals.purge(_date);
  286. }
  287. // finished scraping; start writing
  288. console.log("date:", _date, "pages:", _page, "totals:", _calcTotals(qc.seen), "of", qc.fetchData.expectedTotal);
  289. Status.message += " [ "+_calcTotals(qc.seen)+"/"+ qc.fetchData.expectedTotal+" ]";
  290. if (_calcTotals(qc.seen) === qc.fetchData.expectedTotal) {
  291. Status.message = "Writing to database...";
  292. HITStorage.autoApprovals.purge();
  293. Promise.all(bonusSearch).then(function() { HITStorage.write(HITStorage.data, cbUpdate); });
  294. }
  295. } else if (_date <= qc.extraDays) { // day is older than default range and still fetching extra days
  296. parseMisc("next");
  297. console.log("fetchrequest for", _decDate(Utils.ISODate(_date)));
  298. }
  299. }//}}} parseDetail
  300.  
  301. function parseMisc(type) {//{{{
  302. var _d = doc.documentURI.match(/\d{8}/)[0],
  303. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  304. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "end");
  305. var payload = { encodedDate: _decDate(Utils.ISODate(_d)), pageNumber: 1, sortType: "All" };
  306.  
  307. if (type === "next" && +qc.extraDays > 1) {
  308. setTimeout(HITStorage.fetch, 250, MTURK_BASE+"statusdetail", payload);
  309. console.log("going to next page", payload.encodedDate);
  310. } else if (type === "end" && +qc.extraDays > 1) {
  311. Status.message = "Writing to database...";
  312. Promise.all(bonusSearch).then(function() { HITStorage.write(HITStorage.data, cbUpdate); });
  313. } else
  314. Utils.errorHandler(new TypeError("Failed to execute '"+type+"' in '"+doc.documentURI+"'"));
  315. }//}}}
  316.  
  317. function _decDate(date) {//{{{
  318. var y = date.substr(0,4);
  319. var m = date.substr(5,2);
  320. var d = date.substr(8,2);
  321. date = new Date(y,m-1,d-1);
  322. return Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded() + date.getFullYear();
  323. }//}}}
  324.  
  325. function _calcTotals(obj) {//{{{
  326. var sum = 0;
  327. for (var k in obj){
  328. if (obj.hasOwnProperty(k) && !isNaN(+k))
  329. sum += obj[k].submitted;
  330. }
  331. return sum;
  332. }//}}}
  333. },//}}} parseDOM
  334. autoApprovals: {//{{{
  335. getTime : function(date, hitId) {
  336. if (qc.extraDays || (!Object.keys(qc.aac).length && !Object.keys(qc.aat).length)) return "";
  337. var found = false,
  338. filter = function(id) { return id === hitId; },
  339. autoApp = "";
  340.  
  341. if (qc.aac[date]) {
  342. autoApp = qc.aac[date][Object.keys(qc.aac[date]).filter(filter)[0]] || "";
  343. if (autoApp) found = true;
  344. }
  345. if (!found && Object.keys(qc.aat).length) {
  346. for (var key in qc.aat) { if (qc.aat.hasOwnProperty(key)) { // for all dates in aat
  347. var id = Object.keys(qc.aat[key]).filter(filter)[0];
  348. autoApp = qc.aat[key][id] || "";
  349. if (autoApp) {
  350. found = true;
  351. qc.aac[date] = qc.aac[date] || {};
  352. qc.aac[date][id] = qc.aat[key][id]; // move time from temp var to collection var
  353. delete qc.aat[key][id];
  354. qc.save("aat", "hitdb_autoAppTemp", true);
  355. qc.save("aac", "hitdb_autoAppCollection", true);
  356. break;
  357. }
  358. }} // for key (dates)
  359. } // if !found && aat not empty
  360. return autoApp;
  361. },// getTime
  362. purge : function(date) {
  363. if (date) {
  364. delete qc.aac[date];
  365. qc.save("aac", "hitdb_autoAppCollection", true);
  366. return;
  367. }
  368.  
  369. if (!Object.keys(qc.aat).length) return; // nothing here
  370.  
  371. var pad = function(num) { return Number(num).toPadded(); },
  372. _date = Date.parse(new Date().getFullYear() + "-" + pad(new Date().getMonth()+1) + "-" + pad(new Date().getDate()));
  373.  
  374. for (var key of Object.keys(qc.aat)) {
  375. if (_date - key > 169200000) delete qc.aat[key]; // at least 2 days old, no need to keep it around
  376. }
  377. qc.save("aat", "hitdb_autoAppTemp", true);
  378. } // purge
  379. },//}}} autoApprovals
  380.  
  381. fetch: function(url, payload) { //{{{
  382. //format GET request with query payload
  383. if (payload) {
  384. var args = 0;
  385. url += "?";
  386. for (var k in payload) {
  387. if (payload.hasOwnProperty(k)) {
  388. if (args++) url += "&";
  389. url += k + "=" + payload[k];
  390. }
  391. }
  392. }
  393. // defer XHR to a promise
  394. var fetch = new Promise( function(fulfill, deny) {
  395. var urlreq = new XMLHttpRequest();
  396. urlreq.open("GET", url, true);
  397. urlreq.responseType = "document";
  398. urlreq.send();
  399. urlreq.onload = function() {
  400. if (this.status === 200) {
  401. fulfill(this.response);
  402. } else {
  403. deny(new Error(this.status + " - " + this.statusText));
  404. }
  405. };
  406. urlreq.onerror = function() { deny(new Error(this.status + " - " + this.statusText)); };
  407. urlreq.ontimeout = function() { deny(new Error(this.status + " - " + this.statusText)); };
  408. } );
  409. fetch.then( HITStorage.parseDOM, Utils.errorHandler );
  410.  
  411. }, //}}} fetch
  412. write: function(input, callback) { //{{{
  413. var counts = { requests: 0, total: 0 },
  414. os = Object.keys(input),
  415. dbo = [],
  416. dbt = HITStorage.db.transaction(os, "readwrite");
  417. for (var i=0;i<os.length;i++) { // cycle object stores
  418. dbo[i] = dbt.objectStore(os[i]);
  419. for (var k of input[os[i]]) { // cycle entries to put into object stores
  420. if (typeof callback === 'function' && ++counts.requests)
  421. dbo[i].put(k).onsuccess = callback.bind(counts);
  422. else
  423. dbo[i].put(k);
  424. }
  425. }
  426. }, //}}} write
  427.  
  428. recall: function(store, options) {//{{{
  429. if (options) {
  430. var index = options.index || null,
  431. range = options.range || null,
  432. dir = options.dir || "next",
  433. limit = options.limit || Infinity;
  434. if (options.filter) {
  435. var fs = options.filter.status !== "*" ? new RegExp(options.filter.status, "i") : false,
  436. fq = options.filter.query !== "*" ? new RegExp(options.filter.query,"i") : false,
  437. fd = options.filter.date || null;
  438. }
  439. if (options.progress)
  440. Progress.show();
  441. } // if options
  442.  
  443. var sr = new DBResult(), matches = 0, total = 0;
  444. return new Promise( function(resolve) {
  445. var dbo = HITStorage.db.transaction(store, "readonly").objectStore(store), dbq = null;
  446. if (index)
  447. dbq = dbo.index(index).openCursor(range, dir);
  448. else
  449. dbq = dbo.openCursor(range, dir);
  450. dbq.onsuccess = function() {
  451. var c = this.result;
  452. if (c && matches < limit) {
  453. try { Status.message = "Retrieving data... [ " + matches + " / " + (++total) + " ]"; } catch(e) {}
  454. if ( fd && (c.value.date < (fd[0] || "0000") || c.value.date > (fd[1] || "9999")) ) {
  455. c.continue();
  456. return;
  457. }
  458. if ( (!fs && !fq) || // no query filter and no status filter OR
  459. (fs && !fq && ~c.value.status.search(fs)) || // status match and no query filter OR
  460. (!fs && fq && // query match and no status filter OR
  461. (~c.value.title.search(fq) || ~c.value.requesterName.search(fq) || ~c.value.hitId.search(fq))) ||
  462. (fs && fq && ~c.value.status.search(fs) && // status match and query match
  463. (~c.value.title.search(fq) || ~c.value.requesterName.search(fq) || ~c.value.hitId.search(fq))) ) {
  464. sr.include(c.value);
  465. try { Status.message = "Retrieving data... [ " + (++matches) + " / " + total + " ]"; } catch(e) {}
  466. }
  467. c.continue();
  468. } else {
  469. try { Status.message = "Done."; } catch(e) {}
  470. resolve(sr);
  471. }
  472. }; // IDBCursor
  473. }); // promise
  474. },//}}} HITStorage::recall
  475.  
  476. backup: function(internal) {//{{{
  477. var bData = {},
  478. os = ["STATS", "NOTES", "HIT"],
  479. count = 0;
  480.  
  481. Progress.show();
  482. Status.push("Preparing backup...", "black");
  483.  
  484. for (var store of os)
  485. HITStorage.db.transaction(os, "readonly").objectStore(store).openCursor().onsuccess = populateBackup;
  486.  
  487. function populateBackup(e) {
  488. var cursor = e.target.result;
  489. if (cursor) {
  490. if (!bData[cursor.source.name]) bData[cursor.source.name] = [];
  491. bData[cursor.source.name].push(cursor.value);
  492. cursor.continue();
  493. } else
  494. if (++count === 3)
  495. finalizeBackup();
  496. }
  497. function finalizeBackup() {
  498. if (typeof internal === 'function') { qc.merge = bData; internal(true); return; }
  499. var backupblob = new Blob([JSON.stringify(bData)], {type:"application/json"});
  500. var date = new Date();
  501. var dl = document.createElement("A");
  502. date = date.getFullYear() + Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded();
  503. dl.href = URL.createObjectURL(backupblob);
  504. console.log(dl.href);
  505. dl.download = "hitdb_"+date+".bak";
  506. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  507. dl.click(); // so we make it so and click,
  508. dl.remove(); // then immediately remove it
  509. Progress.hide();
  510. Status.push("Done!", "green");
  511. }
  512.  
  513. }//}}} backup
  514.  
  515. }, //}}} HITStorage
  516.  
  517. Utils = { //{{{
  518. disableButtons: function(arr, status) { //{{{
  519. for (var b of arr) document.getElementById(b).disabled = status;
  520. }, //}}}
  521.  
  522. ftime : function(t) {//{{{
  523. if (String(t).length && +t === 0) return "0s";
  524. if (!t) return "n/a";
  525. var d = Math.floor(t/86400),
  526. h = Math.floor(t%86400/3600),
  527. m = Math.floor(t%86400%3600/60),
  528. s = t%86400%3600%60;
  529. return ((d>0) ? d+" day"+(d>1 ? "s " : " ") : "") + ((h>0) ? h+"h " : "") + ((m>0) ? m+"m " : "") + ((s>0) ? s+"s" : "");
  530. },//}}}ftime
  531.  
  532. ISODate: function(date) { //{{{ MMDDYYYY <-> YYYY-MM-DD
  533. if (date.length === 10)
  534. return date.substr(5,2)+date.substr(-2)+date.substr(0,4);
  535. else
  536. return date.substr(4)+"-"+date.substr(0,2)+"-"+date.substr(2,2);
  537. },//}}} ISODate
  538.  
  539. getPosition: function(element, includeHeight) {//{{{
  540. var offsets = { x: 0, y: includeHeight ? element.offsetHeight : 0 };
  541. do {
  542. offsets.x += element.offsetLeft;
  543. offsets.y += element.offsetTop;
  544. element = element.offsetParent;
  545. } while (element);
  546. return offsets;
  547. },//}}} getPosition
  548.  
  549. errorHandler: function(err) {//{{{
  550. try { Status.push(err.name + ": " + err.message, "red"); }
  551. catch(e) {}
  552. finally { console.error(err); }
  553. }//}}}
  554.  
  555. }, //}}} Utils
  556.  
  557. ProjectedEarnings = {//{{{
  558. data: JSON.parse(localStorage.getItem("hitdb_projectedEarnings") || "{}"),
  559. updateDate: function() {//{{{
  560. var tableList = document.querySelectorAll(".metrics-table"), el, date;
  561. try {
  562. el = tableList[5].rows[1].cells[0].children[0];
  563. date = el.href.match(/\d{8}/)[0];
  564. } catch(e1) {
  565. try {
  566. el = tableList[3].rows[1].cells[0].children[0];
  567. date = el.href.match(/\d{8}/)[0];
  568. } catch(e2) {
  569. for (var tbl of tableList) {
  570. if (tbl.rows.length < 2 || tbl.rows[1].cells.length < 6) continue;
  571. el = tbl.rows[1].cells[0].children[0];
  572. date = el.href.match(/\d{8}/)[0];
  573. } //for
  574. }//catch
  575. }//catch
  576. var day = el.textContent,
  577. isToday = day === "Today",
  578. _date = new Date(),
  579. pad = function(num) { return Number(num).toPadded(); },
  580. weekEnd = null,
  581. weekStart = null;
  582.  
  583. _date.setDate(_date.getDate() - _date.getDay()); // sunday
  584. weekStart = Date.parse(_date.getFullYear() + "-" + pad(_date.getMonth()+1) + "-" + pad(_date.getDate()));
  585. _date.setDate(_date.getDate() + 7); // next sunday
  586. weekEnd = Date.parse(_date.getFullYear() + "-" + pad(_date.getMonth()+1) + "-" + pad(_date.getDate()));
  587.  
  588. if (!Object.keys(this.data).length) {
  589. this.data = {
  590. today: date, weekStart: weekStart, weekEnd: weekEnd, day: new Date().getDay(), dbUpdated: "n/a",
  591. pending: 0, earnings: {}, target: { day: 0, week: 0 }
  592. };
  593. }
  594.  
  595. if ( (Date.parse(Utils.ISODate(date)) >= this.data.weekEnd) ||
  596. (!isToday && new Date().getDay() < this.data.day) ) { // new week
  597. this.data.earnings = {};
  598. this.data.weekEnd = weekEnd;
  599. this.data.weekStart = weekStart;
  600. }
  601. if ( (this.data.today === null && isToday) || (this.data.today !== null && (date !== this.data.today || !isToday)) ) { // new day
  602. this.data.today = date === this.data.today ? null : date;
  603. this.data.day = new Date().getDay();
  604. }
  605.  
  606. this.saveState();
  607. },//}}} updateDate
  608. draw: function(init) {//{{{
  609. var parentTable = document.querySelector("#total_earnings_amount").offsetParent,
  610. rowPending = init ? parentTable.insertRow(-1) : parentTable.rows[4],
  611. rowProjectedDay = init ? parentTable.insertRow(-1) : parentTable.rows[5],
  612. rowProjectedWeek = init ? parentTable.insertRow(-1) : parentTable.rows[6],
  613. title = "Click to set/change the target value",
  614. weekTotal = this.getWeekTotal(),
  615. dayTotal = this.data.earnings[this.data.today] || 0;
  616.  
  617. if (init) {
  618. rowPending.insertCell(-1);rowPending.insertCell(-1);rowPending.className = "even";
  619. rowProjectedDay.insertCell(-1);rowProjectedDay.insertCell(-1);rowProjectedDay.className = "odd";
  620. rowProjectedWeek.insertCell(-1);rowProjectedWeek.insertCell(-1);rowProjectedWeek.className = "even";
  621. for (var i=0;i<rowPending.cells.length;i++) rowPending.cells[i].style.borderTop = "dotted 1px black";
  622. rowPending.cells[0].className = "metrics-table-first-value";
  623. rowProjectedDay.cells[0].className = "metrics-table-first-value";
  624. rowProjectedWeek.cells[0].className = "metrics-table-first-value";
  625. rowPending.cells[1].title = "This value includes all earnings that are not yet fully cleared as 'Paid'";
  626. }
  627.  
  628. rowPending.cells[0].innerHTML = 'Pending earnings '+
  629. '<span style="font-family:arial;font-size:10px;" title="Timestamp of last database update">[ ' + this.data.dbUpdated + ' ]</span>';
  630. rowPending.cells[1].textContent = "$"+Number(this.data.pending).toFixed(2);
  631. rowProjectedDay.cells[0].innerHTML = 'Projected earnings for the day<br>'+
  632. '<meter id="projectedDayProgress" style="width:220px;" title="'+title+
  633. '" value="'+dayTotal+'" max="'+this.data.target.day+'"></meter>'+
  634. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + Number(dayTotal-this.data.target.day).toFixed(2) + '</span>';
  635. rowProjectedDay.cells[1].textContent = "$"+Number(dayTotal).toFixed(2);
  636. rowProjectedWeek.cells[0].innerHTML = 'Projected earnings for the week<br>' +
  637. '<meter id="projectedWeekProgress" style="width:220px;" title="'+title+
  638. '" value="'+weekTotal+'" max="'+this.data.target.week+'"></meter>' +
  639. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + Number(weekTotal-this.data.target.week).toFixed(2) + '</span>';
  640. rowProjectedWeek.cells[1].textContent = "$"+Number(weekTotal).toFixed(2);
  641.  
  642. document.querySelector("#projectedDayProgress").onclick = updateTargets.bind(this, "day");
  643. document.querySelector("#projectedWeekProgress").onclick = updateTargets.bind(this, "week");
  644.  
  645. function updateTargets(span, e) {
  646. /*jshint validthis:true*/
  647. var goal = prompt("Set your " + (span === "day" ? "daily" : "weekly") + " target:",
  648. this.data.target[span === "day" ? "day" : "week"]);
  649. if (goal && !isNaN(goal)) {
  650. this.data.target[span === "day" ? "day" : "week"] = goal;
  651. e.target.max = goal;
  652. e.target.nextSibling.textContent = " "+Number((span === "day" ? dayTotal : weekTotal) - goal).toFixed(2);
  653. this.saveState();
  654. }
  655. }
  656. },//}}} draw
  657.  
  658. getWeekTotal: function() {
  659. var totals = 0;
  660. for (var k of Object.keys(this.data.earnings))
  661. totals += this.data.earnings[k];
  662.  
  663. return Math.decRound(totals, 2);
  664. },
  665. saveState: function() {
  666. localStorage.setItem("hitdb_projectedEarnings", JSON.stringify(this.data));
  667. },
  668.  
  669. clear: function() {
  670. this.data.pending = 0;
  671. for (var day of Object.keys(this.data.earnings))
  672. if (day in qc.fetchData || day === this.data.today) this.data.earnings[day] = 0;
  673. },
  674.  
  675. updateValues: function(obj) {
  676. var vDate = Date.parse(obj.date), iDate = Utils.ISODate(obj.date);
  677.  
  678. if (~obj.status.search(/pending/i)) // sum pending earnings (include approved until fully cleared as paid)
  679. this.data.pending = Math.decRound(obj.reward+this.data.pending, 2);
  680. if (vDate < this.data.weekEnd && vDate >= this.data.weekStart && !~obj.status.search(/rejected/i)){ // sum weekly earnings by day
  681. this.data.earnings[iDate] = Math.decRound(obj.reward+(this.data.earnings[iDate] || 0), 2 );
  682. }
  683. }
  684. },//}}} ProjectedEarnings
  685.  
  686. DBResult = function(resArr, colObj) {//{{{
  687. this.results = resArr || [];
  688. this.collation = colObj || null;
  689. this.formatHTML = function(type, simple) {//{{{
  690. simple = simple || false;
  691. var count = 0, htmlTxt = [], entry = null, _trClass = null;
  692.  
  693. if (this.results.length < 1) return "<h2>No entries found matching your query.</h2>";
  694.  
  695. if (type === "daily") {
  696. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th></th>'+
  697. '<th>Date</th><th>Submitted</th><th>Approved</th><th>Rejected</th><th>Pending</th><th>Earnings</th></tr></thead><tbody>');
  698. var r = this.collate(this.results,"stats");
  699. for (entry of this.results) {
  700. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  701. htmlTxt.push('<tr '+_trClass+' style="text-align:right">' +
  702. '<td><span class="hdbExpandRow">[+]</span></td>'+
  703. '<td style="text-align:center;">' + entry.date + '</td><td>' + entry.submitted + '</td>' +
  704. '<td>' + entry.approved + '</td><td>' + entry.rejected + '</td><td>' + entry.pending + '</td>' +
  705. '<td>' + Number(entry.earnings).toFixed(2) + '</td></tr>');
  706. }
  707. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow" style="text-align:right;"><td>Totals:</td>' +
  708. '<td>' + r.totalEntries + ' days</td><td>' + r.totalSub + '</td>' +
  709. '<td>' + r.totalApp + '</td><td>' + r.totalRej + '</td>' +
  710. '<td>' + r.totalPen + '</td><td>$' +
  711. Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  712. } else if (type === "pending" || type === "requester") {
  713. htmlTxt.push('<thead><tr data-sort="99999" class="hdbHeaderRow"><th width="160">Requester ID</th>' +
  714. '<th>Requester</th><th>' + (type === "pending" ? 'Pending' : 'HITs') + '</th><th>Rewards</th></tr></thead><tbody>');
  715. r = this.collate(this.results,"requesterId");
  716. for (var k in r) {
  717. if (!~k.search(/total/) && r.hasOwnProperty(k)) {
  718. var tr = ['<tr data-sort="'+Math.decRound(r[k].pay,2)+'"><td>' +
  719. '<span class="hdbExpandRow" title="Display all pending HITs from this requester">' +
  720. '[+]</span> ' + r[k][0].requesterId + '</td><td>' + r[k][0].requesterName + '</td>' +
  721. '<td style="text-align:center;">' + r[k].length + '</td><td>' + Number(Math.decRound(r[k].pay,2)).toFixed(2) + '</td></tr>'];
  722.  
  723. for (var hit of r[k]) { // hits in range per requester id
  724. tr.push('<tr data-rid="'+r[k][0].requesterId+'" style="color:#c60000;display:none;"><td style="text-align:right">' +
  725. hit.date + '</td><td width="500" colspan="2" class="nowrap" style="max-width:520" title="'+hit.title+'">' +
  726. '[ <span class="helpSpan" title="Auto-approval time">AA: '+Utils.ftime(hit.autoAppTime).trim()+'</span> ] '+
  727. hit.title + '</td><td style="text-align:right">' + _parseRewards(hit.reward,"pay") + '</td></tr>');
  728. }
  729. htmlTxt.push(tr.join(''));
  730. }
  731. }
  732. htmlTxt.sort(function(a,b) { return +b.substr(15,5).match(/\d+\.?\d*/) - +a.substr(15,5).match(/\d+\.?\d*/); });
  733. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td style="text-align:right;">Totals:</td>' +
  734. '<td style="text-align:center;">' + (Object.keys(this.collation || r).length-7) + ' Requesters</td>' +
  735. '<td style="text-align:right;">' + (this.collation || r).totalEntries + '</td>'+
  736. '<td style="text-align:right;">$' + Number(Math.decRound((this.collation || r).totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  737. } else { // default
  738. if (!simple)
  739. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th colspan="3"></th>' +
  740. '<th colspan="2" title="Bonuses must be added in manually.\n\nClick inside' +
  741. 'the cell to edit, click out of the cell to save">Reward</th><th colspan="3"></th></tr>'+
  742. '<tr class="hdbHeaderRow">' +
  743. '<th style="min-width:65">Date</th><th>Requester</th><th>HIT title</th><th style="font-size:10px;">Pay</th>'+
  744. '<th style="font-size:10px;"><span class="helpSpan" title="Click the cell to edit.\nIts value is automatically saved">'+
  745. 'Bonus</span></th><th>Status</th><th>'+
  746. '<span class="helpSpan" title="Auto-approval times">AA</span></th><th>Feedback</th></tr></thead><tbody>');
  747.  
  748. this.results.sort(function(a,b) { return a.date === b.date ?
  749. (a.requesterName.toLowerCase() > b.requesterName.toLowerCase() ? 1 : -1) : a.date < b.date ? -1 : 1; });
  750. for (entry of this.results) {
  751. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  752. var _stColor = ~entry.status.search(/(paid|approved)/i) ? "green" :
  753. entry.status === "Pending Approval" ? "orange" : "red";
  754. var href = MTURK_BASE+'contact?requesterId='+entry.requesterId+'&requesterName='+entry.requesterName+
  755. '&subject=Regarding+Amazon+Mechanical+Turk+HIT+'+entry.hitId;
  756.  
  757. if (!simple)
  758. htmlTxt.push('<tr '+_trClass+' data-id="'+entry.hitId+'">'+
  759. '<td width="74px">' + entry.date + '</td><td style="max-width:145px;">' +
  760. '<a target="_blank" title="Contact this requester" href="'+href+'">' + entry.requesterName + '</a></td>' +
  761. '<td width="375px" title="HIT ID: '+entry.hitId+'">' +
  762. '<span title="Add a note" id="note-'+entry.hitId+'" style="cursor:pointer;">&nbsp;&#128221;&nbsp;</span>' +
  763. entry.title + '</td><td style="text-align:right">' + _parseRewards(entry.reward,"pay") + '</td>' +
  764. '<td style="text-align:right" class="bonusCell" title="Click to add/edit" contenteditable="true" data-hitid="'+entry.hitId+'">' +
  765. (+_parseRewards(entry.reward,"bonus") ? _parseRewards(entry.reward,"bonus") : "") +
  766. '</td><td style="color:'+_stColor+';text-align:center">' + entry.status + '</td>' +
  767. '<td>' + Utils.ftime(entry.autoAppTime) + '</td><td>' + entry.feedback + '</td></tr>');
  768. else
  769. htmlTxt.push('<tr>' + '<td class="nowrap" title="'+entry.requesterName+'" style="max-width:130">'+entry.requesterName+'</td>' +
  770. '<td class="nowrap" title="'+entry.title+'" style="max-width:520">'+entry.title+'</td><td>'+ _parseRewards(entry.reward,"pay") +
  771. '</td><td class="nowrap" title="'+entry.status+'" style="max-width:60">'+ entry.status+'</td></tr>');
  772. }
  773.  
  774. if (!simple) {
  775. r = this.collation || this.collate(this.results,"requesterId");
  776. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td></td>' +
  777. '<td style="text-align:right">Totals:</td><td style="text-align:center;">' + r.totalEntries + ' HITs</td>' +
  778. '<td style="text-align:right">$' + Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td>' +
  779. '<td style="text-align:right">$' + Number(Math.decRound(r.totalBonus,2)).toFixed(2) + '</td>' +
  780. '<td colspan="3"></td></tr></tfoot>');
  781. }
  782. }
  783. return htmlTxt.join('');
  784. };//}}} formatHTML
  785. this.formatCSV = function(type) {//{{{
  786. var csvTxt = [], entry = null, delimiter="\t";
  787. if (type === "daily") {
  788. csvTxt.push( ["Date", "Submitted", "Approved", "Rejected", "Pending", "Earnings\n"].join(delimiter) );
  789. for (entry of this.results) {
  790. csvTxt.push( [entry.date, entry.submitted, entry.approved, entry.rejected,
  791. entry.pending, Number(entry.earnings).toFixed(2)+"\n"].join(delimiter) );
  792. }
  793. csvToFile(csvTxt, "hitdb_dailyOverview.csv");
  794. } else if (type === "pending" || type === "requester") {
  795. csvTxt.push( ["RequesterId","Requester", (type === "pending" ? "Pending" : "HITs"), "Rewards\n"].join(delimiter) );
  796. var r = this.collation || this.collate(this.results,"requesterId");
  797. for (var k in r) {
  798. if (!~k.search(/total/) && r.hasOwnProperty(k))
  799. csvTxt.push( [k, r[k][0].requesterName, r[k].length, Number(Math.decRound(r[k].pay,2)).toFixed(2)+"\n"].join(delimiter) );
  800. }
  801. csvToFile(csvTxt, "hitdb_"+type+"Overview.csv");
  802. } else {
  803. csvTxt.push(["hitId","date","requesterName","requesterId","title","pay","bonus","status","autoAppTime","feedback\n"].join(delimiter));
  804. for (entry of this.results) {
  805. csvTxt.push([entry.hitId, entry.date, entry.requesterName, entry.requesterId, entry.title,
  806. Number(_parseRewards(entry.reward,"pay")).toFixed(2),
  807. (+_parseRewards(entry.reward,"bonus") ? Number(_parseRewards(entry.reward,"bonus")).toFixed(2) : ""),
  808. entry.status, entry.autoAppTime, entry.feedback+"\n"].join(delimiter));
  809. }
  810. csvToFile(csvTxt, "hitdb_queryResults.csv");
  811. }
  812.  
  813. return "<pre>"+csvTxt.join('')+"</pre>";
  814.  
  815. function csvToFile(csv, filename) {
  816. var blob = new Blob(csv, {type: "text/csv", endings: "native"}),
  817. dl = document.createElement("A");
  818. dl.href = URL.createObjectURL(blob);
  819. dl.download = filename;
  820. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  821. dl.click(); // so we make it so and click,
  822. dl.remove(); // then immediately remove it
  823. return dl;
  824. }
  825. };//}}} formatCSV
  826. this.include = function(value) {
  827. this.results.push(value);
  828. };
  829. this.collate = function(data, index) {//{{{
  830. var r = {
  831. totalPay: 0, totalBonus: 0, totalEntries: data.length,
  832. totalSub: 0, totalApp: 0, totalRej: 0, totalPen: 0
  833. };
  834. for (var e of data) {
  835. if (!r[e[index]]) {
  836. r[e[index]] = [];
  837. Object.defineProperty(r[e[index]], "pay", {value: 0, enumerable: false, configurable: true, writable: true});
  838. }
  839. r[e[index]].push(e);
  840.  
  841. if (index === "stats") {
  842. r.totalSub += e.submitted;
  843. r.totalApp += e.approved;
  844. r.totalRej += e.rejected;
  845. r.totalPen += e.pending;
  846. r.totalPay += e.earnings;
  847. } else {
  848. r[e[index]].pay += (+_parseRewards(e.reward,"pay"));
  849. r.totalPay += (+_parseRewards(e.reward,"pay"));
  850. r.totalBonus += (+_parseRewards(e.reward,"bonus"));
  851. }
  852. }
  853. return r;
  854. };//}}} _collate
  855.  
  856. function _parseRewards(rewards,value) {//{{{
  857. if (!isNaN(rewards)) {
  858. if (value === "pay")
  859. return Number(rewards).toFixed(2);
  860. else
  861. return "0.00";
  862. } else {
  863. if (value === "pay")
  864. return Number(rewards.pay).toFixed(2);
  865. else
  866. return Number(rewards.bonus).toFixed(2);
  867. }
  868. } //}}} _parse
  869. },//}}} databaseresult
  870.  
  871. DashboardUI = {//{{{
  872. draw: function() {//{{{
  873. var controlPanel = document.createElement("TABLE"),
  874. insertionNode = document.querySelector(".footer_separator").previousSibling;
  875. document.body.insertBefore(controlPanel, insertionNode);
  876. controlPanel.width = "760";
  877. controlPanel.align = "center";
  878. controlPanel.id = "hdbControlPanel";
  879. controlPanel.cellSpacing = "0";
  880. controlPanel.cellPadding = "0";
  881. controlPanel.innerHTML = '<tr height="25px"><td width="10" bgcolor="#7FB448" style="padding-left: 10px;"></td>' +
  882. '<td class="white_text_14_bold" style="padding-left:10px; background-color:#7FB448;">' +
  883. 'HIT Database Mk. II&nbsp;<a href="https://greasyfork.org/en/scripts/11733-mturk-hit-database-mk-ii#userGuide" '+
  884. 'class="whatis" target="turkPopUp" onclick="customPopup(this, 500, 400)">' +
  885. '(What\'s this?)</a></td></tr>' +
  886. '<tr><td class="container-content" colspan="2">' +
  887. '<div style="text-align:center;" id="hdbDashboardInterface">' +
  888. '<button id="hdbBackup" title="Export your entire database!\nPerfect for moving between computers or as a periodic backup">Create Backup</button>' +
  889. '<button id="hdbRestore" title="Import data from an external file" style="margin:5px">Import</button>' +
  890. '<button id="hdbUpdate" title="Update... the database" style="color:green;">Update Database</button>' +
  891. '<input id="hdbFileInput" type="file" style="display:none"/>' +
  892. '<br>' +
  893. '<button id="hdbPending" title="Summary of all pending HITs\n Can be exported as CSV" style="margin: 0px 5px 5px;">Pending Overview</button>' +
  894. '<button id="hdbRequester" title="Summary of all requesters\n Can be exported as CSV" style="margin: 0px 5px 5px;">Requester Overview</button>' +
  895. '<button id="hdbDaily" title="Summary of each day you\'ve worked\nCan be exported as CSV" style="margin:0px 5px 5px;">Daily Overview</button>' +
  896. '<br>' +
  897. '<label>Find </label>' +
  898. '<select id="hdbStatusSelect"><option value="*">ALL</option>' +
  899. '<option value="Pending Approval" style="color: orange;">Pending Approval</option>' +
  900. '<option value="Rejected" style="color: red;">Rejected</option>' +
  901. '<option value="Approved - Pending Payment" style="color:green;">Approved - Pending Payment</option>' +
  902. '<option value="(Paid|Approved)" style="color:green;">Paid OR Approved</option></select>' +
  903. '<label> HITs matching: </label><input id="hdbSearchInput" title="Query can be HIT title, HIT ID, or requester name" />' +
  904. '<button id="hdbSearch">Search</button>' +
  905. '<br>' +
  906. '<label>from date </label><input id="hdbMinDate" type="date" size="10" title="Specify a date, or leave blank">' +
  907. '<label> to </label><input id="hdbMaxDate" type="date" size="10" title="Specify a date, or leave blank">' +
  908. '<label for="hdbCSVInput" title="Export results as CSV file" style="margin-left:50px; vertical-align:middle;">export CSV</label>' +
  909. '<input id="hdbCSVInput" title="Export results as CSV file" type="checkbox" style="vertical-align:middle;">' +
  910. '<br>' +
  911. '<label id="hdbStatusText"></label>' +
  912. '<div id="hdbProgressBar" class="hdbProgressContainer"><div class="hdbProgressOuter"><div class="hdbProgressInner"></div></div></div>' +
  913. '</div></td></tr>';
  914.  
  915. var searchResults = document.createElement("DIV");
  916. searchResults.align = "center";
  917. searchResults.id = "hdbSearchResults";
  918. searchResults.style.display = "block";
  919. searchResults.innerHTML =
  920. '<span class="hdbResControl" id="hdbResClear">[ clear results ]</span>' +
  921. '<span class="hdbTablePagination" id="hdbPageTop"></span><br>' +
  922. '<table cellSpacing="0" cellpadding="2" width="760" id="hdbResultsTable"></table>' +
  923. '<span class="hdbResControl" id="hdbVpTop">Back to top</span>' +
  924. '<span class="hdbTablePagination" id="hdbPageBot"></span><br>';
  925. document.body.insertBefore(searchResults, insertionNode);
  926. },//}}} dashboardUI::draw
  927.  
  928. initClickables: function() {//{{{
  929. var updateBtn = document.getElementById("hdbUpdate"),
  930. backupBtn = document.getElementById("hdbBackup"),
  931. restoreBtn = document.getElementById("hdbRestore"),
  932. fileInput = document.getElementById("hdbFileInput"),
  933. exportCSVInput = document.getElementById("hdbCSVInput"),
  934. searchBtn = document.getElementById("hdbSearch"),
  935. searchInput = document.getElementById("hdbSearchInput"),
  936. pendingBtn = document.getElementById("hdbPending"),
  937. reqBtn = document.getElementById("hdbRequester"),
  938. dailyBtn = document.getElementById("hdbDaily"),
  939. fromdate = document.getElementById("hdbMinDate"),
  940. todate = document.getElementById("hdbMaxDate"),
  941. statusSelect = document.getElementById("hdbStatusSelect"),
  942. searchResults = document.getElementById("hdbSearchResults"),
  943. resultsTable = document.getElementById("hdbResultsTable"),
  944. isGecko = /Gecko\/\d+/.test(navigator.userAgent);
  945.  
  946. searchResults.firstChild.onclick = function() { //{{{ clear results
  947. resultsTable.innerHTML = null; qc.sr = [];
  948. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  949. if (~d.search(/page/i)) d.innerHTML = "";
  950. document.getElementById(d).style.display = "none";
  951. }
  952. };//}}}
  953. document.getElementById("hdbVpTop").onclick = function() { autoScroll("#hdbControlPanel"); };
  954.  
  955. updateBtn.onclick = function() { //{{{
  956. if (!HITStorage.db) { Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); return; }
  957. Utils.disableButtons(['hdbUpdate'], true);
  958. Progress.show();
  959. metrics.dbupdate = new Metrics("database_update");
  960. HITStorage.fetch(MTURK_BASE+"status");
  961. Status.message = "fetching status page....";
  962. };//}}}
  963. exportCSVInput.addEventListener("click", function() {//{{{
  964. var a = document.getElementById('hdbAnalytics');
  965. if (a && a.checked) a.click();
  966. if (exportCSVInput.checked) {
  967. searchBtn.textContent = "Export CSV";
  968. pendingBtn.textContent += " (csv)";
  969. reqBtn.textContent += " (csv)";
  970. dailyBtn.textContent += " (csv)";
  971. }
  972. else {
  973. searchBtn.textContent = "Search";
  974. pendingBtn.textContent = pendingBtn.textContent.replace(" (csv)","");
  975. reqBtn.textContent = reqBtn.textContent.replace(" (csv)","");
  976. dailyBtn.textContent = dailyBtn.textContent.replace(" (csv)", "");
  977. }
  978. });//}}}
  979. if (isGecko) {//{{{
  980. fromdate.addEventListener("focus", function() {
  981. var offsets = Utils.getPosition(this, true);
  982. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  983. });
  984. todate.addEventListener("focus", function() {
  985. var offsets = Utils.getPosition(this, true);
  986. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  987. });
  988. }//}}}
  989.  
  990. backupBtn.onclick = HITStorage.backup;
  991. restoreBtn.onclick = function() { fileInput.value = ''; fileInput.click(); };
  992. fileInput.onchange = processFile;
  993. searchInput.onkeydown = function(e) { if (e.keyCode === 13) searchBtn.click(); };
  994.  
  995. searchBtn.addEventListener('click', function(e) {//{{{
  996. if (!/^[se]/i.test(e.target.textContent)) return;
  997. var r = this.getRange(), query = searchInput.value.trim().split(':');
  998. // make searching faster and more efficient in large databases
  999. if (!/(req|id|hitid)$/i.test(query[0])) {
  1000. query = query.join('');
  1001. if (query.length === 30 && !/\s/.test(query)) {
  1002. r.range = window.IDBKeyRange.only(query.toUpperCase());
  1003. r.index = null;
  1004. }
  1005. } else {
  1006. query[1] = /req/.test(query[0]) ? query[1].trimLeft() : query[1].trimLeft().toUpperCase();
  1007. r.index = /req/.test(query[0]) ? 'requesterName' : null;
  1008. r.range = window.IDBKeyRange
  1009. .bound(query[1], query[1].slice(0,query[1].length-1) + String.fromCharCode(query[1].charCodeAt(query[1].length-1)+1));
  1010. query = query[0].split(/(req|id|hitid)$/)[0].trimRight();
  1011. }
  1012.  
  1013. var _filter = { status: statusSelect.value, query: query.length > 0 ? query : "*" };
  1014. var _opt = { index: r.index, range: r.range, dir: r.dir, filter: _filter, progress: true };
  1015.  
  1016. _dbaccess("search", ["HIT", _opt], function(r) {
  1017. var limiter = 500,
  1018. _cb = function(slice) {
  1019. for (var _r of slice)
  1020. HITStorage.recall("NOTES", { index: "hitId", range: window.IDBKeyRange.only(_r.hitId) }).then(noteHandler.bind(null,"attach"));
  1021. var _nodes = [document.querySelectorAll(".bonusCell"), document.querySelectorAll('span[id^="note-"]')];
  1022. for (var i=0;i<_nodes[0].length;i++) {
  1023. var bonus = _nodes[0][i],
  1024. note = _nodes[1][i];
  1025. bonus.dataset.initial = bonus.textContent;
  1026. bonus.onkeydown = updateBonus;
  1027. bonus.onblur = updateBonus;
  1028. note.onclick = noteHandler.bind(null,"new");
  1029. }
  1030. };
  1031. if (exportCSVInput.checked)
  1032. resultsTable.innerHTML = r.formatCSV();
  1033. else if (r.results.length > limiter) {
  1034. var collation = r.collate(r.results, "requesterId");
  1035. do { qc.sr.push(new DBResult(r.results.splice(0,limiter), collation)) } while (r.results.length);
  1036. resultConstrain(qc.sr, 0, "default", _cb);
  1037. } else
  1038. resultConstrain(r, 0, "default", _cb);
  1039. });
  1040. }.bind(this)); //}}} search button click event
  1041. //{{{ overview buttons
  1042. pendingBtn.onclick = function() {
  1043. var _filter = { date: [fromdate.value, todate.value], query: searchInput.value.trim().length > 0 ? searchInput.value : "*" },
  1044. _opt = { index: "status", dir: "prev", range: window.IDBKeyRange.only("Pending Approval"), filter: _filter, progress: true };
  1045.  
  1046. _dbaccess("pending", ["HIT", _opt], function(r) {
  1047. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("pending") : r.formatHTML("pending");
  1048. var expands = document.querySelectorAll(".hdbExpandRow");
  1049. for (var el of expands)
  1050. el.onclick = showHiddenRows;
  1051. });
  1052. }.bind(this); //pending overview click event
  1053. reqBtn.onclick = function() {
  1054. var r = this.getRange();
  1055. var _opt = { index: r.index, range: r.range, progress: true };
  1056.  
  1057. _dbaccess("requester", ["HIT", _opt], function(r) {
  1058. var limiter = 100,
  1059. _cb = function() {
  1060. var expands = document.querySelectorAll(".hdbExpandRow");
  1061. for (var el of expands)
  1062. el.onclick = showHiddenRows;
  1063. };
  1064. if (exportCSVInput.checked)
  1065. resultsTable.innerHTML = r.formatCSV("requester");
  1066. else if (r.results.length > limiter) {
  1067. var collation = r.collate(r.results, "requesterId"), _r = [], count = 0;
  1068. var keys = Object.keys(collation)
  1069. .filter(function(e) { return !/total/.test(e); })
  1070. .sort(function(a,b) { return collation[b].pay - collation[a].pay; });
  1071. keys.forEach(function(key){
  1072. if (++count > limiter) {
  1073. qc.sr.push(new DBResult(_r, collation));
  1074. count = 0; _r = [];
  1075. } else _r = _r.concat(collation[key]);
  1076. });
  1077. qc.sr.push(new DBResult(_r, collation));
  1078. resultConstrain(qc.sr, 0, "requester", _cb);
  1079. } else
  1080. resultConstrain(r, 0, "requester", _cb);
  1081. });
  1082. }.bind(this); //requester overview click event
  1083. dailyBtn.onclick = function() {
  1084. var r = this.getRange("*");
  1085. _dbaccess("daily", ["STATS", { range: r.range, dir: "prev", progress: true }], function(r) {
  1086. resultsTable.innerHTML = exportCSVInput.checked ? r.formatCSV("daily") : r.formatHTML("daily");
  1087. var expands = document.querySelectorAll(".hdbExpandRow");
  1088. for (var el of expands)
  1089. el.onclick = showHitsByDate;
  1090. });
  1091. }.bind(this); //daily overview click event
  1092. //}}}
  1093.  
  1094. function _dbaccess(method, rargs, tfn) {//{{{
  1095. if (!HITStorage.db) { Utils.errorHandler(new TypeError('(AccessViolation) Database is not defined')); return; }
  1096. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], true);
  1097. searchResults.firstChild.click();
  1098. Status.push("Preparing database...", "black");
  1099. metrics.dbrecall = new Metrics("database_recall::"+method);
  1100. metrics.dbrecall.mark("data retrieval", "start");
  1101.  
  1102. HITStorage.recall(rargs[0],rargs[1]).then(function(r) {
  1103. metrics.dbrecall.mark("data retrieval", "end");
  1104. Status.message = "Building HTML...";
  1105. try {
  1106. for (var d of ["hdbResClear","hdbPageTop","hdbVpTop", "hdbPageBot"]) {
  1107. if (~d.search(/page/i) && !/^[sr]/.test(method)) continue;
  1108. document.getElementById(d).style.display = "initial";
  1109. }
  1110. metrics.dbrecall.mark("HTML construction", "start");
  1111. tfn(r);
  1112. metrics.dbrecall.mark("HTML construction", "end");
  1113. } catch(e) {
  1114. Utils.errorHandler(e);
  1115. } finally {
  1116. Utils.disableButtons(['hdbDaily','hdbRequester','hdbPending','hdbSearch'], false);
  1117. autoScroll("#hdbSearchResults");
  1118. Status.push("Done!", "green");
  1119. Progress.hide();
  1120. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1121. }
  1122. });
  1123. }//}}} _dbaccess
  1124. },//}}} dashboardUI::initClickables
  1125.  
  1126. getRange: function(status) {//{{{
  1127. var fromdate = document.getElementById("hdbMinDate"),
  1128. todate = document.getElementById("hdbMaxDate"),
  1129. statusSelect = document.getElementById("hdbStatusSelect");
  1130. var _min = fromdate.value.length > 3 ? fromdate.value : undefined,
  1131. _max = todate.value.length > 3 ? todate.value : undefined;
  1132. status = status || statusSelect.value;
  1133. var _range =
  1134. (_min === undefined && _max === undefined) ?
  1135. (status.length > 1 && !~status.search(/\(/) ? window.IDBKeyRange.only(status) : null) :
  1136. (_min === undefined) ? window.IDBKeyRange.upperBound(_max) :
  1137. (_max === undefined) ? window.IDBKeyRange.lowerBound(_min) :
  1138. (_max < _min) ? window.IDBKeyRange.bound(_max,_min) : window.IDBKeyRange.bound(_min,_max),
  1139. _index = _min === undefined && _max === undefined && status.length > 1 && !~status.search(/\(/) ? "status" : "date";
  1140. return { min: _min, max: _max, range: _range, dir: _max < _min ? "prev" : "next", index: _index };
  1141. }//}}} dashboardUI::getRange
  1142. };//}}} dashboard
  1143.  
  1144. /*
  1145. *
  1146. *
  1147. *
  1148. *
  1149. *///{{{
  1150. // the Set() constructor is never actually used other than to test for Chrome v38+
  1151. // might want to bump requirement up to v45 for those sweet, sweet arrow functions...
  1152. if (!("indexedDB" in window && "Set" in window)) alert("HITDB::Your browser is too outdated or otherwise incompatible with this script!");
  1153. else {
  1154. if (document.location.pathname === "/mturk/dashboard") {
  1155. DashboardUI.draw();
  1156. DashboardUI.initClickables();
  1157. var dbh = window.indexedDB.open(DB_NAME, DB_VERSION);
  1158. dbh.onerror = function(e) { Utils.errorHandler(e.target.error); };
  1159. dbh.onupgradeneeded = HITStorage.versionChange;
  1160. dbh.onsuccess = MERGERSANDACQUISITIONS;
  1161.  
  1162. ProjectedEarnings.updateDate();
  1163. ProjectedEarnings.draw(true);
  1164.  
  1165. var Status = {
  1166. node: document.getElementById("hdbStatusText"),
  1167. get message() { return this.node.textContent; },
  1168. set message(str) { this.node.textContent = str; },
  1169. get color() { return this.node.style.color; },
  1170. set color(c) { this.node.style.color = c; },
  1171. push: function(m,c) { c = c || "black"; this.message = m; this.color = c; }
  1172. }, 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. self.Status = Status; self.Progress = Progress; self.Metrics = Metrics; self.Math.decRound = Math.decRound;
  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. nrow.innerHTML = '<td colspan="7"><table style="width:760;color:#c60;">' + r.formatHTML(null,true) + '</table></td>';
  1451. });
  1452. } else {
  1453. e.target.textContent = "[+]";
  1454. table.removeChild(row.nextSibling);
  1455. }
  1456. }//}}} showHitsByDate
  1457.  
  1458. function updateBonus(e) {//{{{
  1459. if (e instanceof window.KeyboardEvent && e.keyCode === 13) {
  1460. e.target.blur();
  1461. return false;
  1462. } else if (e instanceof window.FocusEvent) {
  1463. var _bonus = +e.target.textContent.replace(/[^\d.]/g,""),
  1464. _tBonusCell = e.target.offsetParent.tFoot.rows[0].cells[4],
  1465. _tBonus = +_tBonusCell.textContent.replace(/\$/,"");
  1466. e.target.textContent = Number(_bonus).toFixed(2);
  1467. _tBonusCell.textContent = '$'+Number(_tBonus-e.target.dataset.initial+_bonus).toFixed(2);
  1468. if (_bonus !== +e.target.dataset.initial) {
  1469. console.log("updating bonus to",_bonus,"from",e.target.dataset.initial,"("+e.target.dataset.hitid+")");
  1470. e.target.dataset.initial = _bonus;
  1471. var _pay = +e.target.previousSibling.textContent,
  1472. _range = window.IDBKeyRange.only(e.target.dataset.hitid);
  1473.  
  1474. HITStorage.db.transaction("HIT", "readwrite").objectStore("HIT").openCursor(_range).onsuccess = function() {
  1475. var c = this.result;
  1476. if (c) {
  1477. var v = c.value;
  1478. v.reward = { pay: _pay, bonus: _bonus };
  1479. c.update(v);
  1480. }
  1481. }; // idbcursor
  1482. } // bonus is new value
  1483. } // keycode
  1484. } //}}} updateBonus
  1485.  
  1486. function noteHandler(type, e) {//{{{
  1487. //
  1488. // TODO restructure event handling/logic tree
  1489. // combine save and delete; it's ugly :(
  1490. // actually this whole thing is messy and in need of refactoring
  1491. //
  1492. if (e instanceof window.KeyboardEvent) {
  1493. if (e.keyCode === 13) {
  1494. e.target.blur();
  1495. return false;
  1496. }
  1497. return;
  1498. }
  1499.  
  1500. if (e instanceof window.FocusEvent) {
  1501. if (e.target.textContent.trim() !== e.target.dataset.initial) {
  1502. if (!e.target.textContent.trim()) { e.target.previousSibling.previousSibling.firstChild.click(); return; }
  1503. var note = e.target.textContent.trim(),
  1504. _range = window.IDBKeyRange.only(e.target.dataset.id),
  1505. inote = e.target.dataset.initial,
  1506. hitId = e.target.dataset.id,
  1507. date = e.target.previousSibling.textContent;
  1508.  
  1509. e.target.dataset.initial = note;
  1510. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1511. if (this.result) {
  1512. var r = this.result.value;
  1513. if (r.note === inote) { // note already exists in database, so we update its value
  1514. r.note = note;
  1515. this.result.update(r);
  1516. return;
  1517. }
  1518. this.result.continue();
  1519. } else {
  1520. if (this.source instanceof window.IDBObjectStore)
  1521. this.source.put({ note:note, date:date, hitId:hitId });
  1522. else
  1523. this.source.objectStore.put({ note:note, date:date, hitId:hitId });
  1524. }
  1525. };
  1526. }
  1527. return; // end of save event; no need to proceed
  1528. }
  1529.  
  1530. if (type === "delete") {
  1531. var tr = e.target.parentNode.parentNode,
  1532. noteCell = tr.lastChild;
  1533. _range = window.IDBKeyRange.only(noteCell.dataset.id);
  1534. if (!noteCell.dataset.initial) tr.remove();
  1535. else {
  1536. HITStorage.db.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1537. if (this.result) {
  1538. if (this.result.value.note === noteCell.dataset.initial) {
  1539. this.result.delete();
  1540. tr.remove();
  1541. return;
  1542. }
  1543. this.result.continue();
  1544. }
  1545. };
  1546. }
  1547. return; // end of deletion event; no need to proceed
  1548. } else {
  1549. if (type === "attach" && !e.results.length) return;
  1550.  
  1551. var trow = e instanceof window.MouseEvent ? e.target.parentNode.parentNode : null,
  1552. tbody = trow ? trow.parentNode : null,
  1553. row = document.createElement("TR"),
  1554. c1 = row.insertCell(0),
  1555. c2 = row.insertCell(1),
  1556. c3 = row.insertCell(2);
  1557. date = new Date();
  1558. hitId = e instanceof window.MouseEvent ? e.target.id.substr(5) : null;
  1559.  
  1560. c1.innerHTML = '<span class="removeNote" title="Delete this note" style="cursor:pointer;color:crimson;">[x]</span>';
  1561. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1562. c1.style.textAlign = "right";
  1563. c2.title = "Date on which the note was added";
  1564. c3.style.color = "crimson";
  1565. c3.colSpan = "6";
  1566. c3.contentEditable = "true";
  1567. c3.onblur = noteHandler.bind(null,"blur");
  1568. c3.onkeydown = noteHandler.bind(null, "kb");
  1569. if (type === "new") {
  1570. row.classList.add(trow.classList);
  1571. tbody.insertBefore(row, trow.nextSibling);
  1572. c2.textContent = date.getFullYear()+"-"+Number(date.getMonth()+1).toPadded()+"-"+Number(date.getDate()).toPadded();
  1573. c3.dataset.initial = "";
  1574. c3.dataset.id = hitId;
  1575. c3.focus();
  1576. return;
  1577. }
  1578.  
  1579. for (var entry of e.results) {
  1580. trow = document.querySelector('tr[data-id="'+entry.hitId+'"]');
  1581. tbody = trow.parentNode;
  1582. row = row.cloneNode(true);
  1583. c1 = row.firstChild;
  1584. c2 = c1.nextSibling;
  1585. c3 = row.lastChild;
  1586. row.classList.add(trow.classList);
  1587. tbody.insertBefore(row, trow.nextSibling);
  1588.  
  1589. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1590. c2.textContent = entry.date;
  1591. c3.textContent = entry.note;
  1592. c3.dataset.initial = entry.note;
  1593. c3.dataset.id = entry.hitId;
  1594. c3.onblur = noteHandler.bind(null,"blur");
  1595. c3.onkeydown = noteHandler.bind(null, "kb");
  1596. }
  1597. } // new/attach
  1598. }//}}} noteHandler
  1599.  
  1600. // writing callback functions {{{
  1601. function cbImport() {
  1602. /*jshint validthis:true*/
  1603. Status.push("Importing " + this.total + " entries");
  1604. if (++this.total !== this.requests) return;
  1605. Status.push("Importing " + this.total + " entries... Done!", "green");
  1606. try { Progress.hide(); metrics.dbimport.stop(); metrics.dbimport.report(); } catch(err) {}
  1607. }
  1608. function cbUpdate() {
  1609. /*jshint validthis:true*/
  1610. if (++this.total !== this.requests) return;
  1611. if (qc.extraDays) qc.extraDays = false;
  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. function MERGERSANDACQUISITIONS() {//{{{
  1864. var merge = localStorage.getItem('hitdb_merge') || false;
  1865. HITStorage.db = this.result;
  1866. self.HITStorage = {db: this.result};
  1867. if (merge) return;
  1868.  
  1869. console.log('merging databases...');
  1870. Progress.show(); Status.push('Merging databases; please wait...');
  1871. Utils.disableButtons(['hdbBackup', 'hdbRestore', 'hdbUpdate', 'hdbPending', 'hdbRequester', 'hdbDaily', 'hdbSearch'], true);
  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. new Promise(function(a) { HITStorage.backup(a); }).then(function() {
  1880. var source = HITStorage.db;
  1881. HITStorage.db = dest;
  1882. HITStorage.write(qc.merge, cbImport);
  1883. source.close(); 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. Utils.disableButtons(['hdbBackup', 'hdbRestore', 'hdbUpdate', 'hdbPending', 'hdbRequester', 'hdbDaily', 'hdbSearch'], false);
  1892. });
  1893. }//}}}
  1894. })(); //scoping
  1895.  
  1896. // vim: ts=2:sw=2:et:fdm=marker:noai