MTurk HIT Database Mk.II

Keep track of the HITs you've done (and more!)

当前为 2015-08-27 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name MTurk HIT Database Mk.II
  3. // @author feihtality
  4. // @namespace https://greasyfork.org/en/users/12709
  5. // @version 0.8.025
  6. // @description Keep track of the HITs you've done (and more!)
  7. // @include /^https://www\.mturk\.com/mturk/(dash|view|sort|find|prev|search).*/
  8. // @exclude https://www.mturk.com/mturk/findhits?*hit_scraper
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. /**\
  13. **
  14. ** This is a complete rewrite of the MTurk HIT Database script from the ground up, which
  15. ** eliminates obsolete methods, fixes many bugs, and brings this script up-to-date
  16. ** with the current modern browser environment.
  17. **
  18. \**/
  19.  
  20.  
  21. /*
  22. * TODO
  23. * optimize searching: index -> date filter
  24. * rewrite error handling
  25. * tagging (?)
  26. * refine searching via R/T buttons
  27. * import from old csv format
  28. *
  29. */
  30.  
  31.  
  32.  
  33. const DB_VERSION = 2;
  34. const DB_NAME = 'HITDB_TESTING';
  35. const MTURK_BASE = 'https://www.mturk.com/mturk/';
  36. //const TO_BASE = 'http://turkopticon.ucsd.edu/api/multi-attrs.php';
  37.  
  38. // polyfill for chrome until v45(?)
  39. if (!NodeList.prototype[Symbol.iterator]) NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  40. // format leading zeros
  41. Number.prototype.toPadded = function(length) {
  42. 'use strict';
  43.  
  44. length = length || 2;
  45. return ("0000000"+this).substr(-length);
  46. };
  47. // decimal rounding
  48. Math.decRound = function(v, shift) {
  49. 'use strict';
  50.  
  51. v = Math.round(+(v+"e"+shift));
  52. return +(v+"e"+-shift);
  53. };
  54. Date.prototype.toLocalISOString = function() {
  55. 'use strict';
  56.  
  57. var pad = function(num) { return Number(num).toPadded(); },
  58. offset = pad(Math.floor(this.getTimezoneOffset()/60)) + pad(this.getTimezoneOffset()%60),
  59. timezone = this.getTimezoneOffset() > 0 ? "-" + offset : "+" + offset;
  60. return this.getFullYear() + "-" + pad(this.getMonth()+1) + "-" + pad(this.getDate()) +
  61. "T" + pad(this.getHours()) + ":" + pad(this.getMinutes()) + ":" + pad(this.getSeconds()) + timezone;
  62. };
  63.  
  64. /***********************************************************************************************/
  65.  
  66. var qc = { extraDays: !!localStorage.getItem("hitdb_extraDays") || false, seen: {} },
  67. metrics = {};
  68. if (localStorage.getItem("hitdb_fetchData"))
  69. qc.fetchData = JSON.parse(localStorage.getItem("hitdb_fetchData"));
  70. else
  71. qc.fetchData = {};
  72.  
  73. var HITStorage = { //{{{
  74. data: {},
  75.  
  76. versionChange: function hsversionChange() { //{{{
  77. 'use strict';
  78.  
  79. var db = this.result;
  80. db.onerror = HITStorage.error;
  81. db.onversionchange = function(e) { console.log("detected version change??",console.dir(e)); db.close(); };
  82. this.onsuccess = function() { db.close(); };
  83. var dbo;
  84.  
  85. console.groupCollapsed("HITStorage.versionChange::onupgradeneeded");
  86.  
  87. if (!db.objectStoreNames.contains("HIT")) {
  88. console.log("creating HIT OS");
  89. dbo = db.createObjectStore("HIT", { keyPath: "hitId" });
  90. dbo.createIndex("date", "date", { unique: false });
  91. dbo.createIndex("requesterName", "requesterName", { unique: false});
  92. dbo.createIndex("title", "title", { unique: false });
  93. dbo.createIndex("reward", "reward", { unique: false });
  94. dbo.createIndex("status", "status", { unique: false });
  95. dbo.createIndex("requesterId", "requesterId", { unique: false });
  96.  
  97. localStorage.setItem("hitdb_extraDays", true);
  98. qc.extraDays = true;
  99. }
  100. if (!db.objectStoreNames.contains("STATS")) {
  101. console.log("creating STATS OS");
  102. dbo = db.createObjectStore("STATS", { keyPath: "date" });
  103. }
  104. if (this.transaction.objectStore("STATS").indexNames.length < 5) { // new in v5: schema additions
  105. this.transaction.objectStore("STATS").createIndex("approved", "approved", { unique: false });
  106. this.transaction.objectStore("STATS").createIndex("earnings", "earnings", { unique: false });
  107. this.transaction.objectStore("STATS").createIndex("pending", "pending", { unique: false });
  108. this.transaction.objectStore("STATS").createIndex("rejected", "rejected", { unique: false });
  109. this.transaction.objectStore("STATS").createIndex("submitted", "submitted", { unique: false });
  110. }
  111.  
  112. (function _updateNotes(dbt) { // new in v5: schema change
  113. if (!db.objectStoreNames.contains("NOTES")) {
  114. console.log("creating NOTES OS");
  115. dbo = db.createObjectStore("NOTES", { keyPath: "id", autoIncrement: true });
  116. dbo.createIndex("hitId", "hitId", { unique: false });
  117. dbo.createIndex("requesterId", "requesterId", { unique: false });
  118. dbo.createIndex("tags", "tags", { unique: false, multiEntry: true });
  119. dbo.createIndex("date", "date", { unique: false });
  120. }
  121. if (db.objectStoreNames.contains("NOTES") && dbt.objectStore("NOTES").indexNames.length < 3) {
  122. _mv(db, dbt, "NOTES", "NOTES", _updateNotes);
  123. }
  124. })(this.transaction);
  125.  
  126. if (db.objectStoreNames.contains("BLOCKS")) {
  127. console.log("migrating BLOCKS to NOTES");
  128. var temp = [];
  129. this.transaction.objectStore("BLOCKS").openCursor().onsuccess = function() {
  130. var cursor = this.result;
  131. if (cursor) {
  132. temp.push( {
  133. requesterId: cursor.value.requesterId,
  134. tags: "Blocked",
  135. note: "This requester was blocked under the old HitDB. Blocking has been deprecated and removed "+
  136. "from HIT Databse. All blocks have been converted to a Note."
  137. } );
  138. cursor.continue();
  139. } else {
  140. console.log("deleting blocks");
  141. db.deleteObjectStore("BLOCKS");
  142. for (var entry of temp)
  143. this.transaction.objectStore("NOTES").add(entry);
  144. }
  145. };
  146. }
  147.  
  148. function _mv(db, transaction, source, dest, fn) { //{{{
  149. var _data = [];
  150. transaction.objectStore(source).openCursor().onsuccess = function() {
  151. var cursor = this.result;
  152. if (cursor) {
  153. _data.push(cursor.value);
  154. cursor.continue();
  155. } else {
  156. db.deleteObjectStore(source);
  157. fn(transaction);
  158. if (_data.length)
  159. for (var i=0;i<_data.length;i++)
  160. transaction.objectStore(dest).add(_data[i]);
  161. //console.dir(_data);
  162. }
  163. };
  164. } //}}}
  165.  
  166. console.groupEnd();
  167. }, // }}} versionChange
  168.  
  169. error: function(e) { //{{{
  170. 'use strict';
  171.  
  172. if (e === "DatabaseCreationError") {
  173. var s = document.getElementById("hdbStatusText");
  174. s.style.color = "red";
  175. s.innerHTML = "Something went wrong during database creation!<br>Please refresh the page and try again";
  176. console.log("Writing failed with",e);
  177. return;
  178. }
  179. if (typeof e === "string")
  180. console.log(e);
  181. else
  182. console.log("Encountered",e.target.error.name,"--",e.target.error.message,e);
  183. }, //}}} onerror
  184.  
  185. parseDOM: function(doc) {//{{{
  186. 'use strict';
  187. var statusLabel = document.querySelector("#hdbStatusText");
  188. statusLabel.style.color = "black";
  189.  
  190. var errorCheck = doc.querySelector('td[class="error_title"]');
  191.  
  192. if (doc.title.search(/Status$/) > 0) // status overview
  193. parseStatus();
  194. else if (doc.querySelector('td[colspan="4"]')) // valid status detail, but no data
  195. parseMisc("next");
  196. else if (doc.title.search(/Status Detail/) > 0) // status detail with data
  197. parseDetail();
  198. else if (errorCheck) { // encountered an error page
  199. // hit max request rate
  200. if (~errorCheck.textContent.indexOf("page request rate")) {
  201. var _d = doc.documentURI.match(/\d{8}/)[0],
  202. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  203. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "start");
  204. console.log("exceeded max requests; refetching", doc.documentURI);
  205. statusLabel.innerHTML = "Exceeded maximum server requests; retrying "+HITStorage.ISODate(_d)+" page "+_p+"."+
  206. "<br>Please wait...";
  207. setTimeout(HITStorage.fetch, 550, doc.documentURI);
  208. return;
  209. }
  210. // no more staus details left in range
  211. else if (qc.extraDays)
  212. parseMisc("end");
  213. }
  214. else
  215. throw "ParseError::unhandled document received @"+doc.documentURI;
  216.  
  217.  
  218. function parseStatus() {//{{{
  219. HITStorage.data = { HIT: [], STATS: [] };
  220. qc.seen = {};
  221. ProjectedEarnings.clear();
  222.  
  223. var _pastDataExists = Boolean(Object.keys(qc.fetchData).length);
  224. var raw = {
  225. day: doc.querySelectorAll(".statusDateColumnValue"),
  226. sub: doc.querySelectorAll(".statusSubmittedColumnValue"),
  227. app: doc.querySelectorAll(".statusApprovedColumnValue"),
  228. rej: doc.querySelectorAll(".statusRejectedColumnValue"),
  229. pen: doc.querySelectorAll(".statusPendingColumnValue"),
  230. pay: doc.querySelectorAll(".statusEarningsColumnValue")
  231. };
  232. var timeout = 0;
  233. for (var i=0;i<raw.day.length;i++) {
  234. var d = {};
  235. var _date = raw.day[i].childNodes[1].href.substr(53);
  236. d.date = HITStorage.ISODate(_date);
  237. d.submitted = +raw.sub[i].textContent;
  238. d.approved = +raw.app[i].textContent;
  239. d.rejected = +raw.rej[i].textContent;
  240. d.pending = +raw.pen[i].textContent;
  241. d.earnings = +raw.pay[i].textContent.substr(1);
  242. HITStorage.data.STATS.push(d);
  243.  
  244. // check whether or not we need to get status detail pages for date, then
  245. // fetch status detail pages per date in range and slightly slow
  246. // down GET requests to avoid making too many in too short an interval
  247. var payload = { encodedDate: _date, pageNumber: 1, sortType: "All" };
  248. if (_pastDataExists) {
  249. // date not in range but is new date (or old date but we need updates)
  250. // lastDate stored in ISO format, fetchData date keys stored in mturk's URI ecnodedDate format
  251. if ( (d.date > qc.fetchData.lastDate) || ~(Object.keys(qc.fetchData).indexOf(_date)) ) {
  252. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  253. timeout += 250;
  254.  
  255. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  256. }
  257. } else { // get everything
  258. setTimeout(HITStorage.fetch, timeout, MTURK_BASE+"statusdetail", payload);
  259. timeout += 250;
  260.  
  261. qc.fetchData[_date] = { submitted: d.submitted, pending: d.pending };
  262. }
  263. } // for
  264. qc.fetchData.expectedTotal = _calcTotals(qc.fetchData);
  265.  
  266. // try for extra days
  267. if (qc.extraDays === true) {
  268. localStorage.removeItem("hitdb_extraDays");
  269. d = _decDate(HITStorage.data.STATS[HITStorage.data.STATS.length-1].date);
  270. qc.extraDays = d; // repurpose extraDays for QC
  271. payload = { encodedDate: d, pageNumber: 1, sortType: "All" };
  272. console.log("fetchrequest for", d, "sent by parseStatus");
  273. setTimeout(HITStorage.fetch, 1000, MTURK_BASE+"statusdetail", payload);
  274. }
  275. qc.fetchData.lastDate = HITStorage.data.STATS[0].date; // most recent date seen
  276.  
  277. }//}}} parseStatus
  278.  
  279. function parseDetail() {//{{{
  280. var _date = doc.documentURI.replace(/.+(\d{8}).+/, "$1");
  281. var _page = doc.documentURI.replace(/.+ber=(\d+).+/, "$1");
  282.  
  283. metrics.dbupdate.mark("[PRE]"+_date+"p"+_page, "end");
  284. console.log("page:", _page, "date:", _date);
  285. statusLabel.textContent = "Processing "+HITStorage.ISODate(_date)+" page "+_page;
  286. var raw = {
  287. req: doc.querySelectorAll(".statusdetailRequesterColumnValue"),
  288. title: doc.querySelectorAll(".statusdetailTitleColumnValue"),
  289. pay: doc.querySelectorAll(".statusdetailAmountColumnValue"),
  290. status: doc.querySelectorAll(".statusdetailStatusColumnValue"),
  291. feedback: doc.querySelectorAll(".statusdetailRequesterFeedbackColumnValue")
  292. };
  293.  
  294. for (var i=0;i<raw.req.length;i++) {
  295. var d = {};
  296. d.date = HITStorage.ISODate(_date);
  297. d.feedback = raw.feedback[i].textContent.trim();
  298. d.hitId = raw.req[i].childNodes[1].href.replace(/.+HIT\+(.+)/, "$1");
  299. d.requesterId = raw.req[i].childNodes[1].href.replace(/.+rId=(.+?)&.+/, "$1");
  300. d.requesterName = raw.req[i].textContent.trim().replace(/\|/g,"");
  301. d.reward = +raw.pay[i].textContent.substr(1);
  302. d.status = raw.status[i].textContent;
  303. d.title = raw.title[i].textContent.replace(/\|/g, "");
  304. HITStorage.data.HIT.push(d);
  305.  
  306. if (!qc.seen[_date]) qc.seen[_date] = {};
  307. qc.seen[_date] = {
  308. submitted: qc.seen[_date].submitted + 1 || 1,
  309. pending: ~d.status.search(/pending/i) ?
  310. (qc.seen[_date].pending + 1 || 1) : (qc.seen[_date].pending || 0)
  311. };
  312.  
  313. ProjectedEarnings.updateValues(d);
  314. }
  315.  
  316. // additional pages remain; get them
  317. if (doc.querySelector('img[src="/media/right_dbl_arrow.gif"]')) {
  318. var payload = { encodedDate: _date, pageNumber: +_page+1, sortType: "All" };
  319. setTimeout(HITStorage.fetch, 250, MTURK_BASE+"statusdetail", payload);
  320. return;
  321. }
  322.  
  323. if (!qc.extraDays) { // not fetching extra days
  324. //no longer any more useful data here, don't need to keep rechecking this date
  325. if (HITStorage.ISODate(_date) !== qc.fetchData.lastDate &&
  326. qc.seen[_date].submitted === qc.fetchData[_date].submitted &&
  327. qc.seen[_date].pending === 0) {
  328. console.log("no more pending hits, removing",_date,"from fetchData");
  329. delete qc.fetchData[_date];
  330. localStorage.setItem("hitdb_fetchData", JSON.stringify(qc.fetchData));
  331. }
  332. // finished scraping; start writing
  333. console.log("totals", _calcTotals(qc.seen), qc.fetchData.expectedTotal);
  334. statusLabel.textContent += " [ "+_calcTotals(qc.seen)+"/"+ qc.fetchData.expectedTotal+" ]";
  335. if (_calcTotals(qc.seen) === qc.fetchData.expectedTotal) {
  336. statusLabel.textContent = "Writing to database...";
  337. HITStorage.write(HITStorage.data, "update");
  338. }
  339. } else if (_date <= qc.extraDays) { // day is older than default range and still fetching extra days
  340. parseMisc("next");
  341. console.log("fetchrequest for", _decDate(HITStorage.ISODate(_date)));
  342. }
  343. }//}}} parseDetail
  344.  
  345. function parseMisc(type) {//{{{
  346. var _d = doc.documentURI.match(/\d{8}/)[0],
  347. _p = doc.documentURI.match(/ber=(\d+)/)[1];
  348. metrics.dbupdate.mark("[PRE]"+_d+"p"+_p, "end");
  349. var payload = { encodedDate: _decDate(HITStorage.ISODate(_d)), pageNumber: 1, sortType: "All" };
  350.  
  351. if (type === "next" && +qc.extraDays > 1) {
  352. setTimeout(HITStorage.fetch, 250, MTURK_BASE+"statusdetail", payload);
  353. console.log("going to next page", payload.encodedDate);
  354. } else if (type === "end" && +qc.extraDays > 1) {
  355. statusLabel.textContent = "Writing to database...";
  356. HITStorage.write(HITStorage.data, "update");
  357. } else
  358. throw 'Unhandled case -- "'+type+'" in '+doc.documentURI;
  359. }//}}}
  360.  
  361. function _decDate(date) {//{{{
  362. var y = date.substr(0,4);
  363. var m = date.substr(5,2);
  364. var d = date.substr(8,2);
  365. date = new Date(y,m-1,d-1);
  366. return Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded() + date.getFullYear();
  367. }//}}}
  368.  
  369. function _calcTotals(obj) {//{{{
  370. var sum = 0;
  371. for (var k in obj){
  372. if (obj.hasOwnProperty(k) && !isNaN(+k))
  373. sum += obj[k].submitted;
  374. }
  375. return sum;
  376. }//}}}
  377. },//}}} parseDOM
  378. ISODate: function(date) { //{{{ MMDDYYYY <-> YYYY-MM-DD
  379. 'use strict';
  380.  
  381. if (date.length === 10)
  382. return date.substr(5,2)+date.substr(-2)+date.substr(0,4);
  383. else
  384. return date.substr(4)+"-"+date.substr(0,2)+"-"+date.substr(2,2);
  385. }, //}}} ISODate
  386.  
  387. fetch: function(url, payload) { //{{{
  388. 'use strict';
  389.  
  390. //format GET request with query payload
  391. if (payload) {
  392. var args = 0;
  393. url += "?";
  394. for (var k in payload) {
  395. if (payload.hasOwnProperty(k)) {
  396. if (args++) url += "&";
  397. url += k + "=" + payload[k];
  398. }
  399. }
  400. }
  401. // defer XHR to a promise
  402. var fetch = new Promise( function(fulfill, deny) {
  403. var urlreq = new XMLHttpRequest();
  404. urlreq.open("GET", url, true);
  405. urlreq.responseType = "document";
  406. urlreq.send();
  407. urlreq.onload = function() {
  408. if (this.status === 200) {
  409. fulfill(this.response);
  410. } else {
  411. deny("Error ".concat(String(this.status)).concat(": "+this.statusText));
  412. }
  413. };
  414. urlreq.onerror = function() { deny("Error ".concat(String(this.status)).concat(": "+this.statusText)); };
  415. urlreq.ontimeout = function() { deny("Error ".concat(String(this.status)).concat(": "+this.statusText)); };
  416. } );
  417. fetch.then( HITStorage.parseDOM, HITStorage.error );
  418.  
  419. }, //}}} fetch
  420. write: function(input, statusUpdate) { //{{{
  421. 'use strict';
  422.  
  423. if (statusUpdate === "update")
  424. qc.timeoutTimer = setTimeout(HITStorage.error, 5555, "DatabaseCreationError");
  425.  
  426. var dbh = window.indexedDB.open(DB_NAME);
  427. dbh.onerror = HITStorage.error;
  428. dbh.onsuccess = function() { _write(this.result); };
  429.  
  430. var counts = { requests: 0, total: 0 };
  431.  
  432. function _write(db) {
  433. db.onerror = HITStorage.error;
  434. var os = Object.keys(input);
  435.  
  436. var dbt = db.transaction(os, "readwrite");
  437. var dbo = [];
  438. for (var i=0;i<os.length;i++) { // cycle object stores
  439. dbo[i] = dbt.objectStore(os[i]);
  440. for (var k of input[os[i]]) { // cycle entries to put into object stores
  441. if (statusUpdate && ++counts.requests)
  442. dbo[i].put(k).onsuccess = _statusCallback;
  443. else
  444. dbo[i].put(k);
  445. }
  446. }
  447. db.close();
  448. }
  449.  
  450. function _statusCallback() {
  451. if (++counts.total === counts.requests) {
  452. var statusLabel = document.querySelector("#hdbStatusText");
  453. statusLabel.style.color = "green";
  454. statusLabel.textContent = statusUpdate === "update" ? "Update Complete!" :
  455. statusUpdate === "restore" ? "Restoring " + counts.total + " entries... Done!" :
  456. "Done!";
  457. document.querySelector("#hdbProgressBar").style.display = "none";
  458.  
  459. if (statusUpdate === "update") {
  460. clearTimeout(qc.timeoutTimer);
  461. ProjectedEarnings.data.dbUpdated = new Date().toLocalISOString();
  462. ProjectedEarnings.saveState();
  463. ProjectedEarnings.draw(false);
  464.  
  465. metrics.dbupdate.stop();
  466. metrics.dbupdate.report();
  467. }
  468. }
  469. }
  470.  
  471. }, //}}} write
  472.  
  473. recall: function(store, options) {//{{{
  474. 'use strict';
  475.  
  476. var index = options ? (options.index || null) : null,
  477. range = options ? (options.range || null) : null,
  478. dir = options ? (options.dir || "next") : "next",
  479. fs = options ? (options.filter ? options.filter.status !== "*" ? new RegExp(options.filter.status, "i") : false : false) : false,
  480. fq = options ? (options.filter ? options.filter.query !== "*" ? new RegExp(options.filter.query,"i") : false : false) : false,
  481. limit = 0;
  482.  
  483. if (options && options.progress) {
  484. var progressBar = document.querySelector("#hdbProgressBar");
  485. //statusText = document.querySelector("#hdbStatusText");
  486. progressBar.style.display = "block";
  487. }
  488. var sr = new DatabaseResult();
  489. return new Promise( function(resolve) {
  490. window.indexedDB.open(DB_NAME).onsuccess = function() {
  491. var dbo = this.result.transaction(store, "readonly").objectStore(store), dbq = null;
  492. if (index)
  493. dbq = dbo.index(index).openCursor(range, dir);
  494. else
  495. dbq = dbo.openCursor(range, dir);
  496. dbq.onsuccess = function() {
  497. var c = this.result;
  498. if (c) {
  499. if ( (!fs && !fq) || // no query filter and no status filter OR
  500. (fs && !fq && ~c.value.status.search(fs)) || // status match and no query filter OR
  501. (!fs && fq && // query match and no status filter OR
  502. (~c.value.title.search(fq) || ~c.value.requesterName.search(fq) || ~c.value.hitId.search(fq))) ||
  503. (fs && fq && ~c.value.status.search(fs) && // status match and query match
  504. (~c.value.title.search(fq) || ~c.value.requesterName.search(fq) || ~c.value.hitId.search(fq))) )
  505. if (limit++ < 3800) // limit to save memory usage in large databases
  506. sr.include(c.value);
  507. c.continue();
  508. } else
  509. resolve(sr);
  510. };
  511. };
  512. } ); // promise
  513. },//}}} recall
  514.  
  515. backup: function() {//{{{
  516. 'use strict';
  517.  
  518. var bData = {},
  519. os = ["STATS", "NOTES", "HIT"],
  520. count = 0,
  521. prog = document.querySelector("#hdbProgressBar");
  522.  
  523. prog.style.display = "block";
  524.  
  525. window.indexedDB.open(DB_NAME).onsuccess = function() {
  526. for (var store of os) {
  527. this.result.transaction(os, "readonly").objectStore(store).openCursor().onsuccess = populateBackup;
  528. }
  529. };
  530. function populateBackup(e) {
  531. var cursor = e.target.result;
  532. if (cursor) {
  533. if (!bData[cursor.source.name]) bData[cursor.source.name] = [];
  534. bData[cursor.source.name].push(cursor.value);
  535. cursor.continue();
  536. } else
  537. if (++count === 3)
  538. finalizeBackup();
  539. }
  540. function finalizeBackup() {
  541. var backupblob = new Blob([JSON.stringify(bData)], {type:"application/json"});
  542. var date = new Date();
  543. var dl = document.createElement("A");
  544. date = date.getFullYear() + Number(date.getMonth()+1).toPadded() + Number(date.getDate()).toPadded();
  545. dl.href = URL.createObjectURL(backupblob);
  546. console.log(dl.href);
  547. dl.download = "hitdb_"+date+".bak";
  548. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  549. dl.click(); // so we make it so and click,
  550. dl.remove(); // then immediately remove it
  551. prog.style.display = "none";
  552. }
  553.  
  554. }//}}} backup
  555.  
  556. };//}}} HITStorage
  557.  
  558. // ProjectedEarnings doesn't belong up here, but it needs to be for variable assignment purposes :(
  559. var ProjectedEarnings = {//{{{
  560. data: localStorage.getItem("hitdb_projectedEarnings") ?
  561. JSON.parse(localStorage.getItem("hitdb_projectedEarnings")) : {},
  562.  
  563. updateDate: function() {//{{{
  564. 'use strict';
  565.  
  566. var el = document.querySelectorAll(".metrics-table")[5].querySelector(".metrics-table-first-value").children[0],
  567. date = el.href.match(/\d{8}/)[0],
  568. day = el.textContent,
  569. isToday = day === "Today",
  570. _date = new Date(),
  571. weekEnd = Date.parse(_date.getFullYear() + "-" +
  572. Number(_date.getMonth()+1).toPadded() + "-" + Number(_date.getDate()-_date.getDay()+7).toPadded()),
  573. weekStart = Date.parse(_date.getFullYear() + "-" +
  574. Number(_date.getMonth()+1).toPadded() + "-" + Number(_date.getDate()-_date.getDay()).toPadded());
  575.  
  576. if (!Object.keys(this.data).length) {
  577. this.data = {
  578. today: date, weekStart: weekStart, weekEnd: weekEnd, day: _date.getDay(), dbUpdated: "n/a",
  579. pending: 0, earnings: { day: 0, week: 0 }, target: { day: 0, week: 0 }
  580. };
  581. }
  582.  
  583. if ( (Date.parse(HITStorage.ISODate(date)) >= this.data.weekEnd) ||
  584. (!isToday && _date.getDay() < this.data.day) ) { // new week
  585. this.data.earnings.week = 0;
  586. this.data.weekEnd = weekEnd;
  587. this.data.weekStart = weekStart;
  588. }
  589. if (date !== this.data.today || !isToday) { // new day
  590. this.data.today = date;
  591. this.data.day = _date.getDay();
  592. this.data.earnings.day = 0;
  593. }
  594.  
  595. this.saveState();
  596. },//}}} updateDate
  597. draw: function(init) {//{{{
  598. 'use strict';
  599.  
  600. var parentTable = document.querySelector("#total_earnings_amount").offsetParent,
  601. rowPending = init ? parentTable.insertRow(-1) : parentTable.rows[4],
  602. rowProjectedDay = init ? parentTable.insertRow(-1) : parentTable.rows[5],
  603. rowProjectedWeek = init ? parentTable.insertRow(-1) : parentTable.rows[6],
  604. title = "Click to set/change the target value";
  605.  
  606. if (init) {
  607. rowPending.insertCell(-1);rowPending.insertCell(-1);rowPending.className = "even";
  608. rowProjectedDay.insertCell(-1);rowProjectedDay.insertCell(-1);rowProjectedDay.className = "odd";
  609. rowProjectedWeek.insertCell(-1);rowProjectedWeek.insertCell(-1);rowProjectedWeek.className = "even";
  610. for (var i=0;i<rowPending.cells.length;i++) rowPending.cells[i].style.borderTop = "dotted 1px black";
  611. rowPending.cells[0].className = "metrics-table-first-value";
  612. rowProjectedDay.cells[0].className = "metrics-table-first-value";
  613. rowProjectedWeek.cells[0].className = "metrics-table-first-value";
  614. rowPending.cells[1].title = "This value includes all earnings that are not yet fully cleared as 'Paid'";
  615. }
  616.  
  617. rowPending.cells[0].innerHTML = 'Pending earnings '+
  618. '<span style="font-family:arial;font-size:10px;" title="Timestamp of last database update">[ ' + this.data.dbUpdated + ' ]</span>';
  619. rowPending.cells[1].textContent = "$"+Number(this.data.pending).toFixed(2);
  620. rowProjectedDay.cells[0].innerHTML = 'Projected earnings for the day<br>'+
  621. '<meter id="projectedDayProgress" style="width:220px;" title="'+title+
  622. '" value="'+this.data.earnings.day+'" max="'+this.data.target.day+'"></meter>'+
  623. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + Number(this.data.earnings.day-this.data.target.day).toFixed(2) + '</span>';
  624. rowProjectedDay.cells[1].textContent = "$"+Number(this.data.earnings.day).toFixed(2);
  625. rowProjectedWeek.cells[0].innerHTML = 'Projected earnings for the week<br>' +
  626. '<meter id="projectedWeekProgress" style="width:220px;" title="'+title+
  627. '" value="'+this.data.earnings.week+'" max="'+this.data.target.week+'"></meter>' +
  628. '<span style="color:blue;font-family:arial;font-size:10px;"> ' + Number(this.data.earnings.week-this.data.target.week).toFixed(2) + '</span>';
  629. rowProjectedWeek.cells[1].textContent = "$"+Number(this.data.earnings.week).toFixed(2);
  630.  
  631. document.querySelector("#projectedDayProgress").onclick = updateTargets.bind(this, "day");
  632. document.querySelector("#projectedWeekProgress").onclick = updateTargets.bind(this, "week");
  633.  
  634. function updateTargets(span, e) {
  635. /*jshint validthis:true*/
  636. var goal = prompt("Set your " + (span === "day" ? "daily" : "weekly") + " target:",
  637. this.data.target[span === "day" ? "day" : "week"]);
  638. if (goal && !isNaN(goal)) {
  639. this.data.target[span === "day" ? "day" : "week"] = goal;
  640. e.target.max = goal;
  641. e.target.nextSibling.textContent = Number(this.data.earnings[span==="day" ? "day":"week"] - goal).toFixed(2);
  642. this.saveState();
  643. }
  644. }
  645. },//}}} draw
  646. saveState: function() {
  647. 'use strict';
  648.  
  649. localStorage.setItem("hitdb_projectedEarnings", JSON.stringify(this.data));
  650. },
  651.  
  652. clear: function() {
  653. 'use strict';
  654.  
  655. this.data.earnings = { day:0, week:0 };
  656. this.data.pending = 0;
  657. },
  658.  
  659. updateValues: function(obj) {
  660. 'use strict';
  661.  
  662. var vDate = Date.parse(obj.date);
  663.  
  664. if (~obj.status.search(/pending/i)) // sum pending earnings (include approved until fully cleared as paid)
  665. this.data.pending = Math.decRound(obj.reward+this.data.pending, 2);
  666. if (HITStorage.ISODate(obj.date) === this.data.today && !~obj.status.search(/rejected/i)) // sum daily earnings
  667. this.data.earnings.day = Math.decRound(obj.reward+this.data.earnings.day, 2);
  668. if (vDate < this.data.weekEnd && vDate >= this.data.weekStart && !~obj.status.search(/rejected/i)) // sum weekly earnings
  669. this.data.earnings.week = Math.decRound(obj.reward+this.data.earnings.week, 2);
  670. }
  671. };//}}} ProjectedEarnings
  672.  
  673. function DatabaseResult() {//{{{
  674. 'use strict';
  675.  
  676. this.results = [];
  677. this.formatHTML = function(type, simple) {//{{{
  678. simple = simple || false;
  679. var count = 0, htmlTxt = [], entry = null, _trClass = null;
  680.  
  681. if (this.results.length < 1) return "<h2>No entries found matching your query.</h2>";
  682.  
  683. if (type === "daily") {
  684. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th style="background:white;"></th>'+
  685. '<th>Date</th><th>Submitted</th><th>Approved</th><th>Rejected</th><th>Pending</th><th>Earnings</th></tr></thead><tbody>');
  686. var r = _collate(this.results,"date");
  687. for (entry of this.results) {
  688. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  689. htmlTxt.push('<tr '+_trClass+' style="text-align:center"><td style="background:white;"></td>'+
  690. '<td>' + entry.date + '</td><td>' + entry.submitted + '</td>' +
  691. '<td>' + entry.approved + '</td><td>' + entry.rejected + '</td><td>' + entry.pending + '</td>' +
  692. '<td>' + Number(entry.earnings).toFixed(2) + '</td></tr>');
  693. }
  694. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td style="text-align:right;">Totals:</td>' +
  695. '<td style="text-align:right;">' + r.totalEntries + ' days</td><td style="text-align:center;">' + r.totalSub + '</td>' +
  696. '<td style="text-align:center;">' + r.totalApp + '</td><td style="text-align:center;">' + r.totalRej + '</td>' +
  697. '<td style="text-align:center;">' + r.totalPen + '</td><td style="text-align:center;">$' +
  698. Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  699. } else if (type === "pending" || type === "requester") {
  700. htmlTxt.push('<thead><tr data-sort="99999" class="hdbHeaderRow"><th>Requester ID</th>' +
  701. '<th width="500">Requester</th><th>' + (type === "pending" ? 'Pending' : 'HITs') + '</th><th>Rewards</th></tr></thead><tbody>');
  702. r = _collate(this.results,"requesterId");
  703. for (var k in r) {
  704. if (!~k.search(/total/) && r.hasOwnProperty(k)) {
  705. var tr = ['<tr data-hits="'+r[k].length+'"><td>' +
  706. '<span style="cursor:pointer;color:blue;" class="hdbExpandRow" title="Display all pending HITs from this requester">' +
  707. '[+]</span> ' + r[k][0].requesterId + '</td><td>' + r[k][0].requesterName + '</td>' +
  708. '<td style="text-align:center;">' + r[k].length + '</td><td>' + Number(Math.decRound(r[k].pay,2)).toFixed(2) + '</td></tr>'];
  709.  
  710. for (var hit of r[k]) { // hits in range per requester id
  711. tr.push('<tr data-rid="'+r[k][0].requesterId+'" style="color:#c60000;display:none;"><td style="text-align:right">' + hit.date + '</td>' +
  712. '<td width="500">' + hit.title + '</td><td></td><td style="text-align:right">' + _parseRewards(hit.reward,"pay") + '</td></tr>');
  713. }
  714. htmlTxt.push(tr.join(''));
  715. }
  716. }
  717. htmlTxt.sort(function(a,b) { return +b.substr(15,5).match(/\d+/) - +a.substr(15,5).match(/\d+/); });
  718. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td style="text-align:right;">Totals:</td>' +
  719. '<td style="text-align:center;">' + (Object.keys(r).length-7) + ' Requesters</td>' +
  720. '<td style="text-align:right;">' + r.totalEntries + '</td>'+
  721. '<td style="text-align:right;">$' + Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td></tr></tfoot>');
  722. } else { // default
  723. if (!simple)
  724. htmlTxt.push('<thead><tr class="hdbHeaderRow"><th colspan="3"></th>' +
  725. '<th colspan="2" title="Bonuses must be added in manually.\n\nClick inside' +
  726. 'the cell to edit, click out of the cell to save">Reward</th><th colspan="2"></th></tr>'+
  727. '<tr class="hdbHeaderRow">' +
  728. '<th>Date</th><th>Requester</th><th>HIT title</th><th style="font-size:10px;">Pay</th>'+
  729. '<th style="font-size:10px;">Bonus</th><th>Status</th><th>Feedback</th></tr></thead><tbody>');
  730.  
  731. for (entry of this.results) {
  732. _trClass = (count++ % 2 === 0) ? 'class="even"' : 'class="odd"';
  733. var _stColor = ~entry.status.search(/(paid|approved)/i) ? "green" :
  734. entry.status === "Pending Approval" ? "orange" : "red";
  735. var href = MTURK_BASE+'contact?requesterId='+entry.requesterId+'&requesterName='+entry.requesterName+
  736. '&subject=Regarding+Amazon+Mechanical+Turk+HIT+'+entry.hitId;
  737.  
  738. if (!simple)
  739. htmlTxt.push('<tr '+_trClass+' data-id="'+entry.hitId+'">'+
  740. '<td width="74px">' + entry.date + '</td><td style="max-width:145px;">' +
  741. '<a target="_blank" title="Contact this requester" href="'+href+'">' + entry.requesterName + '</a></td>' +
  742. '<td width="375px" title="HIT ID: '+entry.hitId+'">' +
  743. '<span title="Add a note" id="note-'+entry.hitId+'" style="cursor:pointer;">&nbsp;&#128221;&nbsp;</span>' +
  744. entry.title + '</td><td style="text-align:right">' + _parseRewards(entry.reward,"pay") + '</td>' +
  745. '<td style="text-align:right" class="bonusCell" title="Click to add/edit" contenteditable="true" data-hitid="'+entry.hitId+'">' +
  746. (+_parseRewards(entry.reward,"bonus") ? _parseRewards(entry.reward,"bonus") : "") +
  747. '</td><td style="color:'+_stColor+';text-align:center">' + entry.status + '</td><td>' + entry.feedback + '</td></tr>');
  748. else
  749. htmlTxt.push('<tr data-rid="'+entry.requesterId+'" style="display:none"><td>'+entry.date+'</td><td>'+entry.title+'</td><td>'+
  750. _parseRewards(entry.reward,"pay") + '</td><td>'+ entry.status+'</td></tr>');
  751. }
  752.  
  753. if (!simple) {
  754. r = _collate(this.results,"requesterId");
  755. htmlTxt.push('</tbody><tfoot><tr class="hdbTotalsRow"><td></td>' +
  756. '<td style="text-align:right">Totals:</td><td style="text-align:center;">' + r.totalEntries + ' HITs</td>' +
  757. '<td style="text-align:right">$' + Number(Math.decRound(r.totalPay,2)).toFixed(2) + '</td>' +
  758. '<td style="text-align:right">$' + Number(Math.decRound(r.totalBonus,2)).toFixed(2) + '</td>' +
  759. '<td></td><td></td></tr></tfoot>');
  760. }
  761. }
  762. return htmlTxt.join('');
  763. };//}}} formatHTML
  764. this.formatCSV = function(type) {//{{{
  765. var csvTxt = [], entry = null, delimiter="\t";
  766. if (type === "daily") {
  767. csvTxt.push( ["Date", "Submitted", "Approved", "Rejected", "Pending", "Earnings\n"].join(delimiter) );
  768. for (entry of this.results) {
  769. csvTxt.push( [entry.date, entry.submitted, entry.approved, entry.rejected,
  770. entry.pending, Number(entry.earnings).toFixed(2)+"\n"].join(delimiter) );
  771. }
  772. csvToFile(csvTxt, "hitdb_dailyOverview.csv");
  773. } else if (type === "pending" || type === "requester") {
  774. csvTxt.push( ["RequesterId","Requester", (type === "pending" ? "Pending" : "HITs"), "Rewards\n"].join(delimiter) );
  775. var r = _collate(this.results,"requesterId");
  776. for (var k in r) {
  777. if (!~k.search(/total/) && r.hasOwnProperty(k))
  778. csvTxt.push( [k, r[k][0].requesterName, r[k].length, Number(Math.decRound(r[k].pay,2)).toFixed(2)+"\n"].join(delimiter) );
  779. }
  780. csvToFile(csvTxt, "hitdb_"+type+"Overview.csv");
  781. } else {
  782. csvTxt.push(["Date","Requester","Title","Pay","Bonus","Status","Feedback\n"].join(delimiter));
  783. for (entry of this.results) {
  784. csvTxt.push([entry.date, entry.requesterName, entry.title, Number(_parseRewards(entry.reward,"pay")).toFixed(2),
  785. (+_parseRewards(entry.reward,"bonus") ? Number(_parseRewards(entry.reward,"bonus")).toFixed(2) : ""),
  786. entry.status, entry.feedback+"\n"].join(delimiter));
  787. }
  788. csvToFile(csvTxt, "hitdb_queryResults.csv");
  789. }
  790.  
  791. return "<pre>"+csvTxt.join('')+"</pre>";
  792.  
  793. function csvToFile(csv, filename) {
  794. var blob = new Blob(csv, {type: "text/csv", endings: "native"}),
  795. dl = document.createElement("A");
  796. dl.href = URL.createObjectURL(blob);
  797. dl.download = filename;
  798. document.body.appendChild(dl); // FF doesn't support forced events unless element is part of the document
  799. dl.click(); // so we make it so and click,
  800. dl.remove(); // then immediately remove it
  801. return dl;
  802. }
  803. };//}}} formatCSV
  804. this.include = function(value) {
  805. this.results.push(value);
  806. };
  807.  
  808. function _parseRewards(rewards,value) {
  809. if (!isNaN(rewards)) {
  810. if (value === "pay")
  811. return Number(rewards).toFixed(2);
  812. else
  813. return "0.00";
  814. } else {
  815. if (value === "pay")
  816. return Number(rewards.pay).toFixed(2);
  817. else
  818. return Number(rewards.bonus).toFixed(2);
  819. }
  820. } // _parse
  821. function _collate(data, index) {
  822. var r = {
  823. totalPay: 0, totalBonus: 0, totalEntries: data.length,
  824. totalSub: 0, totalApp: 0, totalRej: 0, totalPen: 0
  825. };
  826. for (var e of data) {
  827. if (!r[e[index]]) { r[e[index]] = []; r[e[index]].pay = 0; }
  828. r[e[index]].push(e);
  829.  
  830. if (index === "date") {
  831. r.totalSub += e.submitted;
  832. r.totalApp += e.approved;
  833. r.totalRej += e.rejected;
  834. r.totalPen += e.pending;
  835. r.totalPay += e.earnings;
  836. } else {
  837. r[e[index]].pay += (+_parseRewards(e.reward,"pay"));
  838. r.totalPay += (+_parseRewards(e.reward,"pay"));
  839. r.totalBonus += (+_parseRewards(e.reward,"bonus"));
  840. }
  841. }
  842. return r;
  843. } // _collate
  844. }//}}} databaseresult
  845.  
  846. /*
  847. *
  848. * Above contains the core functions. Below is the
  849. * main body, interface, and tangential functions.
  850. *
  851. *///{{{
  852. // the Set() constructor is never actually used other than to test for Chrome v38+
  853. if (!("indexedDB" in window && "Set" in window)) alert("HITDB::Your browser is too outdated or otherwise incompatible with this script!");
  854. else {
  855. /*
  856. var tdbh = window.indexedDB.open(DB_NAME);
  857. tdbh.onerror = function(e) { 'use strict'; console.log("[TESTDB]",e.target.error.name+":", e.target.error.message, e); };
  858. tdbh.onsuccess = INFLATEDUMMYVALUES;
  859. tdbh.onupgradeneeded = BLANKSLATE;
  860. var dbh = null;
  861. */
  862. if (document.location.pathname.search(/dashboard/) > 0) {
  863. var dbh = window.indexedDB.open(DB_NAME, DB_VERSION);
  864. dbh.onerror = function(e) { 'use strict'; console.log("[HITDB]",e.target.error.name+":", e.target.error.message, e); };
  865. dbh.onupgradeneeded = HITStorage.versionChange;
  866. dbh.onsuccess = function() { 'use strict'; this.result.close(); };
  867.  
  868. dashboardUI();
  869.  
  870. ProjectedEarnings.updateDate();
  871. ProjectedEarnings.draw(true);
  872. }
  873. else
  874. beenThereDoneThat();
  875. }
  876. /*}}}
  877. *
  878. * Above is the main body and core functions. Below
  879. * defines UI layout/appearance and tangential functions.
  880. *
  881. */
  882.  
  883. // {{{ css injection
  884. var css = "<style type='text/css'>" +
  885. ".hitdbRTButtons {border:1px solid; font-size: 10px; height: 18px; padding-left: 5px; padding-right: 5px; background: pink;}" +
  886. ".hitdbRTButtons-green {background: lightgreen;}" +
  887. ".hitdbRTButtons-large {width:80px;}" +
  888. ".hdbProgressContainer {margin:auto; width:500px; height:6px; position:relative; display:none; border-radius:10px; overflow:hidden; background:#d3d8db;}" +
  889. ".hdbProgressInner {width:100%; position:absolute; left:0;top:0;bottom:0; animation: kfpin 1.4s infinite; background:" +
  890. "linear-gradient(262deg, rgba(208,69,247,0), rgba(208,69,247,1), rgba(69,197,247,1), rgba(69,197,247,0)); background-size: 300% 500%;}" +
  891. ".hdbProgressOuter {width:30%; position:absolute; left:0;top:0;bottom:0; animation: kfpout 2s cubic-bezier(0,0.55,0.2,1) infinite;}" +
  892. "@keyframes kfpout { 0% {left:-100%;} 70%{left:100%;} 100%{left:100%;} }" +
  893. "@keyframes kfpin { 0%{background-position: 0% 50%} 50%{background-position: 100% 15%} 100%{background-position:0% 30%} }" +
  894. ".hdbCalControls {cursor:pointer;} .hdbCalControls:hover {color:c27fcf;}" +
  895. ".hdbCalCells {background:#f0f6f9; height:19px}" +
  896. ".hdbCalDays {cursor:pointer; text-align:center;} .hdbCalDays:hover {background:#7fb4cf; color:white;}" +
  897. ".hdbDayHeader {width:26px; text-align:center; font-weight:bold; font-size:12px; background:#f0f6f9;}" +
  898. ".hdbCalHeader {background:#7fb4cf; color:white; font-weight:bold; text-align:center; font-size:11px; padding:3px 0px;}" +
  899. "#hdbCalendarPanel {position:absolute; z-index:10; box-shadow:-2px 3px 5px 0px rgba(0,0,0,0.68);}" +
  900. ".hdbTotalsRow {background:#CCC; color:#369; font-weight:bold;}" +
  901. ".hdbHeaderRow {background:#7FB448; font-size:12px; color:white}" +
  902. "</style>";
  903. document.head.innerHTML += css;
  904. // }}}
  905.  
  906. function beenThereDoneThat() {//{{{
  907. //
  908. // TODO refine searching
  909. //
  910. 'use strict';
  911.  
  912. var qualNode = document.querySelector('td[colspan="11"]');
  913. if (qualNode) { // we're on the preview page!
  914. var requester = document.querySelector('input[name="requesterId"]').value,
  915. //hitId = document.querySelector('input[name="hitId"]').value,
  916. autoApproval = document.querySelector('input[name="hitAutoAppDelayInSeconds"]').value,
  917. hitTitle = document.querySelector('div[style*="ellipsis"]').textContent.trim().replace(/\|/g,""),
  918. insertionNode = qualNode.parentNode.parentNode;
  919. var row = document.createElement("TR"), cellL = document.createElement("TD"), cellR = document.createElement("TD");
  920. var _resultsTable = document.createElement("TABLE");
  921. _resultsTable.id = "resultsTableFor"+requester;
  922. insertionNode.parentNode.parentNode.appendChild(_resultsTable);
  923.  
  924. cellR.innerHTML = '<span class="capsule_field_title">Auto-Approval:</span>&nbsp;&nbsp;'+_ftime(autoApproval);
  925. var rbutton = document.createElement("BUTTON");
  926. rbutton.classList.add("hitdbRTButtons","hitdbRTButtons-large");
  927. rbutton.textContent = "Requester";
  928. rbutton.onclick = function(e) {
  929. e.preventDefault();
  930. showResults(requester);
  931. };
  932. var tbutton = rbutton.cloneNode(false);
  933. rbutton.dataset.id = requester;
  934. rbutton.title = "Show HITs completed from this requester";
  935. tbutton.textContent = "HIT Title";
  936. tbutton.onclick = function(e) { e.preventDefault(); };
  937. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(requester)})
  938. .then(processResults.bind(rbutton));
  939. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(hitTitle)})
  940. .then(processResults.bind(tbutton));
  941. row.appendChild(cellL);
  942. row.appendChild(cellR);
  943. cellL.appendChild(rbutton);
  944. cellL.appendChild(tbutton);
  945. cellL.colSpan = "3";
  946. cellR.colSpan = "8";
  947. insertionNode.appendChild(row);
  948. } else { // browsing HITs n sutff
  949. var titleNodes = document.querySelectorAll('a[class="capsulelink"]');
  950. if (titleNodes.length < 1) return; // nothing left to do here!
  951. var requesterNodes = document.querySelectorAll('a[href*="hitgroups&requester"]');
  952. var insertionNodes = [];
  953.  
  954. for (var i=0;i<titleNodes.length;i++) {
  955. var _title = titleNodes[i].textContent.trim().replace(/\|/g,"");
  956. var _tbutton = document.createElement("BUTTON");
  957. var _id = requesterNodes[i].href.replace(/.+Id=(.+)/, "$1");
  958. var _rbutton = document.createElement("BUTTON");
  959. var _div = document.createElement("DIV"), _tr = document.createElement("TR");
  960. _resultsTable = document.createElement("TABLE");
  961. insertionNodes.push(requesterNodes[i].parentNode.parentNode.parentNode);
  962. insertionNodes[i].offsetParent.offsetParent.offsetParent.offsetParent.appendChild(_resultsTable);
  963. _resultsTable.id = "resultsTableFor"+_id;
  964.  
  965. HITStorage.recall("HIT", {index: "title", range: window.IDBKeyRange.only(_title)} )
  966. .then(processResults.bind(_tbutton));
  967. HITStorage.recall("HIT", {index: "requesterId", range: window.IDBKeyRange.only(_id)} )
  968. .then(processResults.bind(_rbutton));
  969.  
  970. _tr.appendChild(_div);
  971. _div.id = "hitdbRTInjection-"+i;
  972. _div.appendChild(_rbutton);
  973. _rbutton.textContent = 'R';
  974. _rbutton.classList.add("hitdbRTButtons");
  975. _rbutton.dataset.id = _id;
  976. _rbutton.onclick = showResults.bind(null, _id, null);
  977. _rbutton.title = "Show HITs completed from this requester";
  978. _div.appendChild(_tbutton);
  979. _tbutton.textContent = 'T';
  980. _tbutton.classList.add("hitdbRTButtons");
  981. insertionNodes[i].appendChild(_tr);
  982. }
  983. } // else
  984.  
  985. function showResults(rid, title) {
  986. console.log(rid,title);
  987. var el = null;
  988. if (rid) {
  989. for (el of document.querySelectorAll('tr[data-rid="'+rid+'"]')) {
  990. if (el.style.display === "none")
  991. el.style.display = "table-row";
  992. else
  993. el.style.display = "none";
  994. }
  995. }
  996. }
  997.  
  998. function processResults(r) {
  999. /*jshint validthis: true*/
  1000. if (r.results.length) {
  1001. this.classList.add("hitdbRTButtons-green");
  1002. if (this.dataset.id) {
  1003. var rtable = document.querySelector("#resultsTableFor"+this.dataset.id);
  1004. rtable.innerHTML += r.formatHTML(null,true);
  1005. }
  1006. }
  1007. }
  1008.  
  1009. function _ftime(t) {
  1010. var d = Math.floor(t/86400);
  1011. var h = Math.floor(t%86400/3600);
  1012. var m = Math.floor(t%86400%3600/60);
  1013. var s = t%86400%3600%60;
  1014. return ((d>0) ? d+" day"+(d>1 ? "s " : " ") : "") + ((h>0) ? h+"h " : "") + ((m>0) ? m+"m " : "") + ((s>0) ? s+"s" : "");
  1015. }
  1016.  
  1017. }//}}} btdt
  1018.  
  1019. function dashboardUI() {//{{{
  1020. //
  1021. // TODO refactor
  1022. //
  1023. 'use strict';
  1024.  
  1025. var controlPanel = document.createElement("TABLE");
  1026. var insertionNode = document.querySelector(".footer_separator").previousSibling;
  1027. document.body.insertBefore(controlPanel, insertionNode);
  1028. controlPanel.width = "760";
  1029. controlPanel.align = "center";
  1030. controlPanel.cellSpacing = "0";
  1031. controlPanel.cellPadding = "0";
  1032. controlPanel.innerHTML = '<tr height="25px"><td width="10" bgcolor="#7FB448" style="padding-left: 10px;"></td>' +
  1033. '<td class="white_text_14_bold" style="padding-left:10px; background-color:#7FB448;">' +
  1034. 'HIT Database Mk. II&nbsp;<a href="https://greasyfork.org/en/scripts/11733-mturk-hit-database-mk-ii" class="whatis" target="_blank">' +
  1035. '(What\'s this?)</a></td></tr>' +
  1036. '<tr><td class="container-content" colspan="2">' +
  1037. '<div style="text-align:center;" id="hdbDashboardInterface">' +
  1038. '<button id="hdbBackup" title="Export your entire database!\nPerfect for moving between computers or as a periodic backup">Create Backup</button>' +
  1039. '<button id="hdbRestore" title="Restore database from external backup file" style="margin:5px">Restore</button>' +
  1040. '<button id="hdbUpdate" title="Update... the database" style="color:green;">Update Database</button>' +
  1041. '<div id="hdbFileSelector" style="display:none"><input id="hdbFileInput" type="file" /></div>' +
  1042. '<br>' +
  1043. '<button id="hdbPending" title="Summary of all pending HITs\n Can be exported as CSV" style="margin: 0px 5px 5px;">Pending Overview</button>' +
  1044. '<button id="hdbRequester" title="Summary of all requesters\n Can be exported as CSV" style="margin: 0px 5px 5px;">Requester Overview</button>' +
  1045. '<button id="hdbDaily" title="Summary of each day you\'ve worked\nCan be exported as CSV" style="margin:0px 5px 5px;">Daily Overview</button>' +
  1046. '<br>' +
  1047. '<label>Find </label>' +
  1048. '<select id="hdbStatusSelect"><option value="*">ALL</option><option value="Approval" style="color: orange;">Pending Approval</option>' +
  1049. '<option value="Rejected" style="color: red;">Rejected</option><option value="Approved" style="color:green;">Approved - Pending Payment</option>' +
  1050. '<option value="(Paid|Approved)" style="color:green;">Paid OR Approved</option></select>' +
  1051. '<label> HITs matching: </label><input id="hdbSearchInput" title="Query can be HIT title, HIT ID, or requester name" />' +
  1052. '<button id="hdbSearch">Search</button>' +
  1053. '<br>' +
  1054. '<label>from date </label><input id="hdbMinDate" maxlength="10" size="10" title="Specify a date, or leave blank">' +
  1055. '<label> to </label><input id="hdbMaxDate" malength="10" size="10" title="Specify a date, or leave blank">' +
  1056. '<label for="hdbCSVInput" title="Export results as CSV file" style="margin-left:50px; vertical-align:middle;">export CSV</label>' +
  1057. '<input id="hdbCSVInput" title="Export results as CSV file" type="checkbox" style="vertical-align:middle;">' +
  1058. '<br>' +
  1059. '<label id="hdbStatusText">placeholder status text</label>' +
  1060. '<div id="hdbProgressBar" class="hdbProgressContainer"><div class="hdbProgressOuter"><div class="hdbProgressInner"></div></div></div>' +
  1061. '</div></td></tr>';
  1062.  
  1063. var updateBtn = document.querySelector("#hdbUpdate"),
  1064. backupBtn = document.querySelector("#hdbBackup"),
  1065. restoreBtn = document.querySelector("#hdbRestore"),
  1066. fileInput = document.querySelector("#hdbFileInput"),
  1067. exportCSVInput = document.querySelector("#hdbCSVInput"),
  1068. searchBtn = document.querySelector("#hdbSearch"),
  1069. searchInput = document.querySelector("#hdbSearchInput"),
  1070. pendingBtn = document.querySelector("#hdbPending"),
  1071. reqBtn = document.querySelector("#hdbRequester"),
  1072. dailyBtn = document.querySelector("#hdbDaily"),
  1073. fromdate = document.querySelector("#hdbMinDate"),
  1074. todate = document.querySelector("#hdbMaxDate"),
  1075. statusSelect = document.querySelector("#hdbStatusSelect"),
  1076. progressBar = document.querySelector("#hdbProgressBar");
  1077.  
  1078. var searchResults = document.createElement("DIV");
  1079. searchResults.align = "center";
  1080. searchResults.id = "hdbSearchResults";
  1081. searchResults.style.display = "block";
  1082. searchResults.innerHTML =
  1083. '<span style="border-bottom:1px solid;color:blue;cursor:pointer;display:none;">[ clear results ]</span><br>' +
  1084. '<table cellSpacing="0" cellpadding="2" id="hdbResultsTable"></table>';
  1085. document.body.insertBefore(searchResults, insertionNode);
  1086.  
  1087. searchResults.firstChild.onclick = function(e) {
  1088. e.target.style.display = "none";
  1089. searchResults.children[2].innerHTML = null;
  1090. };
  1091.  
  1092. updateBtn.onclick = function() {
  1093. progressBar.style.display = "block";
  1094. metrics.dbupdate = new Metrics("database_update");
  1095. HITStorage.fetch(MTURK_BASE+"status");
  1096. document.querySelector("#hdbStatusText").textContent = "fetching status page....";
  1097. };
  1098. exportCSVInput.addEventListener("click", function() {
  1099. if (exportCSVInput.checked) {
  1100. searchBtn.textContent = "Export CSV";
  1101. pendingBtn.textContent += " (csv)";
  1102. reqBtn.textContent += " (csv)";
  1103. dailyBtn.textContent += " (csv)";
  1104. }
  1105. else {
  1106. searchBtn.textContent = "Search";
  1107. pendingBtn.textContent = pendingBtn.textContent.replace(" (csv)","");
  1108. reqBtn.textContent = reqBtn.textContent.replace(" (csv)","");
  1109. dailyBtn.textContent = dailyBtn.textContent.replace(" (csv)", "");
  1110. }
  1111. });
  1112. fromdate.addEventListener("focus", function() {
  1113. var offsets = getPosition(this, true);
  1114. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  1115. });
  1116. todate.addEventListener("focus", function() {
  1117. var offsets = getPosition(this, true);
  1118. new Calendar(offsets.x, offsets.y, this).drawCalendar();
  1119. });
  1120.  
  1121. backupBtn.onclick = HITStorage.backup;
  1122. restoreBtn.onclick = function() { fileInput.click(); };
  1123. fileInput.onchange = processFile;
  1124.  
  1125. searchBtn.onclick = function() {
  1126. var r = getRange();
  1127. var _filter = { status: statusSelect.value, query: searchInput.value.trim().length > 0 ? searchInput.value : "*" };
  1128. var _opt = { index: "date", range: r.range, dir: r.dir, filter: _filter, progress: true };
  1129.  
  1130. metrics.dbrecall = new Metrics("database_recall::search");
  1131. HITStorage.recall("HIT", _opt).then(function(r) {
  1132. searchResults.children[0].style.display = "initial";
  1133. searchResults.children[2].innerHTML = exportCSVInput.checked ? r.formatCSV() : r.formatHTML();
  1134. autoScroll("#hdbSearchResults");
  1135.  
  1136. for (var _r of r.results) { // retrieve and append notes
  1137. HITStorage.recall("NOTES", { index: "hitId", range: window.IDBKeyRange.only(_r.hitId) }).then(noteHandler.bind(null,"attach"));
  1138. }
  1139.  
  1140. var el = null;
  1141. for (el of document.querySelectorAll(".bonusCell")) {
  1142. el.dataset.initial = el.textContent;
  1143. el.onblur = updateBonus;
  1144. el.onkeydown = updateBonus;
  1145. }
  1146. for (el of document.querySelectorAll('span[id^="note-"]')) {
  1147. el.onclick = noteHandler.bind(null,"new");
  1148. }
  1149. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1150. progressBar.style.display = "none";
  1151. });
  1152. }; // search button click event
  1153. pendingBtn.onclick = function() {
  1154. var r = getRange();
  1155. var _filter = { status: "Approval", query: searchInput.value.trim().length > 0 ? searchInput.value : "*" },
  1156. _opt = { index: "date", dir: "prev", range: r.range, filter: _filter, progress: true };
  1157.  
  1158. metrics.dbrecall = new Metrics("database_recall::pending");
  1159. HITStorage.recall("HIT", _opt).then(function(r) {
  1160. searchResults.children[0].style.display = "initial";
  1161. searchResults.children[2].innerHTML = exportCSVInput.checked ? r.formatCSV("pending") : r.formatHTML("pending");
  1162. autoScroll("#hdbSearchResults");
  1163. var expands = document.querySelectorAll(".hdbExpandRow");
  1164. for (var el of expands) {
  1165. el.onclick = showHiddenRows;
  1166. }
  1167. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1168. progressBar.style.display = "none";
  1169. });
  1170. }; //pending overview click event
  1171. reqBtn.onclick = function() {
  1172. var r = getRange();
  1173. var _opt = { index: "date", range: r.range, progress: true };
  1174.  
  1175. metrics.dbrecall = new Metrics("database_recall::requester");
  1176. HITStorage.recall("HIT", _opt).then(function(r) {
  1177. searchResults.children[0].style.display = "initial";
  1178. searchResults.children[2].innerHTML = exportCSVInput.checked ? r.formatCSV("requester") : r.formatHTML("requester");
  1179. autoScroll("#hdbSearchResults");
  1180. var expands = document.querySelectorAll(".hdbExpandRow");
  1181. for (var el of expands) {
  1182. el.onclick = showHiddenRows;
  1183. }
  1184. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1185. progressBar.style.display = "none";
  1186. });
  1187. }; //requester overview click event
  1188. dailyBtn.onclick = function() {
  1189. metrics.dbrecall = new Metrics("database_recall::daily");
  1190. HITStorage.recall("STATS", { dir: "prev" }).then(function(r) {
  1191. searchResults.children[0].style.display = "initial";
  1192. searchResults.children[2].innerHTML = exportCSVInput.checked ? r.formatCSV("daily") : r.formatHTML("daily");
  1193. autoScroll("#hdbSearchResults");
  1194. metrics.dbrecall.stop(); metrics.dbrecall.report();
  1195. });
  1196. }; //daily overview click event
  1197.  
  1198. function getRange() {
  1199. var _min = fromdate.value.length === 10 ? fromdate.value : undefined,
  1200. _max = todate.value.length === 10 ? todate.value : undefined;
  1201. var _range =
  1202. (_min === undefined && _max === undefined) ? null :
  1203. (_min === undefined) ? window.IDBKeyRange.upperBound(_max) :
  1204. (_max === undefined) ? window.IDBKeyRange.lowerBound(_min) :
  1205. (_max < _min) ? window.IDBKeyRange.bound(_max,_min) : window.IDBKeyRange.bound(_min,_max);
  1206. return { min: _min, max: _max, range: _range, dir: _max < _min ? "prev" : "next" };
  1207. }
  1208. function getPosition(element, includeHeight) {
  1209. var offsets = { x: 0, y: includeHeight ? element.offsetHeight : 0 };
  1210. do {
  1211. offsets.x += element.offsetLeft;
  1212. offsets.y += element.offsetTop;
  1213. element = element.offsetParent;
  1214. } while (element);
  1215. return offsets;
  1216. }
  1217. }//}}} dashboard
  1218.  
  1219. function showHiddenRows(e) {//{{{
  1220. 'use strict';
  1221.  
  1222. var rid = e.target.parentNode.textContent.substr(4);
  1223. var nodes = document.querySelectorAll('tr[data-rid="'+rid+'"]'), el = null;
  1224. if (e.target.textContent === "[+]") {
  1225. for (el of nodes)
  1226. el.style.display="table-row";
  1227. e.target.textContent = "[-]";
  1228. } else {
  1229. for (el of nodes)
  1230. el.style.display="none";
  1231. e.target.textContent = "[+]";
  1232. }
  1233. }//}}}
  1234.  
  1235. function updateBonus(e) {//{{{
  1236. 'use strict';
  1237.  
  1238. if (e instanceof window.KeyboardEvent && e.keyCode === 13) {
  1239. e.target.blur();
  1240. return false;
  1241. } else if (e instanceof window.FocusEvent) {
  1242. var _bonus = +e.target.textContent.replace(/\$/,"");
  1243. if (_bonus !== +e.target.dataset.initial) {
  1244. console.log("updating bonus to",_bonus,"from",e.target.dataset.initial,"("+e.target.dataset.hitid+")");
  1245. e.target.dataset.initial = _bonus;
  1246. var _pay = +e.target.previousSibling.textContent,
  1247. _range = window.IDBKeyRange.only(e.target.dataset.hitid);
  1248.  
  1249. window.indexedDB.open(DB_NAME).onsuccess = function() {
  1250. this.result.transaction("HIT", "readwrite").objectStore("HIT").openCursor(_range).onsuccess = function() {
  1251. var c = this.result;
  1252. if (c) {
  1253. var v = c.value;
  1254. v.reward = { pay: _pay, bonus: _bonus };
  1255. c.update(v);
  1256. }
  1257. }; // idbcursor
  1258. }; // idbopen
  1259. } // bonus is new value
  1260. } // keycode
  1261. } //}}} updateBonus
  1262.  
  1263. function noteHandler(type, e) {//{{{
  1264. //
  1265. // TODO restructure event handling/logic tree
  1266. // combine save and delete; it's ugly :(
  1267. // actually this whole thing is messy and in need of refactoring
  1268. //
  1269. 'use strict';
  1270.  
  1271. if (e instanceof window.KeyboardEvent) {
  1272. if (e.keyCode === 13) {
  1273. e.target.blur();
  1274. return false;
  1275. }
  1276. return;
  1277. }
  1278.  
  1279. if (e instanceof window.FocusEvent) {
  1280. if (e.target.textContent.trim() !== e.target.dataset.initial) {
  1281. if (!e.target.textContent.trim()) { e.target.previousSibling.previousSibling.firstChild.click(); return; }
  1282. var note = e.target.textContent.trim(),
  1283. _range = window.IDBKeyRange.only(e.target.dataset.id),
  1284. inote = e.target.dataset.initial,
  1285. hitId = e.target.dataset.id,
  1286. date = e.target.previousSibling.textContent;
  1287.  
  1288. e.target.dataset.initial = note;
  1289. window.indexedDB.open(DB_NAME).onsuccess = function() {
  1290. this.result.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1291. if (this.result) {
  1292. var r = this.result.value;
  1293. if (r.note === inote) { // note already exists in database, so we update its value
  1294. r.note = note;
  1295. this.result.update(r);
  1296. return;
  1297. }
  1298. this.result.continue();
  1299. } else {
  1300. if (this.source instanceof window.IDBObjectStore)
  1301. this.source.put({ note:note, date:date, hitId:hitId });
  1302. else
  1303. this.source.objectStore.put({ note:note, date:date, hitId:hitId });
  1304. }
  1305. };
  1306. this.result.close();
  1307. };
  1308. }
  1309. return; // end of save event; no need to proceed
  1310. }
  1311.  
  1312. if (type === "delete") {
  1313. var tr = e.target.parentNode.parentNode,
  1314. noteCell = tr.lastChild;
  1315. _range = window.IDBKeyRange.only(noteCell.dataset.id);
  1316. if (!noteCell.dataset.initial) tr.remove();
  1317. else {
  1318. window.indexedDB.open(DB_NAME).onsuccess = function() {
  1319. this.result.transaction("NOTES", "readwrite").objectStore("NOTES").index("hitId").openCursor(_range).onsuccess = function() {
  1320. if (this.result) {
  1321. if (this.result.value.note === noteCell.dataset.initial) {
  1322. this.result.delete();
  1323. tr.remove();
  1324. return;
  1325. }
  1326. this.result.continue();
  1327. }
  1328. };
  1329. this.result.close();
  1330. };
  1331. }
  1332. return; // end of deletion event; no need to proceed
  1333. } else {
  1334. if (type === "attach" && !e.results.length) return;
  1335.  
  1336. var trow = e instanceof window.MouseEvent ? e.target.parentNode.parentNode : null,
  1337. tbody = trow ? trow.parentNode : null,
  1338. row = document.createElement("TR"),
  1339. c1 = row.insertCell(0),
  1340. c2 = row.insertCell(1),
  1341. c3 = row.insertCell(2);
  1342. date = new Date();
  1343. hitId = e instanceof window.MouseEvent ? e.target.id.substr(5) : null;
  1344.  
  1345. c1.innerHTML = '<span class="removeNote" title="Delete this note" style="cursor:pointer;color:crimson;">[x]</span>';
  1346. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1347. c1.style.textAlign = "right";
  1348. c2.title = "Date on which the note was added";
  1349. c3.style.color = "crimson";
  1350. c3.colSpan = "5";
  1351. c3.contentEditable = "true";
  1352. c3.onblur = noteHandler.bind(null,"blur");
  1353. c3.onkeydown = noteHandler.bind(null, "kb");
  1354. if (type === "new") {
  1355. row.classList.add(trow.classList);
  1356. tbody.insertBefore(row, trow.nextSibling);
  1357. c2.textContent = date.getFullYear()+"-"+Number(date.getMonth()+1).toPadded()+"-"+Number(date.getDate()).toPadded();
  1358. c3.dataset.initial = "";
  1359. c3.dataset.id = hitId;
  1360. c3.focus();
  1361. return;
  1362. }
  1363.  
  1364. for (var entry of e.results) {
  1365. trow = document.querySelector('tr[data-id="'+entry.hitId+'"]');
  1366. tbody = trow.parentNode;
  1367. row = row.cloneNode(true);
  1368. c1 = row.firstChild;
  1369. c2 = c1.nextSibling;
  1370. c3 = row.lastChild;
  1371. row.classList.add(trow.classList);
  1372. tbody.insertBefore(row, trow.nextSibling);
  1373.  
  1374. c1.firstChild.onclick = noteHandler.bind(null,"delete");
  1375. c2.textContent = entry.date;
  1376. c3.textContent = entry.note;
  1377. c3.dataset.initial = entry.note;
  1378. c3.dataset.id = entry.hitId;
  1379. c3.onblur = noteHandler.bind(null,"blur");
  1380. c3.onkeydown = noteHandler.bind(null, "kb");
  1381. }
  1382. } // new/attach
  1383. }//}}} noteHandler
  1384.  
  1385. function processFile(e) {//{{{
  1386. 'use strict';
  1387.  
  1388. var f = e.target.files;
  1389. if (f.length && f[0].name.search(/\.(bak|csv)$/) && ~f[0].type.search(/(text|json)/)) {
  1390. var reader = new FileReader(), testing = true, isCsv = false;
  1391. reader.readAsText(f[0].slice(0,10));
  1392. reader.onload = function(e) {
  1393. if (testing && e.target.result.search(/(STATS|NOTES|HIT)/) < 0) {
  1394. return error();
  1395. } else if (testing) {
  1396. testing = false;
  1397. document.querySelector("#hdbProgressBar").style.display = "block";
  1398. reader.readAsText(f[0]);
  1399. } else {
  1400. var data = JSON.parse(e.target.result);
  1401. console.log(data);
  1402. HITStorage.write(data, "restore");
  1403. }
  1404. }; // reader.onload
  1405. } else {
  1406. error();
  1407. }
  1408.  
  1409. function error() {
  1410. var s = document.querySelector("#hdbStatusText"),
  1411. e = "Restore::FileReadError : encountered unsupported file";
  1412. s.style.color = "red";
  1413. s.textContent = e;
  1414. throw e;
  1415. }
  1416. }//}}} processFile
  1417.  
  1418. function autoScroll(location, dt) {//{{{
  1419. 'use strict';
  1420.  
  1421. var target = document.querySelector(location).offsetTop,
  1422. pos = window.scrollY,
  1423. dpos = Math.ceil((target - pos)/3);
  1424. dt = dt ? dt-1 : 25; // time step/max recursions
  1425.  
  1426. if (target === pos || dpos === 0 || dt === 0) return;
  1427.  
  1428. window.scrollBy(0, dpos);
  1429. setTimeout(function() { autoScroll(location, dt); }, dt);
  1430. }//}}}
  1431.  
  1432. function Calendar(offsetX, offsetY, caller) {//{{{
  1433. 'use strict';
  1434.  
  1435. this.date = new Date();
  1436. this.offsetX = offsetX;
  1437. this.offsetY = offsetY;
  1438. this.caller = caller;
  1439. this.drawCalendar = function(year,month,day) {//{{{
  1440. year = year || this.date.getFullYear();
  1441. month = month || this.date.getMonth()+1;
  1442. day = day || this.date.getDate();
  1443. var longMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  1444. var date = new Date(year,month-1,day);
  1445. var anchors = _getAnchors(date);
  1446.  
  1447. //make new container if one doesn't already exist
  1448. var container = null;
  1449. if (document.querySelector("#hdbCalendarPanel")) {
  1450. container = document.querySelector("#hdbCalendarPanel");
  1451. container.removeChild( container.getElementsByTagName("TABLE")[0] );
  1452. }
  1453. else {
  1454. container = document.createElement("DIV");
  1455. container.id = "hdbCalendarPanel";
  1456. document.body.appendChild(container);
  1457. }
  1458. container.style.left = this.offsetX;
  1459. container.style.top = this.offsetY;
  1460. var cal = document.createElement("TABLE");
  1461. cal.cellSpacing = "0";
  1462. cal.cellPadding = "0";
  1463. cal.border = "0";
  1464. container.appendChild(cal);
  1465. cal.innerHTML = '<tr>' +
  1466. '<th class="hdbCalHeader hdbCalControls" title="Previous month" style="text-align:right;"><span>&lt;</span></th>' +
  1467. '<th class="hdbCalHeader hdbCalControls" title="Previous year" style="text-align:center;"><span>&#8810;</span></th>' +
  1468. '<th colspan="3" id="hdbCalTableTitle" class="hdbCalHeader">'+date.getFullYear()+'<br>'+longMonths[date.getMonth()]+'</th>' +
  1469. '<th class="hdbCalHeader hdbCalControls" title="Next year" style="text-align:center;"><span>&#8811;</span></th>' +
  1470. '<th class="hdbCalHeader hdbCalControls" title="Next month" style="text-align:left;"><span>&gt;</span></th>' +
  1471. '</tr><tr><th class="hdbDayHeader" style="color:red;">S</th><th class="hdbDayHeader">M</th>' +
  1472. '<th class="hdbDayHeader">T</th><th class="hdbDayHeader">W</th><th class="hdbDayHeader">T</th>' +
  1473. '<th class="hdbDayHeader">F</th><th class="hdbDayHeader">S</th></tr>';
  1474. document.querySelector('th[title="Previous month"]').addEventListener( "click", function() {
  1475. this.drawCalendar(date.getFullYear(), date.getMonth(), 1);
  1476. }.bind(this) );
  1477. document.querySelector('th[title="Previous year"]').addEventListener( "click", function() {
  1478. this.drawCalendar(date.getFullYear()-1, date.getMonth()+1, 1);
  1479. }.bind(this) );
  1480. document.querySelector('th[title="Next month"]').addEventListener( "click", function() {
  1481. this.drawCalendar(date.getFullYear(), date.getMonth()+2, 1);
  1482. }.bind(this) );
  1483. document.querySelector('th[title="Next year"]').addEventListener( "click", function() {
  1484. this.drawCalendar(date.getFullYear()+1, date.getMonth()+1, 1);
  1485. }.bind(this) );
  1486.  
  1487. var hasDay = false, thisDay = 1;
  1488. for (var i=0;i<6;i++) { // cycle weeks
  1489. var row = document.createElement("TR");
  1490. for (var j=0;j<7;j++) { // cycle days
  1491. if (!hasDay && j === anchors.first && thisDay < anchors.total)
  1492. hasDay = true;
  1493. else if (hasDay && thisDay > anchors.total)
  1494. hasDay = false;
  1495.  
  1496. var cell = document.createElement("TD");
  1497. cell.classList.add("hdbCalCells");
  1498. row.appendChild(cell);
  1499. if (hasDay) {
  1500. cell.classList.add("hdbCalDays");
  1501. cell.textContent = thisDay;
  1502. cell.addEventListener("click", _clickHandler.bind(this));
  1503. cell.dataset.year = date.getFullYear();
  1504. cell.dataset.month = date.getMonth()+1;
  1505. cell.dataset.day = thisDay++;
  1506. }
  1507. } // for j
  1508. cal.appendChild(row);
  1509. } // for i
  1510.  
  1511. function _clickHandler(e) {
  1512. /*jshint validthis:true*/
  1513.  
  1514. var y = e.target.dataset.year;
  1515. var m = Number(e.target.dataset.month).toPadded();
  1516. var d = Number(e.target.dataset.day).toPadded();
  1517. this.caller.value = y+"-"+m+"-"+d;
  1518. this.die();
  1519. }
  1520.  
  1521. function _getAnchors(date) {
  1522. var _anchors = {};
  1523. date.setMonth(date.getMonth()+1);
  1524. date.setDate(0);
  1525. _anchors.total = date.getDate();
  1526. date.setDate(1);
  1527. _anchors.first = date.getDay();
  1528. return _anchors;
  1529. }
  1530. };//}}} drawCalendar
  1531.  
  1532. this.die = function() { document.querySelector("#hdbCalendarPanel").remove(); };
  1533.  
  1534. }//}}} Calendar
  1535.  
  1536. // instance metrics apart from window scoped PerformanceTiming API
  1537. function Metrics(name) {//{{{
  1538. 'use strict';
  1539.  
  1540. this.name = name || "undefined";
  1541. this.marks = {};
  1542. this.start = window.performance.now();
  1543. this.end = null;
  1544. this.stop = function(){
  1545. if (!this.end)
  1546. this.end = window.performance.now();
  1547. else
  1548. throw "Metrics::AccessViolation: end point cannot be overwritten";
  1549. };
  1550. this.mark = function(name,position) {
  1551. if (position === "end" && (!this.marks[name] || this.marks[name].end)) return;
  1552.  
  1553. if (!this.marks[name])
  1554. this.marks[name] = {};
  1555.  
  1556. this.marks[name][position] = window.performance.now();
  1557. };
  1558. this.report = function() {
  1559. console.group("Metrics for",this.name.toUpperCase());
  1560. console.log("Process completed in",+Number((this.end-this.start)/1000).toFixed(3),"seconds");
  1561. for (var k in this.marks) {
  1562. if (this.marks.hasOwnProperty(k)) {
  1563. console.log(k,"occurred after",+Number((this.marks[k].start-this.start)/1000).toFixed(3),"seconds,",
  1564. "resolving in", +Number((this.marks[k].end-this.marks[k].start)/1000).toFixed(3), "seconds");
  1565. }
  1566. }
  1567. console.groupEnd();
  1568. };
  1569. }//}}}
  1570.  
  1571. /*
  1572. *
  1573. *
  1574. * * * * * * * * * * * * * TESTING FUNCTIONS -- DELETE BEFORE FINAL RELEASE * * * * * * * * * * *
  1575. *
  1576. *
  1577. */
  1578.  
  1579. function INFLATEDUMMYVALUES() { //{{{
  1580. 'use strict';
  1581.  
  1582. var tdb = this.result;
  1583. tdb.onerror = function(e) { console.log("requesterror",e.target.error.name,e.target.error.message,e); };
  1584. tdb.onversionchange = function(e) { console.log("tdb received versionchange request", e); tdb.close(); };
  1585. //console.log(tdb.transaction("HIT").objectStore("HIT").indexNames.contains("date"));
  1586. console.groupCollapsed("Populating test database");
  1587. var tdbt = {};
  1588. tdbt.trans = tdb.transaction(["HIT", "NOTES", "BLOCKS"], "readwrite");
  1589. tdbt.hit = tdbt.trans.objectStore("HIT");
  1590. tdbt.notes = tdbt.trans.objectStore("NOTES");
  1591. tdbt.blocks= tdbt.trans.objectStore("BLOCKS");
  1592.  
  1593. var filler = { notes:[], hit:[], blocks:[]};
  1594. for (var n=0;n<100000;n++) {
  1595. filler.hit.push({ date: "2015-08-00", requesterName: "tReq"+(n+1), title: "Greatest Title Ever #"+(n+1),
  1596. reward: Number((n+1)%(200/n)+(((n+1)%200)/100)).toFixed(2), status: "moo",
  1597. requesterId: ("RRRRRRR"+n).substr(-7), hitId: ("HHHHHHH"+n).substr(-7) });
  1598. if (n%1000 === 0) {
  1599. filler.notes.push({ requesterId: ("RRRRRRR"+n).substr(-7), note: n+1 +
  1600. " Proin vel erat commodo mi interdum rhoncus. Sed lobortis porttitor arcu, et tristique ipsum semper a." +
  1601. " Donec eget aliquet lectus, vel scelerisque ligula." });
  1602. filler.blocks.push({requesterId: ("RRRRRRR"+n).substr(-7)});
  1603. }
  1604. }
  1605.  
  1606. _write(tdbt.hit, filler.hit);
  1607. _write(tdbt.notes, filler.notes);
  1608. _write(tdbt.blocks, filler.blocks);
  1609.  
  1610. function _write(store, obj) {
  1611. if (obj.length) {
  1612. var t = obj.pop();
  1613. store.put(t).onsuccess = function() { _write(store, obj) };
  1614. } else {
  1615. console.log("population complete");
  1616. }
  1617. }
  1618.  
  1619. console.groupEnd();
  1620.  
  1621. dbh = window.indexedDB.open(DB_NAME, DB_VERSION);
  1622. dbh.onerror = function(e) { console.log("[HITDB]",e.target.error.name+":", e.target.error.message, e); };
  1623. console.log(dbh.readyState, dbh);
  1624. dbh.onupgradeneeded = HITStorage.versionChange;
  1625. dbh.onblocked = function(e) { console.log("blocked event triggered:", e); };
  1626.  
  1627. tdb.close();
  1628.  
  1629. }//}}}
  1630.  
  1631. function BLANKSLATE() { //{{{ create empty db equivalent to original schema to test upgrade
  1632. 'use strict';
  1633. var tdb = this.result;
  1634. if (!tdb.objectStoreNames.contains("HIT")) {
  1635. console.log("creating HIT OS");
  1636. var dbo = tdb.createObjectStore("HIT", { keyPath: "hitId" });
  1637. dbo.createIndex("date", "date", { unique: false });
  1638. dbo.createIndex("requesterName", "requesterName", { unique: false});
  1639. dbo.createIndex("title", "title", { unique: false });
  1640. dbo.createIndex("reward", "reward", { unique: false });
  1641. dbo.createIndex("status", "status", { unique: false });
  1642. dbo.createIndex("requesterId", "requesterId", { unique: false });
  1643.  
  1644. }
  1645. if (!tdb.objectStoreNames.contains("STATS")) {
  1646. console.log("creating STATS OS");
  1647. dbo = tdb.createObjectStore("STATS", { keyPath: "date" });
  1648. }
  1649. if (!tdb.objectStoreNames.contains("NOTES")) {
  1650. console.log("creating NOTES OS");
  1651. dbo = tdb.createObjectStore("NOTES", { keyPath: "requesterId" });
  1652. }
  1653. if (!tdb.objectStoreNames.contains("BLOCKS")) {
  1654. console.log("creating BLOCKS OS");
  1655. dbo = tdb.createObjectStore("BLOCKS", { keyPath: "id", autoIncrement: true });
  1656. dbo.createIndex("requesterId", "requesterId", { unique: false });
  1657. }
  1658. } //}}}
  1659.  
  1660.  
  1661.  
  1662. // vim: ts=2:sw=2:et:fdm=marker:noai