-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
285 lines (245 loc) · 8.16 KB
/
index.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
// Copyright (c) 2023 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
// This script is modified version of
// https://github.com/brave/brave-ios/blob/development/Client/Frontend/UserContent/UserScripts/Playlist.js
(async function (onMediaDetected) {
// This will be replaced by native code on demand.
const siteSpecificDetector = null
/**
* Returns a Promise that resolves with a boolean argument indicating whether
* the `src` URL could be a blob pointing at a MediaSource object.
* @param {string} src
* @returns {Promise}
*/
async function isMediaSourceObjectURL (src) {
if (!src || !src.startsWith('blob:')) {
return false
}
const controller = new AbortController()
const signal = controller.signal
const maybeAbortFetch = new Promise(resolve =>
setTimeout(() => {
resolve(false)
controller.abort()
}, 500)
)
return Promise.any([
fetch(src, { signal }).then(() => false).catch(() => true),
maybeAbortFetch
])
}
/**
* Returns whether given `url` has https protocol.
* @param {string} url
* @returns {boolean}
*/
function isHttpsScheme (url) {
if (!url || typeof url !== 'string') {
return false
}
if (url.startsWith('blob:')) {
url = url.substring(5)
// blob: should be absolute path.
return url.startsWith('https://')
}
let isHttpsScheme = false
try {
// In case of http: or data: protocol, the base URL is not used
isHttpsScheme = new URL(url, window.location).protocol === 'https:'
} catch (e) {
// Ignore
}
return isHttpsScheme
}
/**
* Returns absolute path of given `url`. Note that returns null if it's not
* url nor https scheme.
* @param {string} url
* @returns {?string}
*/
function fixUpUrl (url) {
if (!isHttpsScheme(url)) {
return null
}
if (!url.startsWith('https://')) {
// Fix up relative path to absolute path
url = new URL(url, window.location).href
}
return url
}
/**
* MediaItem will be parsed into C++ object representing PlaylistItem
* @typedef MediaItem
* @type {object}
* @property {string} name
* @property {"video" | "audio"} mimeType
* @property {string} pageSrc - page url
* @property {string} pageTitle - page title
* @property {string} src - media url
* @property {?string} thumbnail - thumbnail url
* @property {boolean} detected
*/
/**
* Get all media items(video or audio) from the given HTMLMediaElement `node`.
* @param {HTMLMediaElement} node
* @returns {MediaItem[]}
*/
async function getNodeData (node) {
const src = fixUpUrl(node.src)
const srcIsMediaSourceObjectURL = await isMediaSourceObjectURL(src)
let mimeType = node.type
if (mimeType == null || typeof mimeType === 'undefined' || mimeType === '') {
if (node.constructor.name === 'HTMLVideoElement') {
mimeType = 'video'
}
if (node.constructor.name === 'HTMLAudioElement') {
mimeType = 'audio'
}
if (node.constructor.name === 'HTMLSourceElement') {
if (node.closest('video')) {
mimeType = 'video'
} else {
mimeType = 'audio'
}
}
}
const result = {
name: getMediaTitle(node),
src,
srcIsMediaSourceObjectURL,
pageSrc: window.location.href,
pageTitle: document.title,
mimeType,
duration: getMediaDurationInSeconds(node),
detected: true
}
if (src) {
return [result]
}
const target = node
const sources = []
for (const node of document.querySelectorAll('source')) {
const source = { ...result }
source.src = fixUpUrl(node.src)
source.srcIsMediaSourceObjectURL = await isMediaSourceObjectURL(source.src)
if (source.src) {
if (node.closest('video') === target) {
sources.push(source)
}
if (node.closest('audio') === target) {
sources.push(source)
}
}
}
return sources
}
/**
* Returns thumbnail url from this page.
* @returns {?string}
*/
function getThumbnail () {
const isThumbnailValid = (thumbnail) => { return thumbnail && thumbnail !== '' }
let thumbnail = document.querySelector('meta[property="og:image"]')?.content
if (!isThumbnailValid(thumbnail) && typeof siteSpecificDetector?.getThumbnail === 'function') {
thumbnail = siteSpecificDetector.getThumbnail()
}
return fixUpUrl(thumbnail)
}
/**
* Returns title of media `node`
* @param {HTMLMediaElement} node
* @returns {?string}
*/
function getMediaTitle (node) {
const isTitleValid = (title) => { return title && title !== '' }
let title = node.title
if (!isTitleValid(title) && typeof siteSpecificDetector?.getMediaTitle === 'function') {
title = siteSpecificDetector.getMediaTitle(node)
}
if (!isTitleValid(title)) { title = document.title }
return title
}
/**
* Returns the author of given media `node`
* @param {HTMLMediaElement} node
* @returns {?string}
*/
function getMediaAuthor (node) {
// TODO(sko) Get metadata of author in more general way
let author = null
if (typeof siteSpecificDetector?.getMediaAuthor === 'function') {
author = siteSpecificDetector.getMediaAuthor(node)
}
return author
}
/**
* Returns duration of given media `node` in seconds
* @param {HTMLMediaElement} node
* @returns {number}
*/
function getMediaDurationInSeconds (node) {
const clampDuration = (value) => {
if (Number.isFinite(value) && value >= 0) return value
if (value === Number.POSITIVE_INFINITY) return Number.MAX_VALUE
return 0.0
}
let duration = node.duration
if (!duration && typeof siteSpecificDetector?.getMediaDurationInSeconds === 'function') { duration = siteSpecificDetector.getMediaDurationInSeconds(node) }
return clampDuration(duration)
}
async function detectMedia () {
const videoElements = document.querySelectorAll('video')
const audioElements = document.querySelectorAll('audio')
// TODO(sko) These data could be incorrect when there're multiple items.
// For now we're assuming that the first media is a representative one.
const thumbnail = getThumbnail()
const author = getMediaAuthor()
let medias = []
for (const e of [...videoElements, ...audioElements]) {
const media = await getNodeData(e)
medias = medias.concat(media)
}
if (medias.length) {
medias[0].thumbnail = thumbnail
medias[0].author = author
}
onMediaDetected(medias)
}
// Firstly, we try to get find all <video> or <audio> tags periodically,
// for a a while from the start up. If we find them, then we attach
// MutationObservers to them to detect source URL.
// After a given amount of time, we do this in requestIdleCallback().
// Note that there's a global object named |pl_worker|. This worker is
// created and bound by PlaylistJSHandler.
const mutationSources = new Set()
const mutationObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
detectMedia()
})
})
const findNewMediaAndObserveMutation = () => {
return document.querySelectorAll('video, audio').forEach((mediaNode) => {
if (mutationSources.has(mediaNode)) return
mutationSources.add(mediaNode)
detectMedia()
mutationObserver.observe(mediaNode, { attributeFilter: ['src'] })
})
}
const pollingIntervalId = window.setInterval(
findNewMediaAndObserveMutation,
1000
)
window.setTimeout(() => {
window.clearInterval(pollingIntervalId)
window.requestIdleCallback(findNewMediaAndObserveMutation)
// TODO(sko) We might want to check if idle callback is waiting too
// long. In that case, we should get back to the polling style. And
// also, this time could be too long for production.
}, 20000)
// Try getting media after page was restored or navigated back.
window.addEventListener('pageshow', () => {
detectMedia()
})
})