]>
Commit | Line | Data |
---|---|---|
39445ead | 1 | import * as Bluebird from 'bluebird' |
92e0f42e | 2 | import { maxBy, minBy } from 'lodash' |
098eb377 | 3 | import { join } from 'path' |
1735c825 C |
4 | import { |
5 | CountOptions, | |
6 | FindOptions, | |
7 | IncludeOptions, | |
8 | ModelIndexesOptions, | |
9 | Op, | |
10 | QueryTypes, | |
11 | ScopeOptions, | |
12 | Sequelize, | |
13 | Transaction, | |
14 | WhereOptions | |
15 | } from 'sequelize' | |
3fd3ab2d | 16 | import { |
4ba3b8ea C |
17 | AllowNull, |
18 | BeforeDestroy, | |
19 | BelongsTo, | |
20 | BelongsToMany, | |
21 | Column, | |
22 | CreatedAt, | |
23 | DataType, | |
24 | Default, | |
25 | ForeignKey, | |
26 | HasMany, | |
2baea0c7 | 27 | HasOne, |
4ba3b8ea C |
28 | Is, |
29 | IsInt, | |
30 | IsUUID, | |
31 | Min, | |
32 | Model, | |
33 | Scopes, | |
34 | Table, | |
9a629c6e | 35 | UpdatedAt |
3fd3ab2d | 36 | } from 'sequelize-typescript' |
453e83ea | 37 | import { UserRight, VideoPrivacy, VideoState } from '../../../shared' |
3fd3ab2d | 38 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' |
d7a25329 | 39 | import { Video, VideoDetails } from '../../../shared/models/videos' |
066e94c5 | 40 | import { VideoFilter } from '../../../shared/models/videos/video-query.type' |
30ff39e7 | 41 | import { peertubeTruncate } from '../../helpers/core-utils' |
da854ddd | 42 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' |
d7a25329 | 43 | import { isBooleanValid } from '../../helpers/custom-validators/misc' |
3fd3ab2d | 44 | import { |
4ba3b8ea C |
45 | isVideoCategoryValid, |
46 | isVideoDescriptionValid, | |
47 | isVideoDurationValid, | |
48 | isVideoLanguageValid, | |
49 | isVideoLicenceValid, | |
418d092a | 50 | isVideoNameValid, |
2baea0c7 C |
51 | isVideoPrivacyValid, |
52 | isVideoStateValid, | |
b64c950a | 53 | isVideoSupportValid |
3fd3ab2d | 54 | } from '../../helpers/custom-validators/videos' |
1735c825 | 55 | import { getVideoFileResolution } from '../../helpers/ffmpeg-utils' |
da854ddd | 56 | import { logger } from '../../helpers/logger' |
f05a1c30 | 57 | import { getServerActor } from '../../helpers/utils' |
65fcc311 | 58 | import { |
1297eb5d | 59 | ACTIVITY_PUB, |
4ba3b8ea | 60 | API_VERSION, |
418d092a | 61 | CONSTRAINTS_FIELDS, |
557b13ae | 62 | LAZY_STATIC_PATHS, |
4ba3b8ea | 63 | REMOTE_SCHEME, |
02756fbd | 64 | STATIC_DOWNLOAD_PATHS, |
4ba3b8ea | 65 | STATIC_PATHS, |
4ba3b8ea C |
66 | VIDEO_CATEGORIES, |
67 | VIDEO_LANGUAGES, | |
68 | VIDEO_LICENCES, | |
2baea0c7 | 69 | VIDEO_PRIVACIES, |
6dd9de95 C |
70 | VIDEO_STATES, |
71 | WEBSERVER | |
74dc3bca | 72 | } from '../../initializers/constants' |
50d6de9c | 73 | import { sendDeleteVideo } from '../../lib/activitypub/send' |
3fd3ab2d C |
74 | import { AccountModel } from '../account/account' |
75 | import { AccountVideoRateModel } from '../account/account-video-rate' | |
50d6de9c | 76 | import { ActorModel } from '../activitypub/actor' |
b6a4fd6b | 77 | import { AvatarModel } from '../avatar/avatar' |
3fd3ab2d | 78 | import { ServerModel } from '../server/server' |
418d092a C |
79 | import { |
80 | buildBlockedAccountSQL, | |
81 | buildTrigramSearchIndex, | |
82 | buildWhereIdOrUUID, | |
3caf77d3 | 83 | createSafeIn, |
418d092a | 84 | createSimilarityAttribute, |
6dd9de95 C |
85 | getVideoSort, |
86 | isOutdated, | |
418d092a C |
87 | throwIfNotValid |
88 | } from '../utils' | |
3fd3ab2d C |
89 | import { TagModel } from './tag' |
90 | import { VideoAbuseModel } from './video-abuse' | |
bfbd9128 | 91 | import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel' |
da854ddd | 92 | import { VideoCommentModel } from './video-comment' |
3fd3ab2d C |
93 | import { VideoFileModel } from './video-file' |
94 | import { VideoShareModel } from './video-share' | |
95 | import { VideoTagModel } from './video-tag' | |
2baea0c7 | 96 | import { ScheduleVideoUpdateModel } from './schedule-video-update' |
40e87e9e | 97 | import { VideoCaptionModel } from './video-caption' |
26b7305a | 98 | import { VideoBlacklistModel } from './video-blacklist' |
d7a25329 | 99 | import { remove } from 'fs-extra' |
9a629c6e | 100 | import { VideoViewModel } from './video-views' |
c48e82b5 | 101 | import { VideoRedundancyModel } from '../redundancy/video-redundancy' |
098eb377 C |
102 | import { |
103 | videoFilesModelToFormattedJSON, | |
104 | VideoFormattingJSONOptions, | |
105 | videoModelToActivityPubObject, | |
106 | videoModelToFormattedDetailsJSON, | |
107 | videoModelToFormattedJSON | |
108 | } from './video-format-utils' | |
6e46de09 | 109 | import { UserVideoHistoryModel } from '../account/user-video-history' |
dc133480 | 110 | import { VideoImportModel } from './video-import' |
09209296 | 111 | import { VideoStreamingPlaylistModel } from './video-streaming-playlist' |
418d092a | 112 | import { VideoPlaylistElementModel } from './video-playlist-element' |
6dd9de95 | 113 | import { CONFIG } from '../../initializers/config' |
e8bafea3 C |
114 | import { ThumbnailModel } from './thumbnail' |
115 | import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type' | |
e2600d8b | 116 | import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type' |
453e83ea C |
117 | import { |
118 | MChannel, | |
0283eaac | 119 | MChannelAccountDefault, |
453e83ea | 120 | MChannelId, |
d7a25329 C |
121 | MStreamingPlaylist, |
122 | MStreamingPlaylistFilesVideo, | |
453e83ea C |
123 | MUserAccountId, |
124 | MUserId, | |
453e83ea | 125 | MVideoAccountLight, |
0283eaac | 126 | MVideoAccountLightBlacklistAllFiles, |
b5fecbf4 | 127 | MVideoAP, |
453e83ea | 128 | MVideoDetails, |
d7a25329 | 129 | MVideoFileVideo, |
b5fecbf4 C |
130 | MVideoFormattable, |
131 | MVideoFormattableDetails, | |
0283eaac | 132 | MVideoForUser, |
453e83ea C |
133 | MVideoFullLight, |
134 | MVideoIdThumbnail, | |
135 | MVideoThumbnail, | |
d636ab58 | 136 | MVideoThumbnailBlacklist, |
b5fecbf4 C |
137 | MVideoWithAllFiles, |
138 | MVideoWithFile, | |
139 | MVideoWithRights | |
453e83ea | 140 | } from '../../typings/models' |
d7a25329 | 141 | import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file' |
453e83ea | 142 | import { MThumbnail } from '../../typings/models/video/thumbnail' |
d7a25329 | 143 | import { VideoFile } from '@shared/models/videos/video-file.model' |
3cf53828 C |
144 | import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths' |
145 | import * as validator from 'validator' | |
6e46de09 | 146 | |
57c36b27 | 147 | // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation |
1735c825 | 148 | const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [ |
57c36b27 C |
149 | buildTrigramSearchIndex('video_name_trigram', 'name'), |
150 | ||
8cd72bd3 C |
151 | { fields: [ 'createdAt' ] }, |
152 | { fields: [ 'publishedAt' ] }, | |
153 | { fields: [ 'duration' ] }, | |
8cd72bd3 | 154 | { fields: [ 'views' ] }, |
8cd72bd3 | 155 | { fields: [ 'channelId' ] }, |
7519127b C |
156 | { |
157 | fields: [ 'originallyPublishedAt' ], | |
158 | where: { | |
159 | originallyPublishedAt: { | |
1735c825 | 160 | [Op.ne]: null |
7519127b C |
161 | } |
162 | } | |
163 | }, | |
439b1744 C |
164 | { |
165 | fields: [ 'category' ], // We don't care videos with an unknown category | |
166 | where: { | |
167 | category: { | |
1735c825 | 168 | [Op.ne]: null |
439b1744 C |
169 | } |
170 | } | |
171 | }, | |
172 | { | |
173 | fields: [ 'licence' ], // We don't care videos with an unknown licence | |
174 | where: { | |
175 | licence: { | |
1735c825 | 176 | [Op.ne]: null |
439b1744 C |
177 | } |
178 | } | |
179 | }, | |
180 | { | |
181 | fields: [ 'language' ], // We don't care videos with an unknown language | |
182 | where: { | |
183 | language: { | |
1735c825 | 184 | [Op.ne]: null |
439b1744 C |
185 | } |
186 | } | |
187 | }, | |
188 | { | |
189 | fields: [ 'nsfw' ], // Most of the videos are not NSFW | |
190 | where: { | |
191 | nsfw: true | |
192 | } | |
193 | }, | |
194 | { | |
195 | fields: [ 'remote' ], // Only index local videos | |
196 | where: { | |
197 | remote: false | |
198 | } | |
199 | }, | |
57c36b27 | 200 | { |
8cd72bd3 C |
201 | fields: [ 'uuid' ], |
202 | unique: true | |
57c36b27 C |
203 | }, |
204 | { | |
8ea6f49a | 205 | fields: [ 'url' ], |
57c36b27 C |
206 | unique: true |
207 | } | |
208 | ] | |
209 | ||
2baea0c7 | 210 | export enum ScopeNames { |
afd2cba5 C |
211 | AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS', |
212 | FOR_API = 'FOR_API', | |
4cb6d457 | 213 | WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS', |
d48ff09d | 214 | WITH_TAGS = 'WITH_TAGS', |
d7a25329 | 215 | WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES', |
191764f3 | 216 | WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE', |
6e46de09 | 217 | WITH_BLACKLISTED = 'WITH_BLACKLISTED', |
bfbd9128 | 218 | WITH_BLOCKLIST = 'WITH_BLOCKLIST', |
09209296 C |
219 | WITH_USER_HISTORY = 'WITH_USER_HISTORY', |
220 | WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS', | |
e8bafea3 C |
221 | WITH_USER_ID = 'WITH_USER_ID', |
222 | WITH_THUMBNAILS = 'WITH_THUMBNAILS' | |
d48ff09d C |
223 | } |
224 | ||
bfbd9128 C |
225 | export type ForAPIOptions = { |
226 | ids?: number[] | |
418d092a C |
227 | |
228 | videoPlaylistId?: number | |
229 | ||
afd2cba5 | 230 | withFiles?: boolean |
bfbd9128 C |
231 | |
232 | withAccountBlockerIds?: number[] | |
afd2cba5 C |
233 | } |
234 | ||
bfbd9128 | 235 | export type AvailableForListIDsOptions = { |
7ad9b984 | 236 | serverAccountId: number |
4e74e803 | 237 | followerActorId: number |
afd2cba5 | 238 | includeLocalVideos: boolean |
418d092a | 239 | |
bfbd9128 | 240 | attributesType?: 'none' | 'id' | 'all' |
8519cc92 | 241 | |
afd2cba5 C |
242 | filter?: VideoFilter |
243 | categoryOneOf?: number[] | |
244 | nsfw?: boolean | |
245 | licenceOneOf?: number[] | |
246 | languageOneOf?: string[] | |
247 | tagsOneOf?: string[] | |
248 | tagsAllOf?: string[] | |
418d092a | 249 | |
afd2cba5 | 250 | withFiles?: boolean |
418d092a | 251 | |
afd2cba5 | 252 | accountId?: number |
d525fc39 | 253 | videoChannelId?: number |
418d092a C |
254 | |
255 | videoPlaylistId?: number | |
256 | ||
9a629c6e | 257 | trendingDays?: number |
453e83ea C |
258 | user?: MUserAccountId |
259 | historyOfUser?: MUserId | |
3caf77d3 C |
260 | |
261 | baseWhere?: WhereOptions[] | |
d525fc39 C |
262 | } |
263 | ||
3acc5084 | 264 | @Scopes(() => ({ |
8ea6f49a | 265 | [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => { |
1735c825 | 266 | const query: FindOptions = { |
418d092a C |
267 | include: [ |
268 | { | |
bfbd9128 C |
269 | model: VideoChannelModel.scope({ |
270 | method: [ | |
271 | VideoChannelScopeNames.SUMMARY, { | |
272 | withAccount: true, | |
273 | withAccountBlockerIds: options.withAccountBlockerIds | |
274 | } as SummaryOptions | |
275 | ] | |
276 | }), | |
76564702 | 277 | required: true |
2fb5b3a5 C |
278 | }, |
279 | { | |
280 | attributes: [ 'type', 'filename' ], | |
281 | model: ThumbnailModel, | |
282 | required: false | |
418d092a C |
283 | } |
284 | ] | |
afd2cba5 C |
285 | } |
286 | ||
bfbd9128 C |
287 | if (options.ids) { |
288 | query.where = { | |
289 | id: { | |
290 | [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken | |
291 | } | |
292 | } | |
293 | } | |
294 | ||
afd2cba5 C |
295 | if (options.withFiles === true) { |
296 | query.include.push({ | |
297 | model: VideoFileModel.unscoped(), | |
298 | required: true | |
299 | }) | |
300 | } | |
301 | ||
418d092a C |
302 | if (options.videoPlaylistId) { |
303 | query.include.push({ | |
304 | model: VideoPlaylistElementModel.unscoped(), | |
15e9d5ca C |
305 | required: true, |
306 | where: { | |
307 | videoPlaylistId: options.videoPlaylistId | |
308 | } | |
418d092a C |
309 | }) |
310 | } | |
311 | ||
afd2cba5 C |
312 | return query |
313 | }, | |
8ea6f49a | 314 | [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => { |
3caf77d3 | 315 | const whereAnd = options.baseWhere ? options.baseWhere : [] |
8519cc92 | 316 | |
1735c825 | 317 | const query: FindOptions = { |
2b62cccd | 318 | raw: true, |
1cd3facc C |
319 | include: [] |
320 | } | |
321 | ||
bfbd9128 C |
322 | const attributesType = options.attributesType || 'id' |
323 | ||
324 | if (attributesType === 'id') query.attributes = [ 'id' ] | |
325 | else if (attributesType === 'none') query.attributes = [ ] | |
326 | ||
3caf77d3 C |
327 | whereAnd.push({ |
328 | id: { | |
329 | [ Op.notIn ]: Sequelize.literal( | |
330 | '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' | |
331 | ) | |
332 | } | |
333 | }) | |
334 | ||
bfbd9128 C |
335 | if (options.serverAccountId) { |
336 | whereAnd.push({ | |
337 | channelId: { | |
338 | [ Op.notIn ]: Sequelize.literal( | |
339 | '(' + | |
340 | 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' + | |
341 | buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) + | |
342 | ')' + | |
343 | ')' | |
344 | ) | |
345 | } | |
346 | }) | |
347 | } | |
3caf77d3 | 348 | |
1cd3facc C |
349 | // Only list public/published videos |
350 | if (!options.filter || options.filter !== 'all-local') { | |
351 | const privacyWhere = { | |
2186386c C |
352 | // Always list public videos |
353 | privacy: VideoPrivacy.PUBLIC, | |
354 | // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding | |
1735c825 | 355 | [ Op.or ]: [ |
2186386c C |
356 | { |
357 | state: VideoState.PUBLISHED | |
358 | }, | |
359 | { | |
1735c825 | 360 | [ Op.and ]: { |
2186386c C |
361 | state: VideoState.TO_TRANSCODE, |
362 | waitTranscoding: false | |
363 | } | |
364 | } | |
365 | ] | |
1cd3facc C |
366 | } |
367 | ||
3caf77d3 | 368 | whereAnd.push(privacyWhere) |
afd2cba5 C |
369 | } |
370 | ||
418d092a C |
371 | if (options.videoPlaylistId) { |
372 | query.include.push({ | |
373 | attributes: [], | |
374 | model: VideoPlaylistElementModel.unscoped(), | |
375 | required: true, | |
376 | where: { | |
377 | videoPlaylistId: options.videoPlaylistId | |
378 | } | |
379 | }) | |
15e9d5ca C |
380 | |
381 | query.subQuery = false | |
418d092a C |
382 | } |
383 | ||
afd2cba5 | 384 | if (options.filter || options.accountId || options.videoChannelId) { |
1735c825 | 385 | const videoChannelInclude: IncludeOptions = { |
afd2cba5 C |
386 | attributes: [], |
387 | model: VideoChannelModel.unscoped(), | |
388 | required: true | |
389 | } | |
390 | ||
391 | if (options.videoChannelId) { | |
392 | videoChannelInclude.where = { | |
393 | id: options.videoChannelId | |
394 | } | |
395 | } | |
396 | ||
397 | if (options.filter || options.accountId) { | |
1735c825 | 398 | const accountInclude: IncludeOptions = { |
afd2cba5 C |
399 | attributes: [], |
400 | model: AccountModel.unscoped(), | |
401 | required: true | |
402 | } | |
403 | ||
404 | if (options.filter) { | |
405 | accountInclude.include = [ | |
406 | { | |
407 | attributes: [], | |
408 | model: ActorModel.unscoped(), | |
409 | required: true, | |
410 | where: VideoModel.buildActorWhereWithFilter(options.filter) | |
411 | } | |
412 | ] | |
413 | } | |
414 | ||
415 | if (options.accountId) { | |
416 | accountInclude.where = { id: options.accountId } | |
417 | } | |
418 | ||
419 | videoChannelInclude.include = [ accountInclude ] | |
420 | } | |
421 | ||
422 | query.include.push(videoChannelInclude) | |
244e76a5 RK |
423 | } |
424 | ||
4e74e803 | 425 | if (options.followerActorId) { |
687d638c C |
426 | let localVideosReq = '' |
427 | if (options.includeLocalVideos === true) { | |
428 | localVideosReq = ' UNION ALL ' + | |
429 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
430 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
431 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
432 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
433 | 'WHERE "actor"."serverId" IS NULL' | |
434 | } | |
435 | ||
436 | // Force actorId to be a number to avoid SQL injections | |
4e74e803 | 437 | const actorIdNumber = parseInt(options.followerActorId.toString(), 10) |
3caf77d3 C |
438 | whereAnd.push({ |
439 | id: { | |
440 | [ Op.in ]: Sequelize.literal( | |
441 | '(' + | |
442 | 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' + | |
443 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + | |
444 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
445 | ' UNION ALL ' + | |
446 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
447 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
448 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
449 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
450 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' + | |
451 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
452 | localVideosReq + | |
453 | ')' | |
454 | ) | |
455 | } | |
b6314e3c | 456 | }) |
687d638c C |
457 | } |
458 | ||
48dce1c9 | 459 | if (options.withFiles === true) { |
3caf77d3 C |
460 | whereAnd.push({ |
461 | id: { | |
462 | [ Op.in ]: Sequelize.literal( | |
463 | '(SELECT "videoId" FROM "videoFile")' | |
464 | ) | |
465 | } | |
244e76a5 RK |
466 | }) |
467 | } | |
468 | ||
d525fc39 C |
469 | // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN() |
470 | if (options.tagsAllOf || options.tagsOneOf) { | |
d525fc39 | 471 | if (options.tagsOneOf) { |
4b1f1b81 C |
472 | const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase()) |
473 | ||
3caf77d3 C |
474 | whereAnd.push({ |
475 | id: { | |
476 | [ Op.in ]: Sequelize.literal( | |
477 | '(' + | |
478 | 'SELECT "videoId" FROM "videoTag" ' + | |
479 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
4b1f1b81 | 480 | 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' + |
3caf77d3 C |
481 | ')' |
482 | ) | |
483 | } | |
b6314e3c | 484 | }) |
d525fc39 C |
485 | } |
486 | ||
487 | if (options.tagsAllOf) { | |
4b1f1b81 C |
488 | const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase()) |
489 | ||
3caf77d3 C |
490 | whereAnd.push({ |
491 | id: { | |
492 | [ Op.in ]: Sequelize.literal( | |
493 | '(' + | |
494 | 'SELECT "videoId" FROM "videoTag" ' + | |
495 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
4b1f1b81 C |
496 | 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' + |
497 | 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length + | |
3caf77d3 C |
498 | ')' |
499 | ) | |
500 | } | |
b6314e3c | 501 | }) |
d525fc39 C |
502 | } |
503 | } | |
504 | ||
505 | if (options.nsfw === true || options.nsfw === false) { | |
3caf77d3 | 506 | whereAnd.push({ nsfw: options.nsfw }) |
d525fc39 C |
507 | } |
508 | ||
509 | if (options.categoryOneOf) { | |
3caf77d3 C |
510 | whereAnd.push({ |
511 | category: { | |
512 | [ Op.or ]: options.categoryOneOf | |
513 | } | |
514 | }) | |
d525fc39 C |
515 | } |
516 | ||
517 | if (options.licenceOneOf) { | |
3caf77d3 C |
518 | whereAnd.push({ |
519 | licence: { | |
520 | [ Op.or ]: options.licenceOneOf | |
521 | } | |
522 | }) | |
0883b324 C |
523 | } |
524 | ||
d525fc39 | 525 | if (options.languageOneOf) { |
3caf77d3 C |
526 | let videoLanguages = options.languageOneOf |
527 | if (options.languageOneOf.find(l => l === '_unknown')) { | |
528 | videoLanguages = videoLanguages.concat([ null ]) | |
d525fc39 | 529 | } |
3caf77d3 C |
530 | |
531 | whereAnd.push({ | |
532 | [Op.or]: [ | |
533 | { | |
534 | language: { | |
535 | [ Op.or ]: videoLanguages | |
536 | } | |
537 | }, | |
538 | { | |
539 | id: { | |
540 | [ Op.in ]: Sequelize.literal( | |
541 | '(' + | |
542 | 'SELECT "videoId" FROM "videoCaption" ' + | |
543 | 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' + | |
544 | ')' | |
545 | ) | |
546 | } | |
547 | } | |
548 | ] | |
549 | }) | |
61b909b9 P |
550 | } |
551 | ||
9a629c6e | 552 | if (options.trendingDays) { |
b36f41ca | 553 | query.include.push(VideoModel.buildTrendingQuery(options.trendingDays)) |
9a629c6e C |
554 | |
555 | query.subQuery = false | |
556 | } | |
557 | ||
8b9a525a C |
558 | if (options.historyOfUser) { |
559 | query.include.push({ | |
560 | model: UserVideoHistoryModel, | |
561 | required: true, | |
562 | where: { | |
563 | userId: options.historyOfUser.id | |
564 | } | |
565 | }) | |
80bfd33c C |
566 | |
567 | // Even if the relation is n:m, we know that a user only have 0..1 video history | |
568 | // So we won't have multiple rows for the same video | |
569 | // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel | |
570 | query.subQuery = false | |
8b9a525a C |
571 | } |
572 | ||
3caf77d3 C |
573 | query.where = { |
574 | [ Op.and ]: whereAnd | |
575 | } | |
576 | ||
244e76a5 | 577 | return query |
bfbd9128 C |
578 | }, |
579 | [ScopeNames.WITH_BLOCKLIST]: { | |
580 | ||
244e76a5 | 581 | }, |
e8bafea3 C |
582 | [ ScopeNames.WITH_THUMBNAILS ]: { |
583 | include: [ | |
584 | { | |
3acc5084 | 585 | model: ThumbnailModel, |
e8bafea3 C |
586 | required: false |
587 | } | |
588 | ] | |
589 | }, | |
09209296 C |
590 | [ ScopeNames.WITH_USER_ID ]: { |
591 | include: [ | |
592 | { | |
593 | attributes: [ 'accountId' ], | |
3acc5084 | 594 | model: VideoChannelModel.unscoped(), |
09209296 C |
595 | required: true, |
596 | include: [ | |
597 | { | |
598 | attributes: [ 'userId' ], | |
3acc5084 | 599 | model: AccountModel.unscoped(), |
09209296 C |
600 | required: true |
601 | } | |
602 | ] | |
603 | } | |
3acc5084 | 604 | ] |
09209296 | 605 | }, |
8ea6f49a | 606 | [ ScopeNames.WITH_ACCOUNT_DETAILS ]: { |
d48ff09d C |
607 | include: [ |
608 | { | |
3acc5084 | 609 | model: VideoChannelModel.unscoped(), |
d48ff09d C |
610 | required: true, |
611 | include: [ | |
6120941f C |
612 | { |
613 | attributes: { | |
614 | exclude: [ 'privateKey', 'publicKey' ] | |
615 | }, | |
3acc5084 | 616 | model: ActorModel.unscoped(), |
3e500247 C |
617 | required: true, |
618 | include: [ | |
619 | { | |
620 | attributes: [ 'host' ], | |
3acc5084 | 621 | model: ServerModel.unscoped(), |
3e500247 | 622 | required: false |
52d9f792 C |
623 | }, |
624 | { | |
3acc5084 | 625 | model: AvatarModel.unscoped(), |
52d9f792 | 626 | required: false |
3e500247 C |
627 | } |
628 | ] | |
6120941f | 629 | }, |
d48ff09d | 630 | { |
3acc5084 | 631 | model: AccountModel.unscoped(), |
d48ff09d C |
632 | required: true, |
633 | include: [ | |
634 | { | |
3acc5084 | 635 | model: ActorModel.unscoped(), |
6120941f C |
636 | attributes: { |
637 | exclude: [ 'privateKey', 'publicKey' ] | |
638 | }, | |
50d6de9c C |
639 | required: true, |
640 | include: [ | |
641 | { | |
3e500247 | 642 | attributes: [ 'host' ], |
3acc5084 | 643 | model: ServerModel.unscoped(), |
50d6de9c | 644 | required: false |
b6a4fd6b C |
645 | }, |
646 | { | |
3acc5084 | 647 | model: AvatarModel.unscoped(), |
b6a4fd6b | 648 | required: false |
50d6de9c C |
649 | } |
650 | ] | |
d48ff09d C |
651 | } |
652 | ] | |
653 | } | |
654 | ] | |
655 | } | |
3acc5084 | 656 | ] |
d48ff09d | 657 | }, |
8ea6f49a | 658 | [ ScopeNames.WITH_TAGS ]: { |
3acc5084 | 659 | include: [ TagModel ] |
d48ff09d | 660 | }, |
8ea6f49a | 661 | [ ScopeNames.WITH_BLACKLISTED ]: { |
191764f3 C |
662 | include: [ |
663 | { | |
453e83ea | 664 | attributes: [ 'id', 'reason', 'unfederated' ], |
3acc5084 | 665 | model: VideoBlacklistModel, |
191764f3 C |
666 | required: false |
667 | } | |
668 | ] | |
669 | }, | |
d7a25329 | 670 | [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => { |
09209296 C |
671 | let subInclude: any[] = [] |
672 | ||
673 | if (withRedundancies === true) { | |
674 | subInclude = [ | |
675 | { | |
676 | attributes: [ 'fileUrl' ], | |
677 | model: VideoRedundancyModel.unscoped(), | |
678 | required: false | |
679 | } | |
680 | ] | |
681 | } | |
682 | ||
683 | return { | |
684 | include: [ | |
685 | { | |
686 | model: VideoFileModel.unscoped(), | |
3acc5084 | 687 | separate: true, // We may have multiple files, having multiple redundancies so let's separate this join |
09209296 C |
688 | required: false, |
689 | include: subInclude | |
690 | } | |
691 | ] | |
692 | } | |
693 | }, | |
694 | [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => { | |
d7a25329 C |
695 | const subInclude: IncludeOptions[] = [ |
696 | { | |
697 | model: VideoFileModel.unscoped(), | |
698 | required: false | |
699 | } | |
700 | ] | |
09209296 C |
701 | |
702 | if (withRedundancies === true) { | |
d7a25329 C |
703 | subInclude.push({ |
704 | attributes: [ 'fileUrl' ], | |
705 | model: VideoRedundancyModel.unscoped(), | |
706 | required: false | |
707 | }) | |
09209296 C |
708 | } |
709 | ||
710 | return { | |
711 | include: [ | |
712 | { | |
713 | model: VideoStreamingPlaylistModel.unscoped(), | |
3acc5084 | 714 | separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join |
09209296 C |
715 | required: false, |
716 | include: subInclude | |
717 | } | |
718 | ] | |
719 | } | |
bbe0f064 | 720 | }, |
8ea6f49a | 721 | [ ScopeNames.WITH_SCHEDULED_UPDATE ]: { |
bbe0f064 C |
722 | include: [ |
723 | { | |
3acc5084 | 724 | model: ScheduleVideoUpdateModel.unscoped(), |
bbe0f064 C |
725 | required: false |
726 | } | |
727 | ] | |
6e46de09 C |
728 | }, |
729 | [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => { | |
730 | return { | |
731 | include: [ | |
732 | { | |
733 | attributes: [ 'currentTime' ], | |
734 | model: UserVideoHistoryModel.unscoped(), | |
735 | required: false, | |
736 | where: { | |
737 | userId | |
738 | } | |
739 | } | |
740 | ] | |
741 | } | |
d48ff09d | 742 | } |
3acc5084 | 743 | })) |
3fd3ab2d C |
744 | @Table({ |
745 | tableName: 'video', | |
57c36b27 | 746 | indexes |
3fd3ab2d C |
747 | }) |
748 | export class VideoModel extends Model<VideoModel> { | |
749 | ||
750 | @AllowNull(false) | |
751 | @Default(DataType.UUIDV4) | |
752 | @IsUUID(4) | |
753 | @Column(DataType.UUID) | |
754 | uuid: string | |
755 | ||
756 | @AllowNull(false) | |
757 | @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) | |
758 | @Column | |
759 | name: string | |
760 | ||
761 | @AllowNull(true) | |
762 | @Default(null) | |
1735c825 | 763 | @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true)) |
3fd3ab2d C |
764 | @Column |
765 | category: number | |
766 | ||
767 | @AllowNull(true) | |
768 | @Default(null) | |
1735c825 | 769 | @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true)) |
3fd3ab2d C |
770 | @Column |
771 | licence: number | |
772 | ||
773 | @AllowNull(true) | |
774 | @Default(null) | |
1735c825 | 775 | @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true)) |
9d3ef9fe C |
776 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max)) |
777 | language: string | |
3fd3ab2d C |
778 | |
779 | @AllowNull(false) | |
780 | @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) | |
781 | @Column | |
782 | privacy: number | |
783 | ||
784 | @AllowNull(false) | |
47564bbe | 785 | @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean')) |
3fd3ab2d C |
786 | @Column |
787 | nsfw: boolean | |
788 | ||
789 | @AllowNull(true) | |
790 | @Default(null) | |
1735c825 | 791 | @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true)) |
3fd3ab2d C |
792 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) |
793 | description: string | |
794 | ||
2422c46b C |
795 | @AllowNull(true) |
796 | @Default(null) | |
1735c825 | 797 | @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true)) |
2422c46b C |
798 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max)) |
799 | support: string | |
800 | ||
3fd3ab2d C |
801 | @AllowNull(false) |
802 | @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) | |
803 | @Column | |
804 | duration: number | |
805 | ||
806 | @AllowNull(false) | |
807 | @Default(0) | |
808 | @IsInt | |
809 | @Min(0) | |
810 | @Column | |
811 | views: number | |
812 | ||
813 | @AllowNull(false) | |
814 | @Default(0) | |
815 | @IsInt | |
816 | @Min(0) | |
817 | @Column | |
818 | likes: number | |
819 | ||
820 | @AllowNull(false) | |
821 | @Default(0) | |
822 | @IsInt | |
823 | @Min(0) | |
824 | @Column | |
825 | dislikes: number | |
826 | ||
827 | @AllowNull(false) | |
828 | @Column | |
829 | remote: boolean | |
830 | ||
831 | @AllowNull(false) | |
832 | @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | |
833 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) | |
834 | url: string | |
835 | ||
47564bbe C |
836 | @AllowNull(false) |
837 | @Column | |
838 | commentsEnabled: boolean | |
839 | ||
156c50af LD |
840 | @AllowNull(false) |
841 | @Column | |
7f2cfe3a | 842 | downloadEnabled: boolean |
156c50af | 843 | |
2186386c C |
844 | @AllowNull(false) |
845 | @Column | |
846 | waitTranscoding: boolean | |
847 | ||
848 | @AllowNull(false) | |
849 | @Default(null) | |
850 | @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state')) | |
851 | @Column | |
852 | state: VideoState | |
853 | ||
3fd3ab2d C |
854 | @CreatedAt |
855 | createdAt: Date | |
856 | ||
857 | @UpdatedAt | |
858 | updatedAt: Date | |
859 | ||
2922e048 | 860 | @AllowNull(false) |
1735c825 | 861 | @Default(DataType.NOW) |
2922e048 JLB |
862 | @Column |
863 | publishedAt: Date | |
864 | ||
7519127b C |
865 | @AllowNull(true) |
866 | @Default(null) | |
c8034165 | 867 | @Column |
868 | originallyPublishedAt: Date | |
869 | ||
3fd3ab2d C |
870 | @ForeignKey(() => VideoChannelModel) |
871 | @Column | |
872 | channelId: number | |
873 | ||
874 | @BelongsTo(() => VideoChannelModel, { | |
feb4bdfd | 875 | foreignKey: { |
50d6de9c | 876 | allowNull: true |
feb4bdfd | 877 | }, |
6b738c7a | 878 | hooks: true |
feb4bdfd | 879 | }) |
3fd3ab2d | 880 | VideoChannel: VideoChannelModel |
7920c273 | 881 | |
3fd3ab2d | 882 | @BelongsToMany(() => TagModel, { |
7920c273 | 883 | foreignKey: 'videoId', |
3fd3ab2d C |
884 | through: () => VideoTagModel, |
885 | onDelete: 'CASCADE' | |
7920c273 | 886 | }) |
3fd3ab2d | 887 | Tags: TagModel[] |
55fa55a9 | 888 | |
e8bafea3 C |
889 | @HasMany(() => ThumbnailModel, { |
890 | foreignKey: { | |
891 | name: 'videoId', | |
892 | allowNull: true | |
893 | }, | |
894 | hooks: true, | |
895 | onDelete: 'cascade' | |
896 | }) | |
897 | Thumbnails: ThumbnailModel[] | |
898 | ||
418d092a C |
899 | @HasMany(() => VideoPlaylistElementModel, { |
900 | foreignKey: { | |
901 | name: 'videoId', | |
bfbd9128 | 902 | allowNull: true |
418d092a | 903 | }, |
bfbd9128 | 904 | onDelete: 'set null' |
418d092a C |
905 | }) |
906 | VideoPlaylistElements: VideoPlaylistElementModel[] | |
907 | ||
3fd3ab2d | 908 | @HasMany(() => VideoAbuseModel, { |
55fa55a9 C |
909 | foreignKey: { |
910 | name: 'videoId', | |
911 | allowNull: false | |
912 | }, | |
913 | onDelete: 'cascade' | |
914 | }) | |
3fd3ab2d | 915 | VideoAbuses: VideoAbuseModel[] |
93e1258c | 916 | |
3fd3ab2d | 917 | @HasMany(() => VideoFileModel, { |
93e1258c C |
918 | foreignKey: { |
919 | name: 'videoId', | |
d7a25329 | 920 | allowNull: true |
93e1258c | 921 | }, |
c48e82b5 | 922 | hooks: true, |
93e1258c C |
923 | onDelete: 'cascade' |
924 | }) | |
3fd3ab2d | 925 | VideoFiles: VideoFileModel[] |
e71bcc0f | 926 | |
09209296 C |
927 | @HasMany(() => VideoStreamingPlaylistModel, { |
928 | foreignKey: { | |
929 | name: 'videoId', | |
930 | allowNull: false | |
931 | }, | |
932 | hooks: true, | |
933 | onDelete: 'cascade' | |
934 | }) | |
935 | VideoStreamingPlaylists: VideoStreamingPlaylistModel[] | |
936 | ||
3fd3ab2d | 937 | @HasMany(() => VideoShareModel, { |
e71bcc0f C |
938 | foreignKey: { |
939 | name: 'videoId', | |
940 | allowNull: false | |
941 | }, | |
942 | onDelete: 'cascade' | |
943 | }) | |
3fd3ab2d | 944 | VideoShares: VideoShareModel[] |
16b90975 | 945 | |
3fd3ab2d | 946 | @HasMany(() => AccountVideoRateModel, { |
16b90975 C |
947 | foreignKey: { |
948 | name: 'videoId', | |
949 | allowNull: false | |
950 | }, | |
951 | onDelete: 'cascade' | |
952 | }) | |
3fd3ab2d | 953 | AccountVideoRates: AccountVideoRateModel[] |
f285faa0 | 954 | |
da854ddd C |
955 | @HasMany(() => VideoCommentModel, { |
956 | foreignKey: { | |
957 | name: 'videoId', | |
958 | allowNull: false | |
959 | }, | |
f05a1c30 C |
960 | onDelete: 'cascade', |
961 | hooks: true | |
da854ddd C |
962 | }) |
963 | VideoComments: VideoCommentModel[] | |
964 | ||
9a629c6e C |
965 | @HasMany(() => VideoViewModel, { |
966 | foreignKey: { | |
967 | name: 'videoId', | |
968 | allowNull: false | |
969 | }, | |
6e46de09 | 970 | onDelete: 'cascade' |
9a629c6e C |
971 | }) |
972 | VideoViews: VideoViewModel[] | |
973 | ||
6e46de09 C |
974 | @HasMany(() => UserVideoHistoryModel, { |
975 | foreignKey: { | |
976 | name: 'videoId', | |
977 | allowNull: false | |
978 | }, | |
979 | onDelete: 'cascade' | |
980 | }) | |
981 | UserVideoHistories: UserVideoHistoryModel[] | |
982 | ||
2baea0c7 C |
983 | @HasOne(() => ScheduleVideoUpdateModel, { |
984 | foreignKey: { | |
985 | name: 'videoId', | |
986 | allowNull: false | |
987 | }, | |
988 | onDelete: 'cascade' | |
989 | }) | |
990 | ScheduleVideoUpdate: ScheduleVideoUpdateModel | |
991 | ||
26b7305a C |
992 | @HasOne(() => VideoBlacklistModel, { |
993 | foreignKey: { | |
994 | name: 'videoId', | |
995 | allowNull: false | |
996 | }, | |
997 | onDelete: 'cascade' | |
998 | }) | |
999 | VideoBlacklist: VideoBlacklistModel | |
1000 | ||
dc133480 C |
1001 | @HasOne(() => VideoImportModel, { |
1002 | foreignKey: { | |
1003 | name: 'videoId', | |
1004 | allowNull: true | |
1005 | }, | |
1006 | onDelete: 'set null' | |
1007 | }) | |
1008 | VideoImport: VideoImportModel | |
1009 | ||
40e87e9e C |
1010 | @HasMany(() => VideoCaptionModel, { |
1011 | foreignKey: { | |
1012 | name: 'videoId', | |
1013 | allowNull: false | |
1014 | }, | |
1015 | onDelete: 'cascade', | |
1016 | hooks: true, | |
8ea6f49a | 1017 | [ 'separate' as any ]: true |
40e87e9e C |
1018 | }) |
1019 | VideoCaptions: VideoCaptionModel[] | |
1020 | ||
f05a1c30 | 1021 | @BeforeDestroy |
453e83ea | 1022 | static async sendDelete (instance: MVideoAccountLight, options) { |
f05a1c30 C |
1023 | if (instance.isOwned()) { |
1024 | if (!instance.VideoChannel) { | |
1025 | instance.VideoChannel = await instance.$get('VideoChannel', { | |
1026 | include: [ | |
453e83ea C |
1027 | ActorModel, |
1028 | AccountModel | |
f05a1c30 C |
1029 | ], |
1030 | transaction: options.transaction | |
0283eaac | 1031 | }) as MChannelAccountDefault |
f05a1c30 C |
1032 | } |
1033 | ||
f05a1c30 C |
1034 | return sendDeleteVideo(instance, options.transaction) |
1035 | } | |
1036 | ||
1037 | return undefined | |
1038 | } | |
1039 | ||
6b738c7a | 1040 | @BeforeDestroy |
40e87e9e | 1041 | static async removeFiles (instance: VideoModel) { |
f05a1c30 | 1042 | const tasks: Promise<any>[] = [] |
f285faa0 | 1043 | |
8e0fd45e | 1044 | logger.info('Removing files of video %s.', instance.url) |
6b738c7a | 1045 | |
3fd3ab2d | 1046 | if (instance.isOwned()) { |
f05a1c30 C |
1047 | if (!Array.isArray(instance.VideoFiles)) { |
1048 | instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[] | |
1049 | } | |
1050 | ||
3fd3ab2d C |
1051 | // Remove physical files and torrents |
1052 | instance.VideoFiles.forEach(file => { | |
1053 | tasks.push(instance.removeFile(file)) | |
1054 | tasks.push(instance.removeTorrent(file)) | |
1055 | }) | |
09209296 C |
1056 | |
1057 | // Remove playlists file | |
1058 | tasks.push(instance.removeStreamingPlaylist()) | |
3fd3ab2d | 1059 | } |
40298b02 | 1060 | |
6b738c7a C |
1061 | // Do not wait video deletion because we could be in a transaction |
1062 | Promise.all(tasks) | |
8ea6f49a C |
1063 | .catch(err => { |
1064 | logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }) | |
1065 | }) | |
6b738c7a C |
1066 | |
1067 | return undefined | |
3fd3ab2d | 1068 | } |
f285faa0 | 1069 | |
453e83ea | 1070 | static listLocal (): Bluebird<MVideoWithAllFiles[]> { |
9f1ddd24 C |
1071 | const query = { |
1072 | where: { | |
1073 | remote: false | |
1074 | } | |
1075 | } | |
1076 | ||
e8bafea3 | 1077 | return VideoModel.scope([ |
d7a25329 | 1078 | ScopeNames.WITH_WEBTORRENT_FILES, |
e8bafea3 C |
1079 | ScopeNames.WITH_STREAMING_PLAYLISTS, |
1080 | ScopeNames.WITH_THUMBNAILS | |
1081 | ]).findAll(query) | |
9f1ddd24 C |
1082 | } |
1083 | ||
50d6de9c | 1084 | static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) { |
3fd3ab2d C |
1085 | function getRawQuery (select: string) { |
1086 | const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + | |
1087 | 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + | |
50d6de9c C |
1088 | 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' + |
1089 | 'WHERE "Account"."actorId" = ' + actorId | |
3fd3ab2d C |
1090 | const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + |
1091 | 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + | |
50d6de9c | 1092 | 'WHERE "VideoShare"."actorId" = ' + actorId |
558d7c23 | 1093 | |
3fd3ab2d C |
1094 | return `(${queryVideo}) UNION (${queryVideoShare})` |
1095 | } | |
aaf61f38 | 1096 | |
3fd3ab2d C |
1097 | const rawQuery = getRawQuery('"Video"."id"') |
1098 | const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') | |
1099 | ||
1100 | const query = { | |
1101 | distinct: true, | |
1102 | offset: start, | |
1103 | limit: count, | |
1735c825 | 1104 | order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings |
3fd3ab2d C |
1105 | where: { |
1106 | id: { | |
1735c825 | 1107 | [ Op.in ]: Sequelize.literal('(' + rawQuery + ')') |
3c75ce12 | 1108 | }, |
1735c825 | 1109 | [ Op.or ]: [ |
3c75ce12 C |
1110 | { privacy: VideoPrivacy.PUBLIC }, |
1111 | { privacy: VideoPrivacy.UNLISTED } | |
1112 | ] | |
3fd3ab2d C |
1113 | }, |
1114 | include: [ | |
40e87e9e C |
1115 | { |
1116 | attributes: [ 'language' ], | |
1117 | model: VideoCaptionModel.unscoped(), | |
1118 | required: false | |
1119 | }, | |
3fd3ab2d | 1120 | { |
1d230c44 | 1121 | attributes: [ 'id', 'url' ], |
2c897999 | 1122 | model: VideoShareModel.unscoped(), |
3fd3ab2d | 1123 | required: false, |
e3d5ea4f C |
1124 | // We only want videos shared by this actor |
1125 | where: { | |
1735c825 | 1126 | [ Op.and ]: [ |
e3d5ea4f C |
1127 | { |
1128 | id: { | |
1735c825 | 1129 | [ Op.not ]: null |
e3d5ea4f C |
1130 | } |
1131 | }, | |
1132 | { | |
1133 | actorId | |
1134 | } | |
1135 | ] | |
1136 | }, | |
50d6de9c C |
1137 | include: [ |
1138 | { | |
2c897999 C |
1139 | attributes: [ 'id', 'url' ], |
1140 | model: ActorModel.unscoped() | |
50d6de9c C |
1141 | } |
1142 | ] | |
3fd3ab2d C |
1143 | }, |
1144 | { | |
2c897999 | 1145 | model: VideoChannelModel.unscoped(), |
3fd3ab2d C |
1146 | required: true, |
1147 | include: [ | |
1148 | { | |
2c897999 C |
1149 | attributes: [ 'name' ], |
1150 | model: AccountModel.unscoped(), | |
1151 | required: true, | |
1152 | include: [ | |
1153 | { | |
e3d5ea4f | 1154 | attributes: [ 'id', 'url', 'followersUrl' ], |
2c897999 C |
1155 | model: ActorModel.unscoped(), |
1156 | required: true | |
1157 | } | |
1158 | ] | |
1159 | }, | |
1160 | { | |
e3d5ea4f | 1161 | attributes: [ 'id', 'url', 'followersUrl' ], |
2c897999 | 1162 | model: ActorModel.unscoped(), |
3fd3ab2d C |
1163 | required: true |
1164 | } | |
1165 | ] | |
1166 | }, | |
3fd3ab2d | 1167 | VideoFileModel, |
2c897999 | 1168 | TagModel |
3fd3ab2d C |
1169 | ] |
1170 | } | |
164174a6 | 1171 | |
3fd3ab2d | 1172 | return Bluebird.all([ |
3acc5084 C |
1173 | VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query), |
1174 | VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT }) | |
3fd3ab2d C |
1175 | ]).then(([ rows, totals ]) => { |
1176 | // totals: totalVideos + totalVideoShares | |
1177 | let totalVideos = 0 | |
1178 | let totalVideoShares = 0 | |
3acc5084 C |
1179 | if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10) |
1180 | if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10) | |
3fd3ab2d C |
1181 | |
1182 | const total = totalVideos + totalVideoShares | |
1183 | return { | |
1184 | data: rows, | |
1185 | total: total | |
1186 | } | |
1187 | }) | |
1188 | } | |
93e1258c | 1189 | |
453e83ea | 1190 | static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) { |
3acc5084 C |
1191 | function buildBaseQuery (): FindOptions { |
1192 | return { | |
1193 | offset: start, | |
1194 | limit: count, | |
1195 | order: getVideoSort(sort), | |
1196 | include: [ | |
1197 | { | |
1198 | model: VideoChannelModel, | |
1199 | required: true, | |
1200 | include: [ | |
1201 | { | |
1202 | model: AccountModel, | |
1203 | where: { | |
1204 | id: accountId | |
1205 | }, | |
1206 | required: true | |
1207 | } | |
1208 | ] | |
1209 | } | |
1210 | ] | |
1211 | } | |
3fd3ab2d | 1212 | } |
d8755eed | 1213 | |
3acc5084 C |
1214 | const countQuery = buildBaseQuery() |
1215 | const findQuery = buildBaseQuery() | |
1216 | ||
a18f275d C |
1217 | const findScopes = [ |
1218 | ScopeNames.WITH_SCHEDULED_UPDATE, | |
1219 | ScopeNames.WITH_BLACKLISTED, | |
1220 | ScopeNames.WITH_THUMBNAILS | |
1221 | ] | |
3acc5084 | 1222 | |
3acc5084 C |
1223 | return Promise.all([ |
1224 | VideoModel.count(countQuery), | |
0283eaac | 1225 | VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery) |
3acc5084 C |
1226 | ]).then(([ count, rows ]) => { |
1227 | return { | |
0283eaac | 1228 | data: rows, |
3acc5084 C |
1229 | total: count |
1230 | } | |
1231 | }) | |
3fd3ab2d | 1232 | } |
93e1258c | 1233 | |
48dce1c9 | 1234 | static async listForApi (options: { |
0626e7af C |
1235 | start: number, |
1236 | count: number, | |
1237 | sort: string, | |
d525fc39 | 1238 | nsfw: boolean, |
06a05d5f | 1239 | includeLocalVideos: boolean, |
48dce1c9 | 1240 | withFiles: boolean, |
d525fc39 C |
1241 | categoryOneOf?: number[], |
1242 | licenceOneOf?: number[], | |
1243 | languageOneOf?: string[], | |
1244 | tagsOneOf?: string[], | |
1245 | tagsAllOf?: string[], | |
0626e7af | 1246 | filter?: VideoFilter, |
48dce1c9 | 1247 | accountId?: number, |
06a05d5f | 1248 | videoChannelId?: number, |
4e74e803 | 1249 | followerActorId?: number |
418d092a | 1250 | videoPlaylistId?: number, |
6e46de09 | 1251 | trendingDays?: number, |
453e83ea C |
1252 | user?: MUserAccountId, |
1253 | historyOfUser?: MUserId | |
7348b1fd | 1254 | }, countVideos = true) { |
7ad9b984 C |
1255 | if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) { |
1256 | throw new Error('Try to filter all-local but no user has not the see all videos right') | |
1cd3facc C |
1257 | } |
1258 | ||
3caf77d3 | 1259 | const query: FindOptions & { where?: null } = { |
48dce1c9 C |
1260 | offset: options.start, |
1261 | limit: options.count, | |
9a629c6e C |
1262 | order: getVideoSort(options.sort) |
1263 | } | |
1264 | ||
1265 | let trendingDays: number | |
1266 | if (options.sort.endsWith('trending')) { | |
1267 | trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS | |
1268 | ||
1269 | query.group = 'VideoModel.id' | |
3fd3ab2d | 1270 | } |
93e1258c | 1271 | |
7ad9b984 C |
1272 | const serverActor = await getServerActor() |
1273 | ||
4e74e803 C |
1274 | // followerActorId === null has a meaning, so just check undefined |
1275 | const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id | |
06a05d5f | 1276 | |
afd2cba5 | 1277 | const queryOptions = { |
4e74e803 | 1278 | followerActorId, |
7ad9b984 | 1279 | serverAccountId: serverActor.Account.id, |
afd2cba5 C |
1280 | nsfw: options.nsfw, |
1281 | categoryOneOf: options.categoryOneOf, | |
1282 | licenceOneOf: options.licenceOneOf, | |
1283 | languageOneOf: options.languageOneOf, | |
1284 | tagsOneOf: options.tagsOneOf, | |
1285 | tagsAllOf: options.tagsAllOf, | |
1286 | filter: options.filter, | |
1287 | withFiles: options.withFiles, | |
1288 | accountId: options.accountId, | |
1289 | videoChannelId: options.videoChannelId, | |
418d092a | 1290 | videoPlaylistId: options.videoPlaylistId, |
9a629c6e | 1291 | includeLocalVideos: options.includeLocalVideos, |
7ad9b984 | 1292 | user: options.user, |
8b9a525a | 1293 | historyOfUser: options.historyOfUser, |
9a629c6e | 1294 | trendingDays |
48dce1c9 C |
1295 | } |
1296 | ||
7348b1fd | 1297 | return VideoModel.getAvailableForApi(query, queryOptions, countVideos) |
93e1258c C |
1298 | } |
1299 | ||
0b18f4aa | 1300 | static async searchAndPopulateAccountAndServer (options: { |
06a05d5f | 1301 | includeLocalVideos: boolean |
d4112450 | 1302 | search?: string |
0b18f4aa C |
1303 | start?: number |
1304 | count?: number | |
1305 | sort?: string | |
1306 | startDate?: string // ISO 8601 | |
1307 | endDate?: string // ISO 8601 | |
31d065cc AM |
1308 | originallyPublishedStartDate?: string |
1309 | originallyPublishedEndDate?: string | |
0b18f4aa C |
1310 | nsfw?: boolean |
1311 | categoryOneOf?: number[] | |
1312 | licenceOneOf?: number[] | |
1313 | languageOneOf?: string[] | |
1314 | tagsOneOf?: string[] | |
1315 | tagsAllOf?: string[] | |
1316 | durationMin?: number // seconds | |
1317 | durationMax?: number // seconds | |
453e83ea | 1318 | user?: MUserAccountId, |
1cd3facc | 1319 | filter?: VideoFilter |
0b18f4aa | 1320 | }) { |
8ea6f49a | 1321 | const whereAnd = [] |
d525fc39 C |
1322 | |
1323 | if (options.startDate || options.endDate) { | |
8ea6f49a | 1324 | const publishedAtRange = {} |
d525fc39 | 1325 | |
1735c825 C |
1326 | if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate |
1327 | if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate | |
d525fc39 C |
1328 | |
1329 | whereAnd.push({ publishedAt: publishedAtRange }) | |
1330 | } | |
1331 | ||
31d065cc AM |
1332 | if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) { |
1333 | const originallyPublishedAtRange = {} | |
1334 | ||
1735c825 C |
1335 | if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate |
1336 | if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate | |
31d065cc AM |
1337 | |
1338 | whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange }) | |
1339 | } | |
1340 | ||
d525fc39 | 1341 | if (options.durationMin || options.durationMax) { |
8ea6f49a | 1342 | const durationRange = {} |
d525fc39 | 1343 | |
1735c825 C |
1344 | if (options.durationMin) durationRange[ Op.gte ] = options.durationMin |
1345 | if (options.durationMax) durationRange[ Op.lte ] = options.durationMax | |
d525fc39 C |
1346 | |
1347 | whereAnd.push({ duration: durationRange }) | |
1348 | } | |
1349 | ||
d4112450 | 1350 | const attributesInclude = [] |
dbfd3e9b C |
1351 | const escapedSearch = VideoModel.sequelize.escape(options.search) |
1352 | const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%') | |
d4112450 | 1353 | if (options.search) { |
3cf53828 C |
1354 | const trigramSearch = { |
1355 | id: { | |
1356 | [ Op.in ]: Sequelize.literal( | |
1357 | '(' + | |
1358 | 'SELECT "video"."id" FROM "video" ' + | |
1359 | 'WHERE ' + | |
1360 | 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' + | |
1361 | 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' + | |
1362 | 'UNION ALL ' + | |
1363 | 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' + | |
1364 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
1365 | 'WHERE "tag"."name" = ' + escapedSearch + | |
1366 | ')' | |
1367 | ) | |
d4112450 | 1368 | } |
3cf53828 C |
1369 | } |
1370 | ||
1371 | if (validator.isUUID(options.search)) { | |
1372 | whereAnd.push({ | |
1373 | [Op.or]: [ | |
1374 | trigramSearch, | |
1375 | { | |
1376 | uuid: options.search | |
1377 | } | |
1378 | ] | |
1379 | }) | |
1380 | } else { | |
1381 | whereAnd.push(trigramSearch) | |
1382 | } | |
d4112450 C |
1383 | |
1384 | attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search)) | |
1385 | } | |
1386 | ||
1387 | // Cannot search on similarity if we don't have a search | |
1388 | if (!options.search) { | |
1389 | attributesInclude.push( | |
1390 | Sequelize.literal('0 as similarity') | |
1391 | ) | |
1392 | } | |
d525fc39 | 1393 | |
3caf77d3 | 1394 | const query = { |
57c36b27 | 1395 | attributes: { |
d4112450 | 1396 | include: attributesInclude |
57c36b27 | 1397 | }, |
d525fc39 C |
1398 | offset: options.start, |
1399 | limit: options.count, | |
3caf77d3 | 1400 | order: getVideoSort(options.sort) |
f05a1c30 C |
1401 | } |
1402 | ||
1403 | const serverActor = await getServerActor() | |
afd2cba5 | 1404 | const queryOptions = { |
4e74e803 | 1405 | followerActorId: serverActor.id, |
7ad9b984 | 1406 | serverAccountId: serverActor.Account.id, |
afd2cba5 C |
1407 | includeLocalVideos: options.includeLocalVideos, |
1408 | nsfw: options.nsfw, | |
1409 | categoryOneOf: options.categoryOneOf, | |
1410 | licenceOneOf: options.licenceOneOf, | |
1411 | languageOneOf: options.languageOneOf, | |
1412 | tagsOneOf: options.tagsOneOf, | |
6e46de09 | 1413 | tagsAllOf: options.tagsAllOf, |
7ad9b984 | 1414 | user: options.user, |
3caf77d3 C |
1415 | filter: options.filter, |
1416 | baseWhere: whereAnd | |
48dce1c9 | 1417 | } |
f05a1c30 | 1418 | |
afd2cba5 | 1419 | return VideoModel.getAvailableForApi(query, queryOptions) |
f05a1c30 C |
1420 | } |
1421 | ||
453e83ea | 1422 | static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> { |
418d092a | 1423 | const where = buildWhereIdOrUUID(id) |
627621c1 C |
1424 | const options = { |
1425 | where, | |
1426 | transaction: t | |
3fd3ab2d | 1427 | } |
d8755eed | 1428 | |
e8bafea3 | 1429 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) |
3fd3ab2d | 1430 | } |
d8755eed | 1431 | |
d636ab58 C |
1432 | static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> { |
1433 | const where = buildWhereIdOrUUID(id) | |
1434 | const options = { | |
1435 | where, | |
1436 | transaction: t | |
1437 | } | |
1438 | ||
1439 | return VideoModel.scope([ | |
1440 | ScopeNames.WITH_THUMBNAILS, | |
1441 | ScopeNames.WITH_BLACKLISTED | |
1442 | ]).findOne(options) | |
1443 | } | |
1444 | ||
453e83ea | 1445 | static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> { |
418d092a | 1446 | const where = buildWhereIdOrUUID(id) |
09209296 C |
1447 | const options = { |
1448 | where, | |
1449 | transaction: t | |
1450 | } | |
1451 | ||
e8bafea3 C |
1452 | return VideoModel.scope([ |
1453 | ScopeNames.WITH_BLACKLISTED, | |
1454 | ScopeNames.WITH_USER_ID, | |
1455 | ScopeNames.WITH_THUMBNAILS | |
1456 | ]).findOne(options) | |
09209296 C |
1457 | } |
1458 | ||
453e83ea | 1459 | static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> { |
418d092a | 1460 | const where = buildWhereIdOrUUID(id) |
627621c1 | 1461 | |
3fd3ab2d | 1462 | const options = { |
627621c1 C |
1463 | attributes: [ 'id' ], |
1464 | where, | |
1465 | transaction: t | |
3fd3ab2d | 1466 | } |
72c7248b | 1467 | |
e8bafea3 | 1468 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) |
627621c1 C |
1469 | } |
1470 | ||
453e83ea | 1471 | static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> { |
e2600d8b C |
1472 | const where = buildWhereIdOrUUID(id) |
1473 | ||
1474 | const query = { | |
1475 | where, | |
1476 | transaction: t, | |
1477 | logging | |
1478 | } | |
1479 | ||
e8bafea3 | 1480 | return VideoModel.scope([ |
d7a25329 | 1481 | ScopeNames.WITH_WEBTORRENT_FILES, |
e8bafea3 C |
1482 | ScopeNames.WITH_STREAMING_PLAYLISTS, |
1483 | ScopeNames.WITH_THUMBNAILS | |
e2600d8b | 1484 | ]).findOne(query) |
3fd3ab2d | 1485 | } |
72c7248b | 1486 | |
453e83ea | 1487 | static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> { |
8fa5653a C |
1488 | const options = { |
1489 | where: { | |
1490 | uuid | |
1491 | } | |
1492 | } | |
1493 | ||
e8bafea3 | 1494 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) |
8fa5653a C |
1495 | } |
1496 | ||
453e83ea | 1497 | static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> { |
1735c825 | 1498 | const query: FindOptions = { |
627621c1 C |
1499 | where: { |
1500 | url | |
4157cdb1 C |
1501 | }, |
1502 | transaction | |
627621c1 C |
1503 | } |
1504 | ||
e8bafea3 | 1505 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query) |
4157cdb1 C |
1506 | } |
1507 | ||
0283eaac | 1508 | static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> { |
1735c825 | 1509 | const query: FindOptions = { |
4157cdb1 C |
1510 | where: { |
1511 | url | |
1512 | }, | |
1513 | transaction | |
1514 | } | |
627621c1 | 1515 | |
09209296 C |
1516 | return VideoModel.scope([ |
1517 | ScopeNames.WITH_ACCOUNT_DETAILS, | |
d7a25329 | 1518 | ScopeNames.WITH_WEBTORRENT_FILES, |
e8bafea3 | 1519 | ScopeNames.WITH_STREAMING_PLAYLISTS, |
453e83ea C |
1520 | ScopeNames.WITH_THUMBNAILS, |
1521 | ScopeNames.WITH_BLACKLISTED | |
09209296 | 1522 | ]).findOne(query) |
627621c1 C |
1523 | } |
1524 | ||
453e83ea | 1525 | static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> { |
418d092a | 1526 | const where = buildWhereIdOrUUID(id) |
627621c1 | 1527 | |
3fd3ab2d | 1528 | const options = { |
3acc5084 | 1529 | order: [ [ 'Tags', 'name', 'ASC' ] ] as any, |
627621c1 | 1530 | where, |
2186386c | 1531 | transaction: t |
3fd3ab2d | 1532 | } |
fd45e8f4 | 1533 | |
3acc5084 | 1534 | const scopes: (string | ScopeOptions)[] = [ |
6e46de09 C |
1535 | ScopeNames.WITH_TAGS, |
1536 | ScopeNames.WITH_BLACKLISTED, | |
09209296 C |
1537 | ScopeNames.WITH_ACCOUNT_DETAILS, |
1538 | ScopeNames.WITH_SCHEDULED_UPDATE, | |
d7a25329 | 1539 | ScopeNames.WITH_WEBTORRENT_FILES, |
e8bafea3 C |
1540 | ScopeNames.WITH_STREAMING_PLAYLISTS, |
1541 | ScopeNames.WITH_THUMBNAILS | |
09209296 C |
1542 | ] |
1543 | ||
1544 | if (userId) { | |
3acc5084 | 1545 | scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] }) |
09209296 C |
1546 | } |
1547 | ||
1548 | return VideoModel | |
1549 | .scope(scopes) | |
1550 | .findOne(options) | |
1551 | } | |
1552 | ||
89cd1275 C |
1553 | static loadForGetAPI (parameters: { |
1554 | id: number | string, | |
1555 | t?: Transaction, | |
1556 | userId?: number | |
453e83ea | 1557 | }): Bluebird<MVideoDetails> { |
89cd1275 | 1558 | const { id, t, userId } = parameters |
418d092a | 1559 | const where = buildWhereIdOrUUID(id) |
09209296 C |
1560 | |
1561 | const options = { | |
1735c825 | 1562 | order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings |
09209296 C |
1563 | where, |
1564 | transaction: t | |
1565 | } | |
1566 | ||
3acc5084 | 1567 | const scopes: (string | ScopeOptions)[] = [ |
09209296 C |
1568 | ScopeNames.WITH_TAGS, |
1569 | ScopeNames.WITH_BLACKLISTED, | |
6e46de09 | 1570 | ScopeNames.WITH_ACCOUNT_DETAILS, |
09209296 | 1571 | ScopeNames.WITH_SCHEDULED_UPDATE, |
e8bafea3 | 1572 | ScopeNames.WITH_THUMBNAILS, |
d7a25329 | 1573 | { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] }, |
3acc5084 | 1574 | { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } |
6e46de09 C |
1575 | ] |
1576 | ||
1577 | if (userId) { | |
3acc5084 | 1578 | scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] }) |
6e46de09 C |
1579 | } |
1580 | ||
d48ff09d | 1581 | return VideoModel |
6e46de09 | 1582 | .scope(scopes) |
da854ddd C |
1583 | .findOne(options) |
1584 | } | |
1585 | ||
09cababd C |
1586 | static async getStats () { |
1587 | const totalLocalVideos = await VideoModel.count({ | |
1588 | where: { | |
1589 | remote: false | |
1590 | } | |
1591 | }) | |
1592 | const totalVideos = await VideoModel.count() | |
1593 | ||
1594 | let totalLocalVideoViews = await VideoModel.sum('views', { | |
1595 | where: { | |
1596 | remote: false | |
1597 | } | |
1598 | }) | |
1599 | // Sequelize could return null... | |
1600 | if (!totalLocalVideoViews) totalLocalVideoViews = 0 | |
1601 | ||
1602 | return { | |
1603 | totalLocalVideos, | |
1604 | totalLocalVideoViews, | |
1605 | totalVideos | |
1606 | } | |
1607 | } | |
1608 | ||
6b616860 C |
1609 | static incrementViews (id: number, views: number) { |
1610 | return VideoModel.increment('views', { | |
1611 | by: views, | |
1612 | where: { | |
1613 | id | |
1614 | } | |
1615 | }) | |
1616 | } | |
1617 | ||
8d427346 C |
1618 | static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) { |
1619 | // Instances only share videos | |
1620 | const query = 'SELECT 1 FROM "videoShare" ' + | |
1621 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + | |
1622 | 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' + | |
1623 | 'LIMIT 1' | |
1624 | ||
1625 | const options = { | |
d5d9b6d7 | 1626 | type: QueryTypes.SELECT as QueryTypes.SELECT, |
8d427346 C |
1627 | bind: { followerActorId, videoId }, |
1628 | raw: true | |
1629 | } | |
1630 | ||
1631 | return VideoModel.sequelize.query(query, options) | |
1632 | .then(results => results.length === 1) | |
1633 | } | |
1634 | ||
453e83ea | 1635 | static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) { |
7d14d4d2 C |
1636 | const options = { |
1637 | where: { | |
1638 | channelId: videoChannel.id | |
1639 | }, | |
1640 | transaction: t | |
1641 | } | |
1642 | ||
1643 | return VideoModel.update({ support: videoChannel.support }, options) | |
1644 | } | |
1645 | ||
453e83ea | 1646 | static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> { |
7d14d4d2 C |
1647 | const query = { |
1648 | attributes: [ 'id' ], | |
1649 | where: { | |
1650 | channelId: videoChannel.id | |
1651 | } | |
1652 | } | |
1653 | ||
1654 | return VideoModel.findAll(query) | |
1655 | .then(videos => videos.map(v => v.id)) | |
1656 | } | |
1657 | ||
2d3741d6 | 1658 | // threshold corresponds to how many video the field should have to be returned |
7348b1fd | 1659 | static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) { |
65b21c96 | 1660 | const serverActor = await getServerActor() |
4e74e803 | 1661 | const followerActorId = serverActor.id |
7348b1fd | 1662 | |
65b21c96 C |
1663 | const scopeOptions: AvailableForListIDsOptions = { |
1664 | serverAccountId: serverActor.Account.id, | |
4e74e803 | 1665 | followerActorId, |
8519cc92 | 1666 | includeLocalVideos: true, |
bfbd9128 | 1667 | attributesType: 'none' // Don't break aggregation |
7348b1fd C |
1668 | } |
1669 | ||
1735c825 | 1670 | const query: FindOptions = { |
2d3741d6 C |
1671 | attributes: [ field ], |
1672 | limit: count, | |
1673 | group: field, | |
3acc5084 C |
1674 | having: Sequelize.where( |
1675 | Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold } | |
1676 | ), | |
1735c825 | 1677 | order: [ (this.sequelize as any).random() ] |
2d3741d6 C |
1678 | } |
1679 | ||
7348b1fd C |
1680 | return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] }) |
1681 | .findAll(query) | |
8ea6f49a | 1682 | .then(rows => rows.map(r => r[ field ])) |
2d3741d6 C |
1683 | } |
1684 | ||
b36f41ca C |
1685 | static buildTrendingQuery (trendingDays: number) { |
1686 | return { | |
1687 | attributes: [], | |
1688 | subQuery: false, | |
1689 | model: VideoViewModel, | |
1690 | required: false, | |
1691 | where: { | |
1692 | startDate: { | |
1735c825 | 1693 | [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays) |
b36f41ca C |
1694 | } |
1695 | } | |
1696 | } | |
1697 | } | |
1698 | ||
066e94c5 | 1699 | private static buildActorWhereWithFilter (filter?: VideoFilter) { |
1cd3facc | 1700 | if (filter && (filter === 'local' || filter === 'all-local')) { |
066e94c5 C |
1701 | return { |
1702 | serverId: null | |
1703 | } | |
1704 | } | |
1705 | ||
1706 | return {} | |
1707 | } | |
afd2cba5 | 1708 | |
6e46de09 | 1709 | private static async getAvailableForApi ( |
3caf77d3 | 1710 | query: FindOptions & { where?: null }, // Forbid where field in query |
7ad9b984 | 1711 | options: AvailableForListIDsOptions, |
6e46de09 C |
1712 | countVideos = true |
1713 | ) { | |
1735c825 | 1714 | const idsScope: ScopeOptions = { |
afd2cba5 C |
1715 | method: [ |
1716 | ScopeNames.AVAILABLE_FOR_LIST_IDS, options | |
1717 | ] | |
1718 | } | |
1719 | ||
8ea6f49a C |
1720 | // Remove trending sort on count, because it uses a group by |
1721 | const countOptions = Object.assign({}, options, { trendingDays: undefined }) | |
1735c825 C |
1722 | const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined }) |
1723 | const countScope: ScopeOptions = { | |
8ea6f49a C |
1724 | method: [ |
1725 | ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions | |
1726 | ] | |
1727 | } | |
1728 | ||
3caf77d3 C |
1729 | const [ count, ids ] = await Promise.all([ |
1730 | countVideos | |
1731 | ? VideoModel.scope(countScope).count(countQuery) | |
1732 | : Promise.resolve<number>(undefined), | |
1733 | ||
1734 | VideoModel.scope(idsScope) | |
1735 | .findAll(query) | |
1736 | .then(rows => rows.map(r => r.id)) | |
8ea6f49a | 1737 | ]) |
afd2cba5 C |
1738 | |
1739 | if (ids.length === 0) return { data: [], total: count } | |
1740 | ||
1735c825 | 1741 | const secondQuery: FindOptions = { |
b6314e3c C |
1742 | offset: 0, |
1743 | limit: query.limit, | |
9a629c6e C |
1744 | attributes: query.attributes, |
1745 | order: [ // Keep original order | |
1746 | Sequelize.literal( | |
2ba92871 | 1747 | ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ') |
9a629c6e C |
1748 | ) |
1749 | ] | |
b6314e3c | 1750 | } |
df0b219d | 1751 | |
2fb5b3a5 | 1752 | const apiScope: (string | ScopeOptions)[] = [] |
df0b219d C |
1753 | |
1754 | if (options.user) { | |
1755 | apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] }) | |
df0b219d C |
1756 | } |
1757 | ||
1758 | apiScope.push({ | |
1759 | method: [ | |
1760 | ScopeNames.FOR_API, { | |
76564702 C |
1761 | ids, |
1762 | withFiles: options.withFiles, | |
df0b219d C |
1763 | videoPlaylistId: options.videoPlaylistId |
1764 | } as ForAPIOptions | |
1765 | ] | |
1766 | }) | |
1767 | ||
b6314e3c | 1768 | const rows = await VideoModel.scope(apiScope).findAll(secondQuery) |
afd2cba5 C |
1769 | |
1770 | return { | |
1771 | data: rows, | |
1772 | total: count | |
1773 | } | |
1774 | } | |
066e94c5 | 1775 | |
098eb377 | 1776 | static getCategoryLabel (id: number) { |
8ea6f49a | 1777 | return VIDEO_CATEGORIES[ id ] || 'Misc' |
ae5a3dd6 C |
1778 | } |
1779 | ||
098eb377 | 1780 | static getLicenceLabel (id: number) { |
8ea6f49a | 1781 | return VIDEO_LICENCES[ id ] || 'Unknown' |
ae5a3dd6 C |
1782 | } |
1783 | ||
098eb377 | 1784 | static getLanguageLabel (id: string) { |
8ea6f49a | 1785 | return VIDEO_LANGUAGES[ id ] || 'Unknown' |
ae5a3dd6 C |
1786 | } |
1787 | ||
098eb377 | 1788 | static getPrivacyLabel (id: number) { |
8ea6f49a | 1789 | return VIDEO_PRIVACIES[ id ] || 'Unknown' |
2186386c | 1790 | } |
2243730c | 1791 | |
098eb377 | 1792 | static getStateLabel (id: number) { |
8ea6f49a | 1793 | return VIDEO_STATES[ id ] || 'Unknown' |
2243730c C |
1794 | } |
1795 | ||
5b77537c C |
1796 | isBlacklisted () { |
1797 | return !!this.VideoBlacklist | |
1798 | } | |
1799 | ||
bfbd9128 C |
1800 | isBlocked () { |
1801 | return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) || | |
1802 | this.VideoChannel.Account.isBlocked() | |
1803 | } | |
1804 | ||
92e0f42e | 1805 | getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) { |
d7a25329 | 1806 | if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) { |
92e0f42e | 1807 | const file = fun(this.VideoFiles, file => file.resolution) |
d7a25329 C |
1808 | |
1809 | return Object.assign(file, { Video: this }) | |
1810 | } | |
1811 | ||
1812 | // No webtorrent files, try with streaming playlist files | |
1813 | if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) { | |
1814 | const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this }) | |
1815 | ||
92e0f42e | 1816 | const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution) |
d7a25329 C |
1817 | return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo }) |
1818 | } | |
aaf61f38 | 1819 | |
d7a25329 | 1820 | return undefined |
e4f97bab | 1821 | } |
aaf61f38 | 1822 | |
92e0f42e C |
1823 | getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo { |
1824 | return this.getQualityFileBy(maxBy) | |
1825 | } | |
1826 | ||
1827 | getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo { | |
1828 | return this.getQualityFileBy(minBy) | |
1829 | } | |
1830 | ||
d7a25329 | 1831 | getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo { |
29d4e137 C |
1832 | if (Array.isArray(this.VideoFiles) === false) return undefined |
1833 | ||
d7a25329 C |
1834 | const file = this.VideoFiles.find(f => f.resolution === resolution) |
1835 | if (!file) return undefined | |
1836 | ||
1837 | return Object.assign(file, { Video: this }) | |
29d4e137 C |
1838 | } |
1839 | ||
453e83ea | 1840 | async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) { |
3acc5084 C |
1841 | thumbnail.videoId = this.id |
1842 | ||
1843 | const savedThumbnail = await thumbnail.save({ transaction }) | |
1844 | ||
e8bafea3 C |
1845 | if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = [] |
1846 | ||
1847 | // Already have this thumbnail, skip | |
3acc5084 | 1848 | if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return |
e8bafea3 | 1849 | |
3acc5084 | 1850 | this.Thumbnails.push(savedThumbnail) |
e8bafea3 C |
1851 | } |
1852 | ||
e8bafea3 C |
1853 | generateThumbnailName () { |
1854 | return this.uuid + '.jpg' | |
7b1f49de C |
1855 | } |
1856 | ||
3acc5084 | 1857 | getMiniature () { |
e8bafea3 C |
1858 | if (Array.isArray(this.Thumbnails) === false) return undefined |
1859 | ||
3acc5084 | 1860 | return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE) |
e8bafea3 C |
1861 | } |
1862 | ||
1863 | generatePreviewName () { | |
1864 | return this.uuid + '.jpg' | |
1865 | } | |
1866 | ||
1867 | getPreview () { | |
1868 | if (Array.isArray(this.Thumbnails) === false) return undefined | |
1869 | ||
1870 | return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW) | |
3fd3ab2d | 1871 | } |
7b1f49de | 1872 | |
3fd3ab2d C |
1873 | isOwned () { |
1874 | return this.remote === false | |
9567011b C |
1875 | } |
1876 | ||
cef534ed C |
1877 | getWatchStaticPath () { |
1878 | return '/videos/watch/' + this.uuid | |
1879 | } | |
1880 | ||
40e87e9e | 1881 | getEmbedStaticPath () { |
3fd3ab2d C |
1882 | return '/videos/embed/' + this.uuid |
1883 | } | |
e4f97bab | 1884 | |
3acc5084 C |
1885 | getMiniatureStaticPath () { |
1886 | const thumbnail = this.getMiniature() | |
e8bafea3 C |
1887 | if (!thumbnail) return null |
1888 | ||
1889 | return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename) | |
e4f97bab | 1890 | } |
227d02fe | 1891 | |
40e87e9e | 1892 | getPreviewStaticPath () { |
e8bafea3 C |
1893 | const preview = this.getPreview() |
1894 | if (!preview) return null | |
1895 | ||
1896 | // We use a local cache, so specify our cache endpoint instead of potential remote URL | |
557b13ae | 1897 | return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename) |
3fd3ab2d | 1898 | } |
40298b02 | 1899 | |
b5fecbf4 | 1900 | toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video { |
098eb377 | 1901 | return videoModelToFormattedJSON(this, options) |
14d3270f | 1902 | } |
14d3270f | 1903 | |
b5fecbf4 | 1904 | toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails { |
098eb377 | 1905 | return videoModelToFormattedDetailsJSON(this) |
244e76a5 RK |
1906 | } |
1907 | ||
1908 | getFormattedVideoFilesJSON (): VideoFile[] { | |
d7a25329 C |
1909 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() |
1910 | return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles) | |
3fd3ab2d | 1911 | } |
e4f97bab | 1912 | |
b5fecbf4 | 1913 | toActivityPubObject (this: MVideoAP): VideoTorrentObject { |
098eb377 | 1914 | return videoModelToActivityPubObject(this) |
3fd3ab2d C |
1915 | } |
1916 | ||
1917 | getTruncatedDescription () { | |
1918 | if (!this.description) return null | |
93e1258c | 1919 | |
bffbebbe | 1920 | const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max |
687c6180 | 1921 | return peertubeTruncate(this.description, { length: maxLength }) |
93e1258c C |
1922 | } |
1923 | ||
d7a25329 C |
1924 | getMaxQualityResolution () { |
1925 | const file = this.getMaxQualityFile() | |
1926 | const videoOrPlaylist = file.getVideoOrStreamingPlaylist() | |
1927 | const originalFilePath = getVideoFilePath(videoOrPlaylist, file) | |
0d0e8dd0 | 1928 | |
056aa7f2 | 1929 | return getVideoFileResolution(originalFilePath) |
3fd3ab2d | 1930 | } |
0d0e8dd0 | 1931 | |
96f29c0f | 1932 | getDescriptionAPIPath () { |
3fd3ab2d | 1933 | return `/api/${API_VERSION}/videos/${this.uuid}/description` |
feb4bdfd C |
1934 | } |
1935 | ||
d7a25329 | 1936 | getHLSPlaylist (): MStreamingPlaylistFilesVideo { |
e2600d8b C |
1937 | if (!this.VideoStreamingPlaylists) return undefined |
1938 | ||
d7a25329 C |
1939 | const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS) |
1940 | playlist.Video = this | |
1941 | ||
1942 | return playlist | |
e2600d8b C |
1943 | } |
1944 | ||
d7a25329 C |
1945 | setHLSPlaylist (playlist: MStreamingPlaylist) { |
1946 | const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ] | |
b9fffa29 | 1947 | |
d7a25329 C |
1948 | if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) { |
1949 | this.VideoStreamingPlaylists = toAdd | |
1950 | return | |
1951 | } | |
1952 | ||
1953 | this.VideoStreamingPlaylists = this.VideoStreamingPlaylists | |
1954 | .filter(s => s.type !== VideoStreamingPlaylistType.HLS) | |
1955 | .concat(toAdd) | |
1956 | } | |
1957 | ||
1958 | removeFile (videoFile: MVideoFile, isRedundancy = false) { | |
1959 | const filePath = getVideoFilePath(this, videoFile, isRedundancy) | |
62689b94 | 1960 | return remove(filePath) |
ed31c059 | 1961 | .catch(err => logger.warn('Cannot delete file %s.', filePath, { err })) |
feb4bdfd C |
1962 | } |
1963 | ||
453e83ea | 1964 | removeTorrent (videoFile: MVideoFile) { |
d7a25329 | 1965 | const torrentPath = getTorrentFilePath(this, videoFile) |
62689b94 | 1966 | return remove(torrentPath) |
ed31c059 | 1967 | .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) |
aaf61f38 C |
1968 | } |
1969 | ||
09209296 | 1970 | removeStreamingPlaylist (isRedundancy = false) { |
66fb2aa3 | 1971 | const directoryPath = getHLSDirectory(this, isRedundancy) |
09209296 | 1972 | |
66fb2aa3 C |
1973 | return remove(directoryPath) |
1974 | .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err })) | |
09209296 C |
1975 | } |
1976 | ||
1297eb5d C |
1977 | isOutdated () { |
1978 | if (this.isOwned()) return false | |
1979 | ||
9f79ade6 | 1980 | return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL) |
1297eb5d C |
1981 | } |
1982 | ||
04b8c3fb C |
1983 | setAsRefreshed () { |
1984 | this.changed('updatedAt', true) | |
1985 | ||
1986 | return this.save() | |
1987 | } | |
1988 | ||
d7a25329 C |
1989 | async publishIfNeededAndSave (t: Transaction) { |
1990 | if (this.state !== VideoState.PUBLISHED) { | |
1991 | this.state = VideoState.PUBLISHED | |
1992 | this.publishedAt = new Date() | |
1993 | await this.save({ transaction: t }) | |
7920c273 | 1994 | |
d7a25329 | 1995 | return true |
6fcd19ba | 1996 | } |
aaf61f38 | 1997 | |
d7a25329 | 1998 | return false |
15d4ee04 | 1999 | } |
a96aed15 | 2000 | |
d7a25329 C |
2001 | getBaseUrls () { |
2002 | if (this.isOwned()) { | |
2003 | return { | |
2004 | baseUrlHttp: WEBSERVER.URL, | |
2005 | baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT | |
2006 | } | |
c48e82b5 C |
2007 | } |
2008 | ||
d7a25329 C |
2009 | return { |
2010 | baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host, | |
2011 | baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host | |
2012 | } | |
c48e82b5 C |
2013 | } |
2014 | ||
09209296 C |
2015 | getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) { |
2016 | return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] | |
2017 | } | |
2018 | ||
453e83ea | 2019 | getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) { |
d7a25329 | 2020 | return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile) |
3fd3ab2d | 2021 | } |
e4f97bab | 2022 | |
453e83ea | 2023 | getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) { |
d7a25329 | 2024 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile) |
02756fbd C |
2025 | } |
2026 | ||
453e83ea | 2027 | getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) { |
d7a25329 | 2028 | return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile) |
3fd3ab2d | 2029 | } |
a96aed15 | 2030 | |
453e83ea | 2031 | getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) { |
d7a25329 | 2032 | return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile) |
b9fffa29 C |
2033 | } |
2034 | ||
453e83ea | 2035 | getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) { |
d7a25329 | 2036 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile) |
02756fbd | 2037 | } |
09209296 | 2038 | |
453e83ea | 2039 | getBandwidthBits (videoFile: MVideoFile) { |
09209296 C |
2040 | return Math.ceil((videoFile.size * 8) / this.duration) |
2041 | } | |
a96aed15 | 2042 | } |