import * as Bluebird from 'bluebird'
import { maxBy, minBy } from 'lodash'
import { join } from 'path'
-import {
- CountOptions,
- FindOptions,
- IncludeOptions,
- ModelIndexesOptions,
- Op,
- QueryTypes,
- ScopeOptions,
- Sequelize,
- Transaction,
- WhereOptions
-} from 'sequelize'
+import { CountOptions, FindOptions, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
import {
AllowNull,
BeforeDestroy,
import { MThumbnail } from '../../typings/models/video/thumbnail'
import { VideoFile } from '@shared/models/videos/video-file.model'
import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
-import * as validator from 'validator'
-
-// FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
-const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
- buildTrigramSearchIndex('video_name_trigram', 'name'),
-
- { fields: [ 'createdAt' ] },
- {
- fields: [
- { name: 'publishedAt', order: 'DESC' },
- { name: 'id', order: 'ASC' }
- ]
- },
- { fields: [ 'duration' ] },
- { fields: [ 'views' ] },
- { fields: [ 'channelId' ] },
- {
- fields: [ 'originallyPublishedAt' ],
- where: {
- originallyPublishedAt: {
- [Op.ne]: null
- }
- }
- },
- {
- fields: [ 'category' ], // We don't care videos with an unknown category
- where: {
- category: {
- [Op.ne]: null
- }
- }
- },
- {
- fields: [ 'licence' ], // We don't care videos with an unknown licence
- where: {
- licence: {
- [Op.ne]: null
- }
- }
- },
- {
- fields: [ 'language' ], // We don't care videos with an unknown language
- where: {
- language: {
- [Op.ne]: null
- }
- }
- },
- {
- fields: [ 'nsfw' ], // Most of the videos are not NSFW
- where: {
- nsfw: true
- }
- },
- {
- fields: [ 'remote' ], // Only index local videos
- where: {
- remote: false
- }
- },
- {
- fields: [ 'uuid' ],
- unique: true
- },
- {
- fields: [ 'url' ],
- unique: true
- }
-]
+import validator from 'validator'
export enum ScopeNames {
AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
if (options.ids) {
query.where = {
id: {
- [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
+ [ Op.in ]: options.ids
}
}
}
'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
- ' UNION ALL ' +
+ ')'
+ )
+ }
+ },
+ {
+ id: {
+ [ Op.in ]: Sequelize.literal(
+ '(' +
'SELECT "video"."id" AS "id" FROM "video" ' +
'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
}))
@Table({
tableName: 'video',
- indexes
+ indexes: [
+ buildTrigramSearchIndex('video_name_trigram', 'name'),
+
+ { fields: [ 'createdAt' ] },
+ {
+ fields: [
+ { name: 'publishedAt', order: 'DESC' },
+ { name: 'id', order: 'ASC' }
+ ]
+ },
+ { fields: [ 'duration' ] },
+ { fields: [ 'views' ] },
+ { fields: [ 'channelId' ] },
+ {
+ fields: [ 'originallyPublishedAt' ],
+ where: {
+ originallyPublishedAt: {
+ [Op.ne]: null
+ }
+ }
+ },
+ {
+ fields: [ 'category' ], // We don't care videos with an unknown category
+ where: {
+ category: {
+ [Op.ne]: null
+ }
+ }
+ },
+ {
+ fields: [ 'licence' ], // We don't care videos with an unknown licence
+ where: {
+ licence: {
+ [Op.ne]: null
+ }
+ }
+ },
+ {
+ fields: [ 'language' ], // We don't care videos with an unknown language
+ where: {
+ language: {
+ [Op.ne]: null
+ }
+ }
+ },
+ {
+ fields: [ 'nsfw' ], // Most of the videos are not NSFW
+ where: {
+ nsfw: true
+ }
+ },
+ {
+ fields: [ 'remote' ], // Only index local videos
+ where: {
+ remote: false
+ }
+ },
+ {
+ fields: [ 'uuid' ],
+ unique: true
+ },
+ {
+ fields: [ 'url' ],
+ unique: true
+ }
+ ]
})
export class VideoModel extends Model<VideoModel> {
if (instance.isOwned()) {
if (!Array.isArray(instance.VideoFiles)) {
- instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
+ instance.VideoFiles = await instance.$get('VideoFiles')
}
// Remove physical files and torrents
})
// Remove playlists file
- tasks.push(instance.removeStreamingPlaylist())
+ if (!Array.isArray(instance.VideoStreamingPlaylists)) {
+ instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
+ }
+
+ for (const p of instance.VideoStreamingPlaylists) {
+ tasks.push(instance.removeStreamingPlaylistFiles(p))
+ }
}
// Do not wait video deletion because we could be in a transaction
})
}
- static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
+ static listUserVideosForApi (
+ accountId: number,
+ start: number,
+ count: number,
+ sort: string,
+ search?: string
+ ) {
function buildBaseQuery (): FindOptions {
- return {
+ let baseQuery = {
offset: start,
limit: count,
order: getVideoSort(sort),
}
]
}
+
+ if (search) {
+ baseQuery = Object.assign(baseQuery, {
+ where: {
+ name: {
+ [ Op.iLike ]: '%' + search + '%'
+ }
+ }
+ })
+ }
+
+ return baseQuery
}
const countQuery = buildBaseQuery()
const findQuery = buildBaseQuery()
- const findScopes = [
+ const findScopes: (string | ScopeOptions)[] = [
ScopeNames.WITH_SCHEDULED_UPDATE,
ScopeNames.WITH_BLACKLISTED,
ScopeNames.WITH_THUMBNAILS
videoPlaylistId?: number,
trendingDays?: number,
user?: MUserAccountId,
- historyOfUser?: MUserId
- }, countVideos = true) {
+ historyOfUser?: MUserId,
+ countVideos?: boolean
+ }) {
if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
throw new Error('Try to filter all-local but no user has not the see all videos right')
}
trendingDays
}
- return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
+ return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
}
static async searchAndPopulateAccountAndServer (options: {
'UNION ALL ' +
'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
- 'WHERE "tag"."name" = ' + escapedSearch +
+ 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
')'
)
}
]
}
- const [ count, ids ] = await Promise.all([
+ const [ count, rows ] = await Promise.all([
countVideos
? VideoModel.scope(countScope).count(countQuery)
: Promise.resolve<number>(undefined),
VideoModel.scope(idsScope)
- .findAll(query)
+ .findAll(Object.assign({}, query, { raw: true }))
.then(rows => rows.map(r => r.id))
+ .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
])
- if (ids.length === 0) return { data: [], total: count }
+ return {
+ data: rows,
+ total: count
+ }
+ }
+
+ private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
+ if (ids.length === 0) return []
const secondQuery: FindOptions = {
offset: 0,
]
})
- const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
-
- return {
- data: rows,
- total: count
- }
+ return VideoModel.scope(apiScope).findAll(secondQuery)
}
private static isPrivacyForFederation (privacy: VideoPrivacy) {
- return privacy === VideoPrivacy.PUBLIC || privacy === VideoPrivacy.UNLISTED
+ const castedPrivacy = parseInt(privacy + '', 10)
+
+ return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
}
static getCategoryLabel (id: number) {
.catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
}
- removeStreamingPlaylist (isRedundancy = false) {
+ async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
const directoryPath = getHLSDirectory(this, isRedundancy)
- return remove(directoryPath)
- .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
+ await remove(directoryPath)
+
+ if (isRedundancy !== true) {
+ let streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
+ streamingPlaylistWithFiles.Video = this
+
+ if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
+ streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
+ }
+
+ // Remove physical files and torrents
+ await Promise.all(
+ streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
+ )
+ }
}
isOutdated () {