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 } from '@shared/core-utils/miscs/http-error-codes'
10 import { ResultList, Video } from '@shared/models'
11 import { VideosSearchQuery } from '../../../../shared/models/search'
12 import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils'
13 import { logger } from '../../../helpers/logger'
14 import { getFormattedObjects } from '../../../helpers/utils'
17 commonVideosFiltersValidator,
23 videosSearchSortValidator,
25 } from '../../../middlewares'
26 import { VideoModel } from '../../../models/video/video'
27 import { MVideoAccountLightBlacklistAllFiles } from '../../../types/models'
29 const searchVideosRouter = express.Router()
31 searchVideosRouter.get('/videos',
32 openapiOperationDoc({ operationId: 'searchVideos' }),
35 videosSearchSortValidator,
38 commonVideosFiltersValidator,
39 videosSearchValidator,
40 asyncMiddleware(searchVideos)
43 // ---------------------------------------------------------------------------
45 export { searchVideosRouter }
47 // ---------------------------------------------------------------------------
49 function searchVideos (req: express.Request, res: express.Response) {
50 const query: VideosSearchQuery = req.query
51 const search = query.search
53 if (isURISearch(search)) {
54 return searchVideoURI(search, res)
57 if (isSearchIndexSearch(query)) {
58 return searchVideosIndex(query, res)
61 return searchVideosDB(query, res)
64 async function searchVideosIndex (query: VideosSearchQuery, res: express.Response) {
65 const result = await buildMutedForSearchIndex(res)
67 let body: VideosSearchQuery = Object.assign(query, result)
69 // Use the default instance NSFW policy if not specified
71 const nsfwPolicy = res.locals.oauth
72 ? res.locals.oauth.token.User.nsfwPolicy
73 : CONFIG.INSTANCE.DEFAULT_NSFW_POLICY
75 body.nsfw = nsfwPolicy === 'do_not_list'
80 body = await Hooks.wrapObject(body, 'filter:api.search.videos.index.list.params')
82 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/videos'
85 logger.debug('Doing videos search index request on %s.', url, { body })
87 const { body: searchIndexResult } = await doJSONRequest<ResultList<Video>>(url, { method: 'POST', json: body })
88 const jsonResult = await Hooks.wrapObject(searchIndexResult, 'filter:api.search.videos.index.list.result')
90 return res.json(jsonResult)
92 logger.warn('Cannot use search index to make video search.', { err })
95 status: HttpStatusCode.INTERNAL_SERVER_ERROR_500,
96 message: 'Cannot use search index to make video search'
101 async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
102 const apiOptions = await Hooks.wrapObject(Object.assign(query, {
103 includeLocalVideos: true,
104 nsfw: buildNSFWFilter(res, query.nsfw),
105 filter: query.filter,
106 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
107 }), 'filter:api.search.videos.local.list.params')
109 const resultList = await Hooks.wrapPromiseFun(
110 VideoModel.searchAndPopulateAccountAndServer,
112 'filter:api.search.videos.local.list.result'
115 return res.json(getFormattedObjects(resultList.data, resultList.total))
118 async function searchVideoURI (url: string, res: express.Response) {
119 let video: MVideoAccountLightBlacklistAllFiles
121 // Check if we can fetch a remote video with the URL
122 if (isUserAbleToSearchRemoteURI(res)) {
133 const result = await getOrCreateAPVideo({ videoObject: url, syncParam })
134 video = result ? result.video : undefined
136 logger.info('Cannot search remote video %s.', url, { err })
139 video = await VideoModel.loadByUrlAndPopulateAccount(sanitizeLocalUrl(url))
143 total: video ? 1 : 0,
144 data: video ? [ video.toFormattedJSON() ] : []
148 function sanitizeLocalUrl (url: string) {
151 // Handle alternative video URLs
152 return url.replace(new RegExp('^' + WEBSERVER.URL + '/w/'), WEBSERVER.URL + '/videos/watch/')