helperFunctions.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. Helper functions
  3. @module Helpers
  4. **/
  5. /**
  6. The Helpers class containing helper functions
  7. @class Helpers
  8. @constructor
  9. **/
  10. Helpers = {};
  11. /**
  12. The preloader dirname
  13. @property preloaderDirname
  14. **/
  15. Helpers.preloaderDirname = window.dirname + '/modules/preloader';
  16. /**
  17. Reruns functions reactively, based on an interval. Use it like so:
  18. Helpers.rerun['10s'].tick();
  19. @method rerun
  20. **/
  21. Helpers.rerun = {
  22. '10s': new ReactiveTimer(10),
  23. '1s': new ReactiveTimer(1)
  24. };
  25. /**
  26. Get the webview from either and ID, or the string "browser"
  27. @method getWebview
  28. @param {String} id The Id of a tab or the string "browser"
  29. */
  30. Helpers.getWebview = function(id) {
  31. return $('webview[data-id="' + id + '"]')[0];
  32. };
  33. /**
  34. Get tab by url and return the id
  35. @method getTabIdByUrl
  36. @param {String} url
  37. @return {String} id
  38. */
  39. Helpers.getTabIdByUrl = function(url, returnEmpty) {
  40. var tabs = Tabs.find().fetch();
  41. url = Helpers.sanitizeUrl(url);
  42. var foundTab = _.find(tabs, function(tab) {
  43. if (tab._id === 'browser' || !tab.url) {
  44. return false;
  45. }
  46. var tabOrigin = new URL(tab.url).origin;
  47. // Local urls always have the same origin as shown below,
  48. // so we shouldn't consider it as a match
  49. if (tabOrigin === 'file://') {
  50. return false;
  51. }
  52. return url && new URL(url).origin.indexOf(tabOrigin) === 0;
  53. });
  54. // switch tab to browser
  55. if (foundTab) {
  56. foundTab = foundTab._id;
  57. } else {
  58. foundTab = 'browser';
  59. }
  60. return foundTab;
  61. };
  62. /**
  63. Format Urls, e.g add a default protocol if on is missing.
  64. @method formatUrl
  65. @param {String} url
  66. **/
  67. Helpers.formatUrl = function(url) {
  68. if (!url) return;
  69. // add http:// if no protocol is present
  70. if (url.length === 64 && !!url.match(/^[0-9a-f]+$/)) {
  71. // if the url looks like a hash, add bzz
  72. url = 'bzz://' + url;
  73. } else if (!!url.match(/^([a-z]*:\/\/)?[^/]*\.eth(\/.*)?$/i)) {
  74. // if uses .eth as a TLD
  75. url = 'bzz://' + url.replace(/^([a-z]*:\/\/)?/i, '');
  76. } else if (!!url.match(/^[^\.\/]*$/i)) {
  77. // doesn't have a protocol nor a TLD
  78. url = 'bzz://' + url + '.eth';
  79. } else if (url.indexOf('://') === -1) {
  80. // if it doesn't have a protocol
  81. url = 'http://' + url;
  82. }
  83. return url;
  84. };
  85. /**
  86. Sanatizes URLs to prevent phishing and XSS attacks
  87. @method sanitizeUrl
  88. @param {String} url
  89. **/
  90. Helpers.sanitizeUrl = function(url, returnEmptyURL) {
  91. url = String(url);
  92. url = url.replace(/[\t\n\r\s]+/g, '');
  93. url = url.replace(/^[:\/]{1,3}/i, 'http://');
  94. if (returnEmptyURL && /^(?:file|javascript|data):/i.test(url)) {
  95. url = false;
  96. }
  97. return url;
  98. };
  99. /**
  100. Takes an URL and creates a breadcrumb out of it.
  101. @method generateBreadcrumb
  102. @return Spacebars.SafeString
  103. **/
  104. Helpers.generateBreadcrumb = function(url) {
  105. var filteredUrl;
  106. var pathname;
  107. filteredUrl = {
  108. protocol: Blaze._escape(url.protocol),
  109. host: Blaze._escape(url.host),
  110. pathname: Blaze._escape(url.pathname),
  111. search: Blaze._escape(url.search),
  112. hash: Blaze._escape(url.hash)
  113. };
  114. filteredUrl.pathname += filteredUrl.search.replace(/\?/g, '/');
  115. filteredUrl.pathname += filteredUrl.hash.replace(/#/g, '/');
  116. pathname = _.reject(
  117. filteredUrl.pathname.replace(/\/$/g, '').split('/'),
  118. function(el) {
  119. return el === '';
  120. }
  121. );
  122. return new Spacebars.SafeString(
  123. filteredUrl.protocol +
  124. '//' +
  125. _
  126. .flatten(['<span>' + filteredUrl.host + ' </span>', pathname])
  127. .join(' ▸ ')
  128. );
  129. };
  130. /**
  131. Clear localStorage
  132. @method getLocalStorageSize
  133. **/
  134. Helpers.getLocalStorageSize = function() {
  135. var size = 0;
  136. if (localStorage) {
  137. _.each(Object.keys(localStorage), function(key) {
  138. size += (localStorage[key].length * 2) / 1024 / 1024;
  139. });
  140. }
  141. return size;
  142. };
  143. /**
  144. Makes tab with index active
  145. @method selecTabWithIndex
  146. @param {Integer} index
  147. */
  148. Helpers.selectTabWithIndex = function(index) {
  149. var tabList = Tabs.find(
  150. {},
  151. { sort: { position: 1 }, fields: { _id: 1 } }
  152. ).fetch();
  153. if (index < tabList.length) {
  154. LocalStore.set('selectedTab', tabList[index]._id);
  155. }
  156. };
  157. /**
  158. Makes last tab active
  159. @method selecLastTab
  160. */
  161. Helpers.selectLastTab = function() {
  162. var lastTab = Tabs.findOne(
  163. {},
  164. { sort: { position: -1 }, fields: { _id: 1 }, limit: 1 }
  165. );
  166. LocalStore.set('selectedTab', lastTab._id);
  167. };
  168. /**
  169. Selects previous or next tab (offset +1 or -1)
  170. @method selectTabWithOffset
  171. */
  172. Helpers.selectTabWithOffset = function(offset) {
  173. var tabList;
  174. var currentTabIndex;
  175. var newTabIndex;
  176. if (Math.abs(offset) !== 1) {
  177. return;
  178. }
  179. tabList = _.pluck(
  180. Tabs.find({}, { sort: { position: 1 }, fields: { _id: 1 } }).fetch(),
  181. '_id'
  182. );
  183. currentTabIndex = tabList.indexOf(LocalStore.get('selectedTab'));
  184. newTabIndex = (currentTabIndex + offset) % tabList.length;
  185. if (newTabIndex < 0) {
  186. newTabIndex = tabList.length - 1;
  187. }
  188. LocalStore.set('selectedTab', tabList[newTabIndex]);
  189. };
  190. /**
  191. Detect Network
  192. @method detectNetwork
  193. **/
  194. Helpers.detectNetwork = function(hash) {
  195. var network = {};
  196. switch (hash) {
  197. case '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3':
  198. console.log('Network is mainnet');
  199. network.type = 'mainnet';
  200. network.name = 'Main';
  201. break;
  202. case '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d':
  203. console.log('Network is Testnet #3 (Ropsten)');
  204. network.type = 'testnet';
  205. network.name = 'Ropsten';
  206. break;
  207. case '0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177':
  208. console.log('Network is Testnet #4 (Rinkeby)');
  209. network.type = 'testnet';
  210. network.name = 'Rinkeby';
  211. break;
  212. case '0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303':
  213. console.log('Network is Testnet #2 (Morden)');
  214. network.type = 'testnet';
  215. network.name = 'Morden';
  216. break;
  217. default:
  218. console.log('Network is privatenet');
  219. network.type = 'privatenet';
  220. network.name = 'Private';
  221. }
  222. return network;
  223. };
  224. /**
  225. Displays an error as global notification
  226. @method displayError
  227. @param {Object} error The error object
  228. @param {Boolean} accounts will show the accounts errors
  229. @return {Boolean}
  230. **/
  231. // Helpers.displayError = function(error, accounts) {
  232. // var duration = 8;
  233. // if(error) {
  234. // if(error.reason){
  235. // // hack to make account errors still work
  236. // if(accounts) {
  237. // GlobalNotification.error({
  238. // content: 'i18n:accounts.error.' + error.reason.toLowerCase().replace(/[ ]+/g, ''),
  239. // duration: duration
  240. // });
  241. // } else {
  242. // GlobalNotification.error({
  243. // content: 'i18n:'+ error.reason,
  244. // duration: duration
  245. // });
  246. // }
  247. // } else if(error.message) {
  248. // GlobalNotification.error({
  249. // content: error.message,
  250. // duration: duration
  251. // });
  252. // } else {
  253. // GlobalNotification.error({
  254. // content: error,
  255. // duration: duration
  256. // });
  257. // }
  258. // return true;
  259. // } else
  260. // return false;
  261. // };
  262. /**
  263. Get form values and build a parameters object out of it.
  264. @method formValuesToParameters
  265. @param {Element} elements DOM-Elements elements, selects, inputs and textareas, to get values from. Must have a name tag
  266. @return {Object} An object with parameters to pass to the API Controller e.g.:
  267. {
  268. key1: 'value1',
  269. key2: 'value2'
  270. }
  271. **/
  272. // Helpers.formValuesToParameters = function(elements) {
  273. // var parameters = {};
  274. // $(elements).each(function(){
  275. // var $element = $(this),
  276. // name = $element.attr('name'),
  277. // value = $element.val();
  278. // // add only values wich are not null or empty
  279. // if(name && !_.isEmpty(value) && value !== 'null' && value !== 'NULL') {
  280. // if(_.isFinite(value))
  281. // parameters[name] = parseInt(value);
  282. // else if(_.isBoolean(value))
  283. // parameters[name] = (value === 'true' || value === 'True' || value === 'TRUE') ? true : false;
  284. // else if($element.attr('type') === 'radio')
  285. // parameters[name] = ($element.is(':checked')) ? true : false;
  286. // else if($element.attr('type') === 'checkbox')
  287. // parameters[name] = ($element.is(':checked')) ? true : false;
  288. // else
  289. // parameters[name] = value;
  290. // }
  291. // $element = null;
  292. // });
  293. // return parameters;
  294. // };
  295. /**
  296. Reactive wrapper for the moment package.
  297. @method moment
  298. @param {String} time a date object passed to moment function.
  299. @return {Object} the moment js package
  300. **/
  301. // Helpers.moment = function(time){
  302. // // react to language changes as well
  303. // TAPi18n.getLanguage();
  304. // if(_.isFinite(time) && moment.unix(time).isValid())
  305. // return moment.unix(time);
  306. // else
  307. // return moment(time);
  308. // };
  309. /**
  310. Formats a timestamp to any format given.
  311. Helpers.formatTime(myTime, "YYYY-MM-DD")
  312. @method formatTime
  313. @param {String} time The timstamp, can be string or unix format
  314. @param {String} format the format string, can also be "iso", to format to ISO string, or "fromnow"
  315. @return {String} The formated time
  316. **/
  317. // Helpers.formatTime = function(time, format) { //parameters
  318. // // make sure not existing values are not Spacebars.kw
  319. // if(format instanceof Spacebars.kw)
  320. // format = null;
  321. // if(time) {
  322. // if(_.isString(format) && !_.isEmpty(format)) {
  323. // if(format.toLowerCase() === 'iso')
  324. // time = Helpers.moment(time).toISOString();
  325. // else if(format.toLowerCase() === 'fromnow') {
  326. // // make reactive updating
  327. // Helpers.rerun['10s'].tick();
  328. // time = Helpers.moment(time).fromNow();
  329. // } else
  330. // time = Helpers.moment(time).format(format);
  331. // }
  332. // return time;
  333. // } else
  334. // return '';
  335. // };
  336. /**
  337. Formats a given number
  338. Helpers.formatNumber(10000, "0.0[000]")
  339. @method formatNumber
  340. @param {Number|String|BigNumber} number the number to format
  341. @param {String} format the format string e.g. "0.0[000]" see http://numeraljs.com for more.
  342. @return {String} The formated time
  343. **/
  344. // Helpers.formatNumber = function(number, format){
  345. // if(format instanceof Spacebars.kw)
  346. // format = null;
  347. // if(number instanceof BigNumber)
  348. // number = number.toString(10);
  349. // format = format || '0,0.0[0000]';
  350. // if(!_.isFinite(number))
  351. // number = numeral().unformat(number);
  352. // if(_.isFinite(number))
  353. // return numeral(number).format(format);
  354. // };
  355. /**
  356. Formats a given number toa unit balance
  357. Helpers.formatBalance(10000, "0.0[000]")
  358. @method formatBalance
  359. @param {Number|String|BigNumber} number the number to format
  360. @param {String} format the format string e.g. "0.0[000]" see http://numeraljs.com for more.
  361. @return {String} The formated balance including the unit
  362. **/
  363. // Helpers.formatBalance = function(number, format){
  364. // number = web3.fromWei(number, LocalStore.get('etherUnit'));
  365. // return Helpers.formatNumber(number, format) +' '+ LocalStore.get('etherUnit');
  366. // };