]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/search.ts
Fix search with bad webfinger handles
[github/Chocobozzz/PeerTube.git] / server / controllers / api / search.ts
CommitLineData
57c36b27 1import * as express from 'express'
687d638c 2import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
f37dc0dd 3import { getFormattedObjects, getServerActor } from '../../helpers/utils'
57c36b27
C
4import { VideoModel } from '../../models/video/video'
5import {
6 asyncMiddleware,
d525fc39 7 commonVideosFiltersValidator,
57c36b27
C
8 optionalAuthenticate,
9 paginationValidator,
57c36b27
C
10 setDefaultPagination,
11 setDefaultSearchSort,
f37dc0dd
C
12 videoChannelsSearchSortValidator,
13 videoChannelsSearchValidator,
14 videosSearchSortValidator,
15 videosSearchValidator
57c36b27 16} from '../../middlewares'
f37dc0dd
C
17import { VideoChannelsSearchQuery, VideosSearchQuery } from '../../../shared/models/search'
18import { getOrCreateActorAndServerAndModel, getOrCreateVideoAndAccountAndChannel } from '../../lib/activitypub'
f6eebcb3 19import { logger } from '../../helpers/logger'
f37dc0dd
C
20import { VideoChannelModel } from '../../models/video/video-channel'
21import { loadActorUrlOrGetFromWebfinger } from '../../helpers/webfinger'
57c36b27
C
22
23const searchRouter = express.Router()
24
25searchRouter.get('/videos',
26 paginationValidator,
27 setDefaultPagination,
28 videosSearchSortValidator,
29 setDefaultSearchSort,
30 optionalAuthenticate,
d525fc39 31 commonVideosFiltersValidator,
f37dc0dd 32 videosSearchValidator,
57c36b27
C
33 asyncMiddleware(searchVideos)
34)
35
f37dc0dd
C
36searchRouter.get('/video-channels',
37 paginationValidator,
38 setDefaultPagination,
39 videoChannelsSearchSortValidator,
40 setDefaultSearchSort,
41 optionalAuthenticate,
f37dc0dd
C
42 videoChannelsSearchValidator,
43 asyncMiddleware(searchVideoChannels)
44)
45
57c36b27
C
46// ---------------------------------------------------------------------------
47
48export { searchRouter }
49
50// ---------------------------------------------------------------------------
51
f37dc0dd
C
52function searchVideoChannels (req: express.Request, res: express.Response) {
53 const query: VideoChannelsSearchQuery = req.query
54 const search = query.search
55
56 const isURISearch = search.startsWith('http://') || search.startsWith('https://')
57
58 const parts = search.split('@')
2ff83ae2
C
59
60 // Handle strings like @toto@example.com
61 if (parts.length === 3 && parts[0].length === 0) parts.shift()
c56b774d 62 const isWebfingerSearch = parts.length === 2 && parts.every(p => p && p.indexOf(' ') === -1)
f37dc0dd 63
f5b0af50 64 if (isURISearch || isWebfingerSearch) return searchVideoChannelURI(search, isWebfingerSearch, res)
f37dc0dd 65
c56b774d
C
66 // @username -> username to search in DB
67 if (query.search.startsWith('@')) query.search = query.search.replace(/^@/, '')
f37dc0dd
C
68 return searchVideoChannelsDB(query, res)
69}
70
71async function searchVideoChannelsDB (query: VideoChannelsSearchQuery, res: express.Response) {
72 const serverActor = await getServerActor()
73
74 const options = {
75 actorId: serverActor.id,
76 search: query.search,
77 start: query.start,
78 count: query.count,
79 sort: query.sort
80 }
81 const resultList = await VideoChannelModel.searchForApi(options)
82
83 return res.json(getFormattedObjects(resultList.data, resultList.total))
84}
85
f5b0af50 86async function searchVideoChannelURI (search: string, isWebfingerSearch: boolean, res: express.Response) {
f37dc0dd 87 let videoChannel: VideoChannelModel
f5b0af50 88 let uri = search
f37dc0dd 89
c56b774d
C
90 if (isWebfingerSearch) {
91 try {
92 uri = await loadActorUrlOrGetFromWebfinger(search)
93 } catch (err) {
94 logger.warn('Cannot load actor URL or get from webfinger.', { search, err })
95
96 return res.json({ total: 0, data: [] })
97 }
98 }
f37dc0dd 99
f5b0af50
C
100 if (isUserAbleToSearchRemoteURI(res)) {
101 try {
e587e0ec 102 const actor = await getOrCreateActorAndServerAndModel(uri, 'all', true, true)
f5b0af50
C
103 videoChannel = actor.VideoChannel
104 } catch (err) {
105 logger.info('Cannot search remote video channel %s.', uri, { err })
106 }
f37dc0dd 107 } else {
f5b0af50 108 videoChannel = await VideoChannelModel.loadByUrlAndPopulateAccount(uri)
f37dc0dd
C
109 }
110
111 return res.json({
112 total: videoChannel ? 1 : 0,
113 data: videoChannel ? [ videoChannel.toFormattedJSON() ] : []
114 })
115}
116
f6eebcb3 117function searchVideos (req: express.Request, res: express.Response) {
d525fc39 118 const query: VideosSearchQuery = req.query
240085d0
C
119 const search = query.search
120 if (search && (search.startsWith('http://') || search.startsWith('https://'))) {
f37dc0dd 121 return searchVideoURI(search, res)
f6eebcb3 122 }
d525fc39 123
f6eebcb3
C
124 return searchVideosDB(query, res)
125}
126
127async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
06a05d5f
C
128 const options = Object.assign(query, {
129 includeLocalVideos: true,
6e46de09 130 nsfw: buildNSFWFilter(res, query.nsfw),
1cd3facc 131 filter: query.filter,
7ad9b984 132 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
06a05d5f 133 })
d525fc39 134 const resultList = await VideoModel.searchAndPopulateAccountAndServer(options)
57c36b27
C
135
136 return res.json(getFormattedObjects(resultList.data, resultList.total))
137}
f6eebcb3 138
f37dc0dd 139async function searchVideoURI (url: string, res: express.Response) {
f6eebcb3
C
140 let video: VideoModel
141
1297eb5d 142 // Check if we can fetch a remote video with the URL
f37dc0dd 143 if (isUserAbleToSearchRemoteURI(res)) {
1297eb5d
C
144 try {
145 const syncParam = {
146 likes: false,
147 dislikes: false,
148 shares: false,
149 comments: false,
150 thumbnail: true,
151 refreshVideo: false
152 }
f6eebcb3 153
4157cdb1 154 const result = await getOrCreateVideoAndAccountAndChannel({ videoObject: url, syncParam })
f37dc0dd 155 video = result ? result.video : undefined
1297eb5d 156 } catch (err) {
f5b0af50 157 logger.info('Cannot search remote video %s.', url, { err })
1297eb5d
C
158 }
159 } else {
160 video = await VideoModel.loadByUrlAndPopulateAccount(url)
f6eebcb3
C
161 }
162
163 return res.json({
164 total: video ? 1 : 0,
165 data: video ? [ video.toFormattedJSON() ] : []
166 })
167}