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