aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/search.ts
blob: 9c2c7d6c1f3b44b6088382643c7ae82e9bf06df4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import * as express from 'express'
import { buildNSFWFilter } from '../../helpers/express-utils'
import { getFormattedObjects } from '../../helpers/utils'
import { VideoModel } from '../../models/video/video'
import {
  asyncMiddleware,
  commonVideosFiltersValidator,
  optionalAuthenticate,
  paginationValidator,
  searchValidator,
  setDefaultPagination,
  setDefaultSearchSort,
  videosSearchSortValidator
} from '../../middlewares'
import { VideosSearchQuery } from '../../../shared/models/search'
import { getOrCreateAccountAndVideoAndChannel } from '../../lib/activitypub'
import { logger } from '../../helpers/logger'

const searchRouter = express.Router()

searchRouter.get('/videos',
  paginationValidator,
  setDefaultPagination,
  videosSearchSortValidator,
  setDefaultSearchSort,
  optionalAuthenticate,
  commonVideosFiltersValidator,
  searchValidator,
  asyncMiddleware(searchVideos)
)

// ---------------------------------------------------------------------------

export { searchRouter }

// ---------------------------------------------------------------------------

function searchVideos (req: express.Request, res: express.Response) {
  const query: VideosSearchQuery = req.query
  if (query.search.startsWith('http://') || query.search.startsWith('https://')) {
    return searchVideoUrl(query.search, res)
  }

  return searchVideosDB(query, res)
}

async function searchVideosDB (query: VideosSearchQuery, res: express.Response) {
  const options = Object.assign(query, {
    includeLocalVideos: true,
    nsfw: buildNSFWFilter(res, query.nsfw)
  })
  const resultList = await VideoModel.searchAndPopulateAccountAndServer(options)

  return res.json(getFormattedObjects(resultList.data, resultList.total))
}

async function searchVideoUrl (url: string, res: express.Response) {
  let video: VideoModel

  try {
    const syncParam = {
      likes: false,
      dislikes: false,
      shares: false,
      comments: false,
      thumbnail: true
    }

    const res = await getOrCreateAccountAndVideoAndChannel(url, syncParam)
    video = res ? res.video : undefined
  } catch (err) {
    logger.info('Cannot search remote video %s.', url)
  }

  return res.json({
    total: video ? 1 : 0,
    data: video ? [ video.toFormattedJSON() ] : []
  })
}