-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
executable file
·129 lines (106 loc) · 2.44 KB
/
main.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
'use strict';
/**
* Dependencies
*/
const MagnetScanner = require('./lib/magnet-scanner');
const advertise = require('./lib/advertiser');
const debug = require('debug')('magnet:App');
const electron = require('electron');
const {
Menu,
MenuItem,
shell,
Tray,
app
} = electron;
function App() {
this.tray = this.createTray();
this.items = {};
app.dock.hide();
this.scanner = new MagnetScanner(this.onItemFound.bind(this))
.on('found', this.onItemFound.bind(this))
.on('lost', this.onItemLost.bind(this))
.start()
this.render();
}
App.prototype = {
createTray() {
const tray = new Tray(`${__dirname}/IconTemplate.png`);
tray.on('drop-text', this.onDropText.bind(this));
tray.setToolTip('Magnet');
return tray;
},
render() {
var menu = new Menu();
var size = Object.keys(this.items).length;
// render all items
for (var key in this.items) {
let item = this.items[key];
menu.append(new MenuItem({
label: item.url,
click: () => shell.openExternal(item.url)
}))
}
if (!size) {
menu.append(new MenuItem({
label: 'Nothing found',
enabled: false
}));
}
if (this.ad) {
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({
label: truncate(this.ad.url, 32),
enabled: false
}));
menu.append(new MenuItem({
label: 'Stop broadcasting',
click: this.stopAdvertising.bind(this)
}));
}
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({
label: 'Quit',
click: app.quit.bind(app)
}));
this.tray.setContextMenu(menu);
},
onItemFound(item) {
debug('item found', item);
if (this.items[item.url]) return;
this.items[item.url] = item;
this.render();
},
onItemLost(item) {
debug('item lost', item);
delete this.items[item.url];
this.render();
},
onDropText(e, text) {
this.advertise(text);
},
advertise(url) {
if (!isUrl(url)) return;
this.ad = advertise(url);
this.render();
},
stopAdvertising() {
this.ad.stop();
delete this.ad;
this.render();
}
}
app.on('ready', () => {
try { new App(); }
catch (e) { console.error(e); }
});
/**
* Utils
*/
function isUrl(string) {
return /^https?\:\/\//.test(string);
}
function truncate(string, max) {
if (string.length < max) return string;
return string.slice(0, max) + '\u2026';
}