Add new follow, mention and user registered notifs
[oweals/peertube.git] / server / controllers / api / search.ts
1 import * as express from 'express'
2 import { buildNSFWFilter, isUserAbleToSearchRemoteURI } 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 { VideoChannelModel } from '../../models/video/video-channel'
21 import { loadActorUrlOrGetFromWebfinger } from '../../helpers/webfinger'
22
23 const searchRouter = express.Router()
24
25 searchRouter.get('/videos',
26   paginationValidator,
27   setDefaultPagination,
28   videosSearchSortValidator,
29   setDefaultSearchSort,
30   optionalAuthenticate,
31   commonVideosFiltersValidator,
32   videosSearchValidator,
33   asyncMiddleware(searchVideos)
34 )
35
36 searchRouter.get('/video-channels',
37   paginationValidator,
38   setDefaultPagination,
39   videoChannelsSearchSortValidator,
40   setDefaultSearchSort,
41   optionalAuthenticate,
42   videoChannelsSearchValidator,
43   asyncMiddleware(searchVideoChannels)
44 )
45
46 // ---------------------------------------------------------------------------
47
48 export { searchRouter }
49
50 // ---------------------------------------------------------------------------
51
52 function 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('@')
59
60   // Handle strings like @toto@example.com
61   if (parts.length === 3 && parts[0].length === 0) parts.shift()
62   const isWebfingerSearch = parts.length === 2 && parts.every(p => p.indexOf(' ') === -1)
63
64   if (isURISearch || isWebfingerSearch) return searchVideoChannelURI(search, isWebfingerSearch, 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, isWebfingerSearch: boolean, res: express.Response) {
85   let videoChannel: VideoChannelModel
86   let uri = search
87
88   if (isWebfingerSearch) uri = await loadActorUrlOrGetFromWebfinger(search)
89
90   if (isUserAbleToSearchRemoteURI(res)) {
91     try {
92       const actor = await getOrCreateActorAndServerAndModel(uri, 'all', true, true)
93       videoChannel = actor.VideoChannel
94     } catch (err) {
95       logger.info('Cannot search remote video channel %s.', uri, { err })
96     }
97   } else {
98     videoChannel = await VideoChannelModel.loadByUrlAndPopulateAccount(uri)
99   }
100
101   return res.json({
102     total: videoChannel ? 1 : 0,
103     data: videoChannel ? [ videoChannel.toFormattedJSON() ] : []
104   })
105 }
106
107 function searchVideos (req: express.Request, res: express.Response) {
108   const query: VideosSearchQuery = req.query
109   const search = query.search
110   if (search && (search.startsWith('http://') || search.startsWith('https://'))) {
111     return searchVideoURI(search, res)
112   }
113
114   return searchVideosDB(query, res)
115 }
116
117 async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
118   const options = Object.assign(query, {
119     includeLocalVideos: true,
120     nsfw: buildNSFWFilter(res, query.nsfw),
121     filter: query.filter,
122     user: res.locals.oauth ? res.locals.oauth.token.User : undefined
123   })
124   const resultList = await VideoModel.searchAndPopulateAccountAndServer(options)
125
126   return res.json(getFormattedObjects(resultList.data, resultList.total))
127 }
128
129 async function searchVideoURI (url: string, res: express.Response) {
130   let video: VideoModel
131
132   // Check if we can fetch a remote video with the URL
133   if (isUserAbleToSearchRemoteURI(res)) {
134     try {
135       const syncParam = {
136         likes: false,
137         dislikes: false,
138         shares: false,
139         comments: false,
140         thumbnail: true,
141         refreshVideo: false
142       }
143
144       const result = await getOrCreateVideoAndAccountAndChannel({ videoObject: url, syncParam })
145       video = result ? result.video : undefined
146     } catch (err) {
147       logger.info('Cannot search remote video %s.', url, { err })
148     }
149   } else {
150     video = await VideoModel.loadByUrlAndPopulateAccount(url)
151   }
152
153   return res.json({
154     total: video ? 1 : 0,
155     data: video ? [ video.toFormattedJSON() ] : []
156   })
157 }