public
Description: Simple to use TVDB (thetvdb.com) API in Python, and automatic TV episode namer
Homepage: http://dbr.lighthouseapp.com/projects/13342-tvdb_api/tickets
Clone URL: git://github.com/dbr/tvdb_api.git
Search Repo:
tvdb_api / tvdb_api.py
100644 608 lines (530 sloc) 21.331 kb
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
#!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvdb_api
#repository:http://github.com/dbr/tvdb_api
#license:Creative Commons GNU GPL v2
# (http://creativecommons.org/licenses/GPL/2.0/)
 
"""
tvdb_api.py
Simple-to-use Python interface to The TVDB's API (www.thetvdb.com)
 
Example usage:
 
>>> from tvdb_api import Tvdb
>>> db = Tvdb()
>>> db['Lost'][4][11]['name']
'Cabin Fever'
"""
__author__ = "dbr/Ben"
__version__ = "0.3"
 
class Cache:
    """
Simple caching URL opener. Acts like:
import urllib
return urllib.urlopen("http://example.com").read()
Caches complete files to temp directory,
>>> ca = Cache()
>>> ca.loadUrl("http://example.com") #doctest: +ELLIPSIS
'<HTML>...'
"""
    import os
    import time
    import tempfile
    import urllib
    try:
        import sha1 as hasher
    except ImportError:
        import md5 as hasher
    
    def __init__(self, max_age=21600, prefix="tvdb_api"):
        self.prefix = prefix
        self.max_age = max_age
        
        tmp = self.tempfile.gettempdir()
        tmppath = self.os.path.join(tmp, prefix)
        if not self.os.path.isdir(tmppath):
            self.os.mkdir(tmppath)
        self.tmp = tmppath
    #end __init__
    
    def getCachePath(self, url):
        """
Calculates the cache path (/temp_directory/hash_of_URL)
"""
        cache_name = self.hasher.new(url).hexdigest()
        cache_path = self.os.path.join(self.tmp, cache_name)
        return cache_path
    #end getUrl
    
    def checkCache(self, url):
        """
Takes a URL, checks if a cache exists for it.
If so, returns path, if not, returns False
"""
        path = self.getCachePath(url)
        if self.os.path.isfile(path):
            cache_modified_time = self.os.stat(path).st_mtime
            time_now = self.time.time()
            if cache_modified_time < time_now - self.max_age:
                # Cache is old
                return False
            else:
                return path
        else:
            return False
    #end checkCache
 
    def loadUrl(self, url):
        """
Takes a URL, returns the contents of the URL, and does the caching.
"""
        cacheExists = self.checkCache(url)
        if cacheExists:
            cache_file = open(cacheExists)
            dat = cache_file.read()
            cache_file.close()
            return dat
        else:
            path = self.getCachePath(url)
            dat = self.urllib.urlopen(url).read()
            target_socket = open(path, "w+")
            target_socket.write(dat)
            target_socket.close()
            return dat
        #end if cacheExists
    #end loadUrl
#end Cache
 
 
# Custom exceptions
class tvdb_error(Exception):
    """
An error with www.thetvdb.com (Cannot connect, for example)
"""
    pass
class tvdb_userabort(Exception):
    """
User aborted the interactive selection (via
the q command, ^c etc)
"""
    pass
class tvdb_shownotfound(Exception):
    """
Show cannot be found on www.thetvdb.com (non-existant show)
"""
    pass
class tvdb_seasonnotfound(Exception):
    """
Season cannot be found on www.thetvdb.com
"""
    pass
class tvdb_episodenotfound(Exception):
    """
Episode cannot be found on www.thetvdb.com
"""
    pass
class tvdb_attributenotfound(Exception):
    """
Raised if an episode does not have the requested
attribute (such as a episode name)
"""
    pass
 
 
class ShowContainer:
    def __init__(self):
        self.shows = {}
    def has_key(self, key):
        return dict.has_key(self.shows, key)
    def __setitem__(self, showid, value):
        dict.__setitem__(self.shows, showid, value)
    def __getitem__(self, showid):
        if not dict.has_key(self.shows, showid):
            raise tvdb_shownotfound
        else:
            return dict.__getitem__(self.shows, showid)
