1# -*- coding: UTF-8 -*-
2#
3# Copyright (C) 2020, Team Kodi
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <https://www.gnu.org/licenses/>.
17#
18# IMDb ratings based on code in metadata.themoviedb.org.python by Team Kodi
19# pylint: disable=missing-docstring
20
21
22import re
23from . import api_utils
24from . import settings
25
26IMDB_RATINGS_URL = 'https://www.imdb.com/title/{}/'
27IMDB_RATING_REGEX = re.compile(r'itemprop="ratingValue".*?>.*?([\d.]+).*?<')
28IMDB_VOTES_REGEX = re.compile(r'itemprop="ratingCount".*?>.*?([\d,]+).*?<')
29
30
31def get_details(imdb_id):
32    if not imdb_id:
33        return {}
34    votes, rating = _get_ratinginfo(imdb_id)
35    return _assemble_imdb_result(votes, rating)
36
37def _get_ratinginfo(imdb_id):
38    response = api_utils.load_info(IMDB_RATINGS_URL.format(imdb_id), default = '', resp_type='text', verboselog=settings.VERBOSELOG)
39    return _parse_imdb_result(response)
40
41def _assemble_imdb_result(votes, rating):
42    result = {}
43    if votes and rating:
44        result['ratings'] = {'imdb': {'votes': votes, 'rating': rating}}
45    return result
46
47def _parse_imdb_result(input_html):
48    rating = _parse_imdb_rating(input_html)
49    votes = _parse_imdb_votes(input_html)
50    return votes, rating
51
52def _parse_imdb_rating(input_html):
53    match = re.search(IMDB_RATING_REGEX, input_html)
54    if (match):
55        return float(match.group(1))
56    return None
57
58def _parse_imdb_votes(input_html):
59    match = re.search(IMDB_VOTES_REGEX, input_html)
60    if (match):
61        return int(match.group(1).replace(',', ''))
62    return None
63