1 import * as express from 'express'
2 import { sanitizeUrl } from '@server/helpers/core-utils'
3 import { pickSearchVideoQuery } from '@server/helpers/query'
4 import { doJSONRequest } from '@server/helpers/requests'
5 import { CONFIG } from '@server/initializers/config'
6 import { WEBSERVER } from '@server/initializers/constants'
7 import { getOrCreateAPVideo } from '@server/lib/activitypub/videos'
8 import { Hooks } from '@server/lib/plugins/hooks'
9 import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search'
10 import { HttpStatusCode, ResultList, Video } from '@shared/models'
11 import { VideosSearchQueryAfterSanitize } 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 = pickSearchVideoQuery(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: VideosSearchQueryAfterSanitize, res: express.Response) {
65 const result = await buildMutedForSearchIndex(res)
67 let body = { ...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: VideosSearchQueryAfterSanitize, res: express.Response) {
102 const apiOptions = await Hooks.wrapObject({
105 includeLocalVideos: true,
106 filter: query.filter,
108 nsfw: buildNSFWFilter(res, query.nsfw),
109 user: res.locals.oauth
110 ? res.locals.oauth.token.User
112 }, 'filter:api.search.videos.local.list.params')
114 const resultList = await Hooks.wrapPromiseFun(
115 VideoModel.searchAndPopulateAccountAndServer,
117 'filter:api.search.videos.local.list.result'
120 return res.json(getFormattedObjects(resultList.data, resultList.total))
123 async function searchVideoURI (url: string, res: express.Response) {
124 let video: MVideoAccountLightBlacklistAllFiles
126 // Check if we can fetch a remote video with the URL
127 if (isUserAbleToSearchRemoteURI(res)) {
138 const result = await getOrCreateAPVideo({ videoObject: url, syncParam })
139 video = result ? result.video : undefined
141 logger.info('Cannot search remote video %s.', url, { err })
144 video = await VideoModel.loadByUrlAndPopulateAccount(sanitizeLocalUrl(url))
148 total: video ? 1 : 0,
149 data: video ? [ video.toFormattedJSON() ] : []
153 function sanitizeLocalUrl (url: string) {
156 // Handle alternative video URLs
157 return url.replace(new RegExp('^' + WEBSERVER.URL + '/w/'), WEBSERVER.URL + '/videos/watch/')