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, VideoStreamingPlaylist, VideoStreamingPlaylistType } from '@shared/models'
8 import { makeRawRequest, PeerTubeServer, webtorrentAdd } from '@shared/server-commands'
9 import { expectStartWith } from './checks'
10 import { hlsInfohashExist } from './tracker'
12 async function checkSegmentHash (options: {
13 server: PeerTubeServer
14 baseUrlPlaylist: string
15 baseUrlSegment: string
17 hlsPlaylist: VideoStreamingPlaylist
19 const { server, baseUrlPlaylist, baseUrlSegment, resolution, hlsPlaylist } = options
20 const command = server.streamingPlaylists
22 const file = hlsPlaylist.files.find(f => f.resolution.id === resolution)
23 const videoName = basename(file.fileUrl)
25 const playlist = await command.get({ url: `${baseUrlPlaylist}/${removeFragmentedMP4Ext(videoName)}.m3u8` })
27 const matches = /#EXT-X-BYTERANGE:(\d+)@(\d+)/.exec(playlist)
29 const length = parseInt(matches[1], 10)
30 const offset = parseInt(matches[2], 10)
31 const range = `${offset}-${offset + length - 1}`
33 const segmentBody = await command.getFragmentedSegment({
34 url: `${baseUrlSegment}/${videoName}`,
35 expectedStatus: HttpStatusCode.PARTIAL_CONTENT_206,
36 range: `bytes=${range}`
39 const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url })
40 expect(sha256(segmentBody)).to.equal(shaBody[videoName][range])
43 async function checkLiveSegmentHash (options: {
44 server: PeerTubeServer
45 baseUrlSegment: string
48 hlsPlaylist: VideoStreamingPlaylist
50 const { server, baseUrlSegment, videoUUID, segmentName, hlsPlaylist } = options
51 const command = server.streamingPlaylists
53 const segmentBody = await command.getFragmentedSegment({ url: `${baseUrlSegment}/${videoUUID}/${segmentName}` })
54 const shaBody = await command.getSegmentSha256({ url: hlsPlaylist.segmentsSha256Url })
56 expect(sha256(segmentBody)).to.equal(shaBody[segmentName])
59 async function checkResolutionsInMasterPlaylist (options: {
60 server: PeerTubeServer
63 transcoded?: boolean // default true
64 withRetry?: boolean // default false
66 const { server, playlistUrl, resolutions, withRetry = false, transcoded = true } = options
68 const masterPlaylist = await server.streamingPlaylists.get({ url: playlistUrl, withRetry })
70 for (const resolution of resolutions) {
71 const reg = transcoded
72 ? new RegExp('#EXT-X-STREAM-INF:BANDWIDTH=\\d+,RESOLUTION=\\d+x' + resolution + ',(FRAME-RATE=\\d+,)?CODECS="avc1.64001f,mp4a.40.2"')
73 : new RegExp('#EXT-X-STREAM-INF:BANDWIDTH=\\d+,RESOLUTION=\\d+x' + resolution + '')
75 expect(masterPlaylist).to.match(reg)
78 const playlistsLength = masterPlaylist.split('\n').filter(line => line.startsWith('#EXT-X-STREAM-INF:BANDWIDTH='))
79 expect(playlistsLength).to.have.lengthOf(resolutions.length)
82 async function completeCheckHlsPlaylist (options: {
83 servers: PeerTubeServer[]
87 resolutions?: number[]
88 objectStorageBaseUrl: string
90 const { videoUUID, hlsOnly, objectStorageBaseUrl } = options
92 const resolutions = options.resolutions ?? [ 240, 360, 480, 720 ]
94 for (const server of options.servers) {
95 const videoDetails = await server.videos.get({ id: videoUUID })
96 const baseUrl = `http://${videoDetails.account.host}`
98 expect(videoDetails.streamingPlaylists).to.have.lengthOf(1)
100 const hlsPlaylist = videoDetails.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
101 expect(hlsPlaylist).to.not.be.undefined
103 const hlsFiles = hlsPlaylist.files
104 expect(hlsFiles).to.have.lengthOf(resolutions.length)
106 if (hlsOnly) expect(videoDetails.files).to.have.lengthOf(0)
107 else expect(videoDetails.files).to.have.lengthOf(resolutions.length)
110 for (const resolution of resolutions) {
111 const file = hlsFiles.find(f => f.resolution.id === resolution)
112 expect(file).to.not.be.undefined
114 expect(file.magnetUri).to.have.lengthOf.above(2)
115 expect(file.torrentUrl).to.match(
116 new RegExp(`${server.url}/lazy-static/torrents/${uuidRegex}-${file.resolution.id}-hls.torrent`)
119 if (objectStorageBaseUrl) {
120 expectStartWith(file.fileUrl, objectStorageBaseUrl)
122 expect(file.fileUrl).to.match(
123 new RegExp(`${baseUrl}/static/streaming-playlists/hls/${videoDetails.uuid}/${uuidRegex}-${file.resolution.id}-fragmented.mp4`)
127 expect(file.resolution.label).to.equal(resolution + 'p')
129 await makeRawRequest({ url: file.torrentUrl, expectedStatus: HttpStatusCode.OK_200 })
130 await makeRawRequest({ url: file.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
132 const torrent = await webtorrentAdd(file.magnetUri, true)
133 expect(torrent.files).to.be.an('array')
134 expect(torrent.files.length).to.equal(1)
135 expect(torrent.files[0].path).to.exist.and.to.not.equal('')
138 // Check master playlist
140 await checkResolutionsInMasterPlaylist({ server, playlistUrl: hlsPlaylist.playlistUrl, resolutions })
142 const masterPlaylist = await server.streamingPlaylists.get({ url: hlsPlaylist.playlistUrl })
145 for (const resolution of resolutions) {
146 expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
147 expect(masterPlaylist).to.contain(`${resolution}.m3u8`)
149 const url = 'http://' + videoDetails.account.host
150 await hlsInfohashExist(url, hlsPlaylist.playlistUrl, i)
156 // Check resolution playlists
158 for (const resolution of resolutions) {
159 const file = hlsFiles.find(f => f.resolution.id === resolution)
160 const playlistName = removeFragmentedMP4Ext(basename(file.fileUrl)) + '.m3u8'
162 const url = objectStorageBaseUrl
163 ? `${objectStorageBaseUrl}hls/${videoUUID}/${playlistName}`
164 : `${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${playlistName}`
166 const subPlaylist = await server.streamingPlaylists.get({ url })
168 expect(subPlaylist).to.match(new RegExp(`${uuidRegex}-${resolution}-fragmented.mp4`))
169 expect(subPlaylist).to.contain(basename(file.fileUrl))
174 const baseUrlAndPath = objectStorageBaseUrl
175 ? objectStorageBaseUrl + 'hls/' + videoUUID
176 : baseUrl + '/static/streaming-playlists/hls/' + videoUUID
178 for (const resolution of resolutions) {
179 await checkSegmentHash({
181 baseUrlPlaylist: baseUrlAndPath,
182 baseUrlSegment: baseUrlAndPath,
191 async function checkVideoFileTokenReinjection (options: {
192 server: PeerTubeServer
194 videoFileToken: string
195 resolutions: number[]
198 const { server, resolutions, videoFileToken, videoUUID, isLive } = options
200 const video = await server.videos.getWithToken({ id: videoUUID })
201 const hls = video.streamingPlaylists[0]
203 const query = { videoFileToken, reinjectVideoFileToken: 'true' }
204 const { text } = await makeRawRequest({ url: hls.playlistUrl, query, expectedStatus: HttpStatusCode.OK_200 })
206 for (let i = 0; i < resolutions.length; i++) {
207 const resolution = resolutions[i]
209 const suffix = isLive
213 expect(text).to.contain(`${suffix}.m3u8?videoFileToken=${videoFileToken}`)
216 const resolutionPlaylists = extractResolutionPlaylistUrls(hls.playlistUrl, text)
217 expect(resolutionPlaylists).to.have.lengthOf(resolutions.length)
219 for (const url of resolutionPlaylists) {
220 const { text } = await makeRawRequest({ url, query, expectedStatus: HttpStatusCode.OK_200 })
222 const extension = isLive
226 expect(text).to.contain(`${extension}?videoFileToken=${videoFileToken}`)
230 function extractResolutionPlaylistUrls (masterPath: string, masterContent: string) {
231 return masterContent.match(/^([^.]+\.m3u8.*)/mg)
232 .map(filename => join(dirname(masterPath), filename))
237 checkLiveSegmentHash,
238 checkResolutionsInMasterPlaylist,
239 completeCheckHlsPlaylist,
240 extractResolutionPlaylistUrls,
241 checkVideoFileTokenReinjection