1 import * as express from 'express'
2 import { buildNSFWFilter } from '../../helpers/express-utils'
3 import { getFormattedObjects } from '../../helpers/utils'
4 import { VideoModel } from '../../models/video/video'
7 commonVideosFiltersValidator,
13 videosSearchSortValidator
14 } from '../../middlewares'
15 import { VideosSearchQuery } from '../../../shared/models/search'
16 import { getOrCreateVideoAndAccountAndChannel } from '../../lib/activitypub'
17 import { logger } from '../../helpers/logger'
18 import { User } from '../../../shared/models/users'
19 import { CONFIG } from '../../initializers/constants'
21 const searchRouter = express.Router()
23 searchRouter.get('/videos',
26 videosSearchSortValidator,
29 commonVideosFiltersValidator,
31 asyncMiddleware(searchVideos)
34 // ---------------------------------------------------------------------------
36 export { searchRouter }
38 // ---------------------------------------------------------------------------
40 function searchVideos (req: express.Request, res: express.Response) {
41 const query: VideosSearchQuery = req.query
42 if (query.search.startsWith('http://') || query.search.startsWith('https://')) {
43 return searchVideoUrl(query.search, res)
46 return searchVideosDB(query, res)
49 async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
50 const options = Object.assign(query, {
51 includeLocalVideos: true,
52 nsfw: buildNSFWFilter(res, query.nsfw)
54 const resultList = await VideoModel.searchAndPopulateAccountAndServer(options)
56 return res.json(getFormattedObjects(resultList.data, resultList.total))
59 async function searchVideoUrl (url: string, res: express.Response) {
61 const user: User = res.locals.oauth ? res.locals.oauth.token.User : undefined
63 // Check if we can fetch a remote video with the URL
65 CONFIG.SEARCH.REMOTE_URI.ANONYMOUS === true ||
66 (CONFIG.SEARCH.REMOTE_URI.USERS === true && user !== undefined)
78 const res = await getOrCreateVideoAndAccountAndChannel(url, syncParam)
79 video = res ? res.video : undefined
81 logger.info('Cannot search remote video %s.', url)
84 video = await VideoModel.loadByUrlAndPopulateAccount(url)
89 data: video ? [ video.toFormattedJSON() ] : []