Monero/Aeon Webminer add-on module for After Dark https://habd.as/code/toxic-swamp/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

toolbar.html 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. {{ partial "modules/toxic-swamp/inline.css.html" }}
  2. {{ partial "modules/toxic-swamp/inline.jsonld.html" }}
  3. {{ $toggle := partial "components/button" (dict "isghost" "true" "type" "success" "name" "toggle") }}
  4. {{ $controls := partial "components/buttongroup" (dict "class" "btn-controls" "body" $toggle) }}
  5. <form hidden name="webminer" class="grid -center js-toolbar">
  6. {{ partial "components/helpblock" (dict "class" "status" "body" (`<small class="js-status"></small>` | safeHTML))}}
  7. {{ partial "components/helpblock" (dict "class" "interstitial" "body" (`<small class="js-interstitial" hidden>Click to activate…</small>` | safeHTML))}}
  8. {{ partial "components/helpblock" (dict "class" "ticker" "body" (`<small class="js-ticker"></small>` | safeHTML))}}
  9. <input name="throttle" type="range" min="10" max="100" step="5" value="30">
  10. &nbsp;{{ $controls }}
  11. {{ partial "components/textinput" (dict "attrs" (dict "type" "hidden" "name" "hashrate" "value" "0")) }}
  12. {{ partial "components/textinput" (dict "attrs" (dict "type" "hidden" "name" "hashes" "value" "0")) }}
  13. </form>
  14. <noscript>
  15. <style>form[name="webminer"] { display: none !important; }</style>
  16. </noscript>
  17. <script>
  18. (function (window, document, undefiend) {
  19. 'use strict';
  20. if (window.frameElement) return document.forms.webminer.remove();
  21. const nodeList = document.head.querySelectorAll('meta[title="mod:toxic-swamp"]');
  22. const metadata = new Map();
  23. for (let [key, value] of nodeList.entries()) {
  24. let kvp = value.content.split(':'); metadata.set(kvp[0],kvp[1]);
  25. }
  26. const active = ['enabled', 'debugging'].includes(metadata.get('status'));
  27. if (!(active && metadata.has('settings'))) return;
  28. const proxies = JSON.parse(atob(metadata.get('settings')));
  29. const proxy = proxies[Object.keys(proxies)[0]];
  30. let locale = 'en';
  31. if (metadata.has('translations')) {
  32. const translations = JSON.parse(metadata.get('translations'));
  33. const preferredLanguage = document.documentElement.lang || navigator.language;
  34. locale = (() => {
  35. const hasPreferred = translations.includes(preferredLanguage);
  36. if (hasPreferred) return preferredLanguage;
  37. const similarLanguage = preferredLanguage.slice(0,2);
  38. const includesSimilar = translations
  39. .map(locale => locale.slice(0,2))
  40. .includes(similarLanguage);
  41. return includesSimilar ? similarLanguage : 'en';
  42. })();
  43. }
  44. const helpText = JSON.parse(
  45. document.getElementById('mod:toxic-swamp:lang:help').textContent
  46. );
  47. const statusText = JSON.parse(
  48. document.getElementById('mod:toxic-swamp:lang:status').textContent
  49. );
  50. const errorText = JSON.parse(
  51. document.getElementById('mod:toxic-swamp:lang:error').textContent
  52. );
  53. const lang = {
  54. help: helpText,
  55. status: statusText,
  56. error: errorText
  57. };
  58. const debug = args =>
  59. (metadata.get('status') === 'debugging') && console.log(args);
  60. class SessionManager {
  61. static get shouldMine () {
  62. return !(sessionStorage.getItem('shouldmine') === 'false');
  63. }
  64. static set shouldMine (shouldMine) {
  65. sessionStorage.setItem('shouldmine', shouldMine);
  66. }
  67. static get totalHashes () {
  68. return Number(sessionStorage.getItem('totalhashes'));
  69. }
  70. static set totalHashes (total) {
  71. sessionStorage.setItem('totalhashes', total);
  72. }
  73. static get throttle () {
  74. return sessionStorage.getItem('throttle');
  75. }
  76. static set throttle (throttle) {
  77. sessionStorage.setItem('throttle', throttle);
  78. }
  79. static get hashrate () {
  80. return sessionStorage.getItem('hashrate');
  81. }
  82. static set hashrate (hashrate) {
  83. sessionStorage.setItem('hashrate', hashrate);
  84. }
  85. }
  86. class WebMiner {
  87. static initialize () {
  88. window.server = window._server;
  89. window.throttleMiner = state.throttle || window._throttleMiner;
  90. }
  91. static start () { window.startMining(proxy.pool, proxy.address); }
  92. static stop () { window.stopMining(); }
  93. static get throttle () { return window.throttleMiner; }
  94. static set throttle (throttle) { window.throttleMiner = throttle; }
  95. static get hashTotal () { return window.totalhashes; }
  96. static set hashTotal (total) { window.totalhashes = total; }
  97. static get sendStack () { return window.sendStack; }
  98. static get receiveStack () { return window.receiveStack; }
  99. }
  100. const form = document.forms.webminer;
  101. const state = {
  102. isMining: false,
  103. shouldMine: SessionManager.shouldMine,
  104. throttle: SessionManager.throttle,
  105. hashrate: SessionManager.hashrate,
  106. totalHashes: SessionManager.totalHashes,
  107. shouldDisclose: window.matchMedia('(min-width: 840px)').matches
  108. };
  109. if (state.throttle) form.throttle.value = 100 - state.throttle;
  110. if (state.hashrate) form.hashrate.value = state.hashrate;
  111. if (state.totalHashes) form.hashes.value = state.totalHashes;
  112. fetchInject([
  113. {{ "/modules/toxic-swamp/webminer.min.js" | relURL }}
  114. ]).then(() => {
  115. const status = form.querySelector('.js-status');
  116. const interstitial = form.querySelector('.js-interstitial');
  117. const ticker = form.querySelector('.js-ticker');
  118. const displaySetting = state.shouldDisclose ? 'full' : 'compact';
  119. let statusIntervalId;
  120. const startMining = () => {
  121. clearInterval(statusIntervalId);
  122. WebMiner.start();
  123. const { receiveStack, sendStack } = WebMiner;
  124. statusIntervalId = setInterval(function () {
  125. while (sendStack.length) updateStatus(sendStack.pop());
  126. while (receiveStack.length) updateStatus(receiveStack.pop());
  127. }, 2000);
  128. };
  129. const stopMining = () => {
  130. WebMiner.stop();
  131. clearInterval(statusIntervalId);
  132. }
  133. const updateStatus = data => {
  134. status.textContent = `[${new Date().toLocaleString()}] `;
  135. if (data.identifier === 'job') {
  136. form.toggle.classList.add('-mining');
  137. status.textContent += `${lang.status.newJob[locale]}: ${data.job_id}`;
  138. } else if (data.identifier === 'solved') {
  139. status.textContent += `${lang.status.solvedJob[locale]}: ${data.job_id}`;
  140. } else if (data.identifier === 'hashsolved') {
  141. status.textContent += lang.status.poolAcceptedHash[locale];
  142. } else if (data.identifier === 'error') {
  143. form.toggle.classList.remove('-mining');
  144. status.textContent += `${lang.status.error[locale]}: ${data.param}`;
  145. } else status.textContent += data;
  146. debug(status.textContent);
  147. };
  148. const showInterstitial = (message, delay = 0) => {
  149. setTimeout(function () {
  150. interstitial.textContent = message;
  151. ticker.hidden = true;
  152. interstitial.hidden = false;
  153. setTimeout(function () {
  154. ticker.hidden = false;
  155. interstitial.hidden = true;
  156. }, 2000);
  157. }, delay);
  158. };
  159. class Actuator {
  160. static activate (shouldPersist = false) {
  161. state.isMining = true;
  162. startMining();
  163. shouldPersist && (() => {
  164. SessionManager.shouldMine = true;
  165. showInterstitial(lang.help.activated[locale]);
  166. })();
  167. }
  168. static deactivate (shouldPersist = false) {
  169. state.isMining = false;
  170. stopMining();
  171. shouldPersist && (() => {
  172. SessionManager.shouldMine = false;
  173. showInterstitial(lang.help.deactivated[locale]);
  174. })();
  175. }
  176. static get status () {
  177. return state.isMining ? 'active' : 'inactive';
  178. }
  179. }
  180. class Toolbar {
  181. static initialize () {
  182. WebMiner.initialize();
  183. setInterval(function () {
  184. const hashTotal = WebMiner.hashTotal;
  185. state.hashrate = Math.floor(hashTotal / 2 + state.hashrate / 2);
  186. state.totalHashes = state.totalHashes + hashTotal;
  187. WebMiner.hashTotal = 0;
  188. }, 1000);
  189. const updateTicker = () => {
  190. Toolbar.updateTickerTotal();
  191. requestAnimationFrame(updateTicker);
  192. };
  193. requestAnimationFrame(updateTicker);
  194. }
  195. static togglePower (wasUserInitiated = false) {
  196. const isMinerActive = Actuator.status === 'active';
  197. const isDeviceOnline = navigator.onLine;
  198. form.toggle.classList.toggle('-active');
  199. isMinerActive
  200. ? Actuator.deactivate(wasUserInitiated) && Toolbar.toggleStatusbar()
  201. : Actuator.activate(wasUserInitiated);
  202. isDeviceOnline
  203. ? updateStatus(lang.status.waitingForServer[locale])
  204. : updateStatus(lang.status.waitingForNetwork[locale]);
  205. }
  206. static setThrottle (throttle) {
  207. WebMiner.throttle = 100 - throttle;
  208. SessionManager.throttle = 100 - throttle;
  209. showInterstitial(`${throttle}% ${lang.help.hashpower[locale]}`);
  210. }
  211. static setDisplayMode (displayMode = 'full') {
  212. const isValidMode = [
  213. 'full', 'compact', 'hidden', 'minimal'
  214. ].includes(displayMode);
  215. if (!isValidMode) throw new Error(lang.error.displayModeInvalid[locale]);
  216. Toolbar.displayMode = displayMode;
  217. Toolbar.updateDisplayMode();
  218. }
  219. static getDisplayMode () {
  220. return Toolbar.displayMode;
  221. }
  222. static updateTickerTotal () {
  223. const total = state.totalHashes + WebMiner.hashTotal;
  224. const hashrate = state.hashrate || 0;
  225. ticker.textContent = `${total} ${lang.help.hashes[locale]} (${hashrate} ${lang.help.unit[locale]})`;
  226. }
  227. static updateDisplayMode () {
  228. const displayMode = Toolbar.displayMode;
  229. const shouldMine = SessionManager.shouldMine;
  230. const visibleItems = new Set([
  231. form, ticker, status, form.toggle, form.throttle
  232. ]);
  233. let hiddenItems;
  234. switch (displayMode) {
  235. case 'full':
  236. hiddenItems = shouldMine ? [] : [].concat(ticker);
  237. break;
  238. case 'compact':
  239. hiddenItems = [].concat([form, ticker, status]);
  240. break;
  241. case 'minimal':
  242. hiddenItems = [].concat([form, ticker, status, form.throttle]);
  243. break;
  244. case 'hidden':
  245. hiddenItems = [].concat(
  246. [form, ticker, status, form.toggle, form.throttle]
  247. );
  248. break;
  249. }
  250. hiddenItems.forEach(hiddenItem => {
  251. hiddenItem.hidden = true;
  252. visibleItems.delete(hiddenItem);
  253. });
  254. visibleItems.forEach(visibleItem => {
  255. visibleItem.hidden = false;
  256. });
  257. }
  258. static toggleStatusbar () {
  259. const isMinerActive = Actuator.status === 'active';
  260. isMinerActive
  261. ? form.classList.toggle('-disclosed')
  262. : form.classList.remove('-disclosed');
  263. }
  264. static registerListeners () {
  265. form.addEventListener(
  266. 'submit', evt => evt.preventDefault()
  267. );
  268. form.throttle.addEventListener(
  269. 'change', evt => Toolbar.setThrottle(evt.target.value)
  270. );
  271. form.toggle.addEventListener(
  272. 'keyup', evt => evt.keyCode === 13 && Toolbar.togglePower(true)
  273. );
  274. form.toggle.addEventListener(
  275. 'click', evt => evt.detail && Toolbar.togglePower(true)
  276. );
  277. form.toggle.addEventListener(
  278. 'mouseenter', evt => Toolbar.toggleStatusbar()
  279. );
  280. form.toggle.addEventListener(
  281. 'mouseleave', evt => Toolbar.toggleStatusbar()
  282. );
  283. form.toggle.addEventListener(
  284. 'focus', evt => Toolbar.toggleStatusbar()
  285. );
  286. form.toggle.addEventListener(
  287. 'blur', evt => Toolbar.toggleStatusbar()
  288. );
  289. }
  290. }
  291. Toolbar.initialize();
  292. Toolbar.setDisplayMode(displaySetting);
  293. Toolbar.registerListeners();
  294. const handleChargingChange = evt => {
  295. const shouldMine = SessionManager.shouldMine;
  296. if (!shouldMine) return;
  297. const isMinerActive = Actuator.status === 'active';
  298. const startedCharging = evt.target.charging;
  299. const isDeviceOnline = navigator.onLine;
  300. if (startedCharging) {
  301. const isDeviceOnline = navigator.onLine;
  302. showInterstitial(lang.help.powered[locale]);
  303. !isMinerActive && Toolbar.togglePower()
  304. if (isDeviceOnline) {
  305. showInterstitial(lang.help.resumed[locale], 3000);
  306. } else {
  307. updateStatus('waiting for network');
  308. showInterstitial(lang.help.disconnected[locale], 3000);
  309. }
  310. } else {
  311. showInterstitial(lang.help.unplugged[locale]);
  312. isMinerActive && Toolbar.togglePower();
  313. isDeviceOnline
  314. ? showInterstitial(lang.help.economy[locale], 3000)
  315. : showInterstitial(lang.help.disconnected[locale], 3000);
  316. }
  317. };
  318. const handleOnlineChange = evt => {
  319. const shouldMine = SessionManager.shouldMine;
  320. if (!shouldMine) return;
  321. const isMinerActive = Actuator.status === 'active';
  322. const wentOnline = evt.type === 'online';
  323. if (wentOnline) {
  324. showInterstitial(lang.help.restored[locale]);
  325. if (isMinerActive) {
  326. updateStatus(lang.status.waitingForServer[locale]);
  327. showInterstitial(lang.help.resumed[locale], 3000);
  328. } else {
  329. showInterstitial(lang.help.activate[locale], 3000);
  330. }
  331. } else {
  332. showInterstitial(lang.help.disconnected[locale]);
  333. if (isMinerActive) {
  334. Toolbar.togglePower();
  335. updateStatus(lang.status.waitingForNetwork[locale]);
  336. showInterstitial(lang.help.paused[locale], 3000);
  337. } else {
  338. showInterstitial(lang.help.paused[locale], 3000);
  339. }
  340. }
  341. };
  342. const handleVisibilityChange = evt => {
  343. const shouldMine = SessionManager.shouldMine;
  344. if (!shouldMine) return;
  345. const isMinerActive = Actuator.status === 'active';
  346. const wasDocumentHidden = document['hidden'];
  347. if (wasDocumentHidden) {
  348. isMinerActive && Toolbar.togglePower();
  349. } else {
  350. navigator.getBattery().then(battery => {
  351. const isDeviceCharging = battery.charging;
  352. if (isDeviceCharging) {
  353. !isMinerActive && Toolbar.togglePower();
  354. } else {
  355. showInterstitial(lang.help.economy[locale]);
  356. showInterstitial(lang.help.override[locale], 3000);
  357. }
  358. });
  359. }
  360. };
  361. const handlePageHide = evt => {
  362. SessionManager.totalHashes = state.totalHashes + WebMiner.hashTotal;
  363. SessionManager.hashrate = state.hashrate;
  364. };
  365. const handlePageShow = Toolbar.updateTickerTotal;
  366. window.addEventListener('online', handleOnlineChange);
  367. window.addEventListener('offline', handleOnlineChange);
  368. window.addEventListener('pageshow', handlePageShow);
  369. window.addEventListener('pagehide', handlePageHide);
  370. document.addEventListener('visibilitychange', handleVisibilityChange);
  371. navigator.getBattery().then(battery => {
  372. battery.onchargingchange = handleChargingChange;
  373. const shouldMine = SessionManager.shouldMine;
  374. if (!shouldMine) return;
  375. const isDeviceOnline = navigator.onLine;
  376. const isDeviceCharging = battery.charging;
  377. if (isDeviceCharging) {
  378. if (isDeviceOnline) return Toolbar.togglePower();
  379. showInterstitial(lang.help.disconnected[locale]);
  380. showInterstitial(lang.help.paused[locale], 3000);
  381. } else {
  382. showInterstitial(lang.help.unplugged[locale]);
  383. showInterstitial(lang.help.paused[locale], 3000);
  384. }
  385. }); // zip it up and zip it out
  386. });
  387. })(window, document);
  388. </script>