1 import memoizee from 'memoizee'
2 import { join } from 'path'
3 import { Op, Transaction } from 'sequelize'
17 } from 'sequelize-typescript'
18 import { CONFIG } from '@server/initializers/config'
19 import { getHLSPrivateFileUrl, getHLSPublicFileUrl } from '@server/lib/object-storage'
20 import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '@server/lib/paths'
21 import { isVideoInPrivateDirectory } from '@server/lib/video-privacy'
22 import { VideoFileModel } from '@server/models/video/video-file'
23 import { MStreamingPlaylist, MStreamingPlaylistFilesVideo, MVideo } from '@server/types/models'
24 import { sha1 } from '@shared/extra-utils'
25 import { VideoStorage } from '@shared/models'
26 import { AttributesOnly } from '@shared/typescript-utils'
27 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
28 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
29 import { isArrayOf } from '../../helpers/custom-validators/misc'
30 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
35 P2P_MEDIA_LOADER_PEER_VERSION,
38 } from '../../initializers/constants'
39 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
40 import { doesExist } from '../shared'
41 import { throwIfNotValid } from '../utils'
42 import { VideoModel } from './video'
45 tableName: 'videoStreamingPlaylist',
51 fields: [ 'videoId', 'type' ],
55 fields: [ 'p2pMediaLoaderInfohashes' ],
60 export class VideoStreamingPlaylistModel extends Model<Partial<AttributesOnly<VideoStreamingPlaylistModel>>> {
69 type: VideoStreamingPlaylistType
73 playlistFilename: string
76 @Is('PlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'playlist url', true))
77 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
81 @Is('VideoStreamingPlaylistInfoHashes', value => throwIfNotValid(value, v => isArrayOf(v, isVideoFileInfoHashValid), 'info hashes'))
82 @Column(DataType.ARRAY(DataType.STRING))
83 p2pMediaLoaderInfohashes: string[]
87 p2pMediaLoaderPeerVersion: number
91 segmentsSha256Filename: string
94 @Is('VideoStreamingSegmentsSha256Url', value => throwIfNotValid(value, isActivityPubUrlValid, 'segments sha256 url', true))
96 segmentsSha256Url: string
98 @ForeignKey(() => VideoModel)
103 @Default(VideoStorage.FILE_SYSTEM)
105 storage: VideoStorage
107 @BelongsTo(() => VideoModel, {
115 @HasMany(() => VideoFileModel, {
121 VideoFiles: VideoFileModel[]
123 @HasMany(() => VideoRedundancyModel, {
130 RedundancyVideos: VideoRedundancyModel[]
132 static doesInfohashExistCached = memoizee(VideoStreamingPlaylistModel.doesInfohashExist, {
134 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
135 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
138 static doesInfohashExist (infoHash: string) {
139 const query = 'SELECT 1 FROM "videoStreamingPlaylist" WHERE $infoHash = ANY("p2pMediaLoaderInfohashes") LIMIT 1'
141 return doesExist(query, { infoHash })
144 static buildP2PMediaLoaderInfoHashes (playlistUrl: string, files: unknown[]) {
145 const hashes: string[] = []
147 // https://github.com/Novage/p2p-media-loader/blob/master/p2p-media-loader-core/lib/p2p-media-manager.ts#L115
148 for (let i = 0; i < files.length; i++) {
149 hashes.push(sha1(`${P2P_MEDIA_LOADER_PEER_VERSION}${playlistUrl}+V${i}`))
155 static listByIncorrectPeerVersion () {
158 p2pMediaLoaderPeerVersion: {
159 [Op.ne]: P2P_MEDIA_LOADER_PEER_VERSION
164 model: VideoModel.unscoped(),
170 return VideoStreamingPlaylistModel.findAll(query)
173 static loadWithVideoAndFiles (id: number) {
177 model: VideoModel.unscoped(),
181 model: VideoFileModel.unscoped()
186 return VideoStreamingPlaylistModel.findByPk<MStreamingPlaylistFilesVideo>(id, options)
189 static loadWithVideo (id: number) {
193 model: VideoModel.unscoped(),
199 return VideoStreamingPlaylistModel.findByPk(id, options)
202 static loadHLSPlaylistByVideo (videoId: number, transaction?: Transaction): Promise<MStreamingPlaylist> {
205 type: VideoStreamingPlaylistType.HLS,
211 return VideoStreamingPlaylistModel.findOne(options)
214 static async loadOrGenerate (video: MVideo, transaction?: Transaction) {
215 let playlist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id, transaction)
218 playlist = new VideoStreamingPlaylistModel({
219 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
220 type: VideoStreamingPlaylistType.HLS,
221 storage: VideoStorage.FILE_SYSTEM,
222 p2pMediaLoaderInfohashes: [],
223 playlistFilename: generateHLSMasterPlaylistFilename(video.isLive),
224 segmentsSha256Filename: generateHlsSha256SegmentsFilename(video.isLive),
228 await playlist.save({ transaction })
231 return Object.assign(playlist, { Video: video })
234 static doesOwnedHLSPlaylistExist (videoUUID: string) {
235 const query = `SELECT 1 FROM "videoStreamingPlaylist" ` +
236 `INNER JOIN "video" ON "video"."id" = "videoStreamingPlaylist"."videoId" ` +
237 `AND "video"."remote" IS FALSE AND "video"."uuid" = $videoUUID ` +
238 `AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1`
240 return doesExist(query, { videoUUID })
243 assignP2PMediaLoaderInfoHashes (video: MVideo, files: unknown[]) {
244 const masterPlaylistUrl = this.getMasterPlaylistUrl(video)
246 this.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(masterPlaylistUrl, files)
249 // ---------------------------------------------------------------------------
251 getMasterPlaylistUrl (video: MVideo) {
252 if (video.isOwned()) {
253 if (this.storage === VideoStorage.OBJECT_STORAGE) {
254 return this.getMasterPlaylistObjectStorageUrl(video)
257 return WEBSERVER.URL + this.getMasterPlaylistStaticPath(video)
260 return this.playlistUrl
263 private getMasterPlaylistObjectStorageUrl (video: MVideo) {
264 if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
265 return getHLSPrivateFileUrl(video, this.playlistFilename)
268 return getHLSPublicFileUrl(this.playlistUrl)
271 // ---------------------------------------------------------------------------
273 getSha256SegmentsUrl (video: MVideo) {
274 if (video.isOwned()) {
275 if (this.storage === VideoStorage.OBJECT_STORAGE) {
276 return this.getSha256SegmentsObjectStorageUrl(video)
279 return WEBSERVER.URL + this.getSha256SegmentsStaticPath(video)
282 return this.segmentsSha256Url
285 private getSha256SegmentsObjectStorageUrl (video: MVideo) {
286 if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
287 return getHLSPrivateFileUrl(video, this.segmentsSha256Filename)
290 return getHLSPublicFileUrl(this.segmentsSha256Url)
293 // ---------------------------------------------------------------------------
296 if (this.type === VideoStreamingPlaylistType.HLS) return 'hls'
301 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
302 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
305 hasSameUniqueKeysThan (other: MStreamingPlaylist) {
306 return this.type === other.type &&
307 this.videoId === other.videoId
310 withVideo (video: MVideo) {
311 return Object.assign(this, { Video: video })
314 private getMasterPlaylistStaticPath (video: MVideo) {
315 if (isVideoInPrivateDirectory(video.privacy)) {
316 return join(STATIC_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS, video.uuid, this.playlistFilename)
319 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.playlistFilename)
322 private getSha256SegmentsStaticPath (video: MVideo) {
323 if (isVideoInPrivateDirectory(video.privacy)) {
324 return join(STATIC_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS, video.uuid, this.segmentsSha256Filename)
327 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.segmentsSha256Filename)