1 import memoizee from 'memoizee'
2 import { join } from 'path'
3 import { Op, Transaction } from 'sequelize'
17 } from 'sequelize-typescript'
18 import { getHLSPublicFileUrl } from '@server/lib/object-storage'
19 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '@server/lib/paths'
20 import { VideoFileModel } from '@server/models/video/video-file'
21 import { MStreamingPlaylist, MStreamingPlaylistFilesVideo, MVideo } from '@server/types/models'
22 import { sha1 } from '@shared/extra-utils'
23 import { VideoStorage } from '@shared/models'
24 import { AttributesOnly } from '@shared/typescript-utils'
25 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
26 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
27 import { isArrayOf } from '../../helpers/custom-validators/misc'
28 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
33 P2P_MEDIA_LOADER_PEER_VERSION,
36 } from '../../initializers/constants'
37 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
38 import { doesExist } from '../shared'
39 import { throwIfNotValid } from '../utils'
40 import { VideoModel } from './video'
43 tableName: 'videoStreamingPlaylist',
49 fields: [ 'videoId', 'type' ],
53 fields: [ 'p2pMediaLoaderInfohashes' ],
58 export class VideoStreamingPlaylistModel extends Model<Partial<AttributesOnly<VideoStreamingPlaylistModel>>> {
67 type: VideoStreamingPlaylistType
71 playlistFilename: string
74 @Is('PlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'playlist url', true))
75 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
79 @Is('VideoStreamingPlaylistInfoHashes', value => throwIfNotValid(value, v => isArrayOf(v, isVideoFileInfoHashValid), 'info hashes'))
80 @Column(DataType.ARRAY(DataType.STRING))
81 p2pMediaLoaderInfohashes: string[]
85 p2pMediaLoaderPeerVersion: number
89 segmentsSha256Filename: string
92 @Is('VideoStreamingSegmentsSha256Url', value => throwIfNotValid(value, isActivityPubUrlValid, 'segments sha256 url', true))
94 segmentsSha256Url: string
96 @ForeignKey(() => VideoModel)
101 @Default(VideoStorage.FILE_SYSTEM)
103 storage: VideoStorage
105 @BelongsTo(() => VideoModel, {
113 @HasMany(() => VideoFileModel, {
119 VideoFiles: VideoFileModel[]
121 @HasMany(() => VideoRedundancyModel, {
128 RedundancyVideos: VideoRedundancyModel[]
130 static doesInfohashExistCached = memoizee(VideoStreamingPlaylistModel.doesInfohashExist, {
132 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
133 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
136 static doesInfohashExist (infoHash: string) {
137 const query = 'SELECT 1 FROM "videoStreamingPlaylist" WHERE $infoHash = ANY("p2pMediaLoaderInfohashes") LIMIT 1'
139 return doesExist(query, { infoHash })
142 static buildP2PMediaLoaderInfoHashes (playlistUrl: string, files: unknown[]) {
143 const hashes: string[] = []
145 // https://github.com/Novage/p2p-media-loader/blob/master/p2p-media-loader-core/lib/p2p-media-manager.ts#L115
146 for (let i = 0; i < files.length; i++) {
147 hashes.push(sha1(`${P2P_MEDIA_LOADER_PEER_VERSION}${playlistUrl}+V${i}`))
153 static listByIncorrectPeerVersion () {
156 p2pMediaLoaderPeerVersion: {
157 [Op.ne]: P2P_MEDIA_LOADER_PEER_VERSION
162 model: VideoModel.unscoped(),
168 return VideoStreamingPlaylistModel.findAll(query)
171 static loadWithVideoAndFiles (id: number) {
175 model: VideoModel.unscoped(),
179 model: VideoFileModel.unscoped()
184 return VideoStreamingPlaylistModel.findByPk<MStreamingPlaylistFilesVideo>(id, options)
187 static loadWithVideo (id: number) {
191 model: VideoModel.unscoped(),
197 return VideoStreamingPlaylistModel.findByPk(id, options)
200 static loadHLSPlaylistByVideo (videoId: number, transaction?: Transaction): Promise<MStreamingPlaylist> {
203 type: VideoStreamingPlaylistType.HLS,
209 return VideoStreamingPlaylistModel.findOne(options)
212 static async loadOrGenerate (video: MVideo, transaction?: Transaction) {
213 let playlist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id, transaction)
216 playlist = new VideoStreamingPlaylistModel({
217 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
218 type: VideoStreamingPlaylistType.HLS,
219 storage: VideoStorage.FILE_SYSTEM,
220 p2pMediaLoaderInfohashes: [],
221 playlistFilename: generateHLSMasterPlaylistFilename(video.isLive),
222 segmentsSha256Filename: generateHlsSha256SegmentsFilename(video.isLive),
226 await playlist.save({ transaction })
229 return Object.assign(playlist, { Video: video })
232 static doesOwnedHLSPlaylistExist (videoUUID: string) {
233 const query = `SELECT 1 FROM "videoStreamingPlaylist" ` +
234 `INNER JOIN "video" ON "video"."id" = "videoStreamingPlaylist"."videoId" ` +
235 `AND "video"."remote" IS FALSE AND "video"."uuid" = $videoUUID ` +
236 `AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1`
238 return doesExist(query, { videoUUID })
241 assignP2PMediaLoaderInfoHashes (video: MVideo, files: unknown[]) {
242 const masterPlaylistUrl = this.getMasterPlaylistUrl(video)
244 this.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(masterPlaylistUrl, files)
247 getMasterPlaylistUrl (video: MVideo) {
248 if (video.isOwned()) {
249 if (this.storage === VideoStorage.OBJECT_STORAGE) {
250 return getHLSPublicFileUrl(this.playlistUrl)
253 return WEBSERVER.URL + this.getMasterPlaylistStaticPath(video.uuid)
256 return this.playlistUrl
259 getSha256SegmentsUrl (video: MVideo) {
260 if (video.isOwned()) {
261 if (this.storage === VideoStorage.OBJECT_STORAGE) {
262 return getHLSPublicFileUrl(this.segmentsSha256Url)
265 return WEBSERVER.URL + this.getSha256SegmentsStaticPath(video.uuid)
268 return this.segmentsSha256Url
272 if (this.type === VideoStreamingPlaylistType.HLS) return 'hls'
277 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
278 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
281 hasSameUniqueKeysThan (other: MStreamingPlaylist) {
282 return this.type === other.type &&
283 this.videoId === other.videoId
286 withVideo (video: MVideo) {
287 return Object.assign(this, { Video: video })
290 private getMasterPlaylistStaticPath (videoUUID: string) {
291 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, videoUUID, this.playlistFilename)
294 private getSha256SegmentsStaticPath (videoUUID: string) {
295 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, videoUUID, this.segmentsSha256Filename)