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