1 import memoizee from 'memoizee'
2 import { join } from 'path'
3 import { Op } from 'sequelize'
17 } from 'sequelize-typescript'
18 import { getHLSPublicFileUrl } from '@server/lib/object-storage'
19 import { VideoFileModel } from '@server/models/video/video-file'
20 import { MStreamingPlaylist, MVideo } from '@server/types/models'
21 import { sha1 } from '@shared/extra-utils'
22 import { VideoStorage } from '@shared/models'
23 import { AttributesOnly } from '@shared/typescript-utils'
24 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
25 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
26 import { isArrayOf } from '../../helpers/custom-validators/misc'
27 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
32 P2P_MEDIA_LOADER_PEER_VERSION,
35 } from '../../initializers/constants'
36 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
37 import { doesExist } from '../shared'
38 import { throwIfNotValid } from '../utils'
39 import { VideoModel } from './video'
42 tableName: 'videoStreamingPlaylist',
48 fields: [ 'videoId', 'type' ],
52 fields: [ 'p2pMediaLoaderInfohashes' ],
57 export class VideoStreamingPlaylistModel extends Model<Partial<AttributesOnly<VideoStreamingPlaylistModel>>> {
66 type: VideoStreamingPlaylistType
70 playlistFilename: string
73 @Is('PlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'playlist url', true))
74 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
78 @Is('VideoStreamingPlaylistInfoHashes', value => throwIfNotValid(value, v => isArrayOf(v, isVideoFileInfoHashValid), 'info hashes'))
79 @Column(DataType.ARRAY(DataType.STRING))
80 p2pMediaLoaderInfohashes: string[]
84 p2pMediaLoaderPeerVersion: number
88 segmentsSha256Filename: string
91 @Is('VideoStreamingSegmentsSha256Url', value => throwIfNotValid(value, isActivityPubUrlValid, 'segments sha256 url', true))
93 segmentsSha256Url: string
95 @ForeignKey(() => VideoModel)
100 @Default(VideoStorage.FILE_SYSTEM)
102 storage: VideoStorage
104 @BelongsTo(() => VideoModel, {
112 @HasMany(() => VideoFileModel, {
118 VideoFiles: VideoFileModel[]
120 @HasMany(() => VideoRedundancyModel, {
127 RedundancyVideos: VideoRedundancyModel[]
129 static doesInfohashExistCached = memoizee(VideoStreamingPlaylistModel.doesInfohashExist, {
131 max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
132 maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
135 static doesInfohashExist (infoHash: string) {
136 const query = 'SELECT 1 FROM "videoStreamingPlaylist" WHERE $infoHash = ANY("p2pMediaLoaderInfohashes") LIMIT 1'
138 return doesExist(query, { infoHash })
141 static buildP2PMediaLoaderInfoHashes (playlistUrl: string, files: unknown[]) {
142 const hashes: string[] = []
144 // https://github.com/Novage/p2p-media-loader/blob/master/p2p-media-loader-core/lib/p2p-media-manager.ts#L115
145 for (let i = 0; i < files.length; i++) {
146 hashes.push(sha1(`${P2P_MEDIA_LOADER_PEER_VERSION}${playlistUrl}+V${i}`))
152 static listByIncorrectPeerVersion () {
155 p2pMediaLoaderPeerVersion: {
156 [Op.ne]: P2P_MEDIA_LOADER_PEER_VERSION
161 model: VideoModel.unscoped(),
167 return VideoStreamingPlaylistModel.findAll(query)
170 static loadWithVideo (id: number) {
174 model: VideoModel.unscoped(),
180 return VideoStreamingPlaylistModel.findByPk(id, options)
183 static loadHLSPlaylistByVideo (videoId: number): Promise<MStreamingPlaylist> {
186 type: VideoStreamingPlaylistType.HLS,
191 return VideoStreamingPlaylistModel.findOne(options)
194 static async loadOrGenerate (video: MVideo) {
195 let playlist = await VideoStreamingPlaylistModel.loadHLSPlaylistByVideo(video.id)
196 if (!playlist) playlist = new VideoStreamingPlaylistModel()
198 return Object.assign(playlist, { videoId: video.id, Video: video })
201 static doesOwnedHLSPlaylistExist (videoUUID: string) {
202 const query = `SELECT 1 FROM "videoStreamingPlaylist" ` +
203 `INNER JOIN "video" ON "video"."id" = "videoStreamingPlaylist"."videoId" ` +
204 `AND "video"."remote" IS FALSE AND "video"."uuid" = $videoUUID ` +
205 `AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1`
207 return doesExist(query, { videoUUID })
210 assignP2PMediaLoaderInfoHashes (video: MVideo, files: unknown[]) {
211 const masterPlaylistUrl = this.getMasterPlaylistUrl(video)
213 this.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(masterPlaylistUrl, files)
216 getMasterPlaylistUrl (video: MVideo) {
217 if (this.storage === VideoStorage.OBJECT_STORAGE) {
218 return getHLSPublicFileUrl(this.playlistUrl)
221 if (video.isOwned()) return WEBSERVER.URL + this.getMasterPlaylistStaticPath(video.uuid)
223 return this.playlistUrl
226 getSha256SegmentsUrl (video: MVideo) {
227 if (this.storage === VideoStorage.OBJECT_STORAGE) {
228 return getHLSPublicFileUrl(this.segmentsSha256Url)
231 if (video.isOwned()) return WEBSERVER.URL + this.getSha256SegmentsStaticPath(video.uuid, video.isLive)
233 return this.segmentsSha256Url
237 if (this.type === VideoStreamingPlaylistType.HLS) return 'hls'
242 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
243 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
246 hasSameUniqueKeysThan (other: MStreamingPlaylist) {
247 return this.type === other.type &&
248 this.videoId === other.videoId
251 withVideo (video: MVideo) {
252 return Object.assign(this, { Video: video })
255 private getMasterPlaylistStaticPath (videoUUID: string) {
256 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, videoUUID, this.playlistFilename)
259 private getSha256SegmentsStaticPath (videoUUID: string, isLive: boolean) {
260 if (isLive) return join('/live', 'segments-sha256', videoUUID)
262 return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, videoUUID, this.segmentsSha256Filename)