MTurk HIT Database Mk.II

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

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

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