class Show:
    def __init__(self):
        self.seasons = {}
        self.data = {}
    def has_key(self, key):
        return dict.has_key(self.seasons, key)
    def __setitem__(self, season_number, value):
        dict.__setitem__(self.seasons, season_number, value)
    def __getitem__(self, season_numer):
        if not dict.has_key(self.seasons, season_numer):
            # Season number doesn't exist
            if dict.has_key(self.data, season_numer):
                # check if it's a bit of data
                return dict.__getitem__(self.data, season_numer)
            else:
                # Nope, it doesn't exist
                raise tvdb_seasonnotfound
        else:
            return dict.__getitem__(self.seasons, season_numer)
    def search(self, contents = None, key = None):
        """
Search all episodes. Can search all values, or a specific one.
Always returns an array (can be empty). First index is first
found episode, and so on.
Each array index is an Episode() instance, so doing
search_results[0]['name'] will retrive the episode name.
Examples
These examples assume t is an instance of Tvdb():
>>> t = Tvdb()
>>>
Search for all episodes of Scrubs episodes
with a bit of data containg "my first day":
>>> t['Scrubs'].search("my first day") #doctest: +ELLIPSIS
[<__main__.Episode instance at 0x...>]
>>>
Search for "My Name Is Earl" named "Faked His Own Death":
>>> t['My Name Is Earl'].search('Faked His Own Death', key = 'name') #doctest: +ELLIPSIS
[<__main__.Episode instance at 0x...>]
>>>
Using search results
>>> results = t['Scrubs'].search("my first")
>>> print results[0]['name']
My First Day
>>> for x in results: print x['name']
My First Day
My First Step
My First Kill
>>>
"""
        if key == contents == None:
            raise TypeError, "must supply atleast one type of search"
        
        results = []
        for cur_season in self.seasons.values():
            for cur_ep in cur_season.episodes.values():
                for cur_key, cur_value in cur_ep.data.items():
                    if key != None:
                        if not cur_key.find(key) > -1:
                            # key doesn't match requested search, skip
                            continue
                    #end if key != None
                    if str(cur_value).lower().find(str(contents).lower()) > -1:
                        results.append(cur_ep)
                        continue
                    #end if cur_value.find()
                #end for cur_key, cur_value
            #end for cur_ep
        #end for cur_season
        return results
            
class Season:
    def __init__(self):
        self.episodes = {}
    def has_key(self, key):
        return dict.has_key(self.episodes, key)
    def __setitem__(self, episode_number, value):
        dict.__setitem__(self.episodes, episode_number, value)
    def __getitem__(self, episode_number):
        if not dict.has_key(self.episodes, episode_number):
            raise tvdb_episodenotfound
        else:
            return dict.__getitem__(self.episodes, episode_number)
class Episode:
    def __init__(self):
        self.data = {}
    def __getitem__(self, key):
        if not dict.has_key(self.data, key):
            raise tvdb_attributenotfound
        else:
            return dict.__getitem__(self.data, key)
    def __setitem__(self, key, value):
        dict.__setitem__(self.data, key, value)
 
 
