1 import express from 'express'
2 import { sanitizeUrl } from '@server/helpers/core-utils'
3 import { pickSearchChannelQuery } 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 { Hooks } from '@server/lib/plugins/hooks'
8 import { buildMutedForSearchIndex, isSearchIndexSearch, isURISearch } from '@server/lib/search'
9 import { getServerActor } from '@server/models/application/application'
10 import { HttpStatusCode, ResultList, VideoChannel } from '@shared/models'
11 import { VideoChannelsSearchQueryAfterSanitize } from '../../../../shared/models/search'
12 import { isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils'
13 import { logger } from '../../../helpers/logger'
14 import { getFormattedObjects } from '../../../helpers/utils'
15 import { getOrCreateAPActor, loadActorUrlOrGetFromWebfinger } from '../../../lib/activitypub/actors'
23 videoChannelsListSearchValidator,
24 videoChannelsSearchSortValidator
25 } from '../../../middlewares'
26 import { VideoChannelModel } from '../../../models/video/video-channel'
27 import { MChannelAccountDefault } from '../../../types/models'
28 import { searchLocalUrl } from './shared'
30 const searchChannelsRouter = express.Router()
32 searchChannelsRouter.get('/video-channels',
33 openapiOperationDoc({ operationId: 'searchChannels' }),
36 videoChannelsSearchSortValidator,
39 videoChannelsListSearchValidator,
40 asyncMiddleware(searchVideoChannels)
43 // ---------------------------------------------------------------------------
45 export { searchChannelsRouter }
47 // ---------------------------------------------------------------------------
49 function searchVideoChannels (req: express.Request, res: express.Response) {
50 const query = pickSearchChannelQuery(req.query)
51 const search = query.search || ''
53 const parts = search.split('@')
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(' '))
59 if (isURISearch(search) || isWebfingerSearch) return searchVideoChannelURI(search, isWebfingerSearch, res)
61 // @username -> username to search in DB
62 if (search.startsWith('@')) query.search = search.replace(/^@/, '')
64 if (isSearchIndexSearch(query)) {
65 return searchVideoChannelsIndex(query, res)
68 return searchVideoChannelsDB(query, res)
71 async function searchVideoChannelsIndex (query: VideoChannelsSearchQueryAfterSanitize, res: express.Response) {
72 const result = await buildMutedForSearchIndex(res)
74 const body = await Hooks.wrapObject(Object.assign(query, result), 'filter:api.search.video-channels.index.list.params')
76 const url = sanitizeUrl(CONFIG.SEARCH.SEARCH_INDEX.URL) + '/api/v1/search/video-channels'
79 logger.debug('Doing video channels search index request on %s.', url, { body })
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')
84 return res.json(jsonResult)
86 logger.warn('Cannot use search index to make video channels search.', { err })
89 status: HttpStatusCode.INTERNAL_SERVER_ERROR_500,
90 message: 'Cannot use search index to make video channels search'
95 async function searchVideoChannelsDB (query: VideoChannelsSearchQueryAfterSanitize, res: express.Response) {
96 const serverActor = await getServerActor()
98 const apiOptions = await Hooks.wrapObject({
101 actorId: serverActor.id
102 }, 'filter:api.search.video-channels.local.list.params')
104 const resultList = await Hooks.wrapPromiseFun(
105 VideoChannelModel.searchForApi,
107 'filter:api.search.video-channels.local.list.result'
110 return res.json(getFormattedObjects(resultList.data, resultList.total))
113 async function searchVideoChannelURI (search: string, isWebfingerSearch: boolean, res: express.Response) {
114 let videoChannel: MChannelAccountDefault
117 if (isWebfingerSearch) {
119 uri = await loadActorUrlOrGetFromWebfinger(search)
121 logger.warn('Cannot load actor URL or get from webfinger.', { search, err })
123 return res.json({ total: 0, data: [] })
127 if (isUserAbleToSearchRemoteURI(res)) {
129 const actor = await getOrCreateAPActor(uri, 'all', true, true)
130 videoChannel = actor.VideoChannel
132 logger.info('Cannot search remote video channel %s.', uri, { err })
135 videoChannel = await searchLocalUrl(sanitizeLocalUrl(uri), url => VideoChannelModel.loadByUrlAndPopulateAccount(url))
139 total: videoChannel ? 1 : 0,
140 data: videoChannel ? [ videoChannel.toFormattedJSON() ] : []
144 function sanitizeLocalUrl (url: string) {
147 // Handle alternative channel URLs
148 return url.replace(new RegExp('^' + WEBSERVER.URL + '/c/'), WEBSERVER.URL + '/video-channels/')