1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
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'
13 async function checkSegmentHash (options: {
14 server: PeerTubeServer
15 baseUrlPlaylist: string
16 baseUrlSegment: string
18 hlsPlaylist: VideoStreamingPlaylist
21 const { server, baseUrlPlaylist, baseUrlSegment, resolution, hlsPlaylist, token } = options
22 const command = server.streamingPlaylists
24 const file = hlsPlaylist.files.find(f => f.resolution.id === resolution)
25 const videoName = basename(file.fileUrl)
27 const playlist = await command.get({ url: `${baseUrlPlaylist}/${removeFragmentedMP4Ext(videoName)}.m3u8`, token })
29 const matches = /#EXT-X-BYTERANGE:(\d+)@(\d+)/.exec(playlist)
31 const length = parseInt(matches[1], 10)
32 const offset = parseInt(matches[2], 10)
33 const range = `${offset}-${offset + length - 1}`
35 const segmentBody = await command.getFragmentedSegment({
36 url: `${baseUrlSegment}/${videoName}`,
37 expectedStatus: HttpStatusCode.PARTIAL_CONTENT_206,
38 range: `bytes=${range}`,
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}`)
46 // ---------------------------------------------------------------------------
48 async function checkLiveSegmentHash (options: {
49 server: PeerTubeServer
50 baseUrlSegment: string
53 hlsPlaylist: VideoStreamingPlaylist
55 const { server, baseUrlSegment, videoUUID, segmentName, hlsPlaylist } = options
56 const command = server.streamingPlaylists
58 const segmentBody = await command.getFragmentedSegment({ url: `${baseUrlSegment}/${videoUUID}/${segmentName}` })
59 const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url })
61 expect(sha256(segmentBody)).to.equal(shaBody[segmentName])
64 // ---------------------------------------------------------------------------
66 async function checkResolutionsInMasterPlaylist (options: {
67 server: PeerTubeServer
71 transcoded?: boolean // default true
72 withRetry?: boolean // default false
74 const { server, playlistUrl, resolutions, token, withRetry = false, transcoded = true } = options
76 const masterPlaylist = await server.streamingPlaylists.get({ url: playlistUrl, token, withRetry })
78 for (const resolution of resolutions) {
79 const base = '#EXT-X-STREAM-INF:BANDWIDTH=\\d+,RESOLUTION=\\d+x' + resolution
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"`))
86 expect(masterPlaylist).to.match(new RegExp(`${base}`))
90 const playlistsLength = masterPlaylist.split('\n').filter(line => line.startsWith('#EXT-X-STREAM-INF:BANDWIDTH='))
91 expect(playlistsLength).to.have.lengthOf(resolutions.length)
94 async function completeCheckHlsPlaylist (options: {
95 servers: PeerTubeServer[]
99 resolutions?: number[]
100 objectStorageBaseUrl?: string
102 const { videoUUID, hlsOnly, objectStorageBaseUrl } = options
104 const resolutions = options.resolutions ?? [ 240, 360, 480, 720 ]
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
110 const privatePath = requiresAuth
113 const token = requiresAuth
117 const baseUrl = `http://${videoDetails.account.host}`
119 expect(videoDetails.streamingPlaylists).to.have.lengthOf(1)
121 const hlsPlaylist = videoDetails.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
122 expect(hlsPlaylist).to.not.be.undefined
124 const hlsFiles = hlsPlaylist.files
125 expect(hlsFiles).to.have.lengthOf(resolutions.length)
127 if (hlsOnly) expect(videoDetails.files).to.have.lengthOf(0)
128 else expect(videoDetails.files).to.have.lengthOf(resolutions.length)
131 for (const resolution of resolutions) {
132 const file = hlsFiles.find(f => f.resolution.id === resolution)
133 expect(file).to.not.be.undefined
135 if (file.resolution.id === VideoResolution.H_NOVIDEO) {
136 expect(file.resolution.label).to.equal('Audio')
138 expect(file.resolution.label).to.equal(resolution + 'p')
141 expect(file.magnetUri).to.have.lengthOf.above(2)
142 await checkWebTorrentWorks(file.magnetUri)
145 const nameReg = `${uuidRegex}-${file.resolution.id}`
147 expect(file.torrentUrl).to.match(new RegExp(`${server.url}/lazy-static/torrents/${nameReg}-hls.torrent`))
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)
155 expect(file.fileUrl).to.match(
156 new RegExp(`${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoDetails.uuid}/${nameReg}-fragmented.mp4`)
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 }),
169 url: file.fileDownloadUrl,
171 expectedStatus: objectStorageBaseUrl
172 ? HttpStatusCode.FOUND_302
173 : HttpStatusCode.OK_200
179 // Check master playlist
181 await checkResolutionsInMasterPlaylist({ server, token, playlistUrl: hlsPlaylist.playlistUrl, resolutions })
183 const masterPlaylist = await server.streamingPlaylists.get({ url: hlsPlaylist.playlistUrl, token })
186 for (const resolution of resolutions) {
187 expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
188 expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
190 const url = 'http://' + videoDetails.account.host
191 await hlsInfohashExist(url, hlsPlaylist.playlistUrl, i)
197 // Check resolution playlists
199 for (const resolution of resolutions) {
200 const file = hlsFiles.find(f => f.resolution.id === resolution)
201 const playlistName = removeFragmentedMP4Ext(basename(file.fileUrl)) + '.m3u8'
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}`
209 url = `${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoUUID}/${playlistName}`
212 const subPlaylist = await server.streamingPlaylists.get({ url, token })
214 expect(subPlaylist).to.match(new RegExp(`${uuidRegex}-${resolution}-fragmented.mp4`))
215 expect(subPlaylist).to.contain(basename(file.fileUrl))
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}`
226 baseUrlAndPath = `${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoUUID}`
229 for (const resolution of resolutions) {
230 await checkSegmentHash({
233 baseUrlPlaylist: baseUrlAndPath,
234 baseUrlSegment: baseUrlAndPath,
243 async function checkVideoFileTokenReinjection (options: {
244 server: PeerTubeServer
246 videoFileToken: string
247 resolutions: number[]
250 const { server, resolutions, videoFileToken, videoUUID, isLive } = options
252 const video = await server.videos.getWithToken({ id: videoUUID })
253 const hls = video.streamingPlaylists[0]
255 const query = { videoFileToken, reinjectVideoFileToken: 'true' }
256 const { text } = await makeRawRequest({ url: hls.playlistUrl, query, expectedStatus: HttpStatusCode.OK_200 })
258 for (let i = 0; i < resolutions.length; i++) {
259 const resolution = resolutions[i]
261 const suffix = isLive
265 expect(text).to.contain(`${suffix}.m3u8?videoFileToken=${videoFileToken}&reinjectVideoFileToken=true`)
268 const resolutionPlaylists = extractResolutionPlaylistUrls(hls.playlistUrl, text)
269 expect(resolutionPlaylists).to.have.lengthOf(resolutions.length)
271 for (const url of resolutionPlaylists) {
272 const { text } = await makeRawRequest({ url, query, expectedStatus: HttpStatusCode.OK_200 })
274 const extension = isLive
278 expect(text).to.contain(`${extension}?videoFileToken=${videoFileToken}`)
279 expect(text).not.to.contain(`reinjectVideoFileToken=true`)
283 function extractResolutionPlaylistUrls (masterPath: string, masterContent: string) {
284 return masterContent.match(/^([^.]+\.m3u8.*)/mg)
285 .map(filename => join(dirname(masterPath), filename))
290 checkLiveSegmentHash,
291 checkResolutionsInMasterPlaylist,
292 completeCheckHlsPlaylist,
293 extractResolutionPlaylistUrls,
294 checkVideoFileTokenReinjection