]>
Commit | Line | Data |
---|---|---|
39445ead | 1 | import * as Bluebird from 'bluebird' |
53abc4c2 | 2 | import { map, maxBy, truncate } from 'lodash' |
571389d4 | 3 | import * as magnetUtil from 'magnet-uri' |
4d4e5cd4 | 4 | import * as parseTorrent from 'parse-torrent' |
65fcc311 | 5 | import { join } from 'path' |
e02643f3 | 6 | import * as Sequelize from 'sequelize' |
3fd3ab2d C |
7 | import { |
8 | AfterDestroy, | |
9 | AllowNull, | |
10 | BelongsTo, | |
11 | BelongsToMany, | |
12 | Column, | |
13 | CreatedAt, | |
14 | DataType, | |
15 | Default, | |
16 | ForeignKey, | |
17 | HasMany, | |
18 | IFindOptions, | |
19 | Is, | |
20 | IsInt, | |
21 | IsUUID, | |
22 | Min, | |
23 | Model, | |
24 | Table, | |
25 | UpdatedAt | |
26 | } from 'sequelize-typescript' | |
27 | import { IIncludeOptions } from 'sequelize-typescript/lib/interfaces/IIncludeOptions' | |
571389d4 | 28 | import { VideoPrivacy, VideoResolution } from '../../../shared' |
3fd3ab2d C |
29 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' |
30 | import { | |
31 | activityPubCollection, | |
32 | createTorrentPromise, | |
33 | generateImageFromVideoFile, | |
34 | getVideoFileHeight, | |
35 | logger, | |
36 | renamePromise, | |
37 | statPromise, | |
38 | transcode, | |
39 | unlinkPromise, | |
40 | writeFilePromise | |
41 | } from '../../helpers' | |
42 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub' | |
a2431b7d | 43 | import { |
3fd3ab2d | 44 | isVideoCategoryValid, |
a2431b7d C |
45 | isVideoDescriptionValid, |
46 | isVideoDurationValid, | |
3fd3ab2d | 47 | isVideoLanguageValid, |
a2431b7d C |
48 | isVideoLicenceValid, |
49 | isVideoNameValid, | |
3fd3ab2d C |
50 | isVideoNSFWValid, |
51 | isVideoPrivacyValid | |
52 | } from '../../helpers/custom-validators/videos' | |
65fcc311 | 53 | import { |
571389d4 | 54 | API_VERSION, |
65fcc311 | 55 | CONFIG, |
571389d4 C |
56 | CONSTRAINTS_FIELDS, |
57 | PREVIEWS_SIZE, | |
65fcc311 C |
58 | REMOTE_SCHEME, |
59 | STATIC_PATHS, | |
571389d4 | 60 | THUMBNAILS_SIZE, |
65fcc311 | 61 | VIDEO_CATEGORIES, |
65fcc311 | 62 | VIDEO_LANGUAGES, |
571389d4 | 63 | VIDEO_LICENCES, |
fd45e8f4 | 64 | VIDEO_PRIVACIES |
3fd3ab2d C |
65 | } from '../../initializers' |
66 | import { getAnnounceActivityPubUrl } from '../../lib/activitypub' | |
39445ead | 67 | import { sendDeleteVideo } from '../../lib/index' |
3fd3ab2d C |
68 | import { AccountModel } from '../account/account' |
69 | import { AccountVideoRateModel } from '../account/account-video-rate' | |
70 | import { ServerModel } from '../server/server' | |
71 | import { getSort, throwIfNotValid } from '../utils' | |
72 | import { TagModel } from './tag' | |
73 | import { VideoAbuseModel } from './video-abuse' | |
74 | import { VideoChannelModel } from './video-channel' | |
75 | import { VideoFileModel } from './video-file' | |
76 | import { VideoShareModel } from './video-share' | |
77 | import { VideoTagModel } from './video-tag' | |
78 | ||
79 | @Table({ | |
80 | tableName: 'video', | |
81 | indexes: [ | |
feb4bdfd | 82 | { |
3fd3ab2d | 83 | fields: [ 'name' ] |
feb4bdfd C |
84 | }, |
85 | { | |
3fd3ab2d C |
86 | fields: [ 'createdAt' ] |
87 | }, | |
88 | { | |
89 | fields: [ 'duration' ] | |
90 | }, | |
91 | { | |
92 | fields: [ 'views' ] | |
93 | }, | |
94 | { | |
95 | fields: [ 'likes' ] | |
96 | }, | |
97 | { | |
98 | fields: [ 'uuid' ] | |
99 | }, | |
100 | { | |
101 | fields: [ 'channelId' ] | |
feb4bdfd | 102 | } |
e02643f3 | 103 | ] |
3fd3ab2d C |
104 | }) |
105 | export class VideoModel extends Model<VideoModel> { | |
106 | ||
107 | @AllowNull(false) | |
108 | @Default(DataType.UUIDV4) | |
109 | @IsUUID(4) | |
110 | @Column(DataType.UUID) | |
111 | uuid: string | |
112 | ||
113 | @AllowNull(false) | |
114 | @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) | |
115 | @Column | |
116 | name: string | |
117 | ||
118 | @AllowNull(true) | |
119 | @Default(null) | |
120 | @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category')) | |
121 | @Column | |
122 | category: number | |
123 | ||
124 | @AllowNull(true) | |
125 | @Default(null) | |
126 | @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence')) | |
127 | @Column | |
128 | licence: number | |
129 | ||
130 | @AllowNull(true) | |
131 | @Default(null) | |
132 | @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language')) | |
133 | @Column | |
134 | language: number | |
135 | ||
136 | @AllowNull(false) | |
137 | @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) | |
138 | @Column | |
139 | privacy: number | |
140 | ||
141 | @AllowNull(false) | |
142 | @Is('VideoNSFW', value => throwIfNotValid(value, isVideoNSFWValid, 'NSFW boolean')) | |
143 | @Column | |
144 | nsfw: boolean | |
145 | ||
146 | @AllowNull(true) | |
147 | @Default(null) | |
148 | @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description')) | |
149 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) | |
150 | description: string | |
151 | ||
152 | @AllowNull(false) | |
153 | @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) | |
154 | @Column | |
155 | duration: number | |
156 | ||
157 | @AllowNull(false) | |
158 | @Default(0) | |
159 | @IsInt | |
160 | @Min(0) | |
161 | @Column | |
162 | views: number | |
163 | ||
164 | @AllowNull(false) | |
165 | @Default(0) | |
166 | @IsInt | |
167 | @Min(0) | |
168 | @Column | |
169 | likes: number | |
170 | ||
171 | @AllowNull(false) | |
172 | @Default(0) | |
173 | @IsInt | |
174 | @Min(0) | |
175 | @Column | |
176 | dislikes: number | |
177 | ||
178 | @AllowNull(false) | |
179 | @Column | |
180 | remote: boolean | |
181 | ||
182 | @AllowNull(false) | |
183 | @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | |
184 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) | |
185 | url: string | |
186 | ||
187 | @CreatedAt | |
188 | createdAt: Date | |
189 | ||
190 | @UpdatedAt | |
191 | updatedAt: Date | |
192 | ||
193 | @ForeignKey(() => VideoChannelModel) | |
194 | @Column | |
195 | channelId: number | |
196 | ||
197 | @BelongsTo(() => VideoChannelModel, { | |
feb4bdfd | 198 | foreignKey: { |
feb4bdfd C |
199 | allowNull: false |
200 | }, | |
201 | onDelete: 'cascade' | |
202 | }) | |
3fd3ab2d | 203 | VideoChannel: VideoChannelModel |
7920c273 | 204 | |
3fd3ab2d | 205 | @BelongsToMany(() => TagModel, { |
7920c273 | 206 | foreignKey: 'videoId', |
3fd3ab2d C |
207 | through: () => VideoTagModel, |
208 | onDelete: 'CASCADE' | |
7920c273 | 209 | }) |
3fd3ab2d | 210 | Tags: TagModel[] |
55fa55a9 | 211 | |
3fd3ab2d | 212 | @HasMany(() => VideoAbuseModel, { |
55fa55a9 C |
213 | foreignKey: { |
214 | name: 'videoId', | |
215 | allowNull: false | |
216 | }, | |
217 | onDelete: 'cascade' | |
218 | }) | |
3fd3ab2d | 219 | VideoAbuses: VideoAbuseModel[] |
93e1258c | 220 | |
3fd3ab2d | 221 | @HasMany(() => VideoFileModel, { |
93e1258c C |
222 | foreignKey: { |
223 | name: 'videoId', | |
224 | allowNull: false | |
225 | }, | |
226 | onDelete: 'cascade' | |
227 | }) | |
3fd3ab2d | 228 | VideoFiles: VideoFileModel[] |
e71bcc0f | 229 | |
3fd3ab2d | 230 | @HasMany(() => VideoShareModel, { |
e71bcc0f C |
231 | foreignKey: { |
232 | name: 'videoId', | |
233 | allowNull: false | |
234 | }, | |
235 | onDelete: 'cascade' | |
236 | }) | |
3fd3ab2d | 237 | VideoShares: VideoShareModel[] |
16b90975 | 238 | |
3fd3ab2d | 239 | @HasMany(() => AccountVideoRateModel, { |
16b90975 C |
240 | foreignKey: { |
241 | name: 'videoId', | |
242 | allowNull: false | |
243 | }, | |
244 | onDelete: 'cascade' | |
245 | }) | |
3fd3ab2d | 246 | AccountVideoRates: AccountVideoRateModel[] |
f285faa0 | 247 | |
3fd3ab2d C |
248 | @AfterDestroy |
249 | static removeFilesAndSendDelete (instance: VideoModel) { | |
250 | const tasks = [] | |
f285faa0 | 251 | |
93e1258c | 252 | tasks.push( |
3fd3ab2d | 253 | instance.removeThumbnail() |
93e1258c C |
254 | ) |
255 | ||
3fd3ab2d C |
256 | if (instance.isOwned()) { |
257 | tasks.push( | |
258 | instance.removePreview(), | |
259 | sendDeleteVideo(instance, undefined) | |
260 | ) | |
40298b02 | 261 | |
3fd3ab2d C |
262 | // Remove physical files and torrents |
263 | instance.VideoFiles.forEach(file => { | |
264 | tasks.push(instance.removeFile(file)) | |
265 | tasks.push(instance.removeTorrent(file)) | |
266 | }) | |
267 | } | |
40298b02 | 268 | |
3fd3ab2d C |
269 | return Promise.all(tasks) |
270 | .catch(err => { | |
271 | logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err) | |
272 | }) | |
273 | } | |
f285faa0 | 274 | |
3fd3ab2d C |
275 | static list () { |
276 | const query = { | |
277 | include: [ VideoFileModel ] | |
278 | } | |
558d7c23 | 279 | |
3fd3ab2d C |
280 | return VideoModel.findAll(query) |
281 | } | |
f285faa0 | 282 | |
3fd3ab2d C |
283 | static listAllAndSharedByAccountForOutbox (accountId: number, start: number, count: number) { |
284 | function getRawQuery (select: string) { | |
285 | const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + | |
286 | 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + | |
287 | 'WHERE "VideoChannel"."accountId" = ' + accountId | |
288 | const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + | |
289 | 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + | |
290 | 'WHERE "VideoShare"."accountId" = ' + accountId | |
558d7c23 | 291 | |
3fd3ab2d C |
292 | return `(${queryVideo}) UNION (${queryVideoShare})` |
293 | } | |
aaf61f38 | 294 | |
3fd3ab2d C |
295 | const rawQuery = getRawQuery('"Video"."id"') |
296 | const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') | |
297 | ||
298 | const query = { | |
299 | distinct: true, | |
300 | offset: start, | |
301 | limit: count, | |
302 | order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ], | |
303 | where: { | |
304 | id: { | |
305 | [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')') | |
306 | } | |
307 | }, | |
308 | include: [ | |
309 | { | |
310 | model: VideoShareModel, | |
311 | required: false, | |
312 | where: { | |
313 | [Sequelize.Op.and]: [ | |
314 | { | |
315 | id: { | |
316 | [Sequelize.Op.not]: null | |
317 | } | |
318 | }, | |
319 | { | |
320 | accountId | |
321 | } | |
322 | ] | |
323 | }, | |
324 | include: [ AccountModel ] | |
325 | }, | |
326 | { | |
327 | model: VideoChannelModel, | |
328 | required: true, | |
329 | include: [ | |
330 | { | |
331 | model: AccountModel, | |
332 | required: true | |
333 | } | |
334 | ] | |
335 | }, | |
336 | { | |
337 | model: AccountVideoRateModel, | |
338 | include: [ AccountModel ] | |
339 | }, | |
340 | VideoFileModel, | |
341 | TagModel | |
342 | ] | |
343 | } | |
164174a6 | 344 | |
3fd3ab2d C |
345 | return Bluebird.all([ |
346 | // FIXME: typing issue | |
347 | VideoModel.findAll(query as any), | |
348 | VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT }) | |
349 | ]).then(([ rows, totals ]) => { | |
350 | // totals: totalVideos + totalVideoShares | |
351 | let totalVideos = 0 | |
352 | let totalVideoShares = 0 | |
353 | if (totals[0]) totalVideos = parseInt(totals[0].total, 10) | |
354 | if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10) | |
355 | ||
356 | const total = totalVideos + totalVideoShares | |
357 | return { | |
358 | data: rows, | |
359 | total: total | |
360 | } | |
361 | }) | |
362 | } | |
93e1258c | 363 | |
3fd3ab2d C |
364 | static listUserVideosForApi (userId: number, start: number, count: number, sort: string) { |
365 | const query = { | |
366 | distinct: true, | |
367 | offset: start, | |
368 | limit: count, | |
369 | order: [ getSort(sort), [ 'Tags', 'name', 'ASC' ] ], | |
370 | include: [ | |
371 | { | |
372 | model: VideoChannelModel, | |
373 | required: true, | |
374 | include: [ | |
375 | { | |
376 | model: AccountModel, | |
377 | where: { | |
378 | userId | |
379 | }, | |
380 | required: true | |
381 | } | |
382 | ] | |
383 | }, | |
384 | TagModel | |
385 | ] | |
386 | } | |
d8755eed | 387 | |
3fd3ab2d C |
388 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { |
389 | return { | |
390 | data: rows, | |
391 | total: count | |
392 | } | |
393 | }) | |
394 | } | |
93e1258c | 395 | |
3fd3ab2d C |
396 | static listForApi (start: number, count: number, sort: string) { |
397 | const query = { | |
398 | distinct: true, | |
399 | offset: start, | |
400 | limit: count, | |
401 | order: [ getSort(sort), [ 'Tags', 'name', 'ASC' ] ], | |
402 | include: [ | |
403 | { | |
404 | model: VideoChannelModel, | |
405 | required: true, | |
406 | include: [ | |
407 | { | |
408 | model: AccountModel, | |
409 | required: true, | |
410 | include: [ | |
411 | { | |
412 | model: ServerModel, | |
413 | required: false | |
414 | } | |
415 | ] | |
416 | } | |
417 | ] | |
418 | }, | |
419 | TagModel | |
420 | ], | |
421 | where: this.createBaseVideosWhere() | |
422 | } | |
93e1258c | 423 | |
3fd3ab2d C |
424 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { |
425 | return { | |
426 | data: rows, | |
427 | total: count | |
428 | } | |
429 | }) | |
93e1258c C |
430 | } |
431 | ||
3fd3ab2d C |
432 | static load (id: number) { |
433 | return VideoModel.findById(id) | |
434 | } | |
fdbda9e3 | 435 | |
3fd3ab2d C |
436 | static loadByUUID (uuid: string, t?: Sequelize.Transaction) { |
437 | const query: IFindOptions<VideoModel> = { | |
438 | where: { | |
439 | uuid | |
440 | }, | |
441 | include: [ VideoFileModel ] | |
442 | } | |
93e1258c | 443 | |
3fd3ab2d | 444 | if (t !== undefined) query.transaction = t |
e4f97bab | 445 | |
3fd3ab2d C |
446 | return VideoModel.findOne(query) |
447 | } | |
93e1258c | 448 | |
3fd3ab2d C |
449 | static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) { |
450 | const query: IFindOptions<VideoModel> = { | |
451 | where: { | |
452 | url | |
453 | }, | |
454 | include: [ | |
455 | VideoFileModel, | |
456 | { | |
457 | model: VideoChannelModel, | |
458 | include: [ AccountModel ] | |
459 | } | |
460 | ] | |
461 | } | |
d8755eed | 462 | |
3fd3ab2d | 463 | if (t !== undefined) query.transaction = t |
d8755eed | 464 | |
3fd3ab2d C |
465 | return VideoModel.findOne(query) |
466 | } | |
d8755eed | 467 | |
3fd3ab2d C |
468 | static loadByUUIDOrURL (uuid: string, url: string, t?: Sequelize.Transaction) { |
469 | const query: IFindOptions<VideoModel> = { | |
470 | where: { | |
471 | [Sequelize.Op.or]: [ | |
472 | { uuid }, | |
473 | { url } | |
474 | ] | |
475 | }, | |
476 | include: [ VideoFileModel ] | |
477 | } | |
feb4bdfd | 478 | |
3fd3ab2d | 479 | if (t !== undefined) query.transaction = t |
feb4bdfd | 480 | |
3fd3ab2d | 481 | return VideoModel.findOne(query) |
72c7248b C |
482 | } |
483 | ||
3fd3ab2d C |
484 | static loadAndPopulateAccountAndServerAndTags (id: number) { |
485 | const options = { | |
486 | order: [ [ 'Tags', 'name', 'ASC' ] ], | |
487 | include: [ | |
488 | { | |
489 | model: VideoChannelModel, | |
490 | include: [ | |
491 | { | |
492 | model: AccountModel, | |
493 | include: [ { model: ServerModel, required: false } ] | |
494 | } | |
495 | ] | |
496 | }, | |
497 | { | |
498 | model: AccountVideoRateModel, | |
499 | include: [ AccountModel ] | |
500 | }, | |
501 | { | |
502 | model: VideoShareModel, | |
503 | include: [ AccountModel ] | |
504 | }, | |
505 | TagModel, | |
506 | VideoFileModel | |
507 | ] | |
508 | } | |
72c7248b | 509 | |
3fd3ab2d C |
510 | return VideoModel.findById(id, options) |
511 | } | |
72c7248b | 512 | |
3fd3ab2d C |
513 | static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) { |
514 | const options = { | |
515 | order: [ [ 'Tags', 'name', 'ASC' ] ], | |
516 | where: { | |
517 | uuid | |
518 | }, | |
519 | include: [ | |
520 | { | |
521 | model: VideoChannelModel, | |
522 | include: [ | |
523 | { | |
524 | model: AccountModel, | |
525 | include: [ { model: ServerModel, required: false } ] | |
526 | } | |
527 | ] | |
528 | }, | |
529 | { | |
530 | model: AccountVideoRateModel, | |
531 | include: [ AccountModel ] | |
532 | }, | |
533 | { | |
534 | model: VideoShareModel, | |
535 | include: [ AccountModel ] | |
536 | }, | |
537 | TagModel, | |
538 | VideoFileModel | |
539 | ] | |
540 | } | |
fd45e8f4 | 541 | |
3fd3ab2d | 542 | return VideoModel.findOne(options) |
aaf61f38 C |
543 | } |
544 | ||
3fd3ab2d C |
545 | static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) { |
546 | const serverInclude: IIncludeOptions = { | |
547 | model: ServerModel, | |
548 | required: false | |
549 | } | |
aaf61f38 | 550 | |
3fd3ab2d C |
551 | const accountInclude: IIncludeOptions = { |
552 | model: AccountModel, | |
553 | include: [ serverInclude ] | |
554 | } | |
e4f97bab | 555 | |
3fd3ab2d C |
556 | const videoChannelInclude: IIncludeOptions = { |
557 | model: VideoChannelModel, | |
558 | include: [ accountInclude ], | |
559 | required: true | |
40ff5707 | 560 | } |
40ff5707 | 561 | |
3fd3ab2d C |
562 | const tagInclude: IIncludeOptions = { |
563 | model: TagModel | |
f595d394 | 564 | } |
f595d394 | 565 | |
3fd3ab2d C |
566 | const query: IFindOptions<VideoModel> = { |
567 | distinct: true, | |
568 | where: this.createBaseVideosWhere(), | |
569 | offset: start, | |
570 | limit: count, | |
571 | order: [ getSort(sort), [ 'Tags', 'name', 'ASC' ] ] | |
f595d394 | 572 | } |
f595d394 | 573 | |
3fd3ab2d C |
574 | // TODO: search on tags too |
575 | // const escapedValue = Video['sequelize'].escape('%' + value + '%') | |
576 | // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal( | |
577 | // `(SELECT "VideoTags"."videoId" | |
578 | // FROM "Tags" | |
579 | // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" | |
580 | // WHERE name ILIKE ${escapedValue} | |
581 | // )` | |
582 | // ) | |
583 | ||
584 | // TODO: search on account too | |
585 | // accountInclude.where = { | |
586 | // name: { | |
587 | // [Sequelize.Op.iLike]: '%' + value + '%' | |
588 | // } | |
589 | // } | |
590 | query.where['name'] = { | |
591 | [Sequelize.Op.iLike]: '%' + value + '%' | |
592 | } | |
16b90975 | 593 | |
3fd3ab2d C |
594 | query.include = [ |
595 | videoChannelInclude, tagInclude | |
596 | ] | |
16b90975 | 597 | |
3fd3ab2d C |
598 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { |
599 | return { | |
600 | data: rows, | |
601 | total: count | |
16b90975 | 602 | } |
3fd3ab2d | 603 | }) |
16b90975 C |
604 | } |
605 | ||
3fd3ab2d C |
606 | private static createBaseVideosWhere () { |
607 | return { | |
608 | id: { | |
609 | [Sequelize.Op.notIn]: VideoModel.sequelize.literal( | |
610 | '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' | |
611 | ) | |
612 | }, | |
613 | privacy: VideoPrivacy.PUBLIC | |
4e50b6a1 | 614 | } |
4e50b6a1 C |
615 | } |
616 | ||
3fd3ab2d C |
617 | getOriginalFile () { |
618 | if (Array.isArray(this.VideoFiles) === false) return undefined | |
aaf61f38 | 619 | |
3fd3ab2d C |
620 | // The original file is the file that have the higher resolution |
621 | return maxBy(this.VideoFiles, file => file.resolution) | |
e4f97bab | 622 | } |
aaf61f38 | 623 | |
3fd3ab2d C |
624 | getVideoFilename (videoFile: VideoFileModel) { |
625 | return this.uuid + '-' + videoFile.resolution + videoFile.extname | |
626 | } | |
165cdc75 | 627 | |
3fd3ab2d C |
628 | getThumbnailName () { |
629 | // We always have a copy of the thumbnail | |
630 | const extension = '.jpg' | |
631 | return this.uuid + extension | |
7b1f49de C |
632 | } |
633 | ||
3fd3ab2d C |
634 | getPreviewName () { |
635 | const extension = '.jpg' | |
636 | return this.uuid + extension | |
637 | } | |
7b1f49de | 638 | |
3fd3ab2d C |
639 | getTorrentFileName (videoFile: VideoFileModel) { |
640 | const extension = '.torrent' | |
641 | return this.uuid + '-' + videoFile.resolution + extension | |
642 | } | |
8e7f08b5 | 643 | |
3fd3ab2d C |
644 | isOwned () { |
645 | return this.remote === false | |
9567011b C |
646 | } |
647 | ||
3fd3ab2d C |
648 | createPreview (videoFile: VideoFileModel) { |
649 | const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height | |
650 | ||
651 | return generateImageFromVideoFile( | |
652 | this.getVideoFilePath(videoFile), | |
653 | CONFIG.STORAGE.PREVIEWS_DIR, | |
654 | this.getPreviewName(), | |
655 | imageSize | |
656 | ) | |
657 | } | |
9567011b | 658 | |
3fd3ab2d C |
659 | createThumbnail (videoFile: VideoFileModel) { |
660 | const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height | |
227d02fe | 661 | |
3fd3ab2d C |
662 | return generateImageFromVideoFile( |
663 | this.getVideoFilePath(videoFile), | |
664 | CONFIG.STORAGE.THUMBNAILS_DIR, | |
665 | this.getThumbnailName(), | |
666 | imageSize | |
667 | ) | |
14d3270f C |
668 | } |
669 | ||
3fd3ab2d C |
670 | getVideoFilePath (videoFile: VideoFileModel) { |
671 | return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
672 | } | |
14d3270f | 673 | |
3fd3ab2d C |
674 | createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) { |
675 | const options = { | |
676 | announceList: [ | |
677 | [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ] | |
678 | ], | |
679 | urlList: [ | |
680 | CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) | |
681 | ] | |
682 | } | |
14d3270f | 683 | |
3fd3ab2d | 684 | const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) |
e4f97bab | 685 | |
3fd3ab2d C |
686 | const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) |
687 | logger.info('Creating torrent %s.', filePath) | |
e4f97bab | 688 | |
3fd3ab2d | 689 | await writeFilePromise(filePath, torrent) |
e4f97bab | 690 | |
3fd3ab2d C |
691 | const parsedTorrent = parseTorrent(torrent) |
692 | videoFile.infoHash = parsedTorrent.infoHash | |
693 | } | |
e4f97bab | 694 | |
3fd3ab2d C |
695 | getEmbedPath () { |
696 | return '/videos/embed/' + this.uuid | |
697 | } | |
e4f97bab | 698 | |
3fd3ab2d C |
699 | getThumbnailPath () { |
700 | return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()) | |
e4f97bab | 701 | } |
227d02fe | 702 | |
3fd3ab2d C |
703 | getPreviewPath () { |
704 | return join(STATIC_PATHS.PREVIEWS, this.getPreviewName()) | |
705 | } | |
40298b02 | 706 | |
3fd3ab2d C |
707 | toFormattedJSON () { |
708 | let serverHost | |
40298b02 | 709 | |
3fd3ab2d C |
710 | if (this.VideoChannel.Account.Server) { |
711 | serverHost = this.VideoChannel.Account.Server.host | |
712 | } else { | |
713 | // It means it's our video | |
714 | serverHost = CONFIG.WEBSERVER.HOST | |
715 | } | |
14d3270f | 716 | |
3fd3ab2d C |
717 | return { |
718 | id: this.id, | |
719 | uuid: this.uuid, | |
720 | name: this.name, | |
721 | category: this.category, | |
722 | categoryLabel: this.getCategoryLabel(), | |
723 | licence: this.licence, | |
724 | licenceLabel: this.getLicenceLabel(), | |
725 | language: this.language, | |
726 | languageLabel: this.getLanguageLabel(), | |
727 | nsfw: this.nsfw, | |
728 | description: this.getTruncatedDescription(), | |
729 | serverHost, | |
730 | isLocal: this.isOwned(), | |
731 | accountName: this.VideoChannel.Account.name, | |
732 | duration: this.duration, | |
733 | views: this.views, | |
734 | likes: this.likes, | |
735 | dislikes: this.dislikes, | |
736 | tags: map<TagModel, string>(this.Tags, 'name'), | |
737 | thumbnailPath: this.getThumbnailPath(), | |
738 | previewPath: this.getPreviewPath(), | |
739 | embedPath: this.getEmbedPath(), | |
740 | createdAt: this.createdAt, | |
741 | updatedAt: this.updatedAt | |
742 | } | |
14d3270f | 743 | } |
14d3270f | 744 | |
3fd3ab2d C |
745 | toFormattedDetailsJSON () { |
746 | const formattedJson = this.toFormattedJSON() | |
e4f97bab | 747 | |
3fd3ab2d C |
748 | // Maybe our server is not up to date and there are new privacy settings since our version |
749 | let privacyLabel = VIDEO_PRIVACIES[this.privacy] | |
750 | if (!privacyLabel) privacyLabel = 'Unknown' | |
e4f97bab | 751 | |
3fd3ab2d C |
752 | const detailsJson = { |
753 | privacyLabel, | |
754 | privacy: this.privacy, | |
755 | descriptionPath: this.getDescriptionPath(), | |
756 | channel: this.VideoChannel.toFormattedJSON(), | |
757 | account: this.VideoChannel.Account.toFormattedJSON(), | |
758 | files: [] | |
759 | } | |
e4f97bab | 760 | |
3fd3ab2d C |
761 | // Format and sort video files |
762 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() | |
763 | detailsJson.files = this.VideoFiles | |
764 | .map(videoFile => { | |
765 | let resolutionLabel = videoFile.resolution + 'p' | |
766 | ||
767 | return { | |
768 | resolution: videoFile.resolution, | |
769 | resolutionLabel, | |
770 | magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs), | |
771 | size: videoFile.size, | |
772 | torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp), | |
773 | fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp) | |
774 | } | |
775 | }) | |
776 | .sort((a, b) => { | |
777 | if (a.resolution < b.resolution) return 1 | |
778 | if (a.resolution === b.resolution) return 0 | |
779 | return -1 | |
780 | }) | |
781 | ||
782 | return Object.assign(formattedJson, detailsJson) | |
783 | } | |
e4f97bab | 784 | |
3fd3ab2d C |
785 | toActivityPubObject (): VideoTorrentObject { |
786 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() | |
787 | if (!this.Tags) this.Tags = [] | |
e4f97bab | 788 | |
3fd3ab2d C |
789 | const tag = this.Tags.map(t => ({ |
790 | type: 'Hashtag' as 'Hashtag', | |
791 | name: t.name | |
792 | })) | |
40298b02 | 793 | |
3fd3ab2d C |
794 | let language |
795 | if (this.language) { | |
796 | language = { | |
797 | identifier: this.language + '', | |
798 | name: this.getLanguageLabel() | |
799 | } | |
800 | } | |
40298b02 | 801 | |
3fd3ab2d C |
802 | let category |
803 | if (this.category) { | |
804 | category = { | |
805 | identifier: this.category + '', | |
806 | name: this.getCategoryLabel() | |
807 | } | |
808 | } | |
40298b02 | 809 | |
3fd3ab2d C |
810 | let licence |
811 | if (this.licence) { | |
812 | licence = { | |
813 | identifier: this.licence + '', | |
814 | name: this.getLicenceLabel() | |
815 | } | |
816 | } | |
9567011b | 817 | |
3fd3ab2d C |
818 | let likesObject |
819 | let dislikesObject | |
e4f97bab | 820 | |
3fd3ab2d C |
821 | if (Array.isArray(this.AccountVideoRates)) { |
822 | const likes: string[] = [] | |
823 | const dislikes: string[] = [] | |
e4f97bab | 824 | |
3fd3ab2d C |
825 | for (const rate of this.AccountVideoRates) { |
826 | if (rate.type === 'like') { | |
827 | likes.push(rate.Account.url) | |
828 | } else if (rate.type === 'dislike') { | |
829 | dislikes.push(rate.Account.url) | |
830 | } | |
831 | } | |
e4f97bab | 832 | |
3fd3ab2d C |
833 | likesObject = activityPubCollection(likes) |
834 | dislikesObject = activityPubCollection(dislikes) | |
835 | } | |
e4f97bab | 836 | |
3fd3ab2d C |
837 | let sharesObject |
838 | if (Array.isArray(this.VideoShares)) { | |
839 | const shares: string[] = [] | |
e4f97bab | 840 | |
3fd3ab2d C |
841 | for (const videoShare of this.VideoShares) { |
842 | const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Account) | |
843 | shares.push(shareUrl) | |
844 | } | |
e4f97bab | 845 | |
3fd3ab2d C |
846 | sharesObject = activityPubCollection(shares) |
847 | } | |
93e1258c | 848 | |
3fd3ab2d C |
849 | const url = [] |
850 | for (const file of this.VideoFiles) { | |
851 | url.push({ | |
852 | type: 'Link', | |
853 | mimeType: 'video/' + file.extname.replace('.', ''), | |
854 | url: this.getVideoFileUrl(file, baseUrlHttp), | |
855 | width: file.resolution, | |
856 | size: file.size | |
857 | }) | |
858 | ||
859 | url.push({ | |
860 | type: 'Link', | |
861 | mimeType: 'application/x-bittorrent', | |
862 | url: this.getTorrentUrl(file, baseUrlHttp), | |
863 | width: file.resolution | |
864 | }) | |
865 | ||
866 | url.push({ | |
867 | type: 'Link', | |
868 | mimeType: 'application/x-bittorrent;x-scheme-handler/magnet', | |
869 | url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs), | |
870 | width: file.resolution | |
871 | }) | |
872 | } | |
93e1258c | 873 | |
3fd3ab2d C |
874 | // Add video url too |
875 | url.push({ | |
876 | type: 'Link', | |
877 | mimeType: 'text/html', | |
878 | url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid | |
879 | }) | |
93e1258c | 880 | |
3fd3ab2d C |
881 | return { |
882 | type: 'Video' as 'Video', | |
883 | id: this.url, | |
884 | name: this.name, | |
885 | // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration | |
886 | duration: 'PT' + this.duration + 'S', | |
887 | uuid: this.uuid, | |
888 | tag, | |
889 | category, | |
890 | licence, | |
891 | language, | |
892 | views: this.views, | |
893 | nsfw: this.nsfw, | |
894 | published: this.createdAt.toISOString(), | |
895 | updated: this.updatedAt.toISOString(), | |
896 | mediaType: 'text/markdown', | |
897 | content: this.getTruncatedDescription(), | |
898 | icon: { | |
899 | type: 'Image', | |
900 | url: this.getThumbnailUrl(baseUrlHttp), | |
901 | mediaType: 'image/jpeg', | |
902 | width: THUMBNAILS_SIZE.width, | |
903 | height: THUMBNAILS_SIZE.height | |
904 | }, | |
905 | url, | |
906 | likes: likesObject, | |
907 | dislikes: dislikesObject, | |
908 | shares: sharesObject | |
909 | } | |
910 | } | |
911 | ||
912 | getTruncatedDescription () { | |
913 | if (!this.description) return null | |
93e1258c | 914 | |
3fd3ab2d C |
915 | const options = { |
916 | length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max | |
917 | } | |
aaf61f38 | 918 | |
3fd3ab2d | 919 | return truncate(this.description, options) |
93e1258c C |
920 | } |
921 | ||
3fd3ab2d C |
922 | optimizeOriginalVideofile = async function () { |
923 | const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR | |
924 | const newExtname = '.mp4' | |
925 | const inputVideoFile = this.getOriginalFile() | |
926 | const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile)) | |
927 | const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname) | |
b769007f | 928 | |
3fd3ab2d C |
929 | const transcodeOptions = { |
930 | inputPath: videoInputPath, | |
931 | outputPath: videoOutputPath | |
932 | } | |
c46edbc2 | 933 | |
3fd3ab2d C |
934 | try { |
935 | // Could be very long! | |
936 | await transcode(transcodeOptions) | |
c46edbc2 | 937 | |
3fd3ab2d | 938 | await unlinkPromise(videoInputPath) |
c46edbc2 | 939 | |
3fd3ab2d C |
940 | // Important to do this before getVideoFilename() to take in account the new file extension |
941 | inputVideoFile.set('extname', newExtname) | |
e71bcc0f | 942 | |
3fd3ab2d C |
943 | await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile)) |
944 | const stats = await statPromise(this.getVideoFilePath(inputVideoFile)) | |
e71bcc0f | 945 | |
3fd3ab2d | 946 | inputVideoFile.set('size', stats.size) |
e71bcc0f | 947 | |
3fd3ab2d C |
948 | await this.createTorrentAndSetInfoHash(inputVideoFile) |
949 | await inputVideoFile.save() | |
fd45e8f4 | 950 | |
3fd3ab2d C |
951 | } catch (err) { |
952 | // Auto destruction... | |
953 | this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err)) | |
fd45e8f4 | 954 | |
3fd3ab2d C |
955 | throw err |
956 | } | |
feb4bdfd C |
957 | } |
958 | ||
3fd3ab2d C |
959 | transcodeOriginalVideofile = async function (resolution: VideoResolution) { |
960 | const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR | |
961 | const extname = '.mp4' | |
aaf61f38 | 962 | |
3fd3ab2d C |
963 | // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed |
964 | const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile())) | |
feb4bdfd | 965 | |
3fd3ab2d C |
966 | const newVideoFile = new VideoFileModel({ |
967 | resolution, | |
968 | extname, | |
969 | size: 0, | |
970 | videoId: this.id | |
971 | }) | |
972 | const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile)) | |
a041b171 | 973 | |
3fd3ab2d C |
974 | const transcodeOptions = { |
975 | inputPath: videoInputPath, | |
976 | outputPath: videoOutputPath, | |
977 | resolution | |
978 | } | |
a041b171 | 979 | |
3fd3ab2d | 980 | await transcode(transcodeOptions) |
a041b171 | 981 | |
3fd3ab2d | 982 | const stats = await statPromise(videoOutputPath) |
d7d5611c | 983 | |
3fd3ab2d | 984 | newVideoFile.set('size', stats.size) |
d7d5611c | 985 | |
3fd3ab2d | 986 | await this.createTorrentAndSetInfoHash(newVideoFile) |
d7d5611c | 987 | |
3fd3ab2d C |
988 | await newVideoFile.save() |
989 | ||
990 | this.VideoFiles.push(newVideoFile) | |
0d0e8dd0 C |
991 | } |
992 | ||
3fd3ab2d C |
993 | getOriginalFileHeight () { |
994 | const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) | |
0d0e8dd0 | 995 | |
3fd3ab2d C |
996 | return getVideoFileHeight(originalFilePath) |
997 | } | |
0d0e8dd0 | 998 | |
3fd3ab2d C |
999 | getDescriptionPath () { |
1000 | return `/api/${API_VERSION}/videos/${this.uuid}/description` | |
feb4bdfd C |
1001 | } |
1002 | ||
3fd3ab2d C |
1003 | getCategoryLabel () { |
1004 | let categoryLabel = VIDEO_CATEGORIES[this.category] | |
1005 | if (!categoryLabel) categoryLabel = 'Misc' | |
aaf61f38 | 1006 | |
3fd3ab2d | 1007 | return categoryLabel |
0a6658fd C |
1008 | } |
1009 | ||
3fd3ab2d C |
1010 | getLicenceLabel () { |
1011 | let licenceLabel = VIDEO_LICENCES[this.licence] | |
1012 | if (!licenceLabel) licenceLabel = 'Unknown' | |
0a6658fd | 1013 | |
3fd3ab2d | 1014 | return licenceLabel |
feb4bdfd | 1015 | } |
7920c273 | 1016 | |
3fd3ab2d C |
1017 | getLanguageLabel () { |
1018 | let languageLabel = VIDEO_LANGUAGES[this.language] | |
1019 | if (!languageLabel) languageLabel = 'Unknown' | |
1020 | ||
1021 | return languageLabel | |
72c7248b C |
1022 | } |
1023 | ||
3fd3ab2d C |
1024 | removeThumbnail () { |
1025 | const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName()) | |
1026 | return unlinkPromise(thumbnailPath) | |
feb4bdfd C |
1027 | } |
1028 | ||
3fd3ab2d C |
1029 | removePreview () { |
1030 | // Same name than video thumbnail | |
1031 | return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName()) | |
7920c273 C |
1032 | } |
1033 | ||
3fd3ab2d C |
1034 | removeFile (videoFile: VideoFileModel) { |
1035 | const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
1036 | return unlinkPromise(filePath) | |
feb4bdfd C |
1037 | } |
1038 | ||
3fd3ab2d C |
1039 | removeTorrent (videoFile: VideoFileModel) { |
1040 | const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1041 | return unlinkPromise(torrentPath) | |
aaf61f38 C |
1042 | } |
1043 | ||
3fd3ab2d C |
1044 | private getBaseUrls () { |
1045 | let baseUrlHttp | |
1046 | let baseUrlWs | |
7920c273 | 1047 | |
3fd3ab2d C |
1048 | if (this.isOwned()) { |
1049 | baseUrlHttp = CONFIG.WEBSERVER.URL | |
1050 | baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT | |
1051 | } else { | |
1052 | baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Server.host | |
1053 | baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Server.host | |
6fcd19ba | 1054 | } |
aaf61f38 | 1055 | |
3fd3ab2d | 1056 | return { baseUrlHttp, baseUrlWs } |
15d4ee04 | 1057 | } |
a96aed15 | 1058 | |
3fd3ab2d C |
1059 | private getThumbnailUrl (baseUrlHttp: string) { |
1060 | return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName() | |
a96aed15 C |
1061 | } |
1062 | ||
3fd3ab2d C |
1063 | private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
1064 | return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile) | |
1065 | } | |
e4f97bab | 1066 | |
3fd3ab2d C |
1067 | private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
1068 | return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) | |
1069 | } | |
a96aed15 | 1070 | |
3fd3ab2d C |
1071 | private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) { |
1072 | const xs = this.getTorrentUrl(videoFile, baseUrlHttp) | |
1073 | const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] | |
1074 | const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ] | |
1075 | ||
1076 | const magnetHash = { | |
1077 | xs, | |
1078 | announce, | |
1079 | urlList, | |
1080 | infoHash: videoFile.infoHash, | |
1081 | name: this.name | |
1082 | } | |
a96aed15 | 1083 | |
3fd3ab2d | 1084 | return magnetUtil.encode(magnetHash) |
a96aed15 | 1085 | } |
a96aed15 | 1086 | } |