]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/search/search-videos.ts
Merge branch 'release/3.3.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / search / search-videos.ts
CommitLineData
37a44fc9
C
1import * as express from 'express'
2import { sanitizeUrl } from '@server/helpers/core-utils'
d6886027 3import { pickSearchVideoQuery } from '@server/helpers/query'
37a44fc9
C
4import { doJSONRequest } from '@server/helpers/requests'
5import { CONFIG } from '@server/initializers/config'
6import { WEBSERVER } from '@server/initializers/constants'
7import { getOrCreateAPVideo } from '@server/lib/activitypub/videos'
8import { Hooks } from '@server/lib/plugins/hooks'
9import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search'
4c7e60bc 10import { HttpStatusCode, ResultList, Video } from '@shared/models'
d6886027 11import { VideosSearchQueryAfterSanitize } from '../../../../shared/models/search'
37a44fc9
C
12import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils'
13import { logger } from '../../../helpers/logger'
14import { getFormattedObjects } from '../../../helpers/utils'
15import {
16 asyncMiddleware,
17 commonVideosFiltersValidator,
18 openapiOperationDoc,
19 optionalAuthenticate,
20 paginationValidator,
21 setDefaultPagination,
22 setDefaultSearchSort,
23 videosSearchSortValidator,
24 videosSearchValidator
25} from '../../../middlewares'
26import { VideoModel } from '../../../models/video/video'
27import { MVideoAccountLightBlacklistAllFiles } from '../../../types/models'
28
29const searchVideosRouter = express.Router()
30
31searchVideosRouter.get('/videos',
32 openapiOperationDoc({ operationId: 'searchVideos' }),
33 paginationValidator,
34 setDefaultPagination,
35 videosSearchSortValidator,
36 setDefaultSearchSort,
37 optionalAuthenticate,
38 commonVideosFiltersValidator,
39 videosSearchValidator,
40 asyncMiddleware(searchVideos)
41)
42
43// ---------------------------------------------------------------------------
44
45export { searchVideosRouter }
46
47// ---------------------------------------------------------------------------
48
49function searchVideos (req: express.Request, res: express.Response) {
d6886027 50 const query = pickSearchVideoQuery(req.query)
37a44fc9
C
51 const search = query.search
52
53 if (isURISearch(search)) {
54 return searchVideoURI(search, res)
55 }
56
57 if (isSearchIndexSearch(query)) {
58 return searchVideosIndex(query, res)
59 }
60
61 return searchVideosDB(query, res)
62}
63
d6886027 64async function searchVideosIndex (query: VideosSearchQueryAfterSanitize, res: express.Response) {
37a44fc9
C
65 const result = await buildMutedForSearchIndex(res)
66
d6886027 67 let body = { ...query, ...result }
37a44fc9
C
68
69 // Use the default instance NSFW policy if not specified
70 if (!body.nsfw) {
71 const nsfwPolicy = res.locals.oauth
72 ? res.locals.oauth.token.User.nsfwPolicy
73 : CONFIG.INSTANCE.DEFAULT_NSFW_POLICY
74
75 body.nsfw = nsfwPolicy === 'do_not_list'
76 ? 'false'
77 : 'both'
78 }
79
80 body = await Hooks.wrapObject(body, 'filter:api.search.videos.index.list.params')
81
82 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/videos'
83
84 try {
85 logger.debug('Doing videos search index request on %s.', url, { body })
86
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')
89
90 return res.json(jsonResult)
91 } catch (err) {
92 logger.warn('Cannot use search index to make video search.', { err })
93
94 return res.fail({
95 status: HttpStatusCode.INTERNAL_SERVER_ERROR_500,
96 message: 'Cannot use search index to make video search'
97 })
98 }
99}
100
d6886027
C
101async function searchVideosDB (query: VideosSearchQueryAfterSanitize, res: express.Response) {
102 const apiOptions = await Hooks.wrapObject({
103 ...query,
104
37a44fc9 105 includeLocalVideos: true,
37a44fc9 106 filter: query.filter,
d6886027
C
107
108 nsfw: buildNSFWFilter(res, query.nsfw),
109 user: res.locals.oauth
110 ? res.locals.oauth.token.User
111 : undefined
112 }, 'filter:api.search.videos.local.list.params')
37a44fc9
C
113
114 const resultList = await Hooks.wrapPromiseFun(
115 VideoModel.searchAndPopulateAccountAndServer,
116 apiOptions,
117 'filter:api.search.videos.local.list.result'
118 )
119
120 return res.json(getFormattedObjects(resultList.data, resultList.total))
121}
122
123async function searchVideoURI (url: string, res: express.Response) {
124 let video: MVideoAccountLightBlacklistAllFiles
125
126 // Check if we can fetch a remote video with the URL
127 if (isUserAbleToSearchRemoteURI(res)) {
128 try {
129 const syncParam = {
130 likes: false,
131 dislikes: false,
132 shares: false,
133 comments: false,
134 thumbnail: true,
135 refreshVideo: false
136 }
137
138 const result = await getOrCreateAPVideo({ videoObject: url, syncParam })
139 video = result ? result.video : undefined
140 } catch (err) {
141 logger.info('Cannot search remote video %s.', url, { err })
142 }
143 } else {
144 video = await VideoModel.loadByUrlAndPopulateAccount(sanitizeLocalUrl(url))
145 }
146
147 return res.json({
148 total: video ? 1 : 0,
149 data: video ? [ video.toFormattedJSON() ] : []
150 })
151}
152
153function sanitizeLocalUrl (url: string) {
154 if (!url) return ''
155
156 // Handle alternative video URLs
157 return url.replace(new RegExp('^' + WEBSERVER.URL + '/w/'), WEBSERVER.URL + '/videos/watch/')
158}