summaryrefslogtreecommitdiffhomepage
path: root/libs/subliminal_patch/providers/titulky.py
blob: 0639a042f640cd6df95257a1063e6e45860f3221 (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import io
import logging
import os
import zipfile
import time

import rarfile
from subzero.language import Language
from guessit import guessit
from requests import Session
from six import text_type

from subliminal import __short_version__
from subliminal.exceptions import AuthenticationError, ConfigurationError, DownloadLimitExceeded
from subliminal.providers import ParserBeautifulSoup, Provider
from subliminal.subtitle import SUBTITLE_EXTENSIONS, fix_line_ending, Subtitle
from subliminal_patch.subtitle import guess_matches
from subliminal.video import Episode, Movie
from subliminal.utils import sanitize_release_group
from subliminal.score import get_equivalent_release_groups
from subliminal_patch.utils import sanitize

logger = logging.getLogger(__name__)


# class TitulkySubtitle(Subtitle):
#     """Titulky Subtitle."""
#     provider_name = 'Titulky'
#
#     def __init__(self, language, page_link, year, version, download_link):
#         super(TitulkySubtitle, self).__init__(language, page_link=page_link)
#         self.year = year
#         self.version = version
#         self.download_link = download_link
#         self.hearing_impaired = None
#         self.encoding = 'UTF-8'
#
#     @property
#     def id(self):
#         return self.download_link
#
#     def get_matches(self, video):
#         matches = set()
#
#         # episode
#         if isinstance(video, Episode):
#             # other properties
#             matches |= guess_matches(video, guessit(self.version, {'type': 'episode'}), partial=True)
#         # movie
#         elif isinstance(video, Movie):
#             # other properties
#             matches |= guess_matches(video, guessit(self.version, {'type': 'movie'}), partial=True)
#
#         return matches

class TitulkySubtitle(Subtitle):
    provider_name = 'titulky'
    
    def __init__(self, language, page_link, season, episode, version, download_link, year, title, asked_for_release_group=None,
                 asked_for_episode=None):
        super(TitulkySubtitle, self).__init__(language, page_link=page_link)
        self.season = season
        self.episode = episode
        self.version = version
        self.year = year
        self.download_link = download_link
        for t in title:
            self.title = t
        if year:
            self.year = int(year)
        
        self.page_link = page_link
        self.asked_for_release_group = asked_for_release_group
        self.asked_for_episode = asked_for_episode
    
    @property
    def id(self):
        return self.download_link
    
    def get_matches(self, video):
        """
        patch: set guessit to single_value
        :param video:
        :return:
        """
        matches = set()

        # episode
        if isinstance(video, Episode):
            # series
            if video.series:
                matches.add('series')
            # year
            if video.original_series and self.year is None or video.year and video.year == self.year:
                matches.add('year')
            # season
            if video.season and self.season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.episode == video.episode:
                matches.add('episode')
            # guess
            matches |= guess_matches(video, guessit(self.version, {'type': 'episode'}))
            pass
        # movie
        elif isinstance(video, Movie):
            # title
            if video.title and (sanitize(self.title) in (
                    sanitize(name) for name in [video.title] + video.alternative_titles)):
                matches.add('title')
            # year
            if video.year and self.year == video.year:
                matches.add('year')
            # guess
            matches |= guess_matches(video, guessit(self.version, {'type': 'movie'}))

        self.matches = matches

        return matches
    
    # def get_matches(self, video):
    #     matches = set()
    #
    #     # episode
    #     if isinstance(video, Episode):
    #         # series
    #         if video.series and (sanitize(self.series_name) in (
    #                 sanitize(name) for name in [video.series] + video.alternative_series)):
    #             matches.add('series')
    #     # movie
    #     elif isinstance(video, Movie):
    #         # title
    #         if video.title and (sanitize(self.movie_name) in (
    #                 sanitize(name) for name in [video.title] + video.alternative_titles)):
    #             matches.add('title')
    #
    #     # # episode
    #     # if isinstance(video, Episode):
    #     #     # other properties
    #     #     matches |= guess_matches(video, guessit(self.version, {'type': 'episode'}), partial=True)
    #     # # movie
    #     # elif isinstance(video, Movie):
    #     #     # other properties
    #     #     matches |= guess_matches(video, guessit(self.version, {'type': 'movie'}), partial=True)
    #
    #     return matches


class TitulkyProvider(Provider):
    """Titulky Provider."""
    languages = {Language(l) for l in ['ces', 'slk']}
    
    server_url = 'https://oldpremium.titulky.com'
    sign_out_url = '?Logoff=true'
    search_url_series = '?Fulltext={}'
    search_url_movies = '?Searching=AdvancedResult&ARelease={}'
    dn_url = 'https://oldpremium.titulky.com'
    download_url = 'https://oldpremium.titulky.com/idown.php?titulky='
    
    UserAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'
    
    subtitle_class = TitulkySubtitle
    
    def __init__(self, username=None, password=None):
        if any((username, password)) and not all((username, password)):
            raise ConfigurationError('Username and password must be specified')
        
        self.username = username
        self.password = password
        self.logged_in = False
        self.session = None
    
    def initialize(self):
        self.session = Session()
        self.session.headers['User-Agent'] = 'Subliminal/{}'.format(__short_version__)
        
        # login
        if self.username and self.password:
            logger.info('Logging in')
            self.session.get(self.server_url)
            data = {'Login': self.username,
                    'Password': self.password}
            r = self.session.post(self.server_url, data, allow_redirects=False, timeout=10)
            
            if 'BadLogin' in r.text:
                raise AuthenticationError(self.username)
            
            logger.debug('Logged in')
            self.logged_in = True
    
    def terminate(self):
        # logout
        if self.logged_in:
            logger.info('Logging out')
            r = self.session.get(self.server_url + self.sign_out_url, timeout=10)
            r.raise_for_status()
            logger.debug('Logged out')
            self.logged_in = False
        
        self.session.close()
    
    def query(self, keyword, season=None, episode=None, year=None, video=None):
        params = keyword
        if season and episode:
            params += ' S{season:02d}E{episode:02d}'.format(season=season, episode=episode)
        elif year:
            params += '&ARok={:4d}'.format(year)
        
        logger.debug('Searching subtitles %r', params)
        subtitles = []
        if season and episode:
            search_link = self.server_url + text_type(self.search_url_series).format(params)
        else:
            search_link = self.server_url + text_type(self.search_url_movies).format(params)
        
        
        r = self.session.get(search_link, timeout=30)
        r.raise_for_status()
        
        if not r.content:
            logger.debug('No data returned from provider')
            return []
        
        # soup = ParserBeautifulSoup(r.content.decode('utf-8', 'ignore'), ['lxml', 'html.parser'])
        
        # for entity in soup.select('table .main_table > tbody > tr'):
        # for entity in soup.find_all("table", class_="main_table"):
        #     moviename = entity.text
        # entity_url = self.server_url + entity['href']
        # logger.debug(entity_url)
        # r = self.session.get(entity_url, timeout=30)
        # r.raise_for_status()
        # logger.debug('looking into ' + entity_url)
        
        soup = ParserBeautifulSoup(r.content.decode('utf-8', 'ignore'), ['lxml', 'html.parser']).find("table",
                                                                                                      class_="main_table")
        # loop over subtitles cells
        if soup:
            subs = soup.find_all("tr", class_="row1")
            subs += soup.find_all("tr", class_="row2")
            for sub in subs:
                page_link = '%s%s' % (self.server_url, sub.a.get('href').encode('utf-8'))
                title = sub.find_all('td')[0:1]
                title = [x.text for x in title]
                version = sub.find(class_="fixedTip")
                if version is None:
                    version = ""
                else:
                    version = version['title']
                try:
                    r = sub.find_all('td')[6:7]
                    # r2 = td.find("td", "img")
                    langs = [x.text.encode('utf-8') for x in r]
                    pass
                except:
                    langs = 'CZ'
                name = '%s (%s)' % (version, langs)
                
                if b'CZ' in langs:
                    language = Language('ces')
                elif b'SK' in langs:
                    language = Language('slk')
                # read the item
                # subtitle = self.subtitle_class(language, page_link, year, version, page_link.replace("detail", "dld"))
                download_link = sub.find('a', class_='titulkydownloadajax')
                download_link = self.download_url + download_link.get('href')
                
                subtitle = self.subtitle_class(language, page_link,
                                               season, episode, version, download_link, year, title,
                                               asked_for_release_group=video.release_group,
                                               asked_for_episode=episode)
                
                logger.debug('Found subtitle %r', subtitle)
                subtitles.append(subtitle)
            
            soup.decompose()
            soup = None
        
        return subtitles
    
    def list_subtitles(self, video, languages):
        if isinstance(video, Episode):
            titles = [video.series] + video.alternative_series
        elif isinstance(video, Movie):
            titles = [video.title] + video.alternative_titles
        else:
            titles = []
        
        subtitles = []
        # query for subtitles with the show_id
        for title in titles:
            if isinstance(video, Episode):
                subtitles += [s for s in self.query(title, season=video.season, episode=video.episode,
                                                    year=video.year, video=video)
                              if s.language in languages]
            elif isinstance(video, Movie):
                subtitles += [s for s in self.query(title, year=video.year, video=video)
                              if s.language in languages]
        
        return subtitles
    
    def download_subtitle(self, subtitle):
        if isinstance(subtitle, TitulkySubtitle):
            # download the subtitle
            logger.info('Downloading subtitle %r', subtitle)
            r = self.session.get(subtitle.download_link, headers={'Referer': subtitle.page_link},
                                 timeout=30)
            r.raise_for_status()
            
            if not r.content:
                logger.debug('Unable to download subtitle. No data returned from provider')
                return
            elif 'Limit vyčerpán' in r.text:
                raise DownloadLimitExceeded
            
            soup = ParserBeautifulSoup(r.text, ['lxml', 'html.parser'])
            # links = soup.find("a", {"id": "downlink"}).find_all('a')
            link = soup.find(id="downlink")
            # TODO: add settings for choice
            
            url = self.dn_url + link.get('href')
            time.sleep(0.5)
            r = self.session.get(url, headers={'Referer': subtitle.download_link},
                                 timeout=30)
            r.raise_for_status()
            
        
        archive_stream = io.BytesIO(r.content)
        archive = None
        if rarfile.is_rarfile(archive_stream):
            logger.debug('Identified rar archive')
            archive = rarfile.RarFile(archive_stream)
            subtitle_content = _get_subtitle_from_archive(archive)
        elif zipfile.is_zipfile(archive_stream):
            logger.debug('Identified zip archive')
            archive = zipfile.ZipFile(archive_stream)
            subtitle_content = _get_subtitle_from_archive(archive)
        else:
            subtitle_content = r.content
        
        if subtitle_content:
            subtitle.content = fix_line_ending(subtitle_content)
        else:
            logger.debug('Could not extract subtitle from %r', archive)


def _get_subtitle_from_archive(archive):
    for name in archive.namelist():
        # discard hidden files
        if os.path.split(name)[-1].startswith('.'):
            continue
        
        # discard non-subtitle files
        if not name.lower().endswith(SUBTITLE_EXTENSIONS):
            continue
        
        return archive.read(name)
    
    return None