]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/search/search-videos.ts
Add channel filters for my videos/followers
[github/Chocobozzz/PeerTube.git] / server / controllers / api / search / search-videos.ts
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'
15 import {
16 asyncMiddleware,
17 commonVideosFiltersValidator,
18 openapiOperationDoc,
19 optionalAuthenticate,
20 paginationValidator,
21 setDefaultPagination,
22 setDefaultSearchSort,
23 videosSearchSortValidator,
24 videosSearchValidator
25 } from '../../../middlewares'
26 import { VideoModel } from '../../../models/video/video'
27 import { MVideoAccountLightBlacklistAllFiles } from '../../../types/models'
28
29 const searchVideosRouter = express.Router()
30
31 searchVideosRouter.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
45 export { searchVideosRouter }
46
47 // ---------------------------------------------------------------------------
48
49 function searchVideos (req: express.Request, res: express.Response) {
50 const query = pickSearchVideoQuery(req.query)
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
64 async function searchVideosIndex (query: VideosSearchQueryAfterSanitize, res: express.Response) {
65 const result = await buildMutedForSearchIndex(res)
66
67 let body = { ...query, ...result }
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
101 async function searchVideosDB (query: VideosSearchQueryAfterSanitize, res: express.Response) {
102 const apiOptions = await Hooks.wrapObject({
103 ...query,
104
105 includeLocalVideos: true,
106 filter: query.filter,
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')
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
123 async 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
153 function 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 }