]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/search.ts
Use raw sql for abuses
[github/Chocobozzz/PeerTube.git] / server / controllers / api / search.ts
CommitLineData
57c36b27 1import * as express from 'express'
5fb2e288
C
2import { sanitizeUrl } from '@server/helpers/core-utils'
3import { doRequest } from '@server/helpers/requests'
4import { CONFIG } from '@server/initializers/config'
5import { getOrCreateVideoAndAccountAndChannel } from '@server/lib/activitypub/videos'
6import { AccountBlocklistModel } from '@server/models/account/account-blocklist'
7import { getServerActor } from '@server/models/application/application'
8import { ServerBlocklistModel } from '@server/models/server/server-blocklist'
9import { ResultList, Video, VideoChannel } from '@shared/models'
10import { SearchTargetQuery } from '@shared/models/search/search-target-query.model'
11import { VideoChannelsSearchQuery, VideosSearchQuery } from '../../../shared/models/search'
687d638c 12import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
5fb2e288 13import { logger } from '../../helpers/logger'
8dc8a34e 14import { getFormattedObjects } from '../../helpers/utils'
5fb2e288
C
15import { loadActorUrlOrGetFromWebfinger } from '../../helpers/webfinger'
16import { getOrCreateActorAndServerAndModel } from '../../lib/activitypub/actor'
57c36b27
C
17import {
18 asyncMiddleware,
d525fc39 19 commonVideosFiltersValidator,
57c36b27
C
20 optionalAuthenticate,
21 paginationValidator,
57c36b27
C
22 setDefaultPagination,
23 setDefaultSearchSort,
f37dc0dd
C
24 videoChannelsSearchSortValidator,
25 videoChannelsSearchValidator,
26 videosSearchSortValidator,
27 videosSearchValidator
57c36b27 28} from '../../middlewares'
5fb2e288 29import { VideoModel } from '../../models/video/video'
f37dc0dd 30import { VideoChannelModel } from '../../models/video/video-channel'
26d6bf65 31import { MChannelAccountDefault, MVideoAccountLightBlacklistAllFiles } from '../../types/models'
57c36b27
C
32
33const searchRouter = express.Router()
34
35searchRouter.get('/videos',
36 paginationValidator,
37 setDefaultPagination,
38 videosSearchSortValidator,
39 setDefaultSearchSort,
40 optionalAuthenticate,
d525fc39 41 commonVideosFiltersValidator,
f37dc0dd 42 videosSearchValidator,
57c36b27
C
43 asyncMiddleware(searchVideos)
44)
45
f37dc0dd
C
46searchRouter.get('/video-channels',
47 paginationValidator,
48 setDefaultPagination,
49 videoChannelsSearchSortValidator,
50 setDefaultSearchSort,
51 optionalAuthenticate,
f37dc0dd
C
52 videoChannelsSearchValidator,
53 asyncMiddleware(searchVideoChannels)
54)
55
57c36b27
C
56// ---------------------------------------------------------------------------
57
58export { searchRouter }
59
60// ---------------------------------------------------------------------------
61
f37dc0dd
C
62function searchVideoChannels (req: express.Request, res: express.Response) {
63 const query: VideoChannelsSearchQuery = req.query
64 const search = query.search
65
66 const isURISearch = search.startsWith('http://') || search.startsWith('https://')
67
68 const parts = search.split('@')
2ff83ae2
C
69
70 // Handle strings like @toto@example.com
71 if (parts.length === 3 && parts[0].length === 0) parts.shift()
bdd428a6 72 const isWebfingerSearch = parts.length === 2 && parts.every(p => p && !p.includes(' '))
f37dc0dd 73
f5b0af50 74 if (isURISearch || isWebfingerSearch) return searchVideoChannelURI(search, isWebfingerSearch, res)
f37dc0dd 75
cce1b3df
C
76 // @username -> username to search in DB
77 if (query.search.startsWith('@')) query.search = query.search.replace(/^@/, '')
5fb2e288 78
3521ab8f 79 if (isSearchIndexSearch(query)) {
5fb2e288
C
80 return searchVideoChannelsIndex(query, res)
81 }
82
f37dc0dd
C
83 return searchVideoChannelsDB(query, res)
84}
85
5fb2e288
C
86async function searchVideoChannelsIndex (query: VideoChannelsSearchQuery, res: express.Response) {
87 logger.debug('Doing channels search on search index.')
88
89 const result = await buildMutedForSearchIndex(res)
90
91 const body = Object.assign(query, result)
92
93 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/video-channels'
94
95 try {
96 const searchIndexResult = await doRequest<ResultList<VideoChannel>>({ uri: url, body, json: true })
97
98 return res.json(searchIndexResult.body)
99 } catch (err) {
100 logger.warn('Cannot use search index to make video channels search.', { err })
101
102 return res.sendStatus(500)
103 }
104}
105
f37dc0dd
C
106async function searchVideoChannelsDB (query: VideoChannelsSearchQuery, res: express.Response) {
107 const serverActor = await getServerActor()
108
109 const options = {
110 actorId: serverActor.id,
111 search: query.search,
112 start: query.start,
113 count: query.count,
114 sort: query.sort
115 }
116 const resultList = await VideoChannelModel.searchForApi(options)
117
118 return res.json(getFormattedObjects(resultList.data, resultList.total))
119}
120
f5b0af50 121async function searchVideoChannelURI (search: string, isWebfingerSearch: boolean, res: express.Response) {
453e83ea 122 let videoChannel: MChannelAccountDefault
f5b0af50 123 let uri = search
f37dc0dd 124
cce1b3df
C
125 if (isWebfingerSearch) {
126 try {
127 uri = await loadActorUrlOrGetFromWebfinger(search)
128 } catch (err) {
129 logger.warn('Cannot load actor URL or get from webfinger.', { search, err })
130
131 return res.json({ total: 0, data: [] })
132 }
133 }
f37dc0dd 134
f5b0af50
C
135 if (isUserAbleToSearchRemoteURI(res)) {
136 try {
e587e0ec 137 const actor = await getOrCreateActorAndServerAndModel(uri, 'all', true, true)
f5b0af50
C
138 videoChannel = actor.VideoChannel
139 } catch (err) {
140 logger.info('Cannot search remote video channel %s.', uri, { err })
141 }
f37dc0dd 142 } else {
f5b0af50 143 videoChannel = await VideoChannelModel.loadByUrlAndPopulateAccount(uri)
f37dc0dd
C
144 }
145
146 return res.json({
147 total: videoChannel ? 1 : 0,
148 data: videoChannel ? [ videoChannel.toFormattedJSON() ] : []
149 })
150}
151
f6eebcb3 152function searchVideos (req: express.Request, res: express.Response) {
d525fc39 153 const query: VideosSearchQuery = req.query
240085d0 154 const search = query.search
5fb2e288 155
240085d0 156 if (search && (search.startsWith('http://') || search.startsWith('https://'))) {
f37dc0dd 157 return searchVideoURI(search, res)
f6eebcb3 158 }
d525fc39 159
3521ab8f 160 if (isSearchIndexSearch(query)) {
5fb2e288
C
161 return searchVideosIndex(query, res)
162 }
163
f6eebcb3
C
164 return searchVideosDB(query, res)
165}
166
5fb2e288
C
167async function searchVideosIndex (query: VideosSearchQuery, res: express.Response) {
168 logger.debug('Doing videos search on search index.')
169
170 const result = await buildMutedForSearchIndex(res)
171
1a40132c
C
172 const body: VideosSearchQuery = Object.assign(query, result)
173
174 // Use the default instance NSFW policy if not specified
175 if (!body.nsfw) {
ba114024
C
176 const nsfwPolicy = res.locals.oauth
177 ? res.locals.oauth.token.User.nsfwPolicy
178 : CONFIG.INSTANCE.DEFAULT_NSFW_POLICY
179
180 body.nsfw = nsfwPolicy === 'do_not_list'
1a40132c
C
181 ? 'false'
182 : 'both'
183 }
5fb2e288
C
184
185 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/videos'
186
187 try {
188 const searchIndexResult = await doRequest<ResultList<Video>>({ uri: url, body, json: true })
189
190 return res.json(searchIndexResult.body)
191 } catch (err) {
192 logger.warn('Cannot use search index to make video search.', { err })
193
194 return res.sendStatus(500)
195 }
196}
197
f6eebcb3 198async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
06a05d5f
C
199 const options = Object.assign(query, {
200 includeLocalVideos: true,
6e46de09 201 nsfw: buildNSFWFilter(res, query.nsfw),
1cd3facc 202 filter: query.filter,
7ad9b984 203 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
06a05d5f 204 })
d525fc39 205 const resultList = await VideoModel.searchAndPopulateAccountAndServer(options)
57c36b27
C
206
207 return res.json(getFormattedObjects(resultList.data, resultList.total))
208}
f6eebcb3 209
f37dc0dd 210async function searchVideoURI (url: string, res: express.Response) {
0283eaac 211 let video: MVideoAccountLightBlacklistAllFiles
f6eebcb3 212
1297eb5d 213 // Check if we can fetch a remote video with the URL
f37dc0dd 214 if (isUserAbleToSearchRemoteURI(res)) {
1297eb5d
C
215 try {
216 const syncParam = {
217 likes: false,
218 dislikes: false,
219 shares: false,
220 comments: false,
221 thumbnail: true,
222 refreshVideo: false
223 }
f6eebcb3 224
4157cdb1 225 const result = await getOrCreateVideoAndAccountAndChannel({ videoObject: url, syncParam })
f37dc0dd 226 video = result ? result.video : undefined
1297eb5d 227 } catch (err) {
f5b0af50 228 logger.info('Cannot search remote video %s.', url, { err })
1297eb5d
C
229 }
230 } else {
231 video = await VideoModel.loadByUrlAndPopulateAccount(url)
f6eebcb3
C
232 }
233
234 return res.json({
235 total: video ? 1 : 0,
236 data: video ? [ video.toFormattedJSON() ] : []
237 })
238}
5fb2e288 239
3521ab8f 240function isSearchIndexSearch (query: SearchTargetQuery) {
5fb2e288
C
241 if (query.searchTarget === 'search-index') return true
242
243 const searchIndexConfig = CONFIG.SEARCH.SEARCH_INDEX
244
245 if (searchIndexConfig.ENABLED !== true) return false
246
247 if (searchIndexConfig.DISABLE_LOCAL_SEARCH) return true
248 if (searchIndexConfig.IS_DEFAULT_SEARCH && !query.searchTarget) return true
249
250 return false
251}
252
253async function buildMutedForSearchIndex (res: express.Response) {
254 const serverActor = await getServerActor()
255 const accountIds = [ serverActor.Account.id ]
256
257 if (res.locals.oauth) {
258 accountIds.push(res.locals.oauth.token.User.Account.id)
259 }
260
261 const [ blockedHosts, blockedAccounts ] = await Promise.all([
262 ServerBlocklistModel.listHostsBlockedBy(accountIds),
263 AccountBlocklistModel.listHandlesBlockedBy(accountIds)
264 ])
265
266 return {
267 blockedHosts,
268 blockedAccounts
269 }
270}