]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/miscs/miscs.ts
replace numbers with typed http status codes (#3409)
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / miscs / miscs.ts
1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
2
3 import * as chai from 'chai'
4 import * as ffmpeg from 'fluent-ffmpeg'
5 import { ensureDir, pathExists, readFile, stat } from 'fs-extra'
6 import { basename, dirname, isAbsolute, join, resolve } from 'path'
7 import * as request from 'supertest'
8 import * as WebTorrent from 'webtorrent'
9 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
10
11 const expect = chai.expect
12 let webtorrent: WebTorrent.Instance
13
14 function immutableAssign<T, U> (target: T, source: U) {
15 return Object.assign<{}, T, U>({}, target, source)
16 }
17
18 // Default interval -> 5 minutes
19 function dateIsValid (dateString: string, interval = 300000) {
20 const dateToCheck = new Date(dateString)
21 const now = new Date()
22
23 return Math.abs(now.getTime() - dateToCheck.getTime()) <= interval
24 }
25
26 function wait (milliseconds: number) {
27 return new Promise(resolve => setTimeout(resolve, milliseconds))
28 }
29
30 function webtorrentAdd (torrent: string, refreshWebTorrent = false) {
31 const WebTorrent = require('webtorrent')
32
33 if (!webtorrent) webtorrent = new WebTorrent()
34 if (refreshWebTorrent === true) webtorrent = new WebTorrent()
35
36 return new Promise<WebTorrent.Torrent>(res => webtorrent.add(torrent, res))
37 }
38
39 function root () {
40 // We are in /miscs
41 let root = join(__dirname, '..', '..', '..')
42
43 if (basename(root) === 'dist') root = resolve(root, '..')
44
45 return root
46 }
47
48 function buildServerDirectory (server: { internalServerNumber: number }, directory: string) {
49 return join(root(), 'test' + server.internalServerNumber, directory)
50 }
51
52 async function testImage (url: string, imageName: string, imagePath: string, extension = '.jpg') {
53 const res = await request(url)
54 .get(imagePath)
55 .expect(HttpStatusCode.OK_200)
56
57 const body = res.body
58
59 const data = await readFile(join(root(), 'server', 'tests', 'fixtures', imageName + extension))
60 const minLength = body.length - ((30 * body.length) / 100)
61 const maxLength = body.length + ((30 * body.length) / 100)
62
63 expect(data.length).to.be.above(minLength, "the generated image is way smaller than the recorded fixture")
64 expect(data.length).to.be.below(maxLength, "the generated image is way larger than the recorded fixture")
65 }
66
67 function buildAbsoluteFixturePath (path: string, customCIPath = false) {
68 if (isAbsolute(path)) return path
69
70 if (customCIPath && process.env.GITHUB_WORKSPACE) {
71 return join(process.env.GITHUB_WORKSPACE, 'fixtures', path)
72 }
73
74 return join(root(), 'server', 'tests', 'fixtures', path)
75 }
76
77 function areHttpImportTestsDisabled () {
78 const disabled = process.env.DISABLE_HTTP_IMPORT_TESTS === 'true'
79
80 if (disabled) console.log('Import tests are disabled')
81
82 return disabled
83 }
84
85 async function generateHighBitrateVideo () {
86 const tempFixturePath = buildAbsoluteFixturePath('video_high_bitrate_1080p.mp4', true)
87
88 await ensureDir(dirname(tempFixturePath))
89
90 const exists = await pathExists(tempFixturePath)
91 if (!exists) {
92 console.log('Generating high bitrate video.')
93
94 // Generate a random, high bitrate video on the fly, so we don't have to include
95 // a large file in the repo. The video needs to have a certain minimum length so
96 // that FFmpeg properly applies bitrate limits.
97 // https://stackoverflow.com/a/15795112
98 return new Promise<string>((res, rej) => {
99 ffmpeg()
100 .outputOptions([ '-f rawvideo', '-video_size 1920x1080', '-i /dev/urandom' ])
101 .outputOptions([ '-ac 2', '-f s16le', '-i /dev/urandom', '-t 10' ])
102 .outputOptions([ '-maxrate 10M', '-bufsize 10M' ])
103 .output(tempFixturePath)
104 .on('error', rej)
105 .on('end', () => res(tempFixturePath))
106 .run()
107 })
108 }
109
110 return tempFixturePath
111 }
112
113 async function generateVideoWithFramerate (fps = 60) {
114 const tempFixturePath = buildAbsoluteFixturePath(`video_${fps}fps.mp4`, true)
115
116 await ensureDir(dirname(tempFixturePath))
117
118 const exists = await pathExists(tempFixturePath)
119 if (!exists) {
120 console.log('Generating video with framerate %d.', fps)
121
122 return new Promise<string>((res, rej) => {
123 ffmpeg()
124 .outputOptions([ '-f rawvideo', '-video_size 1280x720', '-i /dev/urandom' ])
125 .outputOptions([ '-ac 2', '-f s16le', '-i /dev/urandom', '-t 10' ])
126 .outputOptions([ `-r ${fps}` ])
127 .output(tempFixturePath)
128 .on('error', rej)
129 .on('end', () => res(tempFixturePath))
130 .run()
131 })
132 }
133
134 return tempFixturePath
135 }
136
137 async function getFileSize (path: string) {
138 const stats = await stat(path)
139
140 return stats.size
141 }
142
143 // ---------------------------------------------------------------------------
144
145 export {
146 dateIsValid,
147 wait,
148 areHttpImportTestsDisabled,
149 buildServerDirectory,
150 webtorrentAdd,
151 getFileSize,
152 immutableAssign,
153 testImage,
154 buildAbsoluteFixturePath,
155 root,
156 generateHighBitrateVideo,
157 generateVideoWithFramerate
158 }