1 import * as Bluebird from 'bluebird'
2 import { map, maxBy, truncate } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
7 import { VideoPrivacy, VideoResolution } from '../../../shared'
8 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects/video-torrent-object'
9 import { activityPubCollection } from '../../helpers/activitypub'
10 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
11 import { isVideoCategoryValid, isVideoLanguageValid, isVideoPrivacyValid } from '../../helpers/custom-validators/videos'
12 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
14 isActivityPubUrlValid,
15 isVideoDescriptionValid,
20 } from '../../helpers/index'
21 import { logger } from '../../helpers/logger'
34 } from '../../initializers/constants'
35 import { getAnnounceActivityPubUrl } from '../../lib/activitypub/url'
36 import { sendDeleteVideo } from '../../lib/index'
37 import { addMethodsToModel, getSort } from '../utils'
38 import { TagInstance } from './tag-interface'
39 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
40 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
42 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
43 let getOriginalFile: VideoMethods.GetOriginalFile
44 let getVideoFilename: VideoMethods.GetVideoFilename
45 let getThumbnailName: VideoMethods.GetThumbnailName
46 let getThumbnailPath: VideoMethods.GetThumbnailPath
47 let getPreviewName: VideoMethods.GetPreviewName
48 let getPreviewPath: VideoMethods.GetPreviewPath
49 let getTorrentFileName: VideoMethods.GetTorrentFileName
50 let isOwned: VideoMethods.IsOwned
51 let toFormattedJSON: VideoMethods.ToFormattedJSON
52 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
53 let toActivityPubObject: VideoMethods.ToActivityPubObject
54 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
55 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
56 let createPreview: VideoMethods.CreatePreview
57 let createThumbnail: VideoMethods.CreateThumbnail
58 let getVideoFilePath: VideoMethods.GetVideoFilePath
59 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
60 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
61 let getEmbedPath: VideoMethods.GetEmbedPath
62 let getDescriptionPath: VideoMethods.GetDescriptionPath
63 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
64 let getCategoryLabel: VideoMethods.GetCategoryLabel
65 let getLicenceLabel: VideoMethods.GetLicenceLabel
66 let getLanguageLabel: VideoMethods.GetLanguageLabel
68 let list: VideoMethods.List
69 let listForApi: VideoMethods.ListForApi
70 let listAllAndSharedByAccountForOutbox: VideoMethods.ListAllAndSharedByAccountForOutbox
71 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
72 let load: VideoMethods.Load
73 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
74 let loadByUUID: VideoMethods.LoadByUUID
75 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
76 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
77 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
78 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
79 let removeThumbnail: VideoMethods.RemoveThumbnail
80 let removePreview: VideoMethods.RemovePreview
81 let removeFile: VideoMethods.RemoveFile
82 let removeTorrent: VideoMethods.RemoveTorrent
84 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
85 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
89 defaultValue: DataTypes.UUIDV4,
96 type: DataTypes.STRING,
100 const res = isVideoNameValid(value)
101 if (res === false) throw new Error('Video name is not valid.')
106 type: DataTypes.INTEGER,
110 categoryValid: value => {
111 const res = isVideoCategoryValid(value)
112 if (res === false) throw new Error('Video category is not valid.')
117 type: DataTypes.INTEGER,
121 licenceValid: value => {
122 const res = isVideoLicenceValid(value)
123 if (res === false) throw new Error('Video licence is not valid.')
128 type: DataTypes.INTEGER,
132 languageValid: value => {
133 const res = isVideoLanguageValid(value)
134 if (res === false) throw new Error('Video language is not valid.')
139 type: DataTypes.INTEGER,
142 privacyValid: value => {
143 const res = isVideoPrivacyValid(value)
144 if (res === false) throw new Error('Video privacy is not valid.')
149 type: DataTypes.BOOLEAN,
152 nsfwValid: value => {
153 const res = isVideoNSFWValid(value)
154 if (res === false) throw new Error('Video nsfw attribute is not valid.')
159 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
163 descriptionValid: value => {
164 const res = isVideoDescriptionValid(value)
165 if (res === false) throw new Error('Video description is not valid.')
170 type: DataTypes.INTEGER,
173 durationValid: value => {
174 const res = isVideoDurationValid(value)
175 if (res === false) throw new Error('Video duration is not valid.')
180 type: DataTypes.INTEGER,
189 type: DataTypes.INTEGER,
198 type: DataTypes.INTEGER,
207 type: DataTypes.BOOLEAN,
212 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
216 const res = isActivityPubUrlValid(value)
217 if (res === false) throw new Error('Video URL is not valid.')
228 fields: [ 'createdAt' ]
231 fields: [ 'duration' ]
243 fields: [ 'channelId' ]
252 const classMethods = [
256 listAllAndSharedByAccountForOutbox,
258 listUserVideosForApi,
260 loadByUrlAndPopulateAccount,
261 loadAndPopulateAccountAndServerAndTags,
264 loadByUUIDAndPopulateAccountAndServerAndTags,
265 searchAndPopulateAccountAndServerAndTags
267 const instanceMethods = [
270 createTorrentAndSetInfoHash,
286 toFormattedDetailsJSON,
287 optimizeOriginalVideofile,
288 transcodeOriginalVideofile,
289 getOriginalFileHeight,
291 getTruncatedDescription,
297 addMethodsToModel(Video, classMethods, instanceMethods)
302 // ------------------------------ METHODS ------------------------------
304 function associate (models) {
305 Video.belongsTo(models.VideoChannel, {
313 Video.belongsToMany(models.Tag, {
314 foreignKey: 'videoId',
315 through: models.VideoTag,
319 Video.hasMany(models.VideoAbuse, {
327 Video.hasMany(models.VideoFile, {
335 Video.hasMany(models.VideoShare, {
343 Video.hasMany(models.AccountVideoRate, {
352 function afterDestroy (video: VideoInstance) {
356 video.removeThumbnail()
359 if (video.isOwned()) {
361 video.removePreview(),
362 sendDeleteVideo(video, undefined)
365 // Remove physical files and torrents
366 video.VideoFiles.forEach(file => {
367 tasks.push(video.removeFile(file))
368 tasks.push(video.removeTorrent(file))
372 return Promise.all(tasks)
374 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
378 getOriginalFile = function (this: VideoInstance) {
379 if (Array.isArray(this.VideoFiles) === false) return undefined
381 // The original file is the file that have the higher resolution
382 return maxBy(this.VideoFiles, file => file.resolution)
385 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
386 return this.uuid + '-' + videoFile.resolution + videoFile.extname
389 getThumbnailName = function (this: VideoInstance) {
390 // We always have a copy of the thumbnail
391 const extension = '.jpg'
392 return this.uuid + extension
395 getPreviewName = function (this: VideoInstance) {
396 const extension = '.jpg'
397 return this.uuid + extension
400 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
401 const extension = '.torrent'
402 return this.uuid + '-' + videoFile.resolution + extension
405 isOwned = function (this: VideoInstance) {
406 return this.remote === false
409 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
410 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
412 return generateImageFromVideoFile(
413 this.getVideoFilePath(videoFile),
414 CONFIG.STORAGE.PREVIEWS_DIR,
415 this.getPreviewName(),
420 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
421 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
423 return generateImageFromVideoFile(
424 this.getVideoFilePath(videoFile),
425 CONFIG.STORAGE.THUMBNAILS_DIR,
426 this.getThumbnailName(),
431 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
432 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
435 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
438 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
441 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
445 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
447 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
448 logger.info('Creating torrent %s.', filePath)
450 await writeFilePromise(filePath, torrent)
452 const parsedTorrent = parseTorrent(torrent)
453 videoFile.infoHash = parsedTorrent.infoHash
456 getEmbedPath = function (this: VideoInstance) {
457 return '/videos/embed/' + this.uuid
460 getThumbnailPath = function (this: VideoInstance) {
461 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
464 getPreviewPath = function (this: VideoInstance) {
465 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
468 toFormattedJSON = function (this: VideoInstance) {
471 if (this.VideoChannel.Account.Server) {
472 serverHost = this.VideoChannel.Account.Server.host
474 // It means it's our video
475 serverHost = CONFIG.WEBSERVER.HOST
482 category: this.category,
483 categoryLabel: this.getCategoryLabel(),
484 licence: this.licence,
485 licenceLabel: this.getLicenceLabel(),
486 language: this.language,
487 languageLabel: this.getLanguageLabel(),
489 description: this.getTruncatedDescription(),
491 isLocal: this.isOwned(),
492 accountName: this.VideoChannel.Account.name,
493 duration: this.duration,
496 dislikes: this.dislikes,
497 tags: map<TagInstance, string>(this.Tags, 'name'),
498 thumbnailPath: this.getThumbnailPath(),
499 previewPath: this.getPreviewPath(),
500 embedPath: this.getEmbedPath(),
501 createdAt: this.createdAt,
502 updatedAt: this.updatedAt
508 toFormattedDetailsJSON = function (this: VideoInstance) {
509 const formattedJson = this.toFormattedJSON()
511 // Maybe our server is not up to date and there are new privacy settings since our version
512 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
513 if (!privacyLabel) privacyLabel = 'Unknown'
515 const detailsJson = {
517 privacy: this.privacy,
518 descriptionPath: this.getDescriptionPath(),
519 channel: this.VideoChannel.toFormattedJSON(),
520 account: this.VideoChannel.Account.toFormattedJSON(),
524 // Format and sort video files
525 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
526 detailsJson.files = this.VideoFiles
528 let resolutionLabel = videoFile.resolution + 'p'
530 const videoFileJson = {
531 resolution: videoFile.resolution,
533 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
534 size: videoFile.size,
535 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
536 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
542 if (a.resolution < b.resolution) return 1
543 if (a.resolution === b.resolution) return 0
547 return Object.assign(formattedJson, detailsJson)
550 toActivityPubObject = function (this: VideoInstance) {
551 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
552 if (!this.Tags) this.Tags = []
554 const tag = this.Tags.map(t => ({
555 type: 'Hashtag' as 'Hashtag',
562 identifier: this.language + '',
563 name: this.getLanguageLabel()
570 identifier: this.category + '',
571 name: this.getCategoryLabel()
578 identifier: this.licence + '',
579 name: this.getLicenceLabel()
586 if (Array.isArray(this.AccountVideoRates)) {
587 const likes: string[] = []
588 const dislikes: string[] = []
590 for (const rate of this.AccountVideoRates) {
591 if (rate.type === 'like') {
592 likes.push(rate.Account.url)
593 } else if (rate.type === 'dislike') {
594 dislikes.push(rate.Account.url)
598 likesObject = activityPubCollection(likes)
599 dislikesObject = activityPubCollection(dislikes)
603 if (Array.isArray(this.VideoShares)) {
604 const shares: string[] = []
606 for (const videoShare of this.VideoShares) {
607 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Account)
608 shares.push(shareUrl)
611 sharesObject = activityPubCollection(shares)
615 for (const file of this.VideoFiles) {
618 mimeType: 'video/' + file.extname.replace('.', ''),
619 url: getVideoFileUrl(this, file, baseUrlHttp),
620 width: file.resolution,
626 mimeType: 'application/x-bittorrent',
627 url: getTorrentUrl(this, file, baseUrlHttp),
628 width: file.resolution
633 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
634 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
635 width: file.resolution
642 mimeType: 'text/html',
643 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
646 const videoObject: VideoTorrentObject = {
647 type: 'Video' as 'Video',
650 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
651 duration: 'PT' + this.duration + 'S',
659 published: this.createdAt.toISOString(),
660 updated: this.updatedAt.toISOString(),
661 mediaType: 'text/markdown',
662 content: this.getTruncatedDescription(),
665 url: getThumbnailUrl(this, baseUrlHttp),
666 mediaType: 'image/jpeg',
667 width: THUMBNAILS_SIZE.width,
668 height: THUMBNAILS_SIZE.height
672 dislikes: dislikesObject,
679 getTruncatedDescription = function (this: VideoInstance) {
680 if (!this.description) return null
683 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
686 return truncate(this.description, options)
689 optimizeOriginalVideofile = async function (this: VideoInstance) {
690 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
691 const newExtname = '.mp4'
692 const inputVideoFile = this.getOriginalFile()
693 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
694 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
696 const transcodeOptions = {
697 inputPath: videoInputPath,
698 outputPath: videoOutputPath
702 // Could be very long!
703 await transcode(transcodeOptions)
705 await unlinkPromise(videoInputPath)
707 // Important to do this before getVideoFilename() to take in account the new file extension
708 inputVideoFile.set('extname', newExtname)
710 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
711 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
713 inputVideoFile.set('size', stats.size)
715 await this.createTorrentAndSetInfoHash(inputVideoFile)
716 await inputVideoFile.save()
719 // Auto destruction...
720 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
726 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
727 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
728 const extname = '.mp4'
730 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
731 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
733 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
739 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
741 const transcodeOptions = {
742 inputPath: videoInputPath,
743 outputPath: videoOutputPath,
747 await transcode(transcodeOptions)
749 const stats = await statPromise(videoOutputPath)
751 newVideoFile.set('size', stats.size)
753 await this.createTorrentAndSetInfoHash(newVideoFile)
755 await newVideoFile.save()
757 this.VideoFiles.push(newVideoFile)
760 getOriginalFileHeight = function (this: VideoInstance) {
761 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
763 return getVideoFileHeight(originalFilePath)
766 getDescriptionPath = function (this: VideoInstance) {
767 return `/api/${API_VERSION}/videos/${this.uuid}/description`
770 getCategoryLabel = function (this: VideoInstance) {
771 let categoryLabel = VIDEO_CATEGORIES[this.category]
772 if (!categoryLabel) categoryLabel = 'Misc'
777 getLicenceLabel = function (this: VideoInstance) {
778 let licenceLabel = VIDEO_LICENCES[this.licence]
779 if (!licenceLabel) licenceLabel = 'Unknown'
784 getLanguageLabel = function (this: VideoInstance) {
785 let languageLabel = VIDEO_LANGUAGES[this.language]
786 if (!languageLabel) languageLabel = 'Unknown'
791 removeThumbnail = function (this: VideoInstance) {
792 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
793 return unlinkPromise(thumbnailPath)
796 removePreview = function (this: VideoInstance) {
797 // Same name than video thumbnail
798 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
801 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
802 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
803 return unlinkPromise(filePath)
806 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
807 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
808 return unlinkPromise(torrentPath)
811 // ------------------------------ STATICS ------------------------------
815 include: [ Video['sequelize'].models.VideoFile ]
818 return Video.findAll(query)
821 listAllAndSharedByAccountForOutbox = function (accountId: number, start: number, count: number) {
822 function getRawQuery (select: string) {
823 const queryVideo = 'SELECT ' + select + ' FROM "Videos" AS "Video" ' +
824 'INNER JOIN "VideoChannels" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
825 'WHERE "VideoChannel"."accountId" = ' + accountId
826 const queryVideoShare = 'SELECT ' + select + ' FROM "VideoShares" AS "VideoShare" ' +
827 'INNER JOIN "Videos" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
828 'WHERE "VideoShare"."accountId" = ' + accountId
830 let rawQuery = `(${queryVideo}) UNION (${queryVideoShare})`
835 const rawQuery = getRawQuery('"Video"."id"')
836 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
842 order: [ getSort('createdAt'), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
845 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
850 model: Video['sequelize'].models.VideoShare,
853 [Sequelize.Op.and]: [
856 [Sequelize.Op.not]: null
864 include: [ Video['sequelize'].models.Account ]
867 model: Video['sequelize'].models.VideoChannel,
871 model: Video['sequelize'].models.Account,
877 model: Video['sequelize'].models.AccountVideoRate,
878 include: [ Video['sequelize'].models.Account ]
880 Video['sequelize'].models.VideoFile,
881 Video['sequelize'].models.Tag
885 return Bluebird.all([
886 Video.findAll(query),
887 Video['sequelize'].query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
888 ]).then(([ rows, totals ]) => {
889 // totals: totalVideos + totalVideoShares
891 let totalVideoShares = 0
892 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
893 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
895 const total = totalVideos + totalVideoShares
903 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
908 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
911 model: Video['sequelize'].models.VideoChannel,
915 model: Video['sequelize'].models.Account,
923 Video['sequelize'].models.Tag
927 return Video.findAndCountAll(query).then(({ rows, count }) => {
935 listForApi = function (start: number, count: number, sort: string) {
940 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
943 model: Video['sequelize'].models.VideoChannel,
947 model: Video['sequelize'].models.Account,
951 model: Video['sequelize'].models.Server,
958 Video['sequelize'].models.Tag
960 where: createBaseVideosWhere()
963 return Video.findAndCountAll(query).then(({ rows, count }) => {
971 load = function (id: number) {
972 return Video.findById(id)
975 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
976 const query: Sequelize.FindOptions<VideoAttributes> = {
980 include: [ Video['sequelize'].models.VideoFile ]
983 if (t !== undefined) query.transaction = t
985 return Video.findOne(query)
988 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
989 const query: Sequelize.FindOptions<VideoAttributes> = {
994 Video['sequelize'].models.VideoFile,
996 model: Video['sequelize'].models.VideoChannel,
997 include: [ Video['sequelize'].models.Account ]
1002 if (t !== undefined) query.transaction = t
1004 return Video.findOne(query)
1007 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
1008 const query: Sequelize.FindOptions<VideoAttributes> = {
1010 [Sequelize.Op.or]: [
1015 include: [ Video['sequelize'].models.VideoFile ]
1018 if (t !== undefined) query.transaction = t
1020 return Video.findOne(query)
1023 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1025 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1028 model: Video['sequelize'].models.VideoChannel,
1031 model: Video['sequelize'].models.Account,
1032 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1037 model: Video['sequelize'].models.AccountVideoRate,
1038 include: [ Video['sequelize'].models.Account ]
1041 model: Video['sequelize'].models.VideoShare,
1042 include: [ Video['sequelize'].models.Account ]
1044 Video['sequelize'].models.Tag,
1045 Video['sequelize'].models.VideoFile
1049 return Video.findById(id, options)
1052 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1054 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1060 model: Video['sequelize'].models.VideoChannel,
1063 model: Video['sequelize'].models.Account,
1064 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1069 model: Video['sequelize'].models.AccountVideoRate,
1070 include: [ Video['sequelize'].models.Account ]
1073 model: Video['sequelize'].models.VideoShare,
1074 include: [ Video['sequelize'].models.Account ]
1076 Video['sequelize'].models.Tag,
1077 Video['sequelize'].models.VideoFile
1081 return Video.findOne(options)
1084 searchAndPopulateAccountAndServerAndTags = function (value: string, start: number, count: number, sort: string) {
1085 const serverInclude: Sequelize.IncludeOptions = {
1086 model: Video['sequelize'].models.Server,
1090 const accountInclude: Sequelize.IncludeOptions = {
1091 model: Video['sequelize'].models.Account,
1092 include: [ serverInclude ]
1095 const videoChannelInclude: Sequelize.IncludeOptions = {
1096 model: Video['sequelize'].models.VideoChannel,
1097 include: [ accountInclude ],
1101 const tagInclude: Sequelize.IncludeOptions = {
1102 model: Video['sequelize'].models.Tag
1105 const query: Sequelize.FindOptions<VideoAttributes> = {
1107 where: createBaseVideosWhere(),
1110 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1113 // TODO: search on tags too
1114 // const escapedValue = Video['sequelize'].escape('%' + value + '%')
1115 // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1116 // `(SELECT "VideoTags"."videoId"
1118 // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1119 // WHERE name ILIKE ${escapedValue}
1123 // TODO: search on account too
1124 // accountInclude.where = {
1126 // [Sequelize.Op.iLike]: '%' + value + '%'
1129 query.where['name'] = {
1130 [Sequelize.Op.iLike]: '%' + value + '%'
1134 videoChannelInclude, tagInclude
1137 return Video.findAndCountAll(query).then(({ rows, count }) => {
1145 // ---------------------------------------------------------------------------
1147 function createBaseVideosWhere () {
1150 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1151 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1154 privacy: VideoPrivacy.PUBLIC
1158 function getBaseUrls (video: VideoInstance) {
1162 if (video.isOwned()) {
1163 baseUrlHttp = CONFIG.WEBSERVER.URL
1164 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1166 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1167 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1170 return { baseUrlHttp, baseUrlWs }
1173 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1174 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1177 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1178 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1181 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1182 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1185 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1186 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1187 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1188 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1190 const magnetHash = {
1194 infoHash: videoFile.infoHash,
1198 return magnetUtil.encode(magnetHash)