]>
Commit | Line | Data |
---|---|---|
39445ead | 1 | import * as Bluebird from 'bluebird' |
098eb377 | 2 | import { maxBy } from 'lodash' |
571389d4 | 3 | import * as magnetUtil from 'magnet-uri' |
4d4e5cd4 | 4 | import * as parseTorrent from 'parse-torrent' |
098eb377 | 5 | import { join } from 'path' |
e02643f3 | 6 | import * as Sequelize from 'sequelize' |
3fd3ab2d | 7 | import { |
4ba3b8ea C |
8 | AllowNull, |
9 | BeforeDestroy, | |
10 | BelongsTo, | |
11 | BelongsToMany, | |
12 | Column, | |
13 | CreatedAt, | |
14 | DataType, | |
15 | Default, | |
16 | ForeignKey, | |
17 | HasMany, | |
2baea0c7 | 18 | HasOne, |
4ba3b8ea | 19 | IFindOptions, |
9a629c6e | 20 | IIncludeOptions, |
4ba3b8ea C |
21 | Is, |
22 | IsInt, | |
23 | IsUUID, | |
24 | Min, | |
25 | Model, | |
26 | Scopes, | |
27 | Table, | |
9a629c6e | 28 | UpdatedAt |
3fd3ab2d | 29 | } from 'sequelize-typescript' |
098eb377 | 30 | import { VideoPrivacy, VideoState } from '../../../shared' |
3fd3ab2d | 31 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' |
a8462c8e | 32 | import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos' |
066e94c5 | 33 | import { VideoFilter } from '../../../shared/models/videos/video-query.type' |
62689b94 | 34 | import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils' |
da854ddd | 35 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' |
c48e82b5 | 36 | import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc' |
3fd3ab2d | 37 | import { |
4ba3b8ea C |
38 | isVideoCategoryValid, |
39 | isVideoDescriptionValid, | |
40 | isVideoDurationValid, | |
41 | isVideoLanguageValid, | |
42 | isVideoLicenceValid, | |
43 | isVideoNameValid, | |
2baea0c7 C |
44 | isVideoPrivacyValid, |
45 | isVideoStateValid, | |
b64c950a | 46 | isVideoSupportValid |
3fd3ab2d | 47 | } from '../../helpers/custom-validators/videos' |
098eb377 | 48 | import { generateImageFromVideoFile, getVideoFileResolution } from '../../helpers/ffmpeg-utils' |
da854ddd | 49 | import { logger } from '../../helpers/logger' |
f05a1c30 | 50 | import { getServerActor } from '../../helpers/utils' |
65fcc311 | 51 | import { |
1297eb5d | 52 | ACTIVITY_PUB, |
4ba3b8ea C |
53 | API_VERSION, |
54 | CONFIG, | |
55 | CONSTRAINTS_FIELDS, | |
56 | PREVIEWS_SIZE, | |
57 | REMOTE_SCHEME, | |
02756fbd | 58 | STATIC_DOWNLOAD_PATHS, |
4ba3b8ea C |
59 | STATIC_PATHS, |
60 | THUMBNAILS_SIZE, | |
61 | VIDEO_CATEGORIES, | |
62 | VIDEO_LANGUAGES, | |
63 | VIDEO_LICENCES, | |
2baea0c7 C |
64 | VIDEO_PRIVACIES, |
65 | VIDEO_STATES | |
3fd3ab2d | 66 | } from '../../initializers' |
50d6de9c | 67 | import { sendDeleteVideo } from '../../lib/activitypub/send' |
3fd3ab2d C |
68 | import { AccountModel } from '../account/account' |
69 | import { AccountVideoRateModel } from '../account/account-video-rate' | |
50d6de9c | 70 | import { ActorModel } from '../activitypub/actor' |
b6a4fd6b | 71 | import { AvatarModel } from '../avatar/avatar' |
3fd3ab2d | 72 | import { ServerModel } from '../server/server' |
9a629c6e | 73 | import { buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils' |
3fd3ab2d C |
74 | import { TagModel } from './tag' |
75 | import { VideoAbuseModel } from './video-abuse' | |
76 | import { VideoChannelModel } from './video-channel' | |
da854ddd | 77 | import { VideoCommentModel } from './video-comment' |
3fd3ab2d C |
78 | import { VideoFileModel } from './video-file' |
79 | import { VideoShareModel } from './video-share' | |
80 | import { VideoTagModel } from './video-tag' | |
2baea0c7 | 81 | import { ScheduleVideoUpdateModel } from './schedule-video-update' |
40e87e9e | 82 | import { VideoCaptionModel } from './video-caption' |
26b7305a | 83 | import { VideoBlacklistModel } from './video-blacklist' |
098eb377 | 84 | import { remove, writeFile } from 'fs-extra' |
9a629c6e | 85 | import { VideoViewModel } from './video-views' |
c48e82b5 | 86 | import { VideoRedundancyModel } from '../redundancy/video-redundancy' |
098eb377 C |
87 | import { |
88 | videoFilesModelToFormattedJSON, | |
89 | VideoFormattingJSONOptions, | |
90 | videoModelToActivityPubObject, | |
91 | videoModelToFormattedDetailsJSON, | |
92 | videoModelToFormattedJSON | |
93 | } from './video-format-utils' | |
627621c1 | 94 | import * as validator from 'validator' |
3fd3ab2d | 95 | |
57c36b27 C |
96 | // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation |
97 | const indexes: Sequelize.DefineIndexesOptions[] = [ | |
98 | buildTrigramSearchIndex('video_name_trigram', 'name'), | |
99 | ||
8cd72bd3 C |
100 | { fields: [ 'createdAt' ] }, |
101 | { fields: [ 'publishedAt' ] }, | |
102 | { fields: [ 'duration' ] }, | |
103 | { fields: [ 'category' ] }, | |
104 | { fields: [ 'licence' ] }, | |
105 | { fields: [ 'nsfw' ] }, | |
106 | { fields: [ 'language' ] }, | |
107 | { fields: [ 'waitTranscoding' ] }, | |
108 | { fields: [ 'state' ] }, | |
109 | { fields: [ 'remote' ] }, | |
110 | { fields: [ 'views' ] }, | |
111 | { fields: [ 'likes' ] }, | |
112 | { fields: [ 'channelId' ] }, | |
57c36b27 | 113 | { |
8cd72bd3 C |
114 | fields: [ 'uuid' ], |
115 | unique: true | |
57c36b27 C |
116 | }, |
117 | { | |
8ea6f49a | 118 | fields: [ 'url' ], |
57c36b27 C |
119 | unique: true |
120 | } | |
121 | ] | |
122 | ||
2baea0c7 | 123 | export enum ScopeNames { |
afd2cba5 C |
124 | AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS', |
125 | FOR_API = 'FOR_API', | |
4cb6d457 | 126 | WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS', |
d48ff09d | 127 | WITH_TAGS = 'WITH_TAGS', |
bbe0f064 | 128 | WITH_FILES = 'WITH_FILES', |
191764f3 C |
129 | WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE', |
130 | WITH_BLACKLISTED = 'WITH_BLACKLISTED' | |
d48ff09d C |
131 | } |
132 | ||
afd2cba5 C |
133 | type ForAPIOptions = { |
134 | ids: number[] | |
135 | withFiles?: boolean | |
136 | } | |
137 | ||
138 | type AvailableForListIDsOptions = { | |
139 | actorId: number | |
140 | includeLocalVideos: boolean | |
141 | filter?: VideoFilter | |
142 | categoryOneOf?: number[] | |
143 | nsfw?: boolean | |
144 | licenceOneOf?: number[] | |
145 | languageOneOf?: string[] | |
146 | tagsOneOf?: string[] | |
147 | tagsAllOf?: string[] | |
148 | withFiles?: boolean | |
149 | accountId?: number | |
d525fc39 | 150 | videoChannelId?: number |
9a629c6e | 151 | trendingDays?: number |
d525fc39 C |
152 | } |
153 | ||
d48ff09d | 154 | @Scopes({ |
8ea6f49a | 155 | [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => { |
0626e7af | 156 | const accountInclude = { |
03e12d7c | 157 | attributes: [ 'id', 'name' ], |
0626e7af C |
158 | model: AccountModel.unscoped(), |
159 | required: true, | |
0626e7af C |
160 | include: [ |
161 | { | |
03e12d7c | 162 | attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ], |
0626e7af C |
163 | model: ActorModel.unscoped(), |
164 | required: true, | |
0626e7af C |
165 | include: [ |
166 | { | |
167 | attributes: [ 'host' ], | |
168 | model: ServerModel.unscoped(), | |
169 | required: false | |
170 | }, | |
171 | { | |
172 | model: AvatarModel.unscoped(), | |
173 | required: false | |
174 | } | |
175 | ] | |
176 | } | |
177 | ] | |
178 | } | |
179 | ||
48dce1c9 | 180 | const videoChannelInclude = { |
0f320037 | 181 | attributes: [ 'name', 'description', 'id' ], |
48dce1c9 C |
182 | model: VideoChannelModel.unscoped(), |
183 | required: true, | |
48dce1c9 | 184 | include: [ |
0f320037 C |
185 | { |
186 | attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ], | |
187 | model: ActorModel.unscoped(), | |
188 | required: true, | |
189 | include: [ | |
190 | { | |
191 | attributes: [ 'host' ], | |
192 | model: ServerModel.unscoped(), | |
193 | required: false | |
194 | }, | |
195 | { | |
196 | model: AvatarModel.unscoped(), | |
197 | required: false | |
198 | } | |
199 | ] | |
200 | }, | |
48dce1c9 C |
201 | accountInclude |
202 | ] | |
203 | } | |
204 | ||
244e76a5 | 205 | const query: IFindOptions<VideoModel> = { |
afd2cba5 C |
206 | where: { |
207 | id: { | |
8ea6f49a | 208 | [ Sequelize.Op.any ]: options.ids |
afd2cba5 C |
209 | } |
210 | }, | |
211 | include: [ videoChannelInclude ] | |
212 | } | |
213 | ||
214 | if (options.withFiles === true) { | |
215 | query.include.push({ | |
216 | model: VideoFileModel.unscoped(), | |
217 | required: true | |
218 | }) | |
219 | } | |
220 | ||
221 | return query | |
222 | }, | |
8ea6f49a | 223 | [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => { |
afd2cba5 | 224 | const query: IFindOptions<VideoModel> = { |
2b62cccd | 225 | raw: true, |
afd2cba5 | 226 | attributes: [ 'id' ], |
244e76a5 RK |
227 | where: { |
228 | id: { | |
8ea6f49a | 229 | [ Sequelize.Op.and ]: [ |
b6314e3c C |
230 | { |
231 | [ Sequelize.Op.notIn ]: Sequelize.literal( | |
232 | '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' | |
233 | ) | |
234 | } | |
235 | ] | |
244e76a5 | 236 | }, |
2186386c C |
237 | // Always list public videos |
238 | privacy: VideoPrivacy.PUBLIC, | |
239 | // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding | |
240 | [ Sequelize.Op.or ]: [ | |
241 | { | |
242 | state: VideoState.PUBLISHED | |
243 | }, | |
244 | { | |
245 | [ Sequelize.Op.and ]: { | |
246 | state: VideoState.TO_TRANSCODE, | |
247 | waitTranscoding: false | |
248 | } | |
249 | } | |
250 | ] | |
50d6de9c | 251 | }, |
8ea6f49a | 252 | include: [] |
afd2cba5 C |
253 | } |
254 | ||
255 | if (options.filter || options.accountId || options.videoChannelId) { | |
256 | const videoChannelInclude: IIncludeOptions = { | |
257 | attributes: [], | |
258 | model: VideoChannelModel.unscoped(), | |
259 | required: true | |
260 | } | |
261 | ||
262 | if (options.videoChannelId) { | |
263 | videoChannelInclude.where = { | |
264 | id: options.videoChannelId | |
265 | } | |
266 | } | |
267 | ||
268 | if (options.filter || options.accountId) { | |
269 | const accountInclude: IIncludeOptions = { | |
270 | attributes: [], | |
271 | model: AccountModel.unscoped(), | |
272 | required: true | |
273 | } | |
274 | ||
275 | if (options.filter) { | |
276 | accountInclude.include = [ | |
277 | { | |
278 | attributes: [], | |
279 | model: ActorModel.unscoped(), | |
280 | required: true, | |
281 | where: VideoModel.buildActorWhereWithFilter(options.filter) | |
282 | } | |
283 | ] | |
284 | } | |
285 | ||
286 | if (options.accountId) { | |
287 | accountInclude.where = { id: options.accountId } | |
288 | } | |
289 | ||
290 | videoChannelInclude.include = [ accountInclude ] | |
291 | } | |
292 | ||
293 | query.include.push(videoChannelInclude) | |
244e76a5 RK |
294 | } |
295 | ||
687d638c C |
296 | if (options.actorId) { |
297 | let localVideosReq = '' | |
298 | if (options.includeLocalVideos === true) { | |
299 | localVideosReq = ' UNION ALL ' + | |
300 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
301 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
302 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
303 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
304 | 'WHERE "actor"."serverId" IS NULL' | |
305 | } | |
306 | ||
307 | // Force actorId to be a number to avoid SQL injections | |
308 | const actorIdNumber = parseInt(options.actorId.toString(), 10) | |
8ea6f49a | 309 | query.where[ 'id' ][ Sequelize.Op.and ].push({ |
b6314e3c C |
310 | [ Sequelize.Op.in ]: Sequelize.literal( |
311 | '(' + | |
8ea6f49a C |
312 | 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' + |
313 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + | |
314 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
315 | ' UNION ALL ' + | |
316 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
317 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
318 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
319 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
320 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' + | |
321 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
322 | localVideosReq + | |
b6314e3c C |
323 | ')' |
324 | ) | |
325 | }) | |
687d638c C |
326 | } |
327 | ||
48dce1c9 | 328 | if (options.withFiles === true) { |
8ea6f49a | 329 | query.where[ 'id' ][ Sequelize.Op.and ].push({ |
b6314e3c C |
330 | [ Sequelize.Op.in ]: Sequelize.literal( |
331 | '(SELECT "videoId" FROM "videoFile")' | |
332 | ) | |
244e76a5 RK |
333 | }) |
334 | } | |
335 | ||
d525fc39 C |
336 | // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN() |
337 | if (options.tagsAllOf || options.tagsOneOf) { | |
338 | const createTagsIn = (tags: string[]) => { | |
339 | return tags.map(t => VideoModel.sequelize.escape(t)) | |
340 | .join(', ') | |
341 | } | |
342 | ||
343 | if (options.tagsOneOf) { | |
8ea6f49a C |
344 | query.where[ 'id' ][ Sequelize.Op.and ].push({ |
345 | [ Sequelize.Op.in ]: Sequelize.literal( | |
b6314e3c | 346 | '(' + |
d525fc39 C |
347 | 'SELECT "videoId" FROM "videoTag" ' + |
348 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
349 | 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' + | |
b6314e3c C |
350 | ')' |
351 | ) | |
352 | }) | |
d525fc39 C |
353 | } |
354 | ||
355 | if (options.tagsAllOf) { | |
8ea6f49a C |
356 | query.where[ 'id' ][ Sequelize.Op.and ].push({ |
357 | [ Sequelize.Op.in ]: Sequelize.literal( | |
d525fc39 | 358 | '(' + |
b6314e3c C |
359 | 'SELECT "videoId" FROM "videoTag" ' + |
360 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
361 | 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' + | |
362 | 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length + | |
d525fc39 | 363 | ')' |
b6314e3c C |
364 | ) |
365 | }) | |
d525fc39 C |
366 | } |
367 | } | |
368 | ||
369 | if (options.nsfw === true || options.nsfw === false) { | |
8ea6f49a | 370 | query.where[ 'nsfw' ] = options.nsfw |
d525fc39 C |
371 | } |
372 | ||
373 | if (options.categoryOneOf) { | |
8ea6f49a C |
374 | query.where[ 'category' ] = { |
375 | [ Sequelize.Op.or ]: options.categoryOneOf | |
d525fc39 C |
376 | } |
377 | } | |
378 | ||
379 | if (options.licenceOneOf) { | |
8ea6f49a C |
380 | query.where[ 'licence' ] = { |
381 | [ Sequelize.Op.or ]: options.licenceOneOf | |
d525fc39 | 382 | } |
0883b324 C |
383 | } |
384 | ||
d525fc39 | 385 | if (options.languageOneOf) { |
8ea6f49a C |
386 | query.where[ 'language' ] = { |
387 | [ Sequelize.Op.or ]: options.languageOneOf | |
d525fc39 | 388 | } |
61b909b9 P |
389 | } |
390 | ||
9a629c6e | 391 | if (options.trendingDays) { |
b36f41ca | 392 | query.include.push(VideoModel.buildTrendingQuery(options.trendingDays)) |
9a629c6e C |
393 | |
394 | query.subQuery = false | |
395 | } | |
396 | ||
244e76a5 RK |
397 | return query |
398 | }, | |
8ea6f49a | 399 | [ ScopeNames.WITH_ACCOUNT_DETAILS ]: { |
d48ff09d C |
400 | include: [ |
401 | { | |
6120941f | 402 | model: () => VideoChannelModel.unscoped(), |
d48ff09d C |
403 | required: true, |
404 | include: [ | |
6120941f C |
405 | { |
406 | attributes: { | |
407 | exclude: [ 'privateKey', 'publicKey' ] | |
408 | }, | |
3e500247 C |
409 | model: () => ActorModel.unscoped(), |
410 | required: true, | |
411 | include: [ | |
412 | { | |
413 | attributes: [ 'host' ], | |
414 | model: () => ServerModel.unscoped(), | |
415 | required: false | |
52d9f792 C |
416 | }, |
417 | { | |
418 | model: () => AvatarModel.unscoped(), | |
419 | required: false | |
3e500247 C |
420 | } |
421 | ] | |
6120941f | 422 | }, |
d48ff09d | 423 | { |
3e500247 | 424 | model: () => AccountModel.unscoped(), |
d48ff09d C |
425 | required: true, |
426 | include: [ | |
427 | { | |
3e500247 | 428 | model: () => ActorModel.unscoped(), |
6120941f C |
429 | attributes: { |
430 | exclude: [ 'privateKey', 'publicKey' ] | |
431 | }, | |
50d6de9c C |
432 | required: true, |
433 | include: [ | |
434 | { | |
3e500247 C |
435 | attributes: [ 'host' ], |
436 | model: () => ServerModel.unscoped(), | |
50d6de9c | 437 | required: false |
b6a4fd6b C |
438 | }, |
439 | { | |
440 | model: () => AvatarModel.unscoped(), | |
441 | required: false | |
50d6de9c C |
442 | } |
443 | ] | |
d48ff09d C |
444 | } |
445 | ] | |
446 | } | |
447 | ] | |
448 | } | |
449 | ] | |
450 | }, | |
8ea6f49a | 451 | [ ScopeNames.WITH_TAGS ]: { |
d48ff09d C |
452 | include: [ () => TagModel ] |
453 | }, | |
8ea6f49a | 454 | [ ScopeNames.WITH_BLACKLISTED ]: { |
191764f3 C |
455 | include: [ |
456 | { | |
457 | attributes: [ 'id', 'reason' ], | |
458 | model: () => VideoBlacklistModel, | |
459 | required: false | |
460 | } | |
461 | ] | |
462 | }, | |
8ea6f49a | 463 | [ ScopeNames.WITH_FILES ]: { |
d48ff09d C |
464 | include: [ |
465 | { | |
e53f952e | 466 | model: () => VideoFileModel.unscoped(), |
c48e82b5 C |
467 | required: false, |
468 | include: [ | |
469 | { | |
627621c1 | 470 | attributes: [ 'fileUrl' ], |
c48e82b5 C |
471 | model: () => VideoRedundancyModel.unscoped(), |
472 | required: false | |
473 | } | |
474 | ] | |
d48ff09d C |
475 | } |
476 | ] | |
bbe0f064 | 477 | }, |
8ea6f49a | 478 | [ ScopeNames.WITH_SCHEDULED_UPDATE ]: { |
bbe0f064 C |
479 | include: [ |
480 | { | |
481 | model: () => ScheduleVideoUpdateModel.unscoped(), | |
482 | required: false | |
483 | } | |
484 | ] | |
d48ff09d C |
485 | } |
486 | }) | |
3fd3ab2d C |
487 | @Table({ |
488 | tableName: 'video', | |
57c36b27 | 489 | indexes |
3fd3ab2d C |
490 | }) |
491 | export class VideoModel extends Model<VideoModel> { | |
492 | ||
493 | @AllowNull(false) | |
494 | @Default(DataType.UUIDV4) | |
495 | @IsUUID(4) | |
496 | @Column(DataType.UUID) | |
497 | uuid: string | |
498 | ||
499 | @AllowNull(false) | |
500 | @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) | |
501 | @Column | |
502 | name: string | |
503 | ||
504 | @AllowNull(true) | |
505 | @Default(null) | |
506 | @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category')) | |
507 | @Column | |
508 | category: number | |
509 | ||
510 | @AllowNull(true) | |
511 | @Default(null) | |
512 | @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence')) | |
513 | @Column | |
514 | licence: number | |
515 | ||
516 | @AllowNull(true) | |
517 | @Default(null) | |
518 | @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language')) | |
9d3ef9fe C |
519 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max)) |
520 | language: string | |
3fd3ab2d C |
521 | |
522 | @AllowNull(false) | |
523 | @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) | |
524 | @Column | |
525 | privacy: number | |
526 | ||
527 | @AllowNull(false) | |
47564bbe | 528 | @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean')) |
3fd3ab2d C |
529 | @Column |
530 | nsfw: boolean | |
531 | ||
532 | @AllowNull(true) | |
533 | @Default(null) | |
534 | @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description')) | |
535 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) | |
536 | description: string | |
537 | ||
2422c46b C |
538 | @AllowNull(true) |
539 | @Default(null) | |
540 | @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support')) | |
541 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max)) | |
542 | support: string | |
543 | ||
3fd3ab2d C |
544 | @AllowNull(false) |
545 | @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) | |
546 | @Column | |
547 | duration: number | |
548 | ||
549 | @AllowNull(false) | |
550 | @Default(0) | |
551 | @IsInt | |
552 | @Min(0) | |
553 | @Column | |
554 | views: number | |
555 | ||
556 | @AllowNull(false) | |
557 | @Default(0) | |
558 | @IsInt | |
559 | @Min(0) | |
560 | @Column | |
561 | likes: number | |
562 | ||
563 | @AllowNull(false) | |
564 | @Default(0) | |
565 | @IsInt | |
566 | @Min(0) | |
567 | @Column | |
568 | dislikes: number | |
569 | ||
570 | @AllowNull(false) | |
571 | @Column | |
572 | remote: boolean | |
573 | ||
574 | @AllowNull(false) | |
575 | @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | |
576 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) | |
577 | url: string | |
578 | ||
47564bbe C |
579 | @AllowNull(false) |
580 | @Column | |
581 | commentsEnabled: boolean | |
582 | ||
2186386c C |
583 | @AllowNull(false) |
584 | @Column | |
585 | waitTranscoding: boolean | |
586 | ||
587 | @AllowNull(false) | |
588 | @Default(null) | |
589 | @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state')) | |
590 | @Column | |
591 | state: VideoState | |
592 | ||
3fd3ab2d C |
593 | @CreatedAt |
594 | createdAt: Date | |
595 | ||
596 | @UpdatedAt | |
597 | updatedAt: Date | |
598 | ||
2922e048 JLB |
599 | @AllowNull(false) |
600 | @Default(Sequelize.NOW) | |
601 | @Column | |
602 | publishedAt: Date | |
603 | ||
3fd3ab2d C |
604 | @ForeignKey(() => VideoChannelModel) |
605 | @Column | |
606 | channelId: number | |
607 | ||
608 | @BelongsTo(() => VideoChannelModel, { | |
feb4bdfd | 609 | foreignKey: { |
50d6de9c | 610 | allowNull: true |
feb4bdfd | 611 | }, |
6b738c7a | 612 | hooks: true |
feb4bdfd | 613 | }) |
3fd3ab2d | 614 | VideoChannel: VideoChannelModel |
7920c273 | 615 | |
3fd3ab2d | 616 | @BelongsToMany(() => TagModel, { |
7920c273 | 617 | foreignKey: 'videoId', |
3fd3ab2d C |
618 | through: () => VideoTagModel, |
619 | onDelete: 'CASCADE' | |
7920c273 | 620 | }) |
3fd3ab2d | 621 | Tags: TagModel[] |
55fa55a9 | 622 | |
3fd3ab2d | 623 | @HasMany(() => VideoAbuseModel, { |
55fa55a9 C |
624 | foreignKey: { |
625 | name: 'videoId', | |
626 | allowNull: false | |
627 | }, | |
628 | onDelete: 'cascade' | |
629 | }) | |
3fd3ab2d | 630 | VideoAbuses: VideoAbuseModel[] |
93e1258c | 631 | |
3fd3ab2d | 632 | @HasMany(() => VideoFileModel, { |
93e1258c C |
633 | foreignKey: { |
634 | name: 'videoId', | |
635 | allowNull: false | |
636 | }, | |
c48e82b5 | 637 | hooks: true, |
93e1258c C |
638 | onDelete: 'cascade' |
639 | }) | |
3fd3ab2d | 640 | VideoFiles: VideoFileModel[] |
e71bcc0f | 641 | |
3fd3ab2d | 642 | @HasMany(() => VideoShareModel, { |
e71bcc0f C |
643 | foreignKey: { |
644 | name: 'videoId', | |
645 | allowNull: false | |
646 | }, | |
647 | onDelete: 'cascade' | |
648 | }) | |
3fd3ab2d | 649 | VideoShares: VideoShareModel[] |
16b90975 | 650 | |
3fd3ab2d | 651 | @HasMany(() => AccountVideoRateModel, { |
16b90975 C |
652 | foreignKey: { |
653 | name: 'videoId', | |
654 | allowNull: false | |
655 | }, | |
656 | onDelete: 'cascade' | |
657 | }) | |
3fd3ab2d | 658 | AccountVideoRates: AccountVideoRateModel[] |
f285faa0 | 659 | |
da854ddd C |
660 | @HasMany(() => VideoCommentModel, { |
661 | foreignKey: { | |
662 | name: 'videoId', | |
663 | allowNull: false | |
664 | }, | |
f05a1c30 C |
665 | onDelete: 'cascade', |
666 | hooks: true | |
da854ddd C |
667 | }) |
668 | VideoComments: VideoCommentModel[] | |
669 | ||
9a629c6e C |
670 | @HasMany(() => VideoViewModel, { |
671 | foreignKey: { | |
672 | name: 'videoId', | |
673 | allowNull: false | |
674 | }, | |
675 | onDelete: 'cascade', | |
676 | hooks: true | |
677 | }) | |
678 | VideoViews: VideoViewModel[] | |
679 | ||
2baea0c7 C |
680 | @HasOne(() => ScheduleVideoUpdateModel, { |
681 | foreignKey: { | |
682 | name: 'videoId', | |
683 | allowNull: false | |
684 | }, | |
685 | onDelete: 'cascade' | |
686 | }) | |
687 | ScheduleVideoUpdate: ScheduleVideoUpdateModel | |
688 | ||
26b7305a C |
689 | @HasOne(() => VideoBlacklistModel, { |
690 | foreignKey: { | |
691 | name: 'videoId', | |
692 | allowNull: false | |
693 | }, | |
694 | onDelete: 'cascade' | |
695 | }) | |
696 | VideoBlacklist: VideoBlacklistModel | |
697 | ||
40e87e9e C |
698 | @HasMany(() => VideoCaptionModel, { |
699 | foreignKey: { | |
700 | name: 'videoId', | |
701 | allowNull: false | |
702 | }, | |
703 | onDelete: 'cascade', | |
704 | hooks: true, | |
8ea6f49a | 705 | [ 'separate' as any ]: true |
40e87e9e C |
706 | }) |
707 | VideoCaptions: VideoCaptionModel[] | |
708 | ||
f05a1c30 C |
709 | @BeforeDestroy |
710 | static async sendDelete (instance: VideoModel, options) { | |
711 | if (instance.isOwned()) { | |
712 | if (!instance.VideoChannel) { | |
713 | instance.VideoChannel = await instance.$get('VideoChannel', { | |
714 | include: [ | |
715 | { | |
716 | model: AccountModel, | |
717 | include: [ ActorModel ] | |
718 | } | |
719 | ], | |
720 | transaction: options.transaction | |
721 | }) as VideoChannelModel | |
722 | } | |
723 | ||
f05a1c30 C |
724 | return sendDeleteVideo(instance, options.transaction) |
725 | } | |
726 | ||
727 | return undefined | |
728 | } | |
729 | ||
6b738c7a | 730 | @BeforeDestroy |
40e87e9e | 731 | static async removeFiles (instance: VideoModel) { |
f05a1c30 | 732 | const tasks: Promise<any>[] = [] |
f285faa0 | 733 | |
8e0fd45e | 734 | logger.info('Removing files of video %s.', instance.url) |
6b738c7a | 735 | |
f05a1c30 | 736 | tasks.push(instance.removeThumbnail()) |
93e1258c | 737 | |
3fd3ab2d | 738 | if (instance.isOwned()) { |
f05a1c30 C |
739 | if (!Array.isArray(instance.VideoFiles)) { |
740 | instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[] | |
741 | } | |
742 | ||
743 | tasks.push(instance.removePreview()) | |
40298b02 | 744 | |
3fd3ab2d C |
745 | // Remove physical files and torrents |
746 | instance.VideoFiles.forEach(file => { | |
747 | tasks.push(instance.removeFile(file)) | |
748 | tasks.push(instance.removeTorrent(file)) | |
749 | }) | |
750 | } | |
40298b02 | 751 | |
6b738c7a C |
752 | // Do not wait video deletion because we could be in a transaction |
753 | Promise.all(tasks) | |
8ea6f49a C |
754 | .catch(err => { |
755 | logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }) | |
756 | }) | |
6b738c7a C |
757 | |
758 | return undefined | |
3fd3ab2d | 759 | } |
f285faa0 | 760 | |
3fd3ab2d | 761 | static list () { |
d48ff09d | 762 | return VideoModel.scope(ScopeNames.WITH_FILES).findAll() |
3fd3ab2d | 763 | } |
f285faa0 | 764 | |
50d6de9c | 765 | static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) { |
3fd3ab2d C |
766 | function getRawQuery (select: string) { |
767 | const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + | |
768 | 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + | |
50d6de9c C |
769 | 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' + |
770 | 'WHERE "Account"."actorId" = ' + actorId | |
3fd3ab2d C |
771 | const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + |
772 | 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + | |
50d6de9c | 773 | 'WHERE "VideoShare"."actorId" = ' + actorId |
558d7c23 | 774 | |
3fd3ab2d C |
775 | return `(${queryVideo}) UNION (${queryVideoShare})` |
776 | } | |
aaf61f38 | 777 | |
3fd3ab2d C |
778 | const rawQuery = getRawQuery('"Video"."id"') |
779 | const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') | |
780 | ||
781 | const query = { | |
782 | distinct: true, | |
783 | offset: start, | |
784 | limit: count, | |
9a629c6e | 785 | order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]), |
3fd3ab2d C |
786 | where: { |
787 | id: { | |
8ea6f49a | 788 | [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')') |
3c75ce12 | 789 | }, |
8ea6f49a | 790 | [ Sequelize.Op.or ]: [ |
3c75ce12 C |
791 | { privacy: VideoPrivacy.PUBLIC }, |
792 | { privacy: VideoPrivacy.UNLISTED } | |
793 | ] | |
3fd3ab2d C |
794 | }, |
795 | include: [ | |
40e87e9e C |
796 | { |
797 | attributes: [ 'language' ], | |
798 | model: VideoCaptionModel.unscoped(), | |
799 | required: false | |
800 | }, | |
3fd3ab2d | 801 | { |
1d230c44 | 802 | attributes: [ 'id', 'url' ], |
2c897999 | 803 | model: VideoShareModel.unscoped(), |
3fd3ab2d | 804 | required: false, |
e3d5ea4f C |
805 | // We only want videos shared by this actor |
806 | where: { | |
8ea6f49a | 807 | [ Sequelize.Op.and ]: [ |
e3d5ea4f C |
808 | { |
809 | id: { | |
8ea6f49a | 810 | [ Sequelize.Op.not ]: null |
e3d5ea4f C |
811 | } |
812 | }, | |
813 | { | |
814 | actorId | |
815 | } | |
816 | ] | |
817 | }, | |
50d6de9c C |
818 | include: [ |
819 | { | |
2c897999 C |
820 | attributes: [ 'id', 'url' ], |
821 | model: ActorModel.unscoped() | |
50d6de9c C |
822 | } |
823 | ] | |
3fd3ab2d C |
824 | }, |
825 | { | |
2c897999 | 826 | model: VideoChannelModel.unscoped(), |
3fd3ab2d C |
827 | required: true, |
828 | include: [ | |
829 | { | |
2c897999 C |
830 | attributes: [ 'name' ], |
831 | model: AccountModel.unscoped(), | |
832 | required: true, | |
833 | include: [ | |
834 | { | |
e3d5ea4f | 835 | attributes: [ 'id', 'url', 'followersUrl' ], |
2c897999 C |
836 | model: ActorModel.unscoped(), |
837 | required: true | |
838 | } | |
839 | ] | |
840 | }, | |
841 | { | |
e3d5ea4f | 842 | attributes: [ 'id', 'url', 'followersUrl' ], |
2c897999 | 843 | model: ActorModel.unscoped(), |
3fd3ab2d C |
844 | required: true |
845 | } | |
846 | ] | |
847 | }, | |
3fd3ab2d | 848 | VideoFileModel, |
2c897999 | 849 | TagModel |
3fd3ab2d C |
850 | ] |
851 | } | |
164174a6 | 852 | |
3fd3ab2d C |
853 | return Bluebird.all([ |
854 | // FIXME: typing issue | |
855 | VideoModel.findAll(query as any), | |
856 | VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT }) | |
857 | ]).then(([ rows, totals ]) => { | |
858 | // totals: totalVideos + totalVideoShares | |
859 | let totalVideos = 0 | |
860 | let totalVideoShares = 0 | |
8ea6f49a C |
861 | if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10) |
862 | if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10) | |
3fd3ab2d C |
863 | |
864 | const total = totalVideos + totalVideoShares | |
865 | return { | |
866 | data: rows, | |
867 | total: total | |
868 | } | |
869 | }) | |
870 | } | |
93e1258c | 871 | |
26b7305a | 872 | static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) { |
244e76a5 | 873 | const query: IFindOptions<VideoModel> = { |
3fd3ab2d C |
874 | offset: start, |
875 | limit: count, | |
9a629c6e | 876 | order: getVideoSort(sort), |
3fd3ab2d C |
877 | include: [ |
878 | { | |
879 | model: VideoChannelModel, | |
880 | required: true, | |
881 | include: [ | |
882 | { | |
883 | model: AccountModel, | |
884 | where: { | |
7b87d2d5 | 885 | id: accountId |
3fd3ab2d C |
886 | }, |
887 | required: true | |
888 | } | |
889 | ] | |
2baea0c7 C |
890 | }, |
891 | { | |
892 | model: ScheduleVideoUpdateModel, | |
893 | required: false | |
26b7305a C |
894 | }, |
895 | { | |
896 | model: VideoBlacklistModel, | |
897 | required: false | |
d48ff09d | 898 | } |
3fd3ab2d C |
899 | ] |
900 | } | |
d8755eed | 901 | |
244e76a5 RK |
902 | if (withFiles === true) { |
903 | query.include.push({ | |
904 | model: VideoFileModel.unscoped(), | |
905 | required: true | |
906 | }) | |
907 | } | |
908 | ||
3fd3ab2d C |
909 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { |
910 | return { | |
911 | data: rows, | |
912 | total: count | |
913 | } | |
914 | }) | |
915 | } | |
93e1258c | 916 | |
48dce1c9 | 917 | static async listForApi (options: { |
0626e7af C |
918 | start: number, |
919 | count: number, | |
920 | sort: string, | |
d525fc39 | 921 | nsfw: boolean, |
06a05d5f | 922 | includeLocalVideos: boolean, |
48dce1c9 | 923 | withFiles: boolean, |
d525fc39 C |
924 | categoryOneOf?: number[], |
925 | licenceOneOf?: number[], | |
926 | languageOneOf?: string[], | |
927 | tagsOneOf?: string[], | |
928 | tagsAllOf?: string[], | |
0626e7af | 929 | filter?: VideoFilter, |
48dce1c9 | 930 | accountId?: number, |
06a05d5f C |
931 | videoChannelId?: number, |
932 | actorId?: number | |
9a629c6e | 933 | trendingDays?: number |
7348b1fd | 934 | }, countVideos = true) { |
9a629c6e | 935 | const query: IFindOptions<VideoModel> = { |
48dce1c9 C |
936 | offset: options.start, |
937 | limit: options.count, | |
9a629c6e C |
938 | order: getVideoSort(options.sort) |
939 | } | |
940 | ||
941 | let trendingDays: number | |
942 | if (options.sort.endsWith('trending')) { | |
943 | trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS | |
944 | ||
945 | query.group = 'VideoModel.id' | |
3fd3ab2d | 946 | } |
93e1258c | 947 | |
687d638c C |
948 | // actorId === null has a meaning, so just check undefined |
949 | const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id | |
06a05d5f | 950 | |
afd2cba5 C |
951 | const queryOptions = { |
952 | actorId, | |
953 | nsfw: options.nsfw, | |
954 | categoryOneOf: options.categoryOneOf, | |
955 | licenceOneOf: options.licenceOneOf, | |
956 | languageOneOf: options.languageOneOf, | |
957 | tagsOneOf: options.tagsOneOf, | |
958 | tagsAllOf: options.tagsAllOf, | |
959 | filter: options.filter, | |
960 | withFiles: options.withFiles, | |
961 | accountId: options.accountId, | |
962 | videoChannelId: options.videoChannelId, | |
9a629c6e C |
963 | includeLocalVideos: options.includeLocalVideos, |
964 | trendingDays | |
48dce1c9 C |
965 | } |
966 | ||
7348b1fd | 967 | return VideoModel.getAvailableForApi(query, queryOptions, countVideos) |
93e1258c C |
968 | } |
969 | ||
0b18f4aa | 970 | static async searchAndPopulateAccountAndServer (options: { |
06a05d5f | 971 | includeLocalVideos: boolean |
d4112450 | 972 | search?: string |
0b18f4aa C |
973 | start?: number |
974 | count?: number | |
975 | sort?: string | |
976 | startDate?: string // ISO 8601 | |
977 | endDate?: string // ISO 8601 | |
978 | nsfw?: boolean | |
979 | categoryOneOf?: number[] | |
980 | licenceOneOf?: number[] | |
981 | languageOneOf?: string[] | |
982 | tagsOneOf?: string[] | |
983 | tagsAllOf?: string[] | |
984 | durationMin?: number // seconds | |
985 | durationMax?: number // seconds | |
986 | }) { | |
8ea6f49a | 987 | const whereAnd = [] |
d525fc39 C |
988 | |
989 | if (options.startDate || options.endDate) { | |
8ea6f49a | 990 | const publishedAtRange = {} |
d525fc39 | 991 | |
8ea6f49a C |
992 | if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate |
993 | if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate | |
d525fc39 C |
994 | |
995 | whereAnd.push({ publishedAt: publishedAtRange }) | |
996 | } | |
997 | ||
998 | if (options.durationMin || options.durationMax) { | |
8ea6f49a | 999 | const durationRange = {} |
d525fc39 | 1000 | |
8ea6f49a C |
1001 | if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin |
1002 | if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax | |
d525fc39 C |
1003 | |
1004 | whereAnd.push({ duration: durationRange }) | |
1005 | } | |
1006 | ||
d4112450 | 1007 | const attributesInclude = [] |
dbfd3e9b C |
1008 | const escapedSearch = VideoModel.sequelize.escape(options.search) |
1009 | const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%') | |
d4112450 C |
1010 | if (options.search) { |
1011 | whereAnd.push( | |
1012 | { | |
dbfd3e9b C |
1013 | id: { |
1014 | [ Sequelize.Op.in ]: Sequelize.literal( | |
1015 | '(' + | |
8ea6f49a C |
1016 | 'SELECT "video"."id" FROM "video" ' + |
1017 | 'WHERE ' + | |
1018 | 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' + | |
1019 | 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' + | |
1020 | 'UNION ALL ' + | |
1021 | 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' + | |
1022 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
1023 | 'WHERE "tag"."name" = ' + escapedSearch + | |
dbfd3e9b C |
1024 | ')' |
1025 | ) | |
1026 | } | |
d4112450 C |
1027 | } |
1028 | ) | |
1029 | ||
1030 | attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search)) | |
1031 | } | |
1032 | ||
1033 | // Cannot search on similarity if we don't have a search | |
1034 | if (!options.search) { | |
1035 | attributesInclude.push( | |
1036 | Sequelize.literal('0 as similarity') | |
1037 | ) | |
1038 | } | |
d525fc39 | 1039 | |
f05a1c30 | 1040 | const query: IFindOptions<VideoModel> = { |
57c36b27 | 1041 | attributes: { |
d4112450 | 1042 | include: attributesInclude |
57c36b27 | 1043 | }, |
d525fc39 C |
1044 | offset: options.start, |
1045 | limit: options.count, | |
9a629c6e | 1046 | order: getVideoSort(options.sort), |
d525fc39 C |
1047 | where: { |
1048 | [ Sequelize.Op.and ]: whereAnd | |
1049 | } | |
f05a1c30 C |
1050 | } |
1051 | ||
1052 | const serverActor = await getServerActor() | |
afd2cba5 C |
1053 | const queryOptions = { |
1054 | actorId: serverActor.id, | |
1055 | includeLocalVideos: options.includeLocalVideos, | |
1056 | nsfw: options.nsfw, | |
1057 | categoryOneOf: options.categoryOneOf, | |
1058 | licenceOneOf: options.licenceOneOf, | |
1059 | languageOneOf: options.languageOneOf, | |
1060 | tagsOneOf: options.tagsOneOf, | |
1061 | tagsAllOf: options.tagsAllOf | |
48dce1c9 | 1062 | } |
f05a1c30 | 1063 | |
afd2cba5 | 1064 | return VideoModel.getAvailableForApi(query, queryOptions) |
f05a1c30 C |
1065 | } |
1066 | ||
627621c1 C |
1067 | static load (id: number | string, t?: Sequelize.Transaction) { |
1068 | const where = VideoModel.buildWhereIdOrUUID(id) | |
1069 | const options = { | |
1070 | where, | |
1071 | transaction: t | |
3fd3ab2d | 1072 | } |
d8755eed | 1073 | |
627621c1 | 1074 | return VideoModel.findOne(options) |
3fd3ab2d | 1075 | } |
d8755eed | 1076 | |
627621c1 C |
1077 | static loadOnlyId (id: number | string, t?: Sequelize.Transaction) { |
1078 | const where = VideoModel.buildWhereIdOrUUID(id) | |
1079 | ||
3fd3ab2d | 1080 | const options = { |
627621c1 C |
1081 | attributes: [ 'id' ], |
1082 | where, | |
1083 | transaction: t | |
3fd3ab2d | 1084 | } |
72c7248b | 1085 | |
627621c1 C |
1086 | return VideoModel.findOne(options) |
1087 | } | |
1088 | ||
1089 | static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) { | |
1090 | return VideoModel.scope(ScopeNames.WITH_FILES) | |
1091 | .findById(id, { transaction: t, logging }) | |
3fd3ab2d | 1092 | } |
72c7248b | 1093 | |
627621c1 | 1094 | static loadByUUIDWithFile (uuid: string) { |
8fa5653a C |
1095 | const options = { |
1096 | where: { | |
1097 | uuid | |
1098 | } | |
1099 | } | |
1100 | ||
1101 | return VideoModel | |
1102 | .scope([ ScopeNames.WITH_FILES ]) | |
1103 | .findOne(options) | |
1104 | } | |
1105 | ||
4157cdb1 | 1106 | static loadByUrl (url: string, transaction?: Sequelize.Transaction) { |
627621c1 C |
1107 | const query: IFindOptions<VideoModel> = { |
1108 | where: { | |
1109 | url | |
4157cdb1 C |
1110 | }, |
1111 | transaction | |
627621c1 C |
1112 | } |
1113 | ||
4157cdb1 C |
1114 | return VideoModel.findOne(query) |
1115 | } | |
1116 | ||
1117 | static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) { | |
1118 | const query: IFindOptions<VideoModel> = { | |
1119 | where: { | |
1120 | url | |
1121 | }, | |
1122 | transaction | |
1123 | } | |
627621c1 C |
1124 | |
1125 | return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query) | |
1126 | } | |
1127 | ||
1128 | static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction) { | |
1129 | const where = VideoModel.buildWhereIdOrUUID(id) | |
1130 | ||
3fd3ab2d C |
1131 | const options = { |
1132 | order: [ [ 'Tags', 'name', 'ASC' ] ], | |
627621c1 | 1133 | where, |
2186386c | 1134 | transaction: t |
3fd3ab2d | 1135 | } |
fd45e8f4 | 1136 | |
d48ff09d | 1137 | return VideoModel |
191764f3 C |
1138 | .scope([ |
1139 | ScopeNames.WITH_TAGS, | |
1140 | ScopeNames.WITH_BLACKLISTED, | |
1141 | ScopeNames.WITH_FILES, | |
1142 | ScopeNames.WITH_ACCOUNT_DETAILS, | |
1143 | ScopeNames.WITH_SCHEDULED_UPDATE | |
1144 | ]) | |
da854ddd C |
1145 | .findOne(options) |
1146 | } | |
1147 | ||
09cababd C |
1148 | static async getStats () { |
1149 | const totalLocalVideos = await VideoModel.count({ | |
1150 | where: { | |
1151 | remote: false | |
1152 | } | |
1153 | }) | |
1154 | const totalVideos = await VideoModel.count() | |
1155 | ||
1156 | let totalLocalVideoViews = await VideoModel.sum('views', { | |
1157 | where: { | |
1158 | remote: false | |
1159 | } | |
1160 | }) | |
1161 | // Sequelize could return null... | |
1162 | if (!totalLocalVideoViews) totalLocalVideoViews = 0 | |
1163 | ||
1164 | return { | |
1165 | totalLocalVideos, | |
1166 | totalLocalVideoViews, | |
1167 | totalVideos | |
1168 | } | |
1169 | } | |
1170 | ||
6b616860 C |
1171 | static incrementViews (id: number, views: number) { |
1172 | return VideoModel.increment('views', { | |
1173 | by: views, | |
1174 | where: { | |
1175 | id | |
1176 | } | |
1177 | }) | |
1178 | } | |
1179 | ||
2d3741d6 | 1180 | // threshold corresponds to how many video the field should have to be returned |
7348b1fd C |
1181 | static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) { |
1182 | const actorId = (await getServerActor()).id | |
1183 | ||
1184 | const scopeOptions = { | |
1185 | actorId, | |
1186 | includeLocalVideos: true | |
1187 | } | |
1188 | ||
2d3741d6 C |
1189 | const query: IFindOptions<VideoModel> = { |
1190 | attributes: [ field ], | |
1191 | limit: count, | |
1192 | group: field, | |
1193 | having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), { | |
8ea6f49a | 1194 | [ Sequelize.Op.gte ]: threshold |
2d3741d6 | 1195 | }) as any, // FIXME: typings |
2d3741d6 C |
1196 | order: [ this.sequelize.random() ] |
1197 | } | |
1198 | ||
7348b1fd C |
1199 | return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] }) |
1200 | .findAll(query) | |
8ea6f49a | 1201 | .then(rows => rows.map(r => r[ field ])) |
2d3741d6 C |
1202 | } |
1203 | ||
b36f41ca C |
1204 | static buildTrendingQuery (trendingDays: number) { |
1205 | return { | |
1206 | attributes: [], | |
1207 | subQuery: false, | |
1208 | model: VideoViewModel, | |
1209 | required: false, | |
1210 | where: { | |
1211 | startDate: { | |
1212 | [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays) | |
1213 | } | |
1214 | } | |
1215 | } | |
1216 | } | |
1217 | ||
066e94c5 C |
1218 | private static buildActorWhereWithFilter (filter?: VideoFilter) { |
1219 | if (filter && filter === 'local') { | |
1220 | return { | |
1221 | serverId: null | |
1222 | } | |
1223 | } | |
1224 | ||
1225 | return {} | |
1226 | } | |
afd2cba5 | 1227 | |
7348b1fd | 1228 | private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions, countVideos = true) { |
afd2cba5 C |
1229 | const idsScope = { |
1230 | method: [ | |
1231 | ScopeNames.AVAILABLE_FOR_LIST_IDS, options | |
1232 | ] | |
1233 | } | |
1234 | ||
8ea6f49a C |
1235 | // Remove trending sort on count, because it uses a group by |
1236 | const countOptions = Object.assign({}, options, { trendingDays: undefined }) | |
1237 | const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined }) | |
1238 | const countScope = { | |
1239 | method: [ | |
1240 | ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions | |
1241 | ] | |
1242 | } | |
1243 | ||
1244 | const [ count, rowsId ] = await Promise.all([ | |
7348b1fd | 1245 | countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve(undefined), |
8ea6f49a C |
1246 | VideoModel.scope(idsScope).findAll(query) |
1247 | ]) | |
afd2cba5 C |
1248 | const ids = rowsId.map(r => r.id) |
1249 | ||
1250 | if (ids.length === 0) return { data: [], total: count } | |
1251 | ||
1252 | const apiScope = { | |
1253 | method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ] | |
1254 | } | |
b6314e3c C |
1255 | |
1256 | const secondQuery = { | |
1257 | offset: 0, | |
1258 | limit: query.limit, | |
9a629c6e C |
1259 | attributes: query.attributes, |
1260 | order: [ // Keep original order | |
1261 | Sequelize.literal( | |
1262 | ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ') | |
1263 | ) | |
1264 | ] | |
b6314e3c C |
1265 | } |
1266 | const rows = await VideoModel.scope(apiScope).findAll(secondQuery) | |
afd2cba5 C |
1267 | |
1268 | return { | |
1269 | data: rows, | |
1270 | total: count | |
1271 | } | |
1272 | } | |
066e94c5 | 1273 | |
098eb377 | 1274 | static getCategoryLabel (id: number) { |
8ea6f49a | 1275 | return VIDEO_CATEGORIES[ id ] || 'Misc' |
ae5a3dd6 C |
1276 | } |
1277 | ||
098eb377 | 1278 | static getLicenceLabel (id: number) { |
8ea6f49a | 1279 | return VIDEO_LICENCES[ id ] || 'Unknown' |
ae5a3dd6 C |
1280 | } |
1281 | ||
098eb377 | 1282 | static getLanguageLabel (id: string) { |
8ea6f49a | 1283 | return VIDEO_LANGUAGES[ id ] || 'Unknown' |
ae5a3dd6 C |
1284 | } |
1285 | ||
098eb377 | 1286 | static getPrivacyLabel (id: number) { |
8ea6f49a | 1287 | return VIDEO_PRIVACIES[ id ] || 'Unknown' |
2186386c | 1288 | } |
2243730c | 1289 | |
098eb377 | 1290 | static getStateLabel (id: number) { |
8ea6f49a | 1291 | return VIDEO_STATES[ id ] || 'Unknown' |
2243730c C |
1292 | } |
1293 | ||
627621c1 C |
1294 | static buildWhereIdOrUUID (id: number | string) { |
1295 | return validator.isInt('' + id) ? { id } : { uuid: id } | |
1296 | } | |
1297 | ||
3fd3ab2d C |
1298 | getOriginalFile () { |
1299 | if (Array.isArray(this.VideoFiles) === false) return undefined | |
aaf61f38 | 1300 | |
3fd3ab2d C |
1301 | // The original file is the file that have the higher resolution |
1302 | return maxBy(this.VideoFiles, file => file.resolution) | |
e4f97bab | 1303 | } |
aaf61f38 | 1304 | |
3fd3ab2d C |
1305 | getVideoFilename (videoFile: VideoFileModel) { |
1306 | return this.uuid + '-' + videoFile.resolution + videoFile.extname | |
1307 | } | |
165cdc75 | 1308 | |
3fd3ab2d C |
1309 | getThumbnailName () { |
1310 | // We always have a copy of the thumbnail | |
1311 | const extension = '.jpg' | |
1312 | return this.uuid + extension | |
7b1f49de C |
1313 | } |
1314 | ||
3fd3ab2d C |
1315 | getPreviewName () { |
1316 | const extension = '.jpg' | |
1317 | return this.uuid + extension | |
1318 | } | |
7b1f49de | 1319 | |
3fd3ab2d C |
1320 | getTorrentFileName (videoFile: VideoFileModel) { |
1321 | const extension = '.torrent' | |
1322 | return this.uuid + '-' + videoFile.resolution + extension | |
1323 | } | |
8e7f08b5 | 1324 | |
3fd3ab2d C |
1325 | isOwned () { |
1326 | return this.remote === false | |
9567011b C |
1327 | } |
1328 | ||
3fd3ab2d | 1329 | createPreview (videoFile: VideoFileModel) { |
3fd3ab2d C |
1330 | return generateImageFromVideoFile( |
1331 | this.getVideoFilePath(videoFile), | |
1332 | CONFIG.STORAGE.PREVIEWS_DIR, | |
1333 | this.getPreviewName(), | |
26670720 | 1334 | PREVIEWS_SIZE |
3fd3ab2d C |
1335 | ) |
1336 | } | |
9567011b | 1337 | |
3fd3ab2d | 1338 | createThumbnail (videoFile: VideoFileModel) { |
3fd3ab2d C |
1339 | return generateImageFromVideoFile( |
1340 | this.getVideoFilePath(videoFile), | |
1341 | CONFIG.STORAGE.THUMBNAILS_DIR, | |
1342 | this.getThumbnailName(), | |
26670720 | 1343 | THUMBNAILS_SIZE |
3fd3ab2d | 1344 | ) |
14d3270f C |
1345 | } |
1346 | ||
02756fbd C |
1347 | getTorrentFilePath (videoFile: VideoFileModel) { |
1348 | return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1349 | } | |
1350 | ||
3fd3ab2d C |
1351 | getVideoFilePath (videoFile: VideoFileModel) { |
1352 | return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
1353 | } | |
14d3270f | 1354 | |
81e504b3 | 1355 | async createTorrentAndSetInfoHash (videoFile: VideoFileModel) { |
3fd3ab2d | 1356 | const options = { |
6cced8f9 C |
1357 | // Keep the extname, it's used by the client to stream the file inside a web browser |
1358 | name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`, | |
81e504b3 | 1359 | createdBy: 'PeerTube', |
3fd3ab2d | 1360 | announceList: [ |
0edf0581 C |
1361 | [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ], |
1362 | [ CONFIG.WEBSERVER.URL + '/tracker/announce' ] | |
3fd3ab2d | 1363 | ], |
c48e82b5 | 1364 | urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ] |
3fd3ab2d | 1365 | } |
14d3270f | 1366 | |
3fd3ab2d | 1367 | const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) |
e4f97bab | 1368 | |
3fd3ab2d C |
1369 | const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) |
1370 | logger.info('Creating torrent %s.', filePath) | |
e4f97bab | 1371 | |
62689b94 | 1372 | await writeFile(filePath, torrent) |
e4f97bab | 1373 | |
3fd3ab2d C |
1374 | const parsedTorrent = parseTorrent(torrent) |
1375 | videoFile.infoHash = parsedTorrent.infoHash | |
1376 | } | |
e4f97bab | 1377 | |
40e87e9e | 1378 | getEmbedStaticPath () { |
3fd3ab2d C |
1379 | return '/videos/embed/' + this.uuid |
1380 | } | |
e4f97bab | 1381 | |
40e87e9e | 1382 | getThumbnailStaticPath () { |
3fd3ab2d | 1383 | return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()) |
e4f97bab | 1384 | } |
227d02fe | 1385 | |
40e87e9e | 1386 | getPreviewStaticPath () { |
3fd3ab2d C |
1387 | return join(STATIC_PATHS.PREVIEWS, this.getPreviewName()) |
1388 | } | |
40298b02 | 1389 | |
098eb377 C |
1390 | toFormattedJSON (options?: VideoFormattingJSONOptions): Video { |
1391 | return videoModelToFormattedJSON(this, options) | |
14d3270f | 1392 | } |
14d3270f | 1393 | |
2422c46b | 1394 | toFormattedDetailsJSON (): VideoDetails { |
098eb377 | 1395 | return videoModelToFormattedDetailsJSON(this) |
244e76a5 RK |
1396 | } |
1397 | ||
1398 | getFormattedVideoFilesJSON (): VideoFile[] { | |
098eb377 | 1399 | return videoFilesModelToFormattedJSON(this, this.VideoFiles) |
3fd3ab2d | 1400 | } |
e4f97bab | 1401 | |
3fd3ab2d | 1402 | toActivityPubObject (): VideoTorrentObject { |
098eb377 | 1403 | return videoModelToActivityPubObject(this) |
3fd3ab2d C |
1404 | } |
1405 | ||
1406 | getTruncatedDescription () { | |
1407 | if (!this.description) return null | |
93e1258c | 1408 | |
bffbebbe | 1409 | const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max |
c73e83da | 1410 | return peertubeTruncate(this.description, maxLength) |
93e1258c C |
1411 | } |
1412 | ||
056aa7f2 | 1413 | getOriginalFileResolution () { |
3fd3ab2d | 1414 | const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) |
0d0e8dd0 | 1415 | |
056aa7f2 | 1416 | return getVideoFileResolution(originalFilePath) |
3fd3ab2d | 1417 | } |
0d0e8dd0 | 1418 | |
96f29c0f | 1419 | getDescriptionAPIPath () { |
3fd3ab2d | 1420 | return `/api/${API_VERSION}/videos/${this.uuid}/description` |
feb4bdfd C |
1421 | } |
1422 | ||
3fd3ab2d C |
1423 | removeThumbnail () { |
1424 | const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName()) | |
62689b94 | 1425 | return remove(thumbnailPath) |
ed31c059 | 1426 | .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err })) |
feb4bdfd C |
1427 | } |
1428 | ||
3fd3ab2d | 1429 | removePreview () { |
ed31c059 | 1430 | const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName()) |
62689b94 | 1431 | return remove(previewPath) |
ed31c059 | 1432 | .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err })) |
7920c273 C |
1433 | } |
1434 | ||
3fd3ab2d C |
1435 | removeFile (videoFile: VideoFileModel) { |
1436 | const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
62689b94 | 1437 | return remove(filePath) |
ed31c059 | 1438 | .catch(err => logger.warn('Cannot delete file %s.', filePath, { err })) |
feb4bdfd C |
1439 | } |
1440 | ||
3fd3ab2d C |
1441 | removeTorrent (videoFile: VideoFileModel) { |
1442 | const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
62689b94 | 1443 | return remove(torrentPath) |
ed31c059 | 1444 | .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) |
aaf61f38 C |
1445 | } |
1446 | ||
1297eb5d C |
1447 | isOutdated () { |
1448 | if (this.isOwned()) return false | |
1449 | ||
1450 | const now = Date.now() | |
1451 | const createdAtTime = this.createdAt.getTime() | |
1452 | const updatedAtTime = this.updatedAt.getTime() | |
1453 | ||
1454 | return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL && | |
1455 | (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL | |
1456 | } | |
1457 | ||
c48e82b5 | 1458 | getBaseUrls () { |
3fd3ab2d C |
1459 | let baseUrlHttp |
1460 | let baseUrlWs | |
7920c273 | 1461 | |
3fd3ab2d C |
1462 | if (this.isOwned()) { |
1463 | baseUrlHttp = CONFIG.WEBSERVER.URL | |
1464 | baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT | |
1465 | } else { | |
50d6de9c C |
1466 | baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host |
1467 | baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host | |
6fcd19ba | 1468 | } |
aaf61f38 | 1469 | |
3fd3ab2d | 1470 | return { baseUrlHttp, baseUrlWs } |
15d4ee04 | 1471 | } |
a96aed15 | 1472 | |
c48e82b5 C |
1473 | generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) { |
1474 | const xs = this.getTorrentUrl(videoFile, baseUrlHttp) | |
1475 | const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] | |
1476 | let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ] | |
1477 | ||
1478 | const redundancies = videoFile.RedundancyVideos | |
1479 | if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl)) | |
1480 | ||
1481 | const magnetHash = { | |
1482 | xs, | |
1483 | announce, | |
1484 | urlList, | |
1485 | infoHash: videoFile.infoHash, | |
1486 | name: this.name | |
1487 | } | |
1488 | ||
1489 | return magnetUtil.encode(magnetHash) | |
1490 | } | |
1491 | ||
1492 | getThumbnailUrl (baseUrlHttp: string) { | |
3fd3ab2d | 1493 | return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName() |
a96aed15 C |
1494 | } |
1495 | ||
c48e82b5 | 1496 | getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
3fd3ab2d C |
1497 | return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile) |
1498 | } | |
e4f97bab | 1499 | |
c48e82b5 | 1500 | getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
02756fbd C |
1501 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile) |
1502 | } | |
1503 | ||
c48e82b5 | 1504 | getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
3fd3ab2d C |
1505 | return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) |
1506 | } | |
a96aed15 | 1507 | |
c48e82b5 | 1508 | getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
02756fbd C |
1509 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile) |
1510 | } | |
a96aed15 | 1511 | } |