class Tvdb:
    """
Create easy-to-use interface to name of season/episode name
>>> t = Tvdb()
>>> t['Scrubs'][1][24]['name']
'My Last Day'
"""
    from BeautifulSoup import BeautifulStoneSoup
    import random
    
    def __init__(self, interactive=False, debug=False):
        self.shows = ShowContainer() # Holds all Show classes
        self.corrections = {} # Holds show-name to show_id mapping
        
        self.config = {}
        
        self.config['apikey'] = "0629B785CE550C8D" # thetvdb.com API key
        
        self.config['debug_enabled'] = debug # show debugging messages
        self.config['debug_tofile'] = False
        self.config['debug_filename'] = "tvdb.log"
        self.config['debug_path'] = '.'
        
        self.config['interactive'] = interactive # prompt for correct series?
        
        self.cache = Cache(prefix="tvdb_api") # Caches retreived URLs in tmp dir
        self.log = self._initLogger() # Setups the logger (self.log.debug() etc)
        
        # The following url_ configs are based of the
        # http://thetvdb.com/wiki/index.php/Programmers_API
        self.config['url_mirror'] = "http://www.thetvdb.com/api/%(apikey)s/mirrors.xml" % self.config
        self.mirrors = self._getMirrors()
        
        self.config['random_mirror'] = self.random.choice(self.mirrors)
        
        self.config['url_getSeries'] = "%(random_mirror)s/api/GetSeries.php?seriesname=%%s" % self.config
        self.config['url_epInfo'] = "%(random_mirror)s/api/%(apikey)s/series/%%s/all/" % self.config
    #end __init__
    
    def _initLogger(self):
        """
Setups a logger using the logging module, returns a log object
"""
        import os, logging, sys
        logdir = os.path.expanduser( self.config['debug_path'] )
        logpath = os.path.join(logdir, self.config['debug_filename'])
        
        logger = logging.getLogger("tvdb")
        formatter = logging.Formatter('%(asctime)s) %(levelname)s %(message)s')
        
        if self.config['debug_tofile']:
            hdlr = logging.FileHandler(logpath)
        else:
            hdlr = logging.StreamHandler(sys.stdout)
        #end if debug_tofile
        
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
        
        if self.config['debug_enabled']:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
        return logger
    #end initLogger
    
    def _getsoupsrc(self, url):
        """
Helper to get a URL, turn it into
a BeautifulStoneSoup instance (for XML parsing)
"""
        self.log.debug('Retriving URL %s' % (url.replace(" ", "+")))
        
        url = url.replace(" ", "+")
        try:
            src = self.cache.loadUrl(url)
        except IOError, errormsg:
            raise tvdb_error("Could not connect to server: %s\n" % (errormsg))
        #end try
        soup = self.BeautifulStoneSoup(src)
        return soup
    #end _getsoupsrc
    
    def _setItem(self, sid, seas, ep, attrib, value):
        """
Creates a new episode, creating Show(), Season() and
Episode()s as required. Called by _getEps to populute
Since the nice-to-use tvdb[1][24]['name] interface
makes it impossible to do tvdb[1][24]['name] = "name"
and still be capable of checking if an episode exists
so we can raise tvdb_shownotfound, we have a slightly
less pretty method of setting items.. but since the API
is supposed to be read-only, this is the best way to
do it!
The problem is that calling tvdb[1][24]['name'] = "name"
calls __getitem__ on tvdb[1], there is no way to check if
tvdb.__dict__ should have a key "1" before we auto-create it
"""
        if not self.shows.has_key(sid):
            self.shows[sid] = Show()
        if not self.shows[sid].has_key(seas):
            self.shows[sid][seas] = Season()
        if not self.shows[sid][seas].has_key(ep):
            self.shows[sid][seas][ep] = Episode()
        self.shows[sid][seas][ep][attrib] = value
    #end _set_item
    
    def _setShowData(self, sid, key, value):
        if not self.shows.has_key(sid):
            self.shows[sid] = Show()
        self.shows[sid].data.__setitem__(key, value)
    
    def _getMirrors(self):
        """
Gets a list of mirrors from the API
"""
        mirrorSoup = self._getsoupsrc( self.config['url_mirror'] )
        mirrors = []
        for mirror in mirrorSoup.findAll('mirror'):
            self.log.debug('Found mirror %s' % (mirror))
            
            mirrors.append(
                mirror.find('mirrorpath').contents[0]
            )
        #end for mirror
        self.log.debug('Found total of %s mirrors' % (len(mirrors)))
        return mirrors
    #end _getMirrors
 
    def _cleanName(self, name):
        """
Cleans up showname returned by TheTVDB.com
Issues corrected:
- Returns &amp; instead of &, since &s in filenames
are bad, replace &amp; with "and"
"""
        name = name.replace("&amp;", "and")
        return name
    #end _cleanName
    
    def _getSeries(self, series):
        """
This searches TheTVDB.com for the series name,
and either interactivly selects the correct show,
or returns the first result.
"""
        seriesSoup = self._getsoupsrc( self.config['url_getSeries'] % (series) )
        allSeries = []
        for series in seriesSoup.findAll('series'):
            cur_name = series.find('seriesname').contents[0]
            cur_name = self._cleanName(cur_name)
            cur_sid = series.find('id').contents[0]
            self.log.debug('Found series %s (id: %s)' % (cur_name, cur_sid))
            allSeries.append( {'sid':cur_sid, 'name':cur_name} )
        #end for series
        
        if len(allSeries) == 0:
            self.log.debug('Series result returned zero')
            raise tvdb_shownotfound("Show-name search returned zero results (cannot find show on TVDB)")
        
        if not self.config['interactive']:
            self.log.debug('Auto-selecting first search result')
            return allSeries[0]
        else:
            self.log.debug('Interactivily selecting show')
            print "TVDB Search Results:"
            for i in range(len(allSeries[:6])): # list first 6 search results
                i_show = i + 1 # Start at more human readable number 1 (not 0)
                self.log.debug('Showing allSeries[%s] = %s)' % (i_show, allSeries[i]))
                print "%s -> %s (tvdb id: %s)" % (
                    i_show,
                    allSeries[i]['name'].encode("UTF-8","ignore"),
                    allSeries[i]['sid'].encode("UTF-8","ignore")
                )
            
            while True: # return breaks this loop
                try:
                    print "Enter choice (first number, ? for help):"
                    ans = raw_input()
                except KeyboardInterrupt:
                    raise tvdb_userabort("User aborted (^c keyboard interupt)")
            
                self.log.debug('Got choice of: %s' % (ans))
                try:
                    selected_id = int(ans) - 1 # The human entered 1 as first result, not zero
                    self.log.debug('Trying to return ID: %d' % (selected_id))
                    return allSeries[ selected_id ]
                except ValueError: # Input was not number
                    if ans == "q":
                        self.log.debug('Got quit command (q)')
                        raise tvdb_userabort("User aborted ('q' quit command)")
                    elif ans == "?":
                        print "## Help"
                        print "# Enter the number that corresponds to the correct show."
                        print "# ? - this help"
                        print "# q - abort tvnamer"
                    else:
                        self.log.debug('Unknown keypress %s' % (ans))
                #end try
            #end while not valid_input
    #end _getSeries
 
    def _getEps(self, sid):
        """
Takes a series ID, gets the epInfo URL and parses the TVDB
XML file into the shows dict in layout:
shows[series_id][season_number][episode_number]
"""
        self.log.debug('Getting all episodes of %s' % (sid))
        epsSoup = self._getsoupsrc( self.config['url_epInfo']% (sid) )
        for ep in epsSoup.findAll('episode'):
            ep_no = int( ep.find('episodenumber').contents[0] )
            seas_no = int( ep.find('seasonnumber').contents[0] )
            self._setItem(sid, seas_no, ep_no, 'episodenumber', ep_no)
            self._setItem(sid, seas_no, ep_no, 'seasonnumber', seas_no)
            if len( ep.find('episodename').contents ) > 0:
                ep_name = str( ep.find('episodename').contents[0] )
                self._setItem(sid,</