summaryrefslogtreecommitdiff
path: root/searx/engines/youtube_api.py
blob: 4192530b9f62d9fed5f6ded29505c65690e17eb4 (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
 Youtube (Videos)
"""

from json import loads
from urllib.parse import urlencode

from dateutil import parser
from searx.exceptions import SearxEngineAPIException

# about
about = {
    "website": 'https://www.youtube.com/',
    "wikidata_id": 'Q866',
    "official_api_documentation": 'https://developers.google.com/youtube/v3/docs/search/list?apix=true',
    "use_official_api": True,
    "require_api_key": False,
    "results": 'JSON',
}

# engine dependent config
categories = ['videos', 'music']
paging = False
api_key = None

# search-url
base_url = 'https://www.googleapis.com/youtube/v3/search'
search_url = base_url + '?part=snippet&{query}&maxResults=20&key={api_key}'
base_youtube_url = 'https://www.youtube.com/watch?v='


# do search-request
def request(query, params):
    params['url'] = search_url.format(query=urlencode({'q': query}), api_key=api_key)

    # add language tag if specified
    if params['language'] != 'all':
        params['url'] += '&relevanceLanguage=' + params['language'].split('-')[0]

    return params


# get response from search-request
def response(resp):
    results = []

    search_results = loads(resp.text)

    if 'error' in search_results and 'message' in search_results['error']:
        raise SearxEngineAPIException(search_results['error']['message'])

    # return empty array if there are no results
    if 'items' not in search_results:
        return []

    # parse results
    for result in search_results['items']:
        if "videoId" not in result["id"]:
            # ignore channels
            continue

        videoid = result['id']['videoId']

        title = result['snippet']['title']
        content = ''
        thumbnail = ''

        pubdate = result['snippet']['publishedAt']
        publishedDate = parser.parse(pubdate)

        thumbnail = result['snippet']['thumbnails']['high']['url']

        content = result['snippet']['description']

        url = base_youtube_url + videoid

        # append result
        results.append(
            {
                'url': url,
                'title': title,
                'content': content,
                'template': 'videos.html',
                'publishedDate': publishedDate,
                'iframe_src': "https://www.youtube-nocookie.com/embed/" + videoid,
                'thumbnail': thumbnail,
            }
        )

    # return results
    return results