MTurk HIT Database Mk.II

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

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

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