-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
extension.js
561 lines (466 loc) · 13.2 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
/*
GNOME Shell Extension Cast to TV
Developer: Rafostar
Extension GitHub: https://github.com/Rafostar/gnome-shell-extension-cast-to-tv
*/
const Main = imports.ui.main;
const AggregateMenu = Main.panel.statusArea.aggregateMenu;
const NetworkMenu = AggregateMenu._network;
const Local = imports.misc.extensionUtils.getCurrentExtension();
const Soup = Local.imports.soup;
const Widget = Local.imports.widget;
const Helper = Local.imports.helper;
const Settings = Helper.getSettings(Local.path);
const Temp = Local.imports.temp;
let castMenu;
let remoteMenu;
let config;
let signals;
let serviceSignal;
function refreshRemote(playbackData)
{
if(!remoteMenu)
return;
let isShown = (playbackData && playbackData.isPlaying);
remoteMenu.playlist.remoteActive = isShown;
if(!isShown)
{
if(remoteMenu.isActor)
remoteMenu.actor.hide();
else
remoteMenu.hide();
return stopAddonsStreams();
}
if(
!playbackData
|| !playbackData.selection
|| !playbackData.playlist
)
return;
let selection = playbackData.selection;
let playlist = playbackData.playlist;
/* Current track number in playlist */
let trackID = playlist.indexOf(selection.filePath) + 1;
/* List items are counted from 1 */
let listLastID = playlist.length;
/* Disable skip backward if playing first file from list */
if(trackID > 1) remoteMenu.skipBackwardButton.reactive = true;
else remoteMenu.skipBackwardButton.reactive = false;
/* Disable skip forward if playing last file from list */
if(trackID < listLastID) remoteMenu.skipForwardButton.reactive = true;
else remoteMenu.skipForwardButton.reactive = false;
/* Update track title */
if(selection.title)
remoteMenu.trackTitle.setText(selection.title);
else
{
let filename = selection.filePath.substring(
selection.filePath.lastIndexOf('/') + 1);
let title = (filename.includes('.')) ?
filename.split('.').slice(0, -1).join('.') : filename;
if(title) remoteMenu.trackTitle.setText(title);
else remoteMenu.trackTitle.setText("");
}
/* Update widget playlist */
remoteMenu.playlist.loadPlaylist(playlist, selection.filePath);
/* Choose remote to create */
switch(selection.streamType)
{
case 'VIDEO':
remoteMenu.setMode('DIRECT', 'folder-videos-symbolic');
break;
case 'MUSIC':
if(!config.musicVisualizer)
remoteMenu.setMode('DIRECT', 'folder-music-symbolic');
else
remoteMenu.setMode('ENCODE');
break;
case 'PICTURE':
remoteMenu.setMode('PICTURE');
break;
case 'LIVE':
remoteMenu.setMode('LIVE');
break;
default:
remoteMenu.setMode('ENCODE');
break;
}
/* Set slider icon */
if(remoteMenu.positionSlider.isVolume)
remoteMenu.positionSlider.setIcon(remoteMenu.positionSlider.volumeIcon);
else
remoteMenu.positionSlider.setIcon(remoteMenu.positionSlider.defaultIcon);
if(remoteMenu.isActor)
remoteMenu.actor.show();
else
remoteMenu.show();
}
function stopAddonsStreams()
{
if(!castMenu) return;
let menuItems = castMenu.castSubMenu.menu._getMenuItems();
menuItems.forEach(item =>
{
if(
item._onCastStop
&& typeof item._onCastStop === 'function'
)
item._onCastStop();
});
}
function setRemotePosition()
{
let itemIndex = 0;
let remotePosition = Settings.get_string('remote-position');
switch(remotePosition)
{
case 'left':
itemIndex = Main.panel._leftBox.get_children().length;
break;
case 'center-left':
remotePosition = 'center';
break;
case 'center-right':
itemIndex = Main.panel._centerBox.get_children().length;
remotePosition = 'center';
break;
default:
break;
}
/* Place remote on top bar */
Main.panel.addToStatusArea('cast-to-tv-remote', remoteMenu, itemIndex, remotePosition);
}
function updateTempConfig(schemaKey, valueType)
{
let confKey = schemaKey.split('-');
confKey = confKey[0] + confKey[1].charAt(0).toUpperCase() + confKey[1].slice(1);
let postData = {};
postData[confKey] = Settings['get_' + valueType](schemaKey);
switch(confKey)
{
case 'listeningPort':
/* Prevent setting node to same port as gnome */
if(Soup.server.usedPort == postData[confKey])
{
postData[confKey] = (Soup.client.nodePort < Soup.server.usedPort) ?
postData[confKey] + 1 : postData[confKey] - 1;
return Settings.set_int('listening-port', postData[confKey]);
}
config[confKey] = postData[confKey];
Soup.client.postConfig(postData, () => Soup.client.setNodePort(postData[confKey]));
break;
case 'internalPort':
/* Prevent setting gnome to same port as node */
if(Soup.client.nodePort == postData[confKey])
{
postData[confKey] = (Soup.client.nodePort > Soup.server.usedPort) ?
postData[confKey] + 1 : postData[confKey] - 1;
return Settings.set_int('internal-port', postData[confKey]);
}
Soup.server.setPort(postData[confKey], (usedPort) =>
{
if(!usedPort) return;
/* Save port you ended with to gsettings */
if(postData[confKey] != usedPort)
return Settings.set_int('internal-port', usedPort);
postData[confKey] = usedPort;
config[confKey] = usedPort;
Soup.client.postConfig(postData);
});
break;
case 'chromecastName':
case 'playercastName':
if(remoteMenu.opts.useFriendlyName)
{
updateDeviceName(
confKey.substring(0, confKey.length - 4),
postData[confKey]
);
}
Soup.client.postConfig(postData);
break;
case 'chromecastDevices':
case 'chromecastSubtitles':
try { postData[confKey] = JSON.parse(postData[confKey]); }
catch(err) { postData[confKey] = null; }
if(postData[confKey])
Soup.client.postConfig(postData);
break;
case 'musicVisualizer':
config[confKey] = postData[confKey];
Soup.client.postConfig(postData);
break;
default:
if(valueType === 'double')
postData[confKey] = postData[confKey].toFixed(1);
else if(confKey === 'ffmpegPath' && !postData[confKey])
postData[confKey] = '/usr/bin/ffmpeg';
else if(confKey === 'ffprobePath' && !postData[confKey])
postData[confKey] = '/usr/bin/ffprobe';
else if(confKey === 'receiverType')
updateReceiverName(postData[confKey]);
Soup.client.postConfig(postData);
break;
}
}
function updateDeviceName(receiverType, name)
{
if(receiverType !== 'other')
name = name || Settings.get_string(`${receiverType}-name`);
Widget.remoteNames[receiverType] = (name) ? name : null;
if(remoteMenu)
remoteMenu.refreshLabel();
}
function onBrowserData(browser)
{
if(!browser || !browser.name)
return;
updateDeviceName('other', browser.name);
}
function updateReceiverName(receiverType)
{
if(receiverType)
remoteMenu.opts.receiverType = receiverType;
else
receiverType = remoteMenu.opts.receiverType;
if(!remoteMenu.opts.useFriendlyName)
return remoteMenu.refreshLabel();
switch(receiverType)
{
case 'chromecast':
case 'playercast':
updateDeviceName(receiverType);
break;
case 'other':
Soup.client.getBrowser(data => onBrowserData(data));
break;
default:
break;
}
}
function changeSeekTime()
{
remoteMenu.opts.seekTime = Settings.get_int('seek-time');
}
function changeMediaButtonsSize()
{
remoteMenu.setMediaButtonsSize(Settings.get_int('media-buttons-size'));
}
function changeSlidersIconSize()
{
remoteMenu.setSlidersIconSize(Settings.get_int('slider-icon-size'));
}
function changeUnifiedSlider()
{
remoteMenu.setUnifiedSlider(Settings.get_boolean('unified-slider'));
}
function changeLabelVisibility()
{
let showLabel = Settings.get_boolean('remote-label');
if(showLabel)
{
remoteMenu.toplabel.show();
remoteMenu.barArrowIcon.show();
}
else
{
remoteMenu.toplabel.hide();
remoteMenu.barArrowIcon.hide();
}
}
function changeUseFriendlyName()
{
remoteMenu.opts.useFriendlyName = Settings.get_boolean('remote-label-fn');
updateReceiverName();
}
function createRemote()
{
/* Remove previous indicator */
if(remoteMenu) remoteMenu.destroy();
let opts = Temp.getRemoteOpts();
remoteMenu = new Widget.CastRemoteMenu(opts);
/* Add remote to top bar */
setRemotePosition();
/* Refresh label only once after create */
updateReceiverName();
/* Refresh initial status */
Soup.client.getPlaybackData(data => refreshRemote(data));
}
function changeServiceEnabled()
{
let enable = !castMenu.isServiceEnabled;
Settings.set_boolean('service-wanted', enable);
Soup.client.getIsServiceEnabled(data =>
{
/* When wanted state matches service state */
if(data && data.isEnabled === enable || !data && !enable)
return;
enableService(enable);
});
}
function enableService(enable)
{
if(enable)
Helper.startApp(Local.path, 'server-monitor', null, true);
else
Helper.closeOtherApps(Local.path, true);
}
function setIndicator(enable)
{
/* Compatibility with GNOME pre-3.36 */
let indicator = (NetworkMenu.hasOwnProperty('indicators')) ?
NetworkMenu.indicators : NetworkMenu;
let children = indicator.get_children();
if(children && children.length)
{
if(enable && !children.includes(Widget.statusIcon))
indicator.add_child(Widget.statusIcon);
else if(!enable && children.includes(Widget.statusIcon))
indicator.remove_child(Widget.statusIcon);
}
}
function onNodeWebsocket(err, msg)
{
if(!castMenu || !remoteMenu)
return;
if(err) return log('Cast to TV: ' + err.message);
let enable = (msg && msg === 'connected');
if(!enable)
refreshRemote(false);
castMenu.enableFullMenu(enable);
setIndicator(enable);
Soup.server.emitIsServiceEnabled(enable);
}
function onPlaybackStatus(data)
{
if(remoteMenu)
remoteMenu.updateRemote(data);
}
function init()
{
Helper.initTranslations(Local.path);
}
function enable()
{
/* Get config object */
if(!config) config = Temp.getConfig();
/* Create main menu */
castMenu = new Widget.CastMainMenu();
/* Prepare signals array */
signals = [];
let nodeSignals = {
string: [
'ffmpeg-path', 'ffprobe-path', 'receiver-type',
'video-acceleration', 'extractor-dir', 'playercast-name',
'chromecast-name', 'chromecast-devices', 'chromecast-subtitles',
'subs-preferred', 'subs-fallback'
],
int: [
'listening-port', 'internal-port', 'slideshow-time'
],
double: [
'webplayer-subs', 'video-bitrate'
],
boolean: [
'burn-subtitles', 'music-visualizer', 'extractor-reuse'
]
};
/* Connect signals */
for(let type in nodeSignals)
{
for(let setting of nodeSignals[type])
{
signals.push(Settings.connect(`changed::${setting}`,
updateTempConfig.bind(this, setting, type))
);
}
}
/* Connect remaining signals */
signals.push(Settings.connect('changed::remote-position', createRemote.bind(this)));
signals.push(Settings.connect('changed::unified-slider', changeUnifiedSlider.bind(this)));
signals.push(Settings.connect('changed::seek-time', changeSeekTime.bind(this)));
signals.push(Settings.connect('changed::media-buttons-size', changeMediaButtonsSize.bind(this)));
signals.push(Settings.connect('changed::slider-icon-size', changeSlidersIconSize.bind(this)));
signals.push(Settings.connect('changed::remote-label', changeLabelVisibility.bind(this)));
signals.push(Settings.connect('changed::remote-label-fn', changeUseFriendlyName.bind(this)));
/* Other signals */
serviceSignal = castMenu.serviceMenuItem.connect('activate', changeServiceEnabled.bind(this));
/* Create Soup client and server */
if(!Soup.client)
Soup.createClient(Settings.get_int('listening-port'));
if(!Soup.server)
{
let internalPort = Settings.get_int('internal-port');
Soup.createServer(internalPort, (usedPort) =>
{
if(!usedPort) return;
/* Handlers should be set only once, server port can still be changed */
Soup.server.addNodeHandler((err, msg) => onNodeWebsocket(err, msg));
Soup.server.onPlaybackData(data => refreshRemote(data));
Soup.server.onBrowserData(data => onBrowserData(data));
Soup.server.onPlaybackStatus(data => onPlaybackStatus(data));
Soup.server.createWebsockets();
if(internalPort != usedPort)
Settings.set_int('internal-port', usedPort);
});
}
/* Create remote widget */
createRemote();
/* Set insert position after network menu items */
let menuItems = AggregateMenu.menu._getMenuItems();
let menuPosition = menuItems.indexOf(AggregateMenu._network.menu) + 1;
/* Add menu item */
AggregateMenu.menu.addMenuItem(castMenu, menuPosition);
/* Check if service should start */
Soup.client.getIsServiceEnabled(data =>
{
let serviceWanted = Settings.get_boolean('service-wanted');
if(data && data.isEnabled)
{
/* Resume communication with node */
Soup.client.postIsLockScreen(false);
if(!serviceWanted)
enableService(false);
}
else if(serviceWanted)
enableService(true);
});
}
function disable()
{
/* Disconnect signals from settings */
signals.forEach(signal => Settings.disconnect(signal));
signals = null;
/* Disconnect other signals */
castMenu.serviceMenuItem.disconnect(serviceSignal);
serviceSignal = null;
let lockingScreen = (
Main.sessionMode.currentMode == 'unlock-dialog'
|| Main.sessionMode.currentMode == 'lock-screen'
);
if(lockingScreen)
{
/* Pause data communication with node client */
Soup.client.postIsLockScreen(true, () =>
{
Soup.server.disconnectWebsockets();
});
}
else
{
/* Close background service */
enableService(false);
config = null;
/* Close Soup client and server */
Soup.closeClient();
Soup.closeServer();
}
/* Remove top bar indicator */
setIndicator(false);
/* Remove Chromecast Remote */
remoteMenu.destroy();
remoteMenu = null;
/* Remove menu item object */
castMenu.destroy();
castMenu = null;
}