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