1 import * as express from 'express'
2 import { sanitizeUrl } from '@server/helpers/core-utils'
3 import { doJSONRequest } from '@server/helpers/requests'
4 import { CONFIG } from '@server/initializers/config'
5 import { WEBSERVER } from '@server/initializers/constants'
6 import { getOrCreateAPVideo } from '@server/lib/activitypub/videos'
7 import { Hooks } from '@server/lib/plugins/hooks'
8 import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search'
9 import { HttpStatusCode, ResultList, Video } from '@shared/models'
10 import { VideosSearchQuery } from '../../../../shared/models/search'
11 import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils'
12 import { logger } from '../../../helpers/logger'
13 import { getFormattedObjects } from '../../../helpers/utils'
16 commonVideosFiltersValidator,
22 videosSearchSortValidator,
24 } from '../../../middlewares'
25 import { VideoModel } from '../../../models/video/video'
26 import { MVideoAccountLightBlacklistAllFiles } from '../../../types/models'
28 const searchVideosRouter = express.Router()
30 searchVideosRouter.get('/videos',
31 openapiOperationDoc({ operationId: 'searchVideos' }),
34 videosSearchSortValidator,
37 commonVideosFiltersValidator,
38 videosSearchValidator,
39 asyncMiddleware(searchVideos)
42 // ---------------------------------------------------------------------------
44 export { searchVideosRouter }
46 // ---------------------------------------------------------------------------
48 function searchVideos (req: express.Request, res: express.Response) {
49 const query: VideosSearchQuery = req.query
50 const search = query.search
52 if (isURISearch(search)) {
53 return searchVideoURI(search, res)
56 if (isSearchIndexSearch(query)) {
57 return searchVideosIndex(query, res)
60 return searchVideosDB(query, res)
63 async function searchVideosIndex (query: VideosSearchQuery, res: express.Response) {
64 const result = await buildMutedForSearchIndex(res)
66 let body: VideosSearchQuery = Object.assign(query, result)
68 // Use the default instance NSFW policy if not specified
70 const nsfwPolicy = res.locals.oauth
71 ? res.locals.oauth.token.User.nsfwPolicy
72 : CONFIG.INSTANCE.DEFAULT_NSFW_POLICY
74 body.nsfw = nsfwPolicy === 'do_not_list'
79 body = await Hooks.wrapObject(body, 'filter:api.search.videos.index.list.params')
81 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/videos'
84 logger.debug('Doing videos search index request on %s.', url, { body })
86 const { body: searchIndexResult } = await doJSONRequest<ResultList<Video>>(url, { method: 'POST', json: body })
87 const jsonResult = await Hooks.wrapObject(searchIndexResult, 'filter:api.search.videos.index.list.result')
89 return res.json(jsonResult)
91 logger.warn('Cannot use search index to make video search.', { err })
94 status: HttpStatusCode.INTERNAL_SERVER_ERROR_500,
95 message: 'Cannot use search index to make video search'
100 async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
101 const apiOptions = await Hooks.wrapObject(Object.assign(query, {
102 includeLocalVideos: true,
103 nsfw: buildNSFWFilter(res, query.nsfw),
104 filter: query.filter,
105 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
106 }), 'filter:api.search.videos.local.list.params')
108 const resultList = await Hooks.wrapPromiseFun(
109 VideoModel.searchAndPopulateAccountAndServer,
111 'filter:api.search.videos.local.list.result'
114 return res.json(getFormattedObjects(resultList.data, resultList.total))
117 async function searchVideoURI (url: string, res: express.Response) {
118 let video: MVideoAccountLightBlacklistAllFiles
120 // Check if we can fetch a remote video with the URL
121 if (isUserAbleToSearchRemoteURI(res)) {
132 const result = await getOrCreateAPVideo({ videoObject: url, syncParam })
133 video = result ? result.video : undefined
135 logger.info('Cannot search remote video %s.', url, { err })
138 video = await VideoModel.loadByUrlAndPopulateAccount(sanitizeLocalUrl(url))
142 total: video ? 1 : 0,
143 data: video ? [ video.toFormattedJSON() ] : []
147 function sanitizeLocalUrl (url: string) {
150 // Handle alternative video URLs
151 return url.replace(new RegExp('^' + WEBSERVER.URL + '/w/'), WEBSERVER.URL + '/videos/watch/')