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