]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video-streaming-playlist.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / models / video / video-streaming-playlist.ts
CommitLineData
41fb13c3 1import memoizee from 'memoizee'
90a8bd30 2import { join } from 'path'
3b052510 3import { Op, Transaction } from 'sequelize'
0305db28
JB
4import {
5 AllowNull,
6 BelongsTo,
7 Column,
8 CreatedAt,
9 DataType,
10 Default,
11 ForeignKey,
12 HasMany,
13 Is,
14 Model,
15 Table,
16 UpdatedAt
17} from 'sequelize-typescript'
5a122ddd 18import { CONFIG } from '@server/initializers/config'
9ab330b9 19import { getHLSPrivateFileUrl, getHLSPublicFileUrl } from '@server/lib/object-storage'
1bb4c9ab 20import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '@server/lib/paths'
3545e72c 21import { isVideoInPrivateDirectory } from '@server/lib/video-privacy'
90a8bd30 22import { VideoFileModel } from '@server/models/video/video-file'
1bb4c9ab 23import { MStreamingPlaylist, MStreamingPlaylistFilesVideo, MVideo } from '@server/types/models'
f304a158 24import { sha1 } from '@shared/extra-utils'
0305db28 25import { VideoStorage } from '@shared/models'
f304a158 26import { AttributesOnly } from '@shared/typescript-utils'
09209296 27import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
90a8bd30 28import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
09209296 29import { isArrayOf } from '../../helpers/custom-validators/misc'
90a8bd30 30import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
764b1a14
C
31import {
32 CONSTRAINTS_FIELDS,
33 MEMOIZE_LENGTH,
34 MEMOIZE_TTL,
35 P2P_MEDIA_LOADER_PEER_VERSION,
36 STATIC_PATHS,
37 WEBSERVER
38} from '../../initializers/constants'
90a8bd30 39import { VideoRedundancyModel } from '../redundancy/video-redundancy'
8c4bbd94 40import { doesExist, throwIfNotValid } from '../shared'
90a8bd30 41import { VideoModel } from './video'
09209296
C
42
43@Table({
44 tableName: 'videoStreamingPlaylist',
45 indexes: [
46 {
47 fields: [ 'videoId' ]
48 },
49 {
50 fields: [ 'videoId', 'type' ],
51 unique: true
52 },
53 {
54 fields: [ 'p2pMediaLoaderInfohashes' ],
55 using: 'gin'
56 }
3acc5084 57 ]
09209296 58})
16c016e8 59export class VideoStreamingPlaylistModel extends Model<Partial<AttributesOnly<VideoStreamingPlaylistModel>>> {
09209296
C
60 @CreatedAt
61 createdAt: Date
62
63 @UpdatedAt
64 updatedAt: Date
65
66 @AllowNull(false)
67 @Column
68 type: VideoStreamingPlaylistType
69
70 @AllowNull(false)
764b1a14
C
71 @Column
72 playlistFilename: string
73
74 @AllowNull(true)
75 @Is('PlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'playlist url', true))
09209296
C
76 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
77 playlistUrl: string
78
79 @AllowNull(false)
80 @Is('VideoStreamingPlaylistInfoHashes', value => throwIfNotValid(value, v => isArrayOf(v, isVideoFileInfoHashValid), 'info hashes'))
3acc5084 81 @Column(DataType.ARRAY(DataType.STRING))
09209296
C
82 p2pMediaLoaderInfohashes: string[]
83
ae9bbed4
C
84 @AllowNull(false)
85 @Column
86 p2pMediaLoaderPeerVersion: number
87
09209296 88 @AllowNull(false)
764b1a14
C
89 @Column
90 segmentsSha256Filename: string
91
92 @AllowNull(true)
93 @Is('VideoStreamingSegmentsSha256Url', value => throwIfNotValid(value, isActivityPubUrlValid, 'segments sha256 url', true))
09209296
C
94 @Column
95 segmentsSha256Url: string
96
97 @ForeignKey(() => VideoModel)
98 @Column
99 videoId: number
100
0305db28
JB
101 @AllowNull(false)
102 @Default(VideoStorage.FILE_SYSTEM)
103 @Column
104 storage: VideoStorage
105
09209296
C
106 @BelongsTo(() => VideoModel, {
107 foreignKey: {
108 allowNull: false
109 },
110 onDelete: 'CASCADE'
111 })
112 Video: VideoModel
113
d7a25329
C
114 @HasMany(() => VideoFileModel, {
115 foreignKey: {
116 allowNull: true
117 },
118 onDelete: 'CASCADE'
119 })
120 VideoFiles: VideoFileModel[]
121
09209296
C
122 @HasMany(() => VideoRedundancyModel, {
123 foreignKey: {
124 allowNull: false
125 },
126 onDelete: 'CASCADE',
127 hooks: true
128 })
129 RedundancyVideos: VideoRedundancyModel[]
130
35f28e94
C
131 static doesInfohashExistCached = memoizee(VideoStreamingPlaylistModel.doesInfohashExist, {
132 promise: true,
133 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
134 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
135 })
136
09209296
C
137 static doesInfohashExist (infoHash: string) {
138 const query = 'SELECT 1 FROM "videoStreamingPlaylist" WHERE $infoHash = ANY("p2pMediaLoaderInfohashes") LIMIT 1'
09209296 139
8c4bbd94 140 return doesExist(this.sequelize, query, { infoHash })
09209296
C
141 }
142
d7a25329 143 static buildP2PMediaLoaderInfoHashes (playlistUrl: string, files: unknown[]) {
09209296
C
144 const hashes: string[] = []
145
ae9bbed4 146 // https://github.com/Novage/p2p-media-loader/blob/master/p2p-media-loader-core/lib/p2p-media-manager.ts#L115
d7a25329 147 for (let i = 0; i < files.length; i++) {
ae9bbed4 148 hashes.push(sha1(`${P2P_MEDIA_LOADER_PEER_VERSION}${playlistUrl}+V${i}`))
09209296
C
149 }
150
151 return hashes
152 }
153
ae9bbed4
C
154 static listByIncorrectPeerVersion () {
155 const query = {
156 where: {
157 p2pMediaLoaderPeerVersion: {
1735c825 158 [Op.ne]: P2P_MEDIA_LOADER_PEER_VERSION
ae9bbed4 159 }
764b1a14
C
160 },
161 include: [
162 {
163 model: VideoModel.unscoped(),
164 required: true
165 }
166 ]
ae9bbed4
C
167 }
168
169 return VideoStreamingPlaylistModel.findAll(query)
170 }
171
1bb4c9ab
C
172 static loadWithVideoAndFiles (id: number) {
173 const options = {
174 include: [
175 {
176 model: VideoModel.unscoped(),
177 required: true
178 },
179 {
180 model: VideoFileModel.unscoped()
181 }
182 ]
183 }
184
185 return VideoStreamingPlaylistModel.findByPk<MStreamingPlaylistFilesVideo>(id, options)
186 }
187
09209296
C
188 static loadWithVideo (id: number) {
189 const options = {
190 include: [
191 {
192 model: VideoModel.unscoped(),
193 required: true
194 }
195 ]
196 }
197
9b39106d 198 return VideoStreamingPlaylistModel.findByPk(id, options)
09209296
C
199 }
200
3b052510 201 static loadHLSPlaylistByVideo (videoId: number, transaction?: Transaction): Promise<MStreamingPlaylist> {
a5cf76af
C
202 const options = {
203 where: {
204 type: VideoStreamingPlaylistType.HLS,
205 videoId
3b052510
C
206 },
207 transaction
a5cf76af
C
208 }
209
210 return VideoStreamingPlaylistModel.findOne(options)
211 }
212
3b052510
C
213 static async loadOrGenerate (video: MVideo, transaction?: Transaction) {
214 let playlist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id, transaction)
09209296 215
1bb4c9ab
C
216 if (!playlist) {
217 playlist = new VideoStreamingPlaylistModel({
218 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
219 type: VideoStreamingPlaylistType.HLS,
220 storage: VideoStorage.FILE_SYSTEM,
221 p2pMediaLoaderInfohashes: [],
222 playlistFilename: generateHLSMasterPlaylistFilename(video.isLive),
223 segmentsSha256Filename: generateHlsSha256SegmentsFilename(video.isLive),
224 videoId: video.id
225 })
226
227 await playlist.save({ transaction })
228 }
229
230 return Object.assign(playlist, { Video: video })
09209296
C
231 }
232
90701ec1
C
233 static doesOwnedHLSPlaylistExist (videoUUID: string) {
234 const query = `SELECT 1 FROM "videoStreamingPlaylist" ` +
235 `INNER JOIN "video" ON "video"."id" = "videoStreamingPlaylist"."videoId" ` +
236 `AND "video"."remote" IS FALSE AND "video"."uuid" = $videoUUID ` +
237 `AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1`
238
8c4bbd94 239 return doesExist(this.sequelize, query, { videoUUID })
90701ec1
C
240 }
241
764b1a14
C
242 assignP2PMediaLoaderInfoHashes (video: MVideo, files: unknown[]) {
243 const masterPlaylistUrl = this.getMasterPlaylistUrl(video)
09209296 244
764b1a14 245 this.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(masterPlaylistUrl, files)
09209296
C
246 }
247
9ab330b9
C
248 // ---------------------------------------------------------------------------
249
764b1a14 250 getMasterPlaylistUrl (video: MVideo) {
cfd57d2c
C
251 if (video.isOwned()) {
252 if (this.storage === VideoStorage.OBJECT_STORAGE) {
9ab330b9 253 return this.getMasterPlaylistObjectStorageUrl(video)
cfd57d2c 254 }
0305db28 255
3545e72c 256 return WEBSERVER.URL + this.getMasterPlaylistStaticPath(video)
cfd57d2c 257 }
764b1a14
C
258
259 return this.playlistUrl
09209296
C
260 }
261
9ab330b9 262 private getMasterPlaylistObjectStorageUrl (video: MVideo) {
5a122ddd 263 if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
9ab330b9
C
264 return getHLSPrivateFileUrl(video, this.playlistFilename)
265 }
266
267 return getHLSPublicFileUrl(this.playlistUrl)
268 }
269
270 // ---------------------------------------------------------------------------
271
764b1a14 272 getSha256SegmentsUrl (video: MVideo) {
cfd57d2c
C
273 if (video.isOwned()) {
274 if (this.storage === VideoStorage.OBJECT_STORAGE) {
9ab330b9 275 return this.getSha256SegmentsObjectStorageUrl(video)
cfd57d2c 276 }
0305db28 277
3545e72c 278 return WEBSERVER.URL + this.getSha256SegmentsStaticPath(video)
cfd57d2c 279 }
c6c0fa6c 280
764b1a14 281 return this.segmentsSha256Url
09209296
C
282 }
283
9ab330b9 284 private getSha256SegmentsObjectStorageUrl (video: MVideo) {
5a122ddd 285 if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
9ab330b9
C
286 return getHLSPrivateFileUrl(video, this.segmentsSha256Filename)
287 }
288
289 return getHLSPublicFileUrl(this.segmentsSha256Url)
290 }
291
292 // ---------------------------------------------------------------------------
293
09209296
C
294 getStringType () {
295 if (this.type === VideoStreamingPlaylistType.HLS) return 'hls'
296
297 return 'unknown'
298 }
299
d7a25329
C
300 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
301 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
302 }
303
453e83ea 304 hasSameUniqueKeysThan (other: MStreamingPlaylist) {
09209296
C
305 return this.type === other.type &&
306 this.videoId === other.videoId
307 }
764b1a14 308
ad5db104
C
309 withVideo (video: MVideo) {
310 return Object.assign(this, { Video: video })
311 }
312
3545e72c
C
313 private getMasterPlaylistStaticPath (video: MVideo) {
314 if (isVideoInPrivateDirectory(video.privacy)) {
315 return join(STATIC_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS, video.uuid, this.playlistFilename)
316 }
317
318 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.playlistFilename)
764b1a14
C
319 }
320
3545e72c
C
321 private getSha256SegmentsStaticPath (video: MVideo) {
322 if (isVideoInPrivateDirectory(video.privacy)) {
323 return join(STATIC_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS, video.uuid, this.segmentsSha256Filename)
324 }
325
326 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.segmentsSha256Filename)
764b1a14 327 }
09209296 328}