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