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