Repository navigation
Expand file tree
/
Copy pathplugin-loader.js
More file actions
264 lines (239 loc) · 10.7 KB
/
Copy pathplugin-loader.js
File metadata and controls
264 lines (239 loc) · 10.7 KB
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
/*
* plugin-loader.js — custom addition to the Jellyfin Tizen app.
*
* Jellyfin web plugins (Jellyfin Enhanced, Media Bar, All Users Recently Watched, ...)
* are injected by the server's File Transformation plugin into the index.html it serves.
* This app ships its own copy of jellyfin-web, so those injections never reach it.
*
* After sign-in, this loader fetches <server>/web/index.html, finds the tags the server
* added (the ones pointing at "../<Plugin>/..."), and loads them from the server.
* Scripts that assume they run on the server's own origin get two narrow patches:
* - window.location.origin -> the server address
* - includes/endsWith("/web/...") -> "/www/..." (this app's page path)
*
* To skip a plugin on this TV, set localStorage "pluginLoaderDisabled" to a comma
* list of path fragments, e.g. "MediaBar,JellyfinEnhanced".
*/
(function () {
'use strict';
var TAG = '[plugin-loader]';
var POLL_MS = 1000;
function log() {
try { console.log.apply(console, [TAG].concat([].slice.call(arguments))); } catch (e) { /* ignore */ }
}
function signedIn() {
var c = window.ApiClient;
return c && typeof c.serverAddress === 'function' && c.serverAddress()
&& typeof c.accessToken === 'function' && c.accessToken();
}
function waitForSignIn() {
return new Promise(function (resolve) {
(function poll() {
if (signedIn()) resolve(window.ApiClient);
else setTimeout(poll, POLL_MS);
})();
});
}
function absolute(base, url) {
return base + '/' + url.replace(/^(\.\.\/)+/, '').replace(/^\/+/, '');
}
function needsPatch(text) {
return /window\.location\.origin/.test(text)
|| /(includes|endsWith|startsWith)\((["'`])\/web\//.test(text);
}
function patch(text, base) {
return text
.replace(/window\.location\.origin/g, JSON.stringify(base))
.replace(/(includes|endsWith|startsWith)\((["'`])\/web\//g, '$1($2/www/');
}
function disabledList() {
try {
return (localStorage.getItem('pluginLoaderDisabled') || '')
.toLowerCase().split(',')
.map(function (s) { return s.trim(); })
.filter(Boolean);
} catch (e) {
return [];
}
}
function copyAttributes(from, to) {
for (var i = 0; i < from.attributes.length; i++) {
var a = from.attributes[i];
if (a.name === 'src' || a.name === 'defer' || a.name === 'async') continue;
to.setAttribute(a.name, a.value);
}
}
function loadScriptSrc(el) {
return new Promise(function (resolve) {
el.onload = resolve;
el.onerror = function () { log('failed to load', el.src); resolve(); };
document.head.appendChild(el);
});
}
function loadInjected(base) {
return fetch(base + '/web/index.html', { cache: 'no-store' })
.then(function (r) { return r.text(); })
.then(function (html) {
var doc = new DOMParser().parseFromString(html, 'text/html');
var skip = disabledList();
var nodes = [].slice.call(doc.querySelectorAll('script[src], link[rel="stylesheet"][href]'));
// Only tags the server injected: they point one level up ("../Plugin/...").
// The stock web client's own files are same-directory and already bundled here.
nodes = nodes.filter(function (n) {
var u = n.getAttribute('src') || n.getAttribute('href') || '';
if (!/^\.\.\//.test(u)) return false;
var lower = u.toLowerCase();
if (skip.some(function (s) { return lower.indexOf(s) !== -1; })) {
log('skipped (disabled):', u);
return false;
}
return true;
});
log('found', nodes.length, 'server-injected tag(s)');
return nodes.reduce(function (chain, n) {
return chain.then(function () {
if (n.tagName === 'LINK') {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = absolute(base, n.getAttribute('href'));
document.head.appendChild(link);
log('css', link.href);
return;
}
var url = absolute(base, n.getAttribute('src'));
return fetch(url, { cache: 'no-store' })
.then(function (r) { return r.text(); })
.then(function (text) {
var el = document.createElement('script');
copyAttributes(n, el);
if (needsPatch(text)) {
el.textContent = patch(text, base) + '\n//# sourceURL=' + url;
document.head.appendChild(el);
log('js (patched)', url);
return;
}
el.src = url;
log('js', url);
return loadScriptSrc(el);
});
}).catch(function (e) {
log('error loading', n.outerHTML, e && e.message);
});
}, Promise.resolve());
});
}
/*
* Server chunks. Some plugins (Home Screen Sections) don't inject tags: File
* Transformation rewrites the web client's own lazy-loaded chunks instead. When the
* server runs the same jellyfin-web build as this app, chunk loads are redirected to
* the server's (transformed) copies, using the server's chunk names. If a server
* chunk fails to load, the bundled one is used.
*/
var CHUNK_KEY = 'pluginLoaderChunks';
var MAX_CHUNK_DIFFS = 20; // more than this means a different jellyfin-web build
var chunkMap = null; // bundled chunk file -> server chunk URL
function parseChunkMaps(text) {
var m = /\(\{([^{}]*)\}\[e\]\|\|e\)\+"\."\+\{([^{}]*)\}\[e\]\+"\.chunk\.js"/.exec(text || '');
if (!m) return null;
function obj(s) {
var o = {}, r = /(\d+):"([^"]*)"/g, x;
while ((x = r.exec(s))) o[x[1]] = x[2];
return o;
}
return { names: obj(m[1]), hashes: obj(m[2]) };
}
function chunkFile(maps, id) {
return (maps.names[id] || id) + '.' + maps.hashes[id] + '.chunk.js';
}
function localRuntime() {
try {
var x = new XMLHttpRequest();
x.open('GET', 'runtime.bundle.js', false);
x.send();
return parseChunkMaps(x.responseText);
} catch (e) {
return null;
}
}
function buildChunkMap(local, server, base) {
var ids = Object.keys(local.hashes), diffs = 0, map = {};
ids.forEach(function (id) {
if (server.hashes[id] !== local.hashes[id]) diffs++;
if (server.hashes[id]) map[chunkFile(local, id)] = base + '/web/' + chunkFile(server, id);
});
if (diffs > MAX_CHUNK_DIFFS) {
log('server web client is a different build (' + diffs + ' chunks differ); using bundled chunks');
return null;
}
log('loading web client chunks from the server (' + diffs + ' renamed by the server)');
return map;
}
function savedServer() {
try {
var creds = JSON.parse(localStorage.getItem('jellyfin_credentials') || '{}');
var s = (creds.Servers || [])[0] || {};
var a = s.ManualAddress || s.RemoteAddress || s.LocalAddress;
return a ? a.replace(/\/+$/, '') : null;
} catch (e) {
return null;
}
}
function refreshChunkMap(local, base) {
return fetch(base + '/web/runtime.bundle.js', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.text() : ''; })
.then(function (text) {
var server = parseChunkMaps(text);
if (!server) return;
try { localStorage.setItem(CHUNK_KEY, JSON.stringify({ base: base, server: server })); } catch (e) { /* ignore */ }
chunkMap = buildChunkMap(local, server, base);
})
.catch(function (e) { log('chunk map refresh failed:', e && e.message); });
}
function hookChunkLoads() {
var append = Node.prototype.appendChild;
Node.prototype.appendChild = function (node) {
var src = node && node.tagName === 'SCRIPT' && !node._pluginLoaderLocal && node.getAttribute('src');
var url = src && chunkMap && chunkMap[src];
if (url) {
var onload = node.onload, onerror = node.onerror;
node.onerror = function () {
log('server chunk failed, using bundled:', src);
var local = document.createElement('script');
local._pluginLoaderLocal = true;
local.charset = 'utf-8';
local.src = src;
local.onload = onload;
local.onerror = onerror;
append.call(document.head, local);
};
node.src = url;
}
return append.call(this, node);
};
}
if (disabledList().indexOf('chunks') === -1) {
var local = localRuntime();
if (local) {
hookChunkLoads();
try {
var saved = JSON.parse(localStorage.getItem(CHUNK_KEY) || 'null');
if (saved && saved.base === savedServer()) chunkMap = buildChunkMap(local, saved.server, saved.base);
} catch (e) { /* ignore */ }
var start = savedServer();
if (start) refreshChunkMap(local, start);
waitForSignIn().then(function (api) {
var base = api.serverAddress().replace(/\/+$/, '');
if (base !== start) refreshChunkMap(local, base);
});
} else {
log('could not read the bundled chunk list; using bundled chunks');
}
}
waitForSignIn()
.then(function (api) {
var base = api.serverAddress().replace(/\/+$/, '');
log('signed in to', base);
return loadInjected(base);
})
.catch(function (e) { log('loader failed:', e && e.message); });
})();