]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tests/shared/streaming-playlists.ts
Increase timeouts
[github/Chocobozzz/PeerTube.git] / server / tests / shared / streaming-playlists.ts
1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
2
3 import { expect } from 'chai'
4 import { basename, dirname, join } from 'path'
5 import { removeFragmentedMP4Ext, uuidRegex } from '@shared/core-utils'
6 import { sha256 } from '@shared/extra-utils'
7 import { HttpStatusCode, VideoPrivacy, VideoResolution, VideoStreamingPlaylist, VideoStreamingPlaylistType } from '@shared/models'
8 import { makeRawRequest, PeerTubeServer } from '@shared/server-commands'
9 import { expectStartWith } from './checks'
10 import { hlsInfohashExist } from './tracker'
11 import { checkWebTorrentWorks } from './webtorrent'
12
13 async function checkSegmentHash (options: {
14 server: PeerTubeServer
15 baseUrlPlaylist: string
16 baseUrlSegment: string
17 resolution: number
18 hlsPlaylist: VideoStreamingPlaylist
19 token?: string
20 }) {
21 const { server, baseUrlPlaylist, baseUrlSegment, resolution, hlsPlaylist, token } = options
22 const command = server.streamingPlaylists
23
24 const file = hlsPlaylist.files.find(f => f.resolution.id === resolution)
25 const videoName = basename(file.fileUrl)
26
27 const playlist = await command.get({ url: `${baseUrlPlaylist}/${removeFragmentedMP4Ext(videoName)}.m3u8`, token })
28
29 const matches = /#EXT-X-BYTERANGE:(\d+)@(\d+)/.exec(playlist)
30
31 const length = parseInt(matches[1], 10)
32 const offset = parseInt(matches[2], 10)
33 const range = `${offset}-${offset + length - 1}`
34
35 const segmentBody = await command.getFragmentedSegment({
36 url: `${baseUrlSegment}/${videoName}`,
37 expectedStatus: HttpStatusCode.PARTIAL_CONTENT_206,
38 range: `bytes=${range}`,
39 token
40 })
41
42 const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url, token })
43 expect(sha256(segmentBody)).to.equal(shaBody[videoName][range], `Invalid sha256 result for ${videoName} range ${range}`)
44 }
45
46 // ---------------------------------------------------------------------------
47
48 async function checkLiveSegmentHash (options: {
49 server: PeerTubeServer
50 baseUrlSegment: string
51 videoUUID: string
52 segmentName: string
53 hlsPlaylist: VideoStreamingPlaylist
54 }) {
55 const { server, baseUrlSegment, videoUUID, segmentName, hlsPlaylist } = options
56 const command = server.streamingPlaylists
57
58 const segmentBody = await command.getFragmentedSegment({ url: `${baseUrlSegment}/${videoUUID}/${segmentName}` })
59 const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url })
60
61 expect(sha256(segmentBody)).to.equal(shaBody[segmentName])
62 }
63
64 // ---------------------------------------------------------------------------
65
66 async function checkResolutionsInMasterPlaylist (options: {
67 server: PeerTubeServer
68 playlistUrl: string
69 resolutions: number[]
70 token?: string
71 transcoded?: boolean // default true
72 withRetry?: boolean // default false
73 }) {
74 const { server, playlistUrl, resolutions, token, withRetry = false, transcoded = true } = options
75
76 const masterPlaylist = await server.streamingPlaylists.get({ url: playlistUrl, token, withRetry })
77
78 for (const resolution of resolutions) {
79 const base = '#EXT-X-STREAM-INF:BANDWIDTH=\\d+,RESOLUTION=\\d+x' + resolution
80
81 if (resolution === VideoResolution.H_NOVIDEO) {
82 expect(masterPlaylist).to.match(new RegExp(`${base},CODECS="mp4a.40.2"`))
83 } else if (transcoded) {
84 expect(masterPlaylist).to.match(new RegExp(`${base},(FRAME-RATE=\\d+,)?CODECS="avc1.64001f,mp4a.40.2"`))
85 } else {
86 expect(masterPlaylist).to.match(new RegExp(`${base}`))
87 }
88 }
89
90 const playlistsLength = masterPlaylist.split('\n').filter(line => line.startsWith('#EXT-X-STREAM-INF:BANDWIDTH='))
91 expect(playlistsLength).to.have.lengthOf(resolutions.length)
92 }
93
94 async function completeCheckHlsPlaylist (options: {
95 servers: PeerTubeServer[]
96 videoUUID: string
97 hlsOnly: boolean
98
99 resolutions?: number[]
100 objectStorageBaseUrl?: string
101 }) {
102 const { videoUUID, hlsOnly, objectStorageBaseUrl } = options
103
104 const resolutions = options.resolutions ?? [ 240, 360, 480, 720 ]
105
106 for (const server of options.servers) {
107 const videoDetails = await server.videos.getWithToken({ id: videoUUID })
108 const requiresAuth = videoDetails.privacy.id === VideoPrivacy.PRIVATE || videoDetails.privacy.id === VideoPrivacy.INTERNAL
109
110 const privatePath = requiresAuth
111 ? 'private/'
112 : ''
113 const token = requiresAuth
114 ? server.accessToken
115 : undefined
116
117 const baseUrl = `http://${videoDetails.account.host}`
118
119 expect(videoDetails.streamingPlaylists).to.have.lengthOf(1)
120
121 const hlsPlaylist = videoDetails.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
122 expect(hlsPlaylist).to.not.be.undefined
123
124 const hlsFiles = hlsPlaylist.files
125 expect(hlsFiles).to.have.lengthOf(resolutions.length)
126
127 if (hlsOnly) expect(videoDetails.files).to.have.lengthOf(0)
128 else expect(videoDetails.files).to.have.lengthOf(resolutions.length)
129
130 // Check JSON files
131 for (const resolution of resolutions) {
132 const file = hlsFiles.find(f => f.resolution.id === resolution)
133 expect(file).to.not.be.undefined
134
135 if (file.resolution.id === VideoResolution.H_NOVIDEO) {
136 expect(file.resolution.label).to.equal('Audio')
137 } else {
138 expect(file.resolution.label).to.equal(resolution + 'p')
139 }
140
141 expect(file.magnetUri).to.have.lengthOf.above(2)
142 await checkWebTorrentWorks(file.magnetUri)
143
144 {
145 const nameReg = `${uuidRegex}-${file.resolution.id}`
146
147 expect(file.torrentUrl).to.match(new RegExp(`${server.url}/lazy-static/torrents/${nameReg}-hls.torrent`))
148
149 if (objectStorageBaseUrl && requiresAuth) {
150 // eslint-disable-next-line max-len
151 expect(file.fileUrl).to.match(new RegExp(`${server.url}/object-storage-proxy/streaming-playlists/hls/${privatePath}${videoDetails.uuid}/${nameReg}-fragmented.mp4`))
152 } else if (objectStorageBaseUrl) {
153 expectStartWith(file.fileUrl, objectStorageBaseUrl)
154 } else {
155 expect(file.fileUrl).to.match(
156 new RegExp(`${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoDetails.uuid}/${nameReg}-fragmented.mp4`)
157 )
158 }
159 }
160
161 {
162 await Promise.all([
163 makeRawRequest({ url: file.torrentUrl, token, expectedStatus: HttpStatusCode.OK_200 }),
164 makeRawRequest({ url: file.torrentDownloadUrl, token, expectedStatus: HttpStatusCode.OK_200 }),
165 makeRawRequest({ url: file.metadataUrl, token, expectedStatus: HttpStatusCode.OK_200 }),
166 makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 }),
167
168 makeRawRequest({
169 url: file.fileDownloadUrl,
170 token,
171 expectedStatus: objectStorageBaseUrl
172 ? HttpStatusCode.FOUND_302
173 : HttpStatusCode.OK_200
174 })
175 ])
176 }
177 }
178
179 // Check master playlist
180 {
181 await checkResolutionsInMasterPlaylist({ server, token, playlistUrl: hlsPlaylist.playlistUrl, resolutions })
182
183 const masterPlaylist = await server.streamingPlaylists.get({ url: hlsPlaylist.playlistUrl, token })
184
185 let i = 0
186 for (const resolution of resolutions) {
187 expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
188 expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
189
190 const url = 'http://' + videoDetails.account.host
191 await hlsInfohashExist(url, hlsPlaylist.playlistUrl, i)
192
193 i++
194 }
195 }
196
197 // Check resolution playlists
198 {
199 for (const resolution of resolutions) {
200 const file = hlsFiles.find(f => f.resolution.id === resolution)
201 const playlistName = removeFragmentedMP4Ext(basename(file.fileUrl)) + '.m3u8'
202
203 let url: string
204 if (objectStorageBaseUrl && requiresAuth) {
205 url = `${baseUrl}/object-storage-proxy/streaming-playlists/hls/${privatePath}${videoUUID}/${playlistName}`
206 } else if (objectStorageBaseUrl) {
207 url = `${objectStorageBaseUrl}hls/${videoUUID}/${playlistName}`
208 } else {
209 url = `${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoUUID}/${playlistName}`
210 }
211
212 const subPlaylist = await server.streamingPlaylists.get({ url, token })
213
214 expect(subPlaylist).to.match(new RegExp(`${uuidRegex}-${resolution}-fragmented.mp4`))
215 expect(subPlaylist).to.contain(basename(file.fileUrl))
216 }
217 }
218
219 {
220 let baseUrlAndPath: string
221 if (objectStorageBaseUrl && requiresAuth) {
222 baseUrlAndPath = `${baseUrl}/object-storage-proxy/streaming-playlists/hls/${privatePath}${videoUUID}`
223 } else if (objectStorageBaseUrl) {
224 baseUrlAndPath = `${objectStorageBaseUrl}hls/${videoUUID}`
225 } else {
226 baseUrlAndPath = `${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoUUID}`
227 }
228
229 for (const resolution of resolutions) {
230 await checkSegmentHash({
231 server,
232 token,
233 baseUrlPlaylist: baseUrlAndPath,
234 baseUrlSegment: baseUrlAndPath,
235 resolution,
236 hlsPlaylist
237 })
238 }
239 }
240 }
241 }
242
243 async function checkVideoFileTokenReinjection (options: {
244 server: PeerTubeServer
245 videoUUID: string
246 videoFileToken: string
247 resolutions: number[]
248 isLive: boolean
249 }) {
250 const { server, resolutions, videoFileToken, videoUUID, isLive } = options
251
252 const video = await server.videos.getWithToken({ id: videoUUID })
253 const hls = video.streamingPlaylists[0]
254
255 const query = { videoFileToken, reinjectVideoFileToken: 'true' }
256 const { text } = await makeRawRequest({ url: hls.playlistUrl, query, expectedStatus: HttpStatusCode.OK_200 })
257
258 for (let i = 0; i < resolutions.length; i++) {
259 const resolution = resolutions[i]
260
261 const suffix = isLive
262 ? i
263 : `-${resolution}`
264
265 expect(text).to.contain(`${suffix}.m3u8?videoFileToken=${videoFileToken}&reinjectVideoFileToken=true`)
266 }
267
268 const resolutionPlaylists = extractResolutionPlaylistUrls(hls.playlistUrl, text)
269 expect(resolutionPlaylists).to.have.lengthOf(resolutions.length)
270
271 for (const url of resolutionPlaylists) {
272 const { text } = await makeRawRequest({ url, query, expectedStatus: HttpStatusCode.OK_200 })
273
274 const extension = isLive
275 ? '.ts'
276 : '.mp4'
277
278 expect(text).to.contain(`${extension}?videoFileToken=${videoFileToken}`)
279 expect(text).not.to.contain(`reinjectVideoFileToken=true`)
280 }
281 }
282
283 function extractResolutionPlaylistUrls (masterPath: string, masterContent: string) {
284 return masterContent.match(/^([^.]+\.m3u8.*)/mg)
285 .map(filename => join(dirname(masterPath), filename))
286 }
287
288 export {
289 checkSegmentHash,
290 checkLiveSegmentHash,
291 checkResolutionsInMasterPlaylist,
292 completeCheckHlsPlaylist,
293 extractResolutionPlaylistUrls,
294 checkVideoFileTokenReinjection
295 }