1 import { map, maxBy, truncate } from 'lodash'
2 import * as magnetUtil from 'magnet-uri'
3 import * as parseTorrent from 'parse-torrent'
4 import { join } from 'path'
5 import * as safeBuffer from 'safe-buffer'
6 import * as Sequelize from 'sequelize'
7 import { VideoPrivacy, VideoResolution } from '../../../shared'
8 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects/video-torrent-object'
11 generateImageFromVideoFile,
15 isVideoDescriptionValid,
28 } from '../../helpers'
41 } from '../../initializers'
43 import { addMethodsToModel, getSort } from '../utils'
45 import { TagInstance } from './tag-interface'
46 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
47 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
48 import { sendDeleteVideo } from '../../lib/activitypub/send-request'
49 import { isVideoUrlValid } from '../../helpers/custom-validators/videos'
51 const Buffer = safeBuffer.Buffer
53 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
54 let getOriginalFile: VideoMethods.GetOriginalFile
55 let getVideoFilename: VideoMethods.GetVideoFilename
56 let getThumbnailName: VideoMethods.GetThumbnailName
57 let getThumbnailPath: VideoMethods.GetThumbnailPath
58 let getPreviewName: VideoMethods.GetPreviewName
59 let getPreviewPath: VideoMethods.GetPreviewPath
60 let getTorrentFileName: VideoMethods.GetTorrentFileName
61 let isOwned: VideoMethods.IsOwned
62 let toFormattedJSON: VideoMethods.ToFormattedJSON
63 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
64 let toActivityPubObject: VideoMethods.ToActivityPubObject
65 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
66 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
67 let createPreview: VideoMethods.CreatePreview
68 let createThumbnail: VideoMethods.CreateThumbnail
69 let getVideoFilePath: VideoMethods.GetVideoFilePath
70 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
71 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
72 let getEmbedPath: VideoMethods.GetEmbedPath
73 let getDescriptionPath: VideoMethods.GetDescriptionPath
74 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
75 let getCategoryLabel: VideoMethods.GetCategoryLabel
76 let getLicenceLabel: VideoMethods.GetLicenceLabel
77 let getLanguageLabel: VideoMethods.GetLanguageLabel
79 let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData
80 let list: VideoMethods.List
81 let listForApi: VideoMethods.ListForApi
82 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
83 let loadByHostAndUUID: VideoMethods.LoadByHostAndUUID
84 let listOwnedAndPopulateAccountAndTags: VideoMethods.ListOwnedAndPopulateAccountAndTags
85 let listOwnedByAccount: VideoMethods.ListOwnedByAccount
86 let load: VideoMethods.Load
87 let loadByUUID: VideoMethods.LoadByUUID
88 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
89 let loadLocalVideoByUUID: VideoMethods.LoadLocalVideoByUUID
90 let loadAndPopulateAccount: VideoMethods.LoadAndPopulateAccount
91 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
92 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
93 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
94 let removeThumbnail: VideoMethods.RemoveThumbnail
95 let removePreview: VideoMethods.RemovePreview
96 let removeFile: VideoMethods.RemoveFile
97 let removeTorrent: VideoMethods.RemoveTorrent
99 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
100 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
103 type: DataTypes.UUID,
104 defaultValue: DataTypes.UUIDV4,
111 type: DataTypes.STRING,
114 nameValid: value => {
115 const res = isVideoNameValid(value)
116 if (res === false) throw new Error('Video name is not valid.')
121 type: DataTypes.INTEGER,
124 categoryValid: value => {
125 const res = isVideoCategoryValid(value)
126 if (res === false) throw new Error('Video category is not valid.')
131 type: DataTypes.INTEGER,
135 licenceValid: value => {
136 const res = isVideoLicenceValid(value)
137 if (res === false) throw new Error('Video licence is not valid.')
142 type: DataTypes.INTEGER,
145 languageValid: value => {
146 const res = isVideoLanguageValid(value)
147 if (res === false) throw new Error('Video language is not valid.')
152 type: DataTypes.INTEGER,
155 privacyValid: value => {
156 const res = isVideoPrivacyValid(value)
157 if (res === false) throw new Error('Video privacy is not valid.')
162 type: DataTypes.BOOLEAN,
165 nsfwValid: value => {
166 const res = isVideoNSFWValid(value)
167 if (res === false) throw new Error('Video nsfw attribute is not valid.')
172 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
175 descriptionValid: value => {
176 const res = isVideoDescriptionValid(value)
177 if (res === false) throw new Error('Video description is not valid.')
182 type: DataTypes.INTEGER,
185 durationValid: value => {
186 const res = isVideoDurationValid(value)
187 if (res === false) throw new Error('Video duration is not valid.')
192 type: DataTypes.INTEGER,
201 type: DataTypes.INTEGER,
210 type: DataTypes.INTEGER,
219 type: DataTypes.BOOLEAN,
224 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
228 const res = isVideoUrlValid(value)
229 if (res === false) throw new Error('Video URL is not valid.')
240 fields: [ 'createdAt' ]
243 fields: [ 'duration' ]
255 fields: [ 'channelId' ]
264 const classMethods = [
267 generateThumbnailFromData,
270 listUserVideosForApi,
271 listOwnedAndPopulateAccountAndTags,
274 loadAndPopulateAccount,
275 loadAndPopulateAccountAndServerAndTags,
279 loadLocalVideoByUUID,
280 loadByUUIDAndPopulateAccountAndServerAndTags,
281 searchAndPopulateAccountAndServerAndTags
283 const instanceMethods = [
286 createTorrentAndSetInfoHash,
302 toFormattedDetailsJSON,
303 optimizeOriginalVideofile,
304 transcodeOriginalVideofile,
305 getOriginalFileHeight,
307 getTruncatedDescription,
313 addMethodsToModel(Video, classMethods, instanceMethods)
318 // ------------------------------ METHODS ------------------------------
320 function associate (models) {
321 Video.belongsTo(models.VideoChannel, {
329 Video.belongsToMany(models.Tag, {
330 foreignKey: 'videoId',
331 through: models.VideoTag,
335 Video.hasMany(models.VideoAbuse, {
343 Video.hasMany(models.VideoFile, {
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 account: 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(),
523 // Format and sort video files
524 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
525 detailsJson.files = this.VideoFiles
527 let resolutionLabel = videoFile.resolution + 'p'
529 const videoFileJson = {
530 resolution: videoFile.resolution,
532 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
533 size: videoFile.size,
534 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
535 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
541 if (a.resolution < b.resolution) return 1
542 if (a.resolution === b.resolution) return 0
546 return Object.assign(formattedJson, detailsJson)
549 toActivityPubObject = function (this: VideoInstance) {
550 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
552 const tag = this.Tags.map(t => ({
553 type: 'Hashtag' as 'Hashtag',
558 for (const file of this.VideoFiles) {
561 mimeType: 'video/' + file.extname.replace('.', ''),
562 url: getVideoFileUrl(this, file, baseUrlHttp),
563 width: file.resolution,
569 mimeType: 'application/x-bittorrent',
570 url: getTorrentUrl(this, file, baseUrlHttp),
571 width: file.resolution
576 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
577 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
578 width: file.resolution
582 const videoObject: VideoTorrentObject = {
583 type: 'Video' as 'Video',
584 id: getActivityPubUrl('video', this.uuid),
586 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
587 duration: 'PT' + this.duration + 'S',
591 identifier: this.category + '',
592 name: this.getCategoryLabel()
595 identifier: this.licence + '',
596 name: this.getLicenceLabel()
599 identifier: this.language + '',
600 name: this.getLanguageLabel()
604 published: this.createdAt.toISOString(),
605 updated: this.updatedAt.toISOString(),
606 mediaType: 'text/markdown',
607 content: this.getTruncatedDescription(),
610 url: getThumbnailUrl(this, baseUrlHttp),
611 mediaType: 'image/jpeg',
612 width: THUMBNAILS_SIZE.width,
613 height: THUMBNAILS_SIZE.height
621 getTruncatedDescription = function (this: VideoInstance) {
623 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
626 return truncate(this.description, options)
629 optimizeOriginalVideofile = async function (this: VideoInstance) {
630 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
631 const newExtname = '.mp4'
632 const inputVideoFile = this.getOriginalFile()
633 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
634 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
636 const transcodeOptions = {
637 inputPath: videoInputPath,
638 outputPath: videoOutputPath
642 // Could be very long!
643 await transcode(transcodeOptions)
645 await unlinkPromise(videoInputPath)
647 // Important to do this before getVideoFilename() to take in account the new file extension
648 inputVideoFile.set('extname', newExtname)
650 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
651 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
653 inputVideoFile.set('size', stats.size)
655 await this.createTorrentAndSetInfoHash(inputVideoFile)
656 await inputVideoFile.save()
659 // Auto destruction...
660 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
666 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
667 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
668 const extname = '.mp4'
670 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
671 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
673 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
679 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
681 const transcodeOptions = {
682 inputPath: videoInputPath,
683 outputPath: videoOutputPath,
687 await transcode(transcodeOptions)
689 const stats = await statPromise(videoOutputPath)
691 newVideoFile.set('size', stats.size)
693 await this.createTorrentAndSetInfoHash(newVideoFile)
695 await newVideoFile.save()
697 this.VideoFiles.push(newVideoFile)
700 getOriginalFileHeight = function (this: VideoInstance) {
701 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
703 return getVideoFileHeight(originalFilePath)
706 getDescriptionPath = function (this: VideoInstance) {
707 return `/api/${API_VERSION}/videos/${this.uuid}/description`
710 getCategoryLabel = function (this: VideoInstance) {
711 let categoryLabel = VIDEO_CATEGORIES[this.category]
713 // Maybe our server is not up to date and there are new categories since our version
714 if (!categoryLabel) categoryLabel = 'Misc'
719 getLicenceLabel = function (this: VideoInstance) {
720 let licenceLabel = VIDEO_LICENCES[this.licence]
722 // Maybe our server is not up to date and there are new licences since our version
723 if (!licenceLabel) licenceLabel = 'Unknown'
728 getLanguageLabel = function (this: VideoInstance) {
729 // Language is an optional attribute
730 let languageLabel = VIDEO_LANGUAGES[this.language]
731 if (!languageLabel) languageLabel = 'Unknown'
736 removeThumbnail = function (this: VideoInstance) {
737 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
738 return unlinkPromise(thumbnailPath)
741 removePreview = function (this: VideoInstance) {
742 // Same name than video thumbnail
743 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
746 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
747 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
748 return unlinkPromise(filePath)
751 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
752 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
753 return unlinkPromise(torrentPath)
756 // ------------------------------ STATICS ------------------------------
758 generateThumbnailFromData = function (video: VideoInstance, thumbnailData: string) {
759 // Creating the thumbnail for a remote video
761 const thumbnailName = video.getThumbnailName()
762 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
763 return writeFilePromise(thumbnailPath, Buffer.from(thumbnailData, 'binary')).then(() => {
770 include: [ Video['sequelize'].models.VideoFile ]
773 return Video.findAll(query)
776 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
781 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
784 model: Video['sequelize'].models.VideoChannel,
788 model: Video['sequelize'].models.Account,
796 Video['sequelize'].models.Tag
800 return Video.findAndCountAll(query).then(({ rows, count }) => {
808 listForApi = function (start: number, count: number, sort: string) {
813 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
816 model: Video['sequelize'].models.VideoChannel,
820 model: Video['sequelize'].models.Account,
824 model: Video['sequelize'].models.Server,
831 Video['sequelize'].models.Tag
833 where: createBaseVideosWhere()
836 return Video.findAndCountAll(query).then(({ rows, count }) => {
844 loadByHostAndUUID = function (fromHost: string, uuid: string, t?: Sequelize.Transaction) {
845 const query: Sequelize.FindOptions<VideoAttributes> = {
851 model: Video['sequelize'].models.VideoFile
854 model: Video['sequelize'].models.VideoChannel,
857 model: Video['sequelize'].models.Account,
860 model: Video['sequelize'].models.Server,
873 if (t !== undefined) query.transaction = t
875 return Video.findOne(query)
878 listOwnedAndPopulateAccountAndTags = function () {
884 Video['sequelize'].models.VideoFile,
886 model: Video['sequelize'].models.VideoChannel,
887 include: [ Video['sequelize'].models.Account ]
889 Video['sequelize'].models.Tag
893 return Video.findAll(query)
896 listOwnedByAccount = function (account: string) {
903 model: Video['sequelize'].models.VideoFile
906 model: Video['sequelize'].models.VideoChannel,
909 model: Video['sequelize'].models.Account,
919 return Video.findAll(query)
922 load = function (id: number) {
923 return Video.findById(id)
926 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
927 const query: Sequelize.FindOptions<VideoAttributes> = {
931 include: [ Video['sequelize'].models.VideoFile ]
934 if (t !== undefined) query.transaction = t
936 return Video.findOne(query)
939 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
940 const query: Sequelize.FindOptions<VideoAttributes> = {
947 include: [ Video['sequelize'].models.VideoFile ]
950 if (t !== undefined) query.transaction = t
952 return Video.findOne(query)
955 loadLocalVideoByUUID = function (uuid: string, t?: Sequelize.Transaction) {
956 const query: Sequelize.FindOptions<VideoAttributes> = {
961 include: [ Video['sequelize'].models.VideoFile ]
964 if (t !== undefined) query.transaction = t
966 return Video.findOne(query)
969 loadAndPopulateAccount = function (id: number) {
972 Video['sequelize'].models.VideoFile,
974 model: Video['sequelize'].models.VideoChannel,
975 include: [ Video['sequelize'].models.Account ]
980 return Video.findById(id, options)
983 loadAndPopulateAccountAndServerAndTags = function (id: number) {
987 model: Video['sequelize'].models.VideoChannel,
990 model: Video['sequelize'].models.Account,
991 include: [ { model: Video['sequelize'].models.Server, required: false } ]
995 Video['sequelize'].models.Tag,
996 Video['sequelize'].models.VideoFile
1000 return Video.findById(id, options)
1003 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1010 model: Video['sequelize'].models.VideoChannel,
1013 model: Video['sequelize'].models.Account,
1014 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1018 Video['sequelize'].models.Tag,
1019 Video['sequelize'].models.VideoFile
1023 return Video.findOne(options)
1026 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1027 const serverInclude: Sequelize.IncludeOptions = {
1028 model: Video['sequelize'].models.Server,
1032 const accountInclude: Sequelize.IncludeOptions = {
1033 model: Video['sequelize'].models.Account,
1034 include: [ serverInclude ]
1037 const videoChannelInclude: Sequelize.IncludeOptions = {
1038 model: Video['sequelize'].models.VideoChannel,
1039 include: [ accountInclude ],
1043 const tagInclude: Sequelize.IncludeOptions = {
1044 model: Video['sequelize'].models.Tag
1047 const query: Sequelize.FindOptions<VideoAttributes> = {
1049 where: createBaseVideosWhere(),
1052 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1055 if (field === 'tags') {
1056 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1057 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1058 `(SELECT "VideoTags"."videoId"
1060 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1061 WHERE name ILIKE ${escapedValue}
1064 } else if (field === 'host') {
1065 // FIXME: Include our server? (not stored in the database)
1066 serverInclude.where = {
1068 [Sequelize.Op.iLike]: '%' + value + '%'
1071 serverInclude.required = true
1072 } else if (field === 'account') {
1073 accountInclude.where = {
1075 [Sequelize.Op.iLike]: '%' + value + '%'
1079 query.where[field] = {
1080 [Sequelize.Op.iLike]: '%' + value + '%'
1085 videoChannelInclude, tagInclude
1088 return Video.findAndCountAll(query).then(({ rows, count }) => {
1096 // ---------------------------------------------------------------------------
1098 function createBaseVideosWhere () {
1101 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1102 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1105 privacy: VideoPrivacy.PUBLIC
1109 function getBaseUrls (video: VideoInstance) {
1113 if (video.isOwned()) {
1114 baseUrlHttp = CONFIG.WEBSERVER.URL
1115 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1117 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1118 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1121 return { baseUrlHttp, baseUrlWs }
1124 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1125 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1128 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1129 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1132 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1133 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1136 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1137 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1138 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1139 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1141 const magnetHash = {
1145 infoHash: videoFile.infoHash,
1149 return magnetUtil.encode(magnetHash)