1 import 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'
28 import { searchLocalUrl } from './shared'
30 const searchVideosRouter = express.Router()
32 searchVideosRouter.get('/videos',
33 openapiOperationDoc({ operationId: 'searchVideos' }),
36 videosSearchSortValidator,
39 commonVideosFiltersValidator,
40 videosSearchValidator,
41 asyncMiddleware(searchVideos)
44 // ---------------------------------------------------------------------------
46 export { searchVideosRouter }
48 // ---------------------------------------------------------------------------
50 function searchVideos (req: express.Request, res: express.Response) {
51 const query = pickSearchVideoQuery(req.query)
52 const search = query.search
54 if (isURISearch(search)) {
55 return searchVideoURI(search, res)
58 if (isSearchIndexSearch(query)) {
59 return searchVideosIndex(query, res)
62 return searchVideosDB(query, res)
65 async function searchVideosIndex (query: VideosSearchQueryAfterSanitize, res: express.Response) {
66 const result = await buildMutedForSearchIndex(res)
68 let body = { ...query, ...result }
70 // Use the default instance NSFW policy if not specified
72 const nsfwPolicy = res.locals.oauth
73 ? res.locals.oauth.token.User.nsfwPolicy
74 : CONFIG.INSTANCE.DEFAULT_NSFW_POLICY
76 body.nsfw = nsfwPolicy === 'do_not_list'
81 body = await Hooks.wrapObject(body, 'filter:api.search.videos.index.list.params')
83 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/videos'
86 logger.debug('Doing videos search index request on %s.', url, { body })
88 const { body: searchIndexResult } = await doJSONRequest<ResultList<Video>>(url, { method: 'POST', json: body })
89 const jsonResult = await Hooks.wrapObject(searchIndexResult, 'filter:api.search.videos.index.list.result')
91 return res.json(jsonResult)
93 logger.warn('Cannot use search index to make video search.', { err })
96 status: HttpStatusCode.INTERNAL_SERVER_ERROR_500,
97 message: 'Cannot use search index to make video search'
102 async function searchVideosDB (query: VideosSearchQueryAfterSanitize, res: express.Response) {
103 const apiOptions = await Hooks.wrapObject({
106 includeLocalVideos: true,
107 filter: query.filter,
109 nsfw: buildNSFWFilter(res, query.nsfw),
110 user: res.locals.oauth
111 ? res.locals.oauth.token.User
113 }, 'filter:api.search.videos.local.list.params')
115 const resultList = await Hooks.wrapPromiseFun(
116 VideoModel.searchAndPopulateAccountAndServer,
118 'filter:api.search.videos.local.list.result'
121 return res.json(getFormattedObjects(resultList.data, resultList.total))
124 async function searchVideoURI (url: string, res: express.Response) {
125 let video: MVideoAccountLightBlacklistAllFiles
127 // Check if we can fetch a remote video with the URL
128 if (isUserAbleToSearchRemoteURI(res)) {
139 const result = await getOrCreateAPVideo({ videoObject: url, syncParam })
140 video = result ? result.video : undefined
142 logger.info('Cannot search remote video %s.', url, { err })
145 video = await searchLocalUrl(sanitizeLocalUrl(url), url => VideoModel.loadByUrlAndPopulateAccount(url))
149 total: video ? 1 : 0,
150 data: video ? [ video.toFormattedJSON() ] : []
154 function sanitizeLocalUrl (url: string) {
157 // Handle alternative video URLs
158 return url.replace(new RegExp('^' + WEBSERVER.URL + '/w/'), WEBSERVER.URL + '/videos/watch/')