]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/search/search-video-channels.ts
Prepare changelog
[github/Chocobozzz/PeerTube.git] / server / controllers / api / search / search-video-channels.ts
CommitLineData
41fb13c3 1import express from 'express'
37a44fc9 2import { sanitizeUrl } from '@server/helpers/core-utils'
d6886027 3import { pickSearchChannelQuery } from '@server/helpers/query'
dedcd583 4import { doJSONRequest, findLatestRedirection } from '@server/helpers/requests'
37a44fc9
C
5import { CONFIG } from '@server/initializers/config'
6import { WEBSERVER } from '@server/initializers/constants'
7import { Hooks } from '@server/lib/plugins/hooks'
8import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search'
9import { getServerActor } from '@server/models/application/application'
4c7e60bc 10import { HttpStatusCode, ResultList, VideoChannel } from '@shared/models'
d6886027 11import { VideoChannelsSearchQueryAfterSanitize } from '../../../../shared/models/search'
37a44fc9
C
12import { isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils'
13import { logger } from '../../../helpers/logger'
14import { getFormattedObjects } from '../../../helpers/utils'
15import { getOrCreateAPActor, loadActorUrlOrGetFromWebfinger } from '../../../lib/activitypub/actors'
16import {
17 asyncMiddleware,
18 openapiOperationDoc,
19 optionalAuthenticate,
20 paginationValidator,
21 setDefaultPagination,
22 setDefaultSearchSort,
23 videoChannelsListSearchValidator,
24 videoChannelsSearchSortValidator
25} from '../../../middlewares'
26import { VideoChannelModel } from '../../../models/video/video-channel'
27import { MChannelAccountDefault } from '../../../types/models'
400043b1 28import { searchLocalUrl } from './shared'
37a44fc9
C
29
30const searchChannelsRouter = express.Router()
31
32searchChannelsRouter.get('/video-channels',
33 openapiOperationDoc({ operationId: 'searchChannels' }),
34 paginationValidator,
35 setDefaultPagination,
36 videoChannelsSearchSortValidator,
37 setDefaultSearchSort,
38 optionalAuthenticate,
39 videoChannelsListSearchValidator,
40 asyncMiddleware(searchVideoChannels)
41)
42
43// ---------------------------------------------------------------------------
44
45export { searchChannelsRouter }
46
47// ---------------------------------------------------------------------------
48
49function searchVideoChannels (req: express.Request, res: express.Response) {
d6886027 50 const query = pickSearchChannelQuery(req.query)
ab632f43 51 const search = query.search || ''
37a44fc9
C
52
53 const parts = search.split('@')
54
55 // Handle strings like @toto@example.com
56 if (parts.length === 3 && parts[0].length === 0) parts.shift()
57 const isWebfingerSearch = parts.length === 2 && parts.every(p => p && !p.includes(' '))
58
b3ed044d 59 if (isURISearch(search) || isWebfingerSearch) return searchVideoChannelURI(search, res)
37a44fc9
C
60
61 // @username -> username to search in DB
ab632f43 62 if (search.startsWith('@')) query.search = search.replace(/^@/, '')
37a44fc9
C
63
64 if (isSearchIndexSearch(query)) {
65 return searchVideoChannelsIndex(query, res)
66 }
67
68 return searchVideoChannelsDB(query, res)
69}
70
d6886027 71async function searchVideoChannelsIndex (query: VideoChannelsSearchQueryAfterSanitize, res: express.Response) {
37a44fc9
C
72 const result = await buildMutedForSearchIndex(res)
73
74 const body = await Hooks.wrapObject(Object.assign(query, result), 'filter:api.search.video-channels.index.list.params')
75
76 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/video-channels'
77
78 try {
79 logger.debug('Doing video channels search index request on %s.', url, { body })
80
81 const { body: searchIndexResult } = await doJSONRequest<ResultList<VideoChannel>>(url, { method: 'POST', json: body })
82 const jsonResult = await Hooks.wrapObject(searchIndexResult, 'filter:api.search.video-channels.index.list.result')
83
84 return res.json(jsonResult)
85 } catch (err) {
86 logger.warn('Cannot use search index to make video channels search.', { err })
87
88 return res.fail({
89 status: HttpStatusCode.INTERNAL_SERVER_ERROR_500,
90 message: 'Cannot use search index to make video channels search'
91 })
92 }
93}
94
d6886027 95async function searchVideoChannelsDB (query: VideoChannelsSearchQueryAfterSanitize, res: express.Response) {
37a44fc9
C
96 const serverActor = await getServerActor()
97
98 const apiOptions = await Hooks.wrapObject({
d6886027
C
99 ...query,
100
101 actorId: serverActor.id
37a44fc9
C
102 }, 'filter:api.search.video-channels.local.list.params')
103
104 const resultList = await Hooks.wrapPromiseFun(
105 VideoChannelModel.searchForApi,
106 apiOptions,
107 'filter:api.search.video-channels.local.list.result'
108 )
109
110 return res.json(getFormattedObjects(resultList.data, resultList.total))
111}
112
b3ed044d 113async function searchVideoChannelURI (search: string, res: express.Response) {
37a44fc9
C
114 let videoChannel: MChannelAccountDefault
115 let uri = search
116
b3ed044d 117 if (!isURISearch(search)) {
37a44fc9
C
118 try {
119 uri = await loadActorUrlOrGetFromWebfinger(search)
120 } catch (err) {
121 logger.warn('Cannot load actor URL or get from webfinger.', { search, err })
122
123 return res.json({ total: 0, data: [] })
124 }
125 }
126
127 if (isUserAbleToSearchRemoteURI(res)) {
128 try {
dedcd583
C
129 const latestUri = await findLatestRedirection(uri, { activityPub: true })
130
131 const actor = await getOrCreateAPActor(latestUri, 'all', true, true)
37a44fc9
C
132 videoChannel = actor.VideoChannel
133 } catch (err) {
134 logger.info('Cannot search remote video channel %s.', uri, { err })
135 }
136 } else {
400043b1 137 videoChannel = await searchLocalUrl(sanitizeLocalUrl(uri), url => VideoChannelModel.loadByUrlAndPopulateAccount(url))
37a44fc9
C
138 }
139
140 return res.json({
141 total: videoChannel ? 1 : 0,
142 data: videoChannel ? [ videoChannel.toFormattedJSON() ] : []
143 })
144}
145
146function sanitizeLocalUrl (url: string) {
147 if (!url) return ''
148
149 // Handle alternative channel URLs
150 return url.replace(new RegExp('^' + WEBSERVER.URL + '/c/'), WEBSERVER.URL + '/video-channels/')
151}