forked from jellyfin/jellyfin-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dashboard.js
250 lines (209 loc) · 7.16 KB
/
dashboard.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
import ServerConnections from '../components/ServerConnections';
import toast from '../components/toast/toast';
import loading from '../components/loading/loading';
import { appRouter } from '../components/router/appRouter';
import baseAlert from '../components/alert';
import baseConfirm from '../components/confirm/confirm';
import globalize from '../scripts/globalize';
import * as webSettings from '../scripts/settings/webSettings';
import datetime from '../scripts/datetime';
import { setBackdropTransparency } from '../components/backdrop/backdrop';
import DirectoryBrowser from '../components/directorybrowser/directorybrowser';
import dialogHelper from '../components/dialogHelper/dialogHelper';
import itemIdentifier from '../components/itemidentifier/itemidentifier';
import { getLocationSearch } from './url.ts';
export function getCurrentUser() {
return window.ApiClient.getCurrentUser(false);
}
// TODO: investigate url prefix support for serverAddress function
export async function serverAddress() {
const apiClient = window.ApiClient ?? ServerConnections.currentApiClient();
if (apiClient) {
return Promise.resolve(apiClient.serverAddress());
}
// Use servers specified in config.json
const urls = await webSettings.getServers();
if (urls.length === 0) {
// Otherwise use computed base URL
let url;
const index = window.location.href.toLowerCase().lastIndexOf('/web');
if (index != -1) {
url = window.location.href.substring(0, index);
} else {
// fallback to location without path
url = window.location.origin;
}
// Don't use bundled app URL (file:) as server URL
if (url.startsWith('file:')) {
return Promise.resolve();
}
urls.push(url);
}
console.debug('URL candidates:', urls);
const promises = urls.map(url => {
return fetch(`${url}/System/Info/Public`)
.then(async resp => {
if (!resp.ok) {
return;
}
return {
url,
config: await resp.json()
};
}).catch(error => {
console.error(error);
});
});
return Promise.all(promises).then(responses => {
return responses.filter(obj => obj?.config);
}).then(configs => {
const selection = configs.find(obj => !obj.config.StartupWizardCompleted) || configs[0];
return selection?.url;
}).catch(error => {
console.error(error);
});
}
export function getCurrentUserId() {
const apiClient = window.ApiClient;
if (apiClient) {
return apiClient.getCurrentUserId();
}
return null;
}
export function onServerChanged(_userId, _accessToken, apiClient) {
ServerConnections.setLocalApiClient(apiClient);
}
export function logout() {
ServerConnections.logout().then(function () {
webSettings.getMultiServer().then(multi => {
multi ? navigate('selectserver.html') : navigate('login.html');
});
});
}
export function getPluginUrl(name) {
return 'configurationpage?name=' + encodeURIComponent(name);
}
export function getConfigurationResourceUrl(name) {
return ApiClient.getUrl('web/ConfigurationPage', {
name: name
});
}
/**
* Navigate to a url.
* @param {string} url - The url to navigate to.
* @param {boolean} [preserveQueryString] - A flag to indicate the current query string should be appended to the new url.
* @returns {Promise<any>}
*/
export function navigate(url, preserveQueryString) {
if (!url) {
throw new Error('url cannot be null or empty');
}
const queryString = getLocationSearch();
if (preserveQueryString && queryString) {
url += queryString;
}
return appRouter.show(url);
}
export function processPluginConfigurationUpdateResult() {
loading.hide();
toast(globalize.translate('SettingsSaved'));
}
export function processServerConfigurationUpdateResult() {
loading.hide();
toast(globalize.translate('SettingsSaved'));
}
export function processErrorResponse(response) {
loading.hide();
let status = '' + response.status;
if (response.statusText) {
status = response.statusText;
}
baseAlert({
title: status,
text: response.headers ? response.headers.get('X-Application-Error-Code') : null
});
}
export function alert(options) {
if (typeof options == 'string') {
toast({
text: options
});
} else {
baseAlert({
title: options.title || globalize.translate('HeaderAlert'),
text: options.message
}).then(options.callback || function () { /* no-op */ });
}
}
export function capabilities(appHost) {
return Object.assign({
PlayableMediaTypes: ['Audio', 'Video'],
SupportedCommands: ['MoveUp', 'MoveDown', 'MoveLeft', 'MoveRight', 'PageUp', 'PageDown', 'PreviousLetter', 'NextLetter', 'ToggleOsd', 'ToggleContextMenu', 'Select', 'Back', 'SendKey', 'SendString', 'GoHome', 'GoToSettings', 'VolumeUp', 'VolumeDown', 'Mute', 'Unmute', 'ToggleMute', 'SetVolume', 'SetAudioStreamIndex', 'SetSubtitleStreamIndex', 'DisplayContent', 'GoToSearch', 'DisplayMessage', 'SetRepeatMode', 'SetShuffleQueue', 'ChannelUp', 'ChannelDown', 'PlayMediaSource', 'PlayTrailers'],
SupportsPersistentIdentifier: window.appMode === 'cordova' || window.appMode === 'android',
SupportsMediaControl: true
}, appHost.getPushTokenInfo());
}
export function selectServer() {
if (window.NativeShell && typeof window.NativeShell.selectServer === 'function') {
window.NativeShell.selectServer();
} else {
navigate('selectserver.html');
}
}
export function hideLoadingMsg() {
loading.hide();
}
export function showLoadingMsg() {
loading.show();
}
export function confirm(message, title, callback) {
baseConfirm(message, title).then(function() {
callback(true);
}).catch(function() {
callback(false);
});
}
export const pageClassOn = function(eventName, className, fn) {
document.addEventListener(eventName, function (event) {
const target = event.target;
if (target.classList.contains(className)) {
fn.call(target, event);
}
});
};
export const pageIdOn = function(eventName, id, fn) {
document.addEventListener(eventName, function (event) {
const target = event.target;
if (target.id === id) {
fn.call(target, event);
}
});
};
const Dashboard = {
alert,
capabilities,
confirm,
getPluginUrl,
getConfigurationResourceUrl,
getCurrentUser,
getCurrentUserId,
hideLoadingMsg,
logout,
navigate,
onServerChanged,
processErrorResponse,
processPluginConfigurationUpdateResult,
processServerConfigurationUpdateResult,
selectServer,
serverAddress,
showLoadingMsg,
datetime,
DirectoryBrowser,
dialogHelper,
itemIdentifier,
setBackdropTransparency
};
// This is used in plugins and templates, so keep it defined for now.
// TODO: Remove once plugins don't need it
window.Dashboard = Dashboard;
export default Dashboard;