forked from rotki/rotki
/
utils.js
294 lines (262 loc) · 9.38 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
var fs = require('fs');
var Tail = require('tail').Tail;
var settings = require("./settings.js")();
require("./balances_table.js")();
const {dialog} = require('electron').remote;
// Prompt a directory selection dialog and pass selected directory to callback
// Callback should be a function which accepts a single argument which will be
// a list of pathnames. The list should only contain 1 entry.
function prompt_directory_select_async(callback) {
dialog.showOpenDialog({
title:"Select a directory",
properties: ["openDirectory"]
}, callback);
}
function utc_now() {
return Math.floor(Date.now() / 1000);
}
function timestamp_to_date(ts) {
let date = new Date(ts * 1000);
return (
("0" + date.getUTCDate()).slice(-2)+ '/' +
("0" + (date.getUTCMonth() + 1)).slice(-2) + '/' +
date.getUTCFullYear() + ' ' +
("0" + date.getUTCHours()).slice(-2) + ':' +
("0" + date.getUTCMinutes()).slice(-2)
);
}
var log_searcher = null;
function _setup_log_watcher(callback) {
if (log_searcher) {
if (!fs.existsSync("rotkehlchen.log")) {
return;
}
clearInterval(log_searcher);
}
var options = { fromBeginning: true};
var tail = new Tail("rotkehlchen.log");
var rePattern = new RegExp('.*(WARNING|ERROR):.*:(.*)');
tail.on("line", function(data) {
var matches = data.match(rePattern);
if (matches != null) {
callback(matches[2], new Date().getTime() / 1000);
console.log(matches[2]);
}
});
tail.on("error", function(error) {
console.log('TAIL ERROR: ', error);
});
}
// Show an error with TITLE and CONTENT
// If CALLBACK is given then it should be a callback
// to call when close is pressed
function showError(title, content, callback) {
if (!callback) {
callback = function() {};
}
$.confirm({
title: title,
content: content,
type: 'red',
typeAnimated: true,
buttons: {
close: callback
}
});
}
// Show an Info message with TITLE and CONTENT
function showInfo(title, content) {
$.confirm({
title: title,
content: content,
type: 'green',
typeAnimated: true,
buttons: {
close: function() {}
}
});
}
function showWarning(title, content) {
$.confirm({
title: title,
content: content,
type: 'yellow',
typeAnimated: true,
buttons: {
close: function() {}
}
});
}
// TODO: Remove this/replace with something else. In the case of a huge log hangs the entire app
function setup_log_watcher(callback) {
// if the log file is not found keep trying until it is
if (!fs.existsSync("rotkehlchen.log")) {
log_searcher = setInterval(function() {_setup_log_watcher(callback);}, 5000);
return;
}
_setup_log_watcher(callback);
}
function reload_table_currency_val(table, colnum) {
table.rows().invalidate();
$(table.column(colnum).header()).text(settings.main_currency.ticker_symbol + ' value');
table.draw();
}
function reload_table_currency_val_if_existing(table, colnum) {
if (table) {
reload_table_currency_val(table, colnum);
}
}
function string_capitalize(s) {
return s && s[0].toUpperCase() + s.slice(1);
}
function throw_with_trace(str) {
let err = new Error();
throw str + "\n" + err.stack;
}
function date_text_to_utc_ts(txt) {
// for now assuming YYY/MM/DD HH:MM
if (settings.datetime_format != 'd/m/Y G:i') {
throw "Invalid datetime format";
}
let m = txt.match(/\d+/g);
let day = parseInt(m[0]);
let month = parseInt(m[1]) - 1;
let year = parseInt(m[2]);
let hours = parseInt(m[3]);
let seconds = parseInt(m[4]);
return (new Date(Date.UTC(year, month, day, hours, seconds))).getTime() / 1000;
}
function dt_edit_drawcallback(id, edit_fn, delete_fn) {
return function (settings) {
let dt_api = this;
let ctx_menu_items = {};
if (edit_fn) {
ctx_menu_items['edit'] = {name: "Edit", icon: "fa-edit"};
}
if (delete_fn) {
ctx_menu_items['delete'] = {name: "Delete", icon: "fa-trash"};
}
ctx_menu_items['sep1'] = "---------";
ctx_menu_items['quit'] = {name: "Quit", icon: "fa-sign-out"};
// idea taken from: https://stackoverflow.com/questions/43161236/how-to-show-edit-and-delete-buttons-on-datatables-when-right-click-to-rows
$.contextMenu({
selector: '#' + id + '_body tr td',
callback: function(key, options) {
var tr = $(this).closest('tr');
var row = $('#'+id).DataTable().row(tr);
// TODO: When move to SQL instead of files, simply use the primary key/id to select
switch (key) {
case 'delete' :
if (delete_fn) {
delete_fn(row);
}
break;
case 'edit' :
if (edit_fn) {
edit_fn(row);
}
break;
case 'quit':
break;
}
},
items: ctx_menu_items
});
};
}
function unsuggest_element(selector) {
$(selector).pulsate('destroy');
$(selector).removeAttr('style');
}
function suggest_element(selector, state_to_set) {
settings.start_suggestion = state_to_set;
$(selector).pulsate({
color: "#e45325", // set the color of the pulse
reach: 20, // how far the pulse goes in px
speed: 1000, // how long one pulse takes in ms
pause: 0, // how long the pause between pulses is in ms
glow: true, // if the glow should be shown too
repeat: true, // will repeat forever if true, if given a number will repeat for that many times
onHover: false // if true only pulsate if user hovers over the element
});
}
function suggest_element_until_click(selector, state_to_set) {
suggest_element(selector, state_to_set);
$(selector).click(function(event) {
unsuggest_element(selector);
});
}
function get_total_asssets_value(asset_dict) {
var value = 0;
for (var asset in asset_dict) {
if (asset_dict.hasOwnProperty(asset)) {
value += parseFloat(asset_dict[asset]['usd_value']);
}
}
return value;
}
function get_fiat_exchange_rates(currencies) {
client.invoke("get_fiat_exchange_rates", currencies, (error, res) => {
if (error || res == null) {
showError('Connectivity Error', 'Failed to acquire fiat to USD exchange rates: ' + error);
return;
}
console.log("get_fiat_exchange_rates for " + currencies + " returned okay");
let rates = res['exchange_rates'];
for (let asset in rates) {
if(rates.hasOwnProperty(asset)) {
settings.usd_to_fiat_exchange_rates[asset] = parseFloat(rates[asset]);
}
}
// something noticed is that if a zero rpc call from node to python happens
// within very close proximity to another one with the same function then
// it's very possible one will timeout with heartbear error. That is why
// we call the full exchange rate update here after we get the main
// currency exchange rate
if (currencies) {
get_fiat_exchange_rates(); // for all currencies
}
});
}
function* iterate_saved_balances() {
let saved_balances = total_balances_get();
for (var location in saved_balances) {
if (saved_balances.hasOwnProperty(location)) {
let total = get_total_asssets_value(saved_balances[location]);
if (settings.EXCHANGES.indexOf(location) >= 0) {
yield [location, total, null];
} else {
let icon;
if (location == 'blockchain') {
icon = 'fa-hdd-o';
} else if (location == 'banks') {
icon = 'fa-university';
} else {
throw 'Invalid location at dashboard box from saved balance creation';
}
yield [location, total, icon];
}
}
}
}
module.exports = function() {
this.prompt_directory_select_async = prompt_directory_select_async;
this.utc_now = utc_now;
this.timestamp_to_date = timestamp_to_date;
this.string_capitalize = string_capitalize;
this.setup_log_watcher = setup_log_watcher;
this.showError = showError;
this.showInfo = showInfo;
this.showWarning = showWarning;
this.date_text_to_utc_ts = date_text_to_utc_ts;
this.reload_table_currency_val = reload_table_currency_val;
this.reload_table_currency_val_if_existing = reload_table_currency_val_if_existing;
this.get_total_asssets_value = get_total_asssets_value;
this.throw_with_trace = throw_with_trace;
this.dt_edit_drawcallback = dt_edit_drawcallback;
this.suggest_element = suggest_element;
this.unsuggest_element = unsuggest_element;
this.suggest_element_until_click = suggest_element_until_click;
this.get_fiat_exchange_rates = get_fiat_exchange_rates;
this.iterate_saved_balances = iterate_saved_balances;
};