]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/search.ts
9c2c7d6c1f3b44b6088382643c7ae82e9bf06df4
[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 } from '../../helpers/utils'
4 import { VideoModel } from '../../models/video/video'
5 import {
6 asyncMiddleware,
7 commonVideosFiltersValidator,
8 optionalAuthenticate,
9 paginationValidator,
10 searchValidator,
11 setDefaultPagination,
12 setDefaultSearchSort,
13 videosSearchSortValidator
14 } from '../../middlewares'
15 import { VideosSearchQuery } from '../../../shared/models/search'
16 import { getOrCreateAccountAndVideoAndChannel } from '../../lib/activitypub'
17 import { logger } from '../../helpers/logger'
18
19 const searchRouter = express.Router()
20
21 searchRouter.get('/videos',
22 paginationValidator,
23 setDefaultPagination,
24 videosSearchSortValidator,
25 setDefaultSearchSort,
26 optionalAuthenticate,
27 commonVideosFiltersValidator,
28 searchValidator,
29 asyncMiddleware(searchVideos)
30 )
31
32 // ---------------------------------------------------------------------------
33
34 export { searchRouter }
35
36 // ---------------------------------------------------------------------------
37
38 function searchVideos (req: express.Request, res: express.Response) {
39 const query: VideosSearchQuery = req.query
40 if (query.search.startsWith('http://') || query.search.startsWith('https://')) {
41 return searchVideoUrl(query.search, res)
42 }
43
44 return searchVideosDB(query, res)
45 }
46
47 async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
48 const options = Object.assign(query, {
49 includeLocalVideos: true,
50 nsfw: buildNSFWFilter(res, query.nsfw)
51 })
52 const resultList = await VideoModel.searchAndPopulateAccountAndServer(options)
53
54 return res.json(getFormattedObjects(resultList.data, resultList.total))
55 }
56
57 async function searchVideoUrl (url: string, res: express.Response) {
58 let video: VideoModel
59
60 try {
61 const syncParam = {
62 likes: false,
63 dislikes: false,
64 shares: false,
65 comments: false,
66 thumbnail: true
67 }
68
69 const res = await getOrCreateAccountAndVideoAndChannel(url, syncParam)
70 video = res ? res.video : undefined
71 } catch (err) {
72 logger.info('Cannot search remote video %s.', url)
73 }
74
75 return res.json({
76 total: video ? 1 : 0,
77 data: video ? [ video.toFormattedJSON() ] : []
78 })
79 }