-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathextension.js
814 lines (692 loc) · 26.1 KB
/
extension.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
/*
Sia Cloud Storage Gnome Shell Extension
https://github.com/pmknutsen/gnome-shell-sia
*/
const St = imports.gi.St; // https://developer.gnome.org/st/stable/
const GLib = imports.gi.GLib; // https://developer.gnome.org/glib/stable/
const Gio = imports.gi.Gio; // https://developer.gnome.org/gio/stable/
const Lang = imports.lang;
const Tweener = imports.ui.tweener;
const Util = imports.misc.util;
const Soup = imports.gi.Soup;
const Main = imports.ui.main;
const MessageTray = imports.ui.messageTray;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const Panel = imports.ui.panel;
const GETTEXT_DOMAIN = 'gnome-shell-extension-sia';
const Gettext = imports.gettext.domain(GETTEXT_DOMAIN);
const _ = Gettext.gettext;
/* Import local .js dependencies */
const ExtensionUtils = imports.misc.extensionUtils;
const Extension = ExtensionUtils.getCurrentExtension();
const Convenience = Extension.imports.lib.convenience;
const BigNumber = Extension.imports.lib.bignumber;
const _pdiag = Extension.imports.passworddialog;
const _sendDialog = Extension.imports.senddialog;
/* Clipboard stuff */
const Clipboard = St.Clipboard.get_default();
const CLIPBOARD_TYPE = St.ClipboardType.CLIPBOARD;
/* Global variables */
let siaMonitor;
const HOMEDIR = GLib.get_home_dir();
const SIADIR = 'Sia';
const SYNCFOLDERNAME = 'Desktop'; // name used for folder in Sia renter (and UI)
const TIMER_INTERVAL = 30; // update interval, sec
const FILE_SYNC_LIMIT = 5; // max # files to sync each cycle
const SYNC_RECURSION_LIM = 20; // Sync recursion limit, folders
const MAX_FILES_QUEUED = 100; // max # files in renter queue (limits sync intensity) 5
const REDUNDANCY = 6; // redundancy factor (should match what is hardcoded in siad)
const DEFAULTDURATION = 2000; // default upload duration (blocks)
const RENEWFILES = false; // renew uploaded files
const ENABLELOGGING = false; // log messages printed to log()
const COMPLETETHRESH = 99; // % uploaded considered 100% complete
let g_syncPause = false;
let walletUnlocked = false;
let g_currentBlock = 0;
let g_fileEmblems = [];
let g_versionOk = true;
/* Start sync timer */
let timeoutID = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, TIMER_INTERVAL, timerExec);
/* Start Soup session (used by getJSON) */
const HTTP_TOO_MANY_REQUESTS = 429;
const _httpSession = new Soup.SessionAsync();
_httpSession['user-agent'] = 'Sia-Agent';
Soup.Session.prototype.add_feature.call(
_httpSession,
new Soup.ProxyResolverDefault()
);
/**
* Define new entry in the gnome3 status-area.
* @type {Lang.Class}
*/
const Sia = new Lang.Class({
Name : 'Sia',
Extends : PanelMenu.Button,
_walletstatus : null,
_walletbalance : null,
_walletpending : null,
_walletsend : null,
_walletreceive : null,
_pausesync : null,
_siaIcon : null,
_filesSynced : null,
_filesRedundancy : null,
_gbUsed : null,
_init : function() {
this.parent(0.0, "Sia");
/* Display icon */
this._siaIcon = new St.Icon({ icon_name: 'sia-icon', style_class: 'sia-icon' });
this.actor.add_child(this._siaIcon);
/* Create menu */
this._createMenu();
getWalletLockStatus();
/* Create the ~/Sia directory */
createSiaDir();
/* Auto-start siad if not already running */
this._startSiad();
},
_startSiad : function() {
getJSON('GET', '/consensus', null, function(code, json) {
let result = JSON.parse(json);
if (result === undefined || result === null) {
/* Start siad */
let path = GLib.find_program_in_path('siad');
if (path === null) {
showNotification('Sia not found on this system. Start siad manually, or add siad to your path.');
} else {
/* Run autostart.sh to start siad */
let shpath = HOMEDIR + '/.local/share/gnome-shell/extensions/sia@pmknutsen.github.com/autostart.sh';
Util.spawn(['chmod', '+x', shpath]);
Util.spawn([shpath]);
showNotification('Starting Sia daemon...');
}
}
});
},
_createMenu : function() {
this._walletstatus = this._newPopupMenuItem(this, 'Sia is not running', 'emblem-readonly', 'menu-item', this._getWalletPass);
this._walletbalance = this._newPopupMenuItem(this, 'Balance: 0 SC', null, 'menu-subitem', this._updateBalance);
this._walletpending = this._newPopupMenuItem(this, 'Pending: 0 SC', null, 'menu-subitem', this._updateBalance);
this._walletsend = this._newPopupMenuItem(this, 'Send Funds...', null, 'menu-subitem', this._sendSiacoins);
this._walletreceive = this._newPopupMenuItem(this, 'Receive Funds...', null, 'menu-subitem', this._receiveSiacoins);
this._newPopupSeparator(this, this._updateBalance);
this._newPopupMenuItem(this, 'Open Sia Folder', 'folder-open', 'menu-item', this._openSyncFolder);
this._filesSynced = this._newPopupMenuItem(this, '', null, 'menu-subitem2', syncSiaFolder);
this._filesRedundancy = this._newPopupMenuItem(this, '', null, 'menu-subitem2', syncSiaFolder);
this._gbUsed = this._newPopupMenuItem(this, '', null, 'menu-subitem2', syncSiaFolder);
this._pausesync = this._newPopupMenuItem(this, 'Pause Syncing', null, 'menu-subitem', pauseSync);
},
_newPopupMenuItem : function(parent, title, iconname, style, method) {
let item = new IconMenuItem(title, iconname, style);
item.connect('activate', Lang.bind(this, method));
parent.menu.addMenuItem(item);
return item;
},
_newPopupSeparator : function(parent, method) {
let item = new PopupMenu.PopupSeparatorMenuItem();
item.connect('activate', Lang.bind(this, method));
parent.menu.addMenuItem(item);
},
/* Display wallet authentication dialog */
_getWalletPass : function() {
getJSON('GET', '/wallet', null, function(code, json) {
let wallet = JSON.parse(json);
if (wallet !== null) {
if (wallet.unlocked) {
lockWallet();
} else {
let pdiag = new _pdiag.PasswordDialog;
pdiag.set_callback(unlockWallet);
pdiag.open(global.get_current_time());
}
}
});
},
/* Send Siacoins */
_sendSiacoins : function() {
let sendDialog = new _sendDialog.InputDialog;
sendDialog.set_callback(sendSiacoins);
sendDialog.open(global.get_current_time());
},
/* Receive Siacoins (copy address to clipboard) */
_receiveSiacoins : function() {
/* Get new address */
getJSON('GET', '/wallet/address', null, function(code, json) {
let result = JSON.parse(json);
Clipboard.set_text(CLIPBOARD_TYPE, result.address);
showNotification('Siacoin address copied to clipboard.');
});
},
/* Open synchronization folder */
_openSyncFolder : function() {
Util.spawn(['nautilus', SIADIR]);
},
/* Update wallet balance */
_updateBalance : function() {
getJSON('GET', '/wallet', null, updateWalletBalance);
},
});
/* Start plugin */
function init(metadata) {
Convenience.initTranslations(GETTEXT_DOMAIN);
}
/* Called when the extension is activated (maybe multiple times) */
function enable() {
siaMonitor = new Sia();
Main.panel.addToStatusArea('sia', siaMonitor);
showWalletUnlockedItems(walletUnlocked);
updateBlockCounter();
updateRenterMenu();
}
/* Called when the extension is deactivated (maybe multiple times) */
function disable() {
siaMonitor.destroy();
}
/* Log to log() */
function logMsg(msg) {
if (ENABLELOGGING)
log('Sia: ' + msg);
return;
}
/* Pause synchronization */
function pauseSync() {
g_syncPause = !g_syncPause;
if (g_syncPause) {
siaMonitor._pausesync.label.text = 'Resume Syncing';
} else {
siaMonitor._pausesync.label.text = 'Pause Syncing';
showNotification('Synchronization resumed.');
}
return true;
}
/* Create the ~/Sia sync folder */
function createSiaDir() {
Util.spawn(['mkdir', '-p', SIADIR]);
Util.spawn(['gvfs-set-attribute', SIADIR, '-t', 'string', 'metadata::custom-icon', getIconPath()]);
}
/* Get path to Sia icon */
function getIconPath() {
let icon = 'file://' + HOMEDIR + '/.local/share/gnome-shell/extensions/sia@pmknutsen.github.com/img/icon.png';
return icon;
}
/* Send Siacoins */
function sendSiacoins(address, siacoins) {
/* Validate address */
if (address === null) return;
if (!isAddress(address)) {
showNotification('Invalid address.');
return;
}
/* Validate address */
if (siacoins <= 0) {
showNotification('Invalid amount.');
return;
}
/* Convert Siacoins to hastings */
let hastings = convertHastings(siacoins);
/* Send Siacoins */
getJSON('POST', '/wallet/siacoins', 'amount=' + hastings + '&destination=' + address, function(code, json) {
let result = JSON.parse(json);
if (result === null) {
showNotification('Failed to send. Wallet not responding.');
} else {
if ('transactionids' in result) {
/* Copy transaction ID to clipboard */
Clipboard.set_text(CLIPBOARD_TYPE, result.transactionids[0]);
showNotification('Sent ' + siacoins + ' SC. Transaction ID copied to clipboard.');
} else {
showNotification('Failed to send funds!');
}
}
});
}
/* Convert Siacoins to hastings */
function convertSiacoin(hastings) {
var number = new BigNumber.BigNumber(hastings);
var ConversionFactor = new BigNumber.BigNumber(10).pow(24);
return number.dividedBy(ConversionFactor).round(2);
}
/* Convert Siacoins to hastings */
function convertHastings(siacoins) {
var number = new BigNumber.BigNumber(siacoins);
var ConversionFactor = new BigNumber.BigNumber(10).pow(24);
return number.times(ConversionFactor).toFixed(0);
}
/* Address has to be lowercase hex and 76 chars */
function isAddress(str) {
if (str === null) return false;
return str.match(/^[a-f0-9]{76}$/) !== null;
}
/* Synchronization local folder with Sia renter
The file upload logic is for now very simple:
If a local file is not in the renter, then add it.
If a local file is in the renter, then add it if:
filesizes don't match
or file in renter has expired
Hidden files (w/dot prefix) are ignored.
*/
let syncLevel = 0;
/* Synchronize the Sia folder */
function syncSiaFolder() {
/* Do not sync if wallet is locked */
if (!walletUnlocked) return;
/* Get list of files in renter */
getJSON('GET', '/renter/files', null, function(code, json) {
let files = JSON.parse(json);
if (files === null) return;
files = files.files;
/* Abort sync if there are too many unavailable files in renter queue */
if (getIncompleteFiles(files) >= MAX_FILES_QUEUED) {
logMsg('Too many files in renter queue. Sync aborted.');
return;
}
/* Start sync */
syncLevel = 0;
if (!g_syncPause) {
let fcount = syncFolder(HOMEDIR + '/' + SIADIR, files, 0);
if (fcount > 0) {
showNotification('Started upload of ' + fcount + ' files.');
}
}
});
};
/* Sync a specific folder - function calls itself recursively */
function syncFolder(path, renter, fcount) {
syncLevel += 1;
if (syncLevel > SYNC_RECURSION_LIM) {
showNotification('Reached directory recursion limit (' + SYNC_RECURSION_LIM + ').');
return fcount;
}
/* Get list of local files and directories */
let files = [];
let dirs = [];
let file_info = null;
let children = null;
let folder = Gio.file_new_for_path( path );
try {
children = folder.enumerate_children('*', 0, null, null);
} catch (err) {
logMsg('Permissions denied on ' + path + ': ' + err);
return fcount;
}
while ((file_info = children.next_file(null, null)) !== null) {
if (file_info.get_is_hidden()) { continue; } // skip hidden files
if (isDirectory(file_info)) { dirs.push(file_info); } // is directory
else { files.push(file_info); } // is file
}
children.close(null, null);
/* Sync files in current folder */
fcount = syncFiles(path, files, renter, fcount);
/* Process sub-directories recursively */
let d;
for (d = 0; d < dirs.length; d++) {
fcount = syncFolder(path + '/' + dirs[d].get_name() , renter, fcount);
}
return fcount;
}
/* Synchronize files with renter */
function syncFiles(path, files, renter, fcount) {
let f, r;
for (f = 0; f < files.length; f++) {
let filename = files[f].get_name();
let upload = true;
let siaPath = path + '/' + filename;
let fileUpdated = false;
/* Append path to filename */
let nickname = siaPath;
/* Remove root path and leading slash from nickname */
nickname = nickname.replace(HOMEDIR + '/' + SIADIR + '/', '');
nickname = SYNCFOLDERNAME + '/' + nickname;
/* Compare file with files in renter
Skip files that are already in the renter unless file size is different
*/
for (var r in renter) {
if (renter[r]['siapath'] == nickname) {
let remainingBlocks = renter[r].expiration - g_currentBlock;
let elapsedBlocks = DEFAULTDURATION - remainingBlocks;
/* Do not upload empty files */
if ( files[f].get_size() === 0 ) {
logMsg('Will not upload empty file: ' + filename);
upload = false;
}
/* Check if the file has been updated locally */
else if ( files[f].get_size() !== renter[r].filesize )
fileUpdated = true;
/* Do not upload if file has remaining time or is still syncing */
else if ( remainingBlocks > 0 || renter[r].uploadprogress <= 99 ) {
logMsg('File already in renter: ' + filename);
upload = false;
}
/* Update file icon emblems/overlays */
let emblem = null;
if (renter[r].uploadprogress < COMPLETETHRESH)
emblem = 'view-refresh';
if (renter[r].available)
emblem = 'emblem-default';
if (renter[r].uploadprogress > COMPLETETHRESH) // full redundancy reached
emblem = 'emblem-favorite';
if ( remainingBlocks > 0 && remainingBlocks < 300 )
emblem = 'emblem-urgent';
if (emblem !== null)
g_fileEmblems.push({path:siaPath, emblem:emblem});
/* Delete expired files in renter */
if (remainingBlocks == 0)
deleteSiaFile(nickname);
/* Deleted stalled files - defined as 'unavailable' and with start-of-upload time > 48 h/GB ago
TODO: There is still a risk of stalled files persisting if upload never started.
*/
let fileSize = renter[r].filesize / Math.pow(1024, 3); // bytes -> GB
let blocks = Math.ceil(fileSize) * (6 * 48);
if ( (!renter[r].available && elapsedBlocks > blocks && renter[r].expiration > 0 ) ) {
logMsg('Upload of ' + siaPath + ' aborted: ' + JSON.stringify(renter[r]));
deleteSiaFile(nickname);
}
break;
}
}
/* Upload file */
if (upload && walletUnlocked && fcount < FILE_SYNC_LIMIT) {
/* If a file has been updated, download .sia file into current path and remove from renter.
The local file will be re-uploaded in the next sync cycle.
TODO Fix after 1.x API update
*/
if (fileUpdated) {
/* Get path */
let dotsiaPath = siaPath.substring(0, siaPath.lastIndexOf("/"));
let dotsiaFile = siaPath.split("/").pop();
dotsiaPath = dotsiaPath + '/.' + dotsiaFile + '.sia';
/* Download .sia file */
getJSON('GET', '/renter/share?siapaths=' + nickname + '&destination=' + dotsiaPath, '', checkDownload);
logMsg('Download .sia of ' + nickname);
/* Delete file in renter */
deleteSiaFile(nickname);
} else {
getJSON('POST', '/renter/upload/' + nickname, 'source=' + siaPath, checkUpload);
logMsg('Upload ' + siaPath);
fcount += 1;
}
}
}
return fcount;
}
/* Get number of files in renter that are still syncing */
function getIncompleteFiles(files) {
let incomplete = 0;
for (var f in files) {
if ( files[f].uploadprogress < COMPLETETHRESH )
incomplete += 1;
}
return incomplete;
}
/* Update emblems on files and directories
Emblems are updated sequentially and asynchronously with information provided by
the global variable g_fileEmblems.
*/
function setEmblems() {
/* Iterate over g_fileEmblems while its not empty */
while ( g_fileEmblems.length > 0 ) {
let emlinfo = g_fileEmblems.shift();
let priority = GLib.PRIORITY_DEFAULT;
let cancellable = new Gio.Cancellable();
let flags = Gio.FileQueryInfoFlags.NONE;
let file = Gio.File.new_for_path(emlinfo.path);
file.query_info_async('metadata::emblems', flags, priority, cancellable, (file, res) => {
let info = file.query_info_finish(res);
info.set_attribute_stringv('metadata::emblems', [emlinfo.emblem]);
file.set_attributes_async(info, flags, priority, cancellable, (file, res) => {
file.set_attributes_finish(res);
});
});
};
}
/* Delete file in renter */
function deleteSiaFile(siapath) {
getJSON('POST', '/renter/delete/' + siapath, null, function (code, json) {
let result = JSON.parse(json);
if (result === null)
logMsg('Sia: File deletion failed: ' + json);
});
};
/* Verify new file download and report errors */
function checkDownload(code, json) {
let result = JSON.parse(json);
if (result === null)
logMsg('File download failed: ' + json);
};
/* Verify new file upload and report errors */
function checkUpload(code, json) {
let result = JSON.parse(json);
if (result === null)
logMsg('File upload failed.');
};
/* Update menu with renter statistics */
function updateRenterMenu() {
/* Get list of renter contracts */
getJSON('GET', '/renter/contracts', null, function(code, json) {
let contracts = JSON.parse(json);
contracts = contracts.contracts;
let r;
let totalStorage = 0;
for (r = 0; r < contracts.length; r++) {
totalStorage += contracts[r].size;
}
totalStorage = totalStorage / Math.pow(1024, 3); // bytes -> GB
/* Get list of files in renter */
getJSON('GET', '/renter/files', null, function(code, json) {
let files = JSON.parse(json);
if (files === null) return;
files = files.files;
let filesSynced = 0;
let usedStorage = 0;
let avgUploadProgress = 0.001;
let r;
for (r = 0; r < files.length; r++) {
usedStorage += files[r].filesize * (files[r].uploadprogress / 100) * REDUNDANCY;
if (files[r].available)
filesSynced += 1;
avgUploadProgress += files[r].uploadprogress;
}
usedStorage = usedStorage / Math.pow(1024, 3); // bytes -> GB
siaMonitor._filesSynced.label.text = filesSynced + ' of ' + r + ' files available';
if (avgUploadProgress < 0.01)
siaMonitor._filesRedundancy.label.text = 'No files in upload queue';
else
siaMonitor._filesRedundancy.label.text = 'Upload progress ' + Math.round(avgUploadProgress / r) + '%';
siaMonitor._gbUsed.label.text = usedStorage.toFixed(2) + ' GB used';
});
});
}
/* Check if Gio object is a directory */
function isDirectory(file) {
return Gio.FileType.DIRECTORY == file.get_file_type();
}
/* Unlock wallet */
function unlockWallet(password) {
if (password !== null && password !== '') {
getJSON('POST', '/wallet/unlock', 'encryptionpassword=' + password, getWalletLockStatus);
}
};
/* Lock wallet */
function lockWallet() {
getJSON('POST', '/wallet/lock', null, getWalletLockStatus);
}
/* Get wallet lock status */
function getWalletLockStatus() {
getJSON('GET', '/wallet', null, function(code, json) {
if (json === null) {
updateWalletLockStatus(false);
} else {
let wallet = JSON.parse(json);
if (wallet.unlocked)
updateWalletLockStatus(true);
else
updateWalletLockStatus(false);
}
});
}
/* Run timer functions */
function timerExec() {
/* Make sure ~/Sia exists */
createSiaDir();
/* Update block counter */
updateBlockCounter();
/* Update wallet status */
getWalletLockStatus();
/* Update wallet balance/pending */
siaMonitor._updateBalance()
/* Update renter statistics */
updateRenterMenu();
/* Sync, if wallet has positive balance */
if ( siaMonitor._walletbalance.label.amount > 0 )
syncSiaFolder();
/* Update file/directory emblems */
setEmblems();
return true;
}
/* Get current block height */
function updateBlockCounter() {
getJSON('GET', '/consensus', null, function(code, json) {
let consensus = JSON.parse(json);
if (consensus !== null) {
g_currentBlock = consensus.height;
}
});
}
/* Display wallet lock status */
function updateWalletLockStatus(unlocked) {
if (unlocked === null || unlocked === undefined)
unlocked = false;
if (unlocked) {
if ( siaMonitor._walletstatus.label.text.localeCompare('Unlock wallet...') === 0 ) {
showNotification('Wallet unlocked');
}
siaMonitor._walletstatus.label.text = 'Lock wallet...';
getJSON('GET', '/wallet', null, updateWalletBalance);
} else {
siaMonitor._walletstatus.label.text = 'Unlock wallet...';
}
walletUnlocked = unlocked;
};
/* Update the wallet balance in menu */
function updateWalletBalance(code, json) {
let data = JSON.parse(json);
let unlocked = true;
if (data === null || json === undefined)
if (!data.unlocked) unlocked = false;
showWalletUnlockedItems(unlocked);
if (!unlocked) return;
let balance = prettySiacoin( convertSiacoin( data.confirmedsiacoinbalance ) );
let incoming = convertSiacoin( data.unconfirmedincomingsiacoins );
let outcoming = convertSiacoin( data.unconfirmedoutgoingsiacoins );
let pending = (incoming - outcoming).toFixed(2);
pending = prettySiacoin( pending );
/* Check for new ongoing transfers */
notifyNewTransaction(balance, pending);
siaMonitor._walletbalance.label.text = "Balance: " + balance + " SC";
siaMonitor._walletbalance.label.amount = convertSiacoin( data.confirmedsiacoinbalance );
siaMonitor._walletpending.label.text = "Pending: " + pending + " SC";
siaMonitor._walletpending.label.amount = pending;
}
/* Show/hide items when wallet is unlocked/locked */
function showWalletUnlockedItems(unlocked) {
if (unlocked) {
siaMonitor._walletbalance.actor.show();
siaMonitor._walletpending.actor.show();
siaMonitor._walletsend.actor.show();
siaMonitor._walletreceive.actor.show();
siaMonitor._filesSynced.actor.show();
siaMonitor._filesRedundancy.actor.show();
siaMonitor._gbUsed.actor.show();
siaMonitor._pausesync.actor.show();
} else {
siaMonitor._walletbalance.actor.hide();
siaMonitor._walletpending.actor.hide();
siaMonitor._walletsend.actor.hide();
siaMonitor._walletreceive.actor.hide();
siaMonitor._filesSynced.actor.hide();
siaMonitor._filesRedundancy.actor.hide();
siaMonitor._gbUsed.actor.hide();
siaMonitor._pausesync.actor.hide();
}
return;
}
/* Notify about any new transactions */
function notifyNewTransaction(balance, pending) {
/* Get change in balance */
let oldbalance = siaMonitor._walletbalance.label.amount;
if (oldbalance === undefined || oldbalance === null)
return;
let dbalance = balance - oldbalance;
/* Get change in pending */
let oldpending = siaMonitor._walletpending.label.amount;
if (oldpending === undefined || oldpending === null)
return;
let dpending = pending - oldpending;
dpending = prettySiacoin(dpending.toFixed(2));
/* Report changes in pending, except amounts are confirmed */
if (dpending > 0 && dbalance == 0)
showNotification('New incoming transfer: ' + dpending + ' SC');
/* Do not show outgoing transfers. Ends up being annoying during sync. */
//else if (dpending < 0)
// showNotification('New outgoing transfer: ' + dpending + ' SC');
}
/* Prettify a Siacoin amount with commas. Input is a string */
function prettySiacoin(siacoins) {
if (siacoins === '0' || siacoins === undefined || siacoins === null) return '0';
siacoins = siacoins.toString();
return siacoins.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
/* Query REST API and return results string (assumed to be JSON) */
const getJSON = function (method, query, postParams, callback) {
let url = 'http://localhost:9980' + query;
let msg = Soup.Message.new(method, url);
if (postParams !== null) {
msg.set_request('application/x-www-form-urlencoded', Soup.MemoryUse.COPY, postParams, postParams.length);
}
_httpSession.queue_message(msg, function (session, msg) {
if (msg.status_code == 200) {
callback(null, msg.response_body.data);
} else {
siaMonitor._walletstatus.label.text = 'Sia not running';
callback(msg.status_code, null);
}
}
);
}
/* Display desktop notification */
function showNotification(text) {
/* TODO Fix icon so that getIconPath() can be used as source */
let source = new MessageTray.Source('Sia', 'sia-icon');
Main.messageTray.add(source);
let notification = new MessageTray.Notification(source, 'Sia', text);
notification.setTransient(true);
source.notify(notification);
}
/* Class for creating menu items with an icon */
const IconMenuItem = new Lang.Class({
Name: 'IconMenuItem',
Extends: PopupMenu.PopupBaseMenuItem,
_init: function (text, iconName, style, params) {
this.parent(params);
this._icon = new St.Icon({ x_align: St.Align.END, style_class: 'popup-menu-icon' });
this.actor.add_child(this._icon);
this._setIcon(iconName);
this.label = new St.Label({ text: text, style_class: style });
this.actor.add_child(this.label);
this.actor.label_actor = this.label
},
_setIcon: function(name) {
this._icon.gicon = this._createIcon(name);
},
_createIcon: function(name, params) {
if (!name)
return null;
if (name[0] == '/')
return Gio.FileIcon.new(Gio.File.new_for_path(name));
// This is to hack through the gtk silly icon theme code. GTK doesn't want to mix
// symbolic icon and normal icon together, while in our case, it's much better to
// show an icon instead of hide everything.
return Gio.ThemedIcon.new_with_default_fallbacks(name + '-symbolic-hack');
}
});