No need to use LWPCookieJar() since we're not reading or writing the
[pyTivo/wmcbrine.git] / metadata.py
blob3f7cf70e9add949a9dee3d58d064670500d86671
1 #!/usr/bin/env python
3 import logging
4 import os
5 import subprocess
6 import sys
7 from datetime import datetime
8 from xml.dom import minidom
9 from xml.parsers import expat
10 try:
11 import plistlib
12 except:
13 pass
15 import mutagen
16 from lrucache import LRUCache
18 import config
19 import plugins.video.transcode
21 # Something to strip
22 TRIBUNE_CR = ' Copyright Tribune Media Services, Inc.'
24 TV_RATINGS = {'TV-Y7': 1, 'TV-Y': 2, 'TV-G': 3, 'TV-PG': 4, 'TV-14': 5,
25 'TV-MA': 6, 'TV-NR': 7, 'TVY7': 1, 'TVY': 2, 'TVG': 3,
26 'TVPG': 4, 'TV14': 5, 'TVMA': 6, 'TVNR': 7, 'Y7': 1,
27 'Y': 2, 'G': 3, 'PG': 4, '14': 5, 'MA': 6, 'NR': 7,
28 'UNRATED': 7, 'X1': 1, 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5,
29 'X6': 6, 'X7': 7}
31 MPAA_RATINGS = {'G': 1, 'PG': 2, 'PG-13': 3, 'PG13': 3, 'R': 4, 'X': 5,
32 'NC-17': 6, 'NC17': 6, 'NR': 8, 'UNRATED': 8, 'G1': 1,
33 'P2': 2, 'P3': 3, 'R4': 4, 'X5': 5, 'N6': 6, 'N8': 8}
35 STAR_RATINGS = {'1': 1, '1.5': 2, '2': 3, '2.5': 4, '3': 5, '3.5': 6,
36 '4': 7, '*': 1, '**': 3, '***': 5, '****': 7, 'X1': 1,
37 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5, 'X6': 6, 'X7': 7}
39 HUMAN = {'mpaaRating': {1: 'G', 2: 'PG', 3: 'PG-13', 4: 'R', 5: 'X',
40 6: 'NC-17', 8: 'NR'},
41 'tvRating': {1: 'Y7', 2: 'Y', 3: 'G', 4: 'PG', 5: '14',
42 6: 'MA', 7: 'NR'},
43 'starRating': {1: '1', 2: '1.5', 3: '2', 4: '2.5', 5: '3',
44 6: '3.5', 7: '4'}}
46 BOM = '\xef\xbb\xbf'
48 tivo_cache = LRUCache(50)
49 mp4_cache = LRUCache(50)
50 dvrms_cache = LRUCache(50)
51 nfo_cache = LRUCache(50)
53 mswindows = (sys.platform == "win32")
55 def get_mpaa(rating):
56 return HUMAN['mpaaRating'].get(rating, 'NR')
58 def get_tv(rating):
59 return HUMAN['tvRating'].get(rating, 'NR')
61 def get_stars(rating):
62 return HUMAN['starRating'].get(rating, '')
64 def tag_data(element, tag):
65 for name in tag.split('/'):
66 found = False
67 for new_element in element.childNodes:
68 if new_element.nodeName == name:
69 found = True
70 element = new_element
71 break
72 if not found:
73 return ''
74 if not element.firstChild:
75 return ''
76 return element.firstChild.data
78 def _vtag_data(element, tag):
79 for name in tag.split('/'):
80 new_element = element.getElementsByTagName(name)
81 if not new_element:
82 return []
83 element = new_element[0]
84 elements = element.getElementsByTagName('element')
85 return [x.firstChild.data for x in elements if x.firstChild]
87 def _vtag_data_alternate(element, tag):
88 elements = [element]
89 for name in tag.split('/'):
90 new_elements = []
91 for elmt in elements:
92 new_elements += elmt.getElementsByTagName(name)
93 elements = new_elements
94 return [x.firstChild.data for x in elements if x.firstChild]
96 def _tag_value(element, tag):
97 item = element.getElementsByTagName(tag)
98 if item:
99 value = item[0].attributes['value'].value
100 return int(value[0])
102 def from_moov(full_path):
103 if full_path in mp4_cache:
104 return mp4_cache[full_path]
106 metadata = {}
107 len_desc = 0
109 try:
110 mp4meta = mutagen.File(unicode(full_path, 'utf-8'))
111 assert(mp4meta)
112 except:
113 mp4_cache[full_path] = {}
114 return {}
116 # The following 1-to-1 correspondence of atoms to pyTivo
117 # variables is TV-biased
118 keys = {'tvnn': 'callsign', 'tven': 'episodeNumber',
119 'tvsh': 'seriesTitle'}
121 for key, value in mp4meta.items():
122 if type(value) == list:
123 value = value[0]
124 if key == 'stik':
125 metadata['isEpisode'] = ['false', 'true'][value == 'TV Show']
126 elif key in keys:
127 metadata[keys[key]] = value
128 # These keys begin with the copyright symbol \xA9
129 elif key == '\xa9day':
130 if len(value) == 4:
131 value += '-01-01T16:00:00Z'
132 metadata['originalAirDate'] = value
133 #metadata['time'] = value
134 elif key in ['\xa9gen', 'gnre']:
135 for k in ('vProgramGenre', 'vSeriesGenre'):
136 if k in metadata:
137 metadata[k].append(value)
138 else:
139 metadata[k] = [value]
140 elif key == '\xa9nam':
141 if 'tvsh' in mp4meta:
142 metadata['episodeTitle'] = value
143 else:
144 metadata['title'] = value
146 # Description in desc, cmt, and/or ldes tags. Keep the longest.
147 elif key in ['desc', '\xa9cmt', 'ldes'] and len(value) > len_desc:
148 metadata['description'] = value
149 len_desc = len(value)
151 # A common custom "reverse DNS format" tag
152 elif (key == '----:com.apple.iTunes:iTunEXTC' and
153 ('us-tv' in value or 'mpaa' in value)):
154 rating = value.split("|")[1].upper()
155 if rating in TV_RATINGS and 'us-tv' in value:
156 metadata['tvRating'] = TV_RATINGS[rating]
157 elif rating in MPAA_RATINGS and 'mpaa' in value:
158 metadata['mpaaRating'] = MPAA_RATINGS[rating]
160 # Actors, directors, producers, AND screenwriters may be in a long
161 # embedded XML plist.
162 elif (key == '----:com.apple.iTunes:iTunMOVI' and
163 'plistlib' in sys.modules):
164 items = {'cast': 'vActor', 'directors': 'vDirector',
165 'producers': 'vProducer', 'screenwriters': 'vWriter'}
166 data = plistlib.readPlistFromString(value)
167 for item in items:
168 if item in data:
169 metadata[items[item]] = [x['name'] for x in data[item]]
171 mp4_cache[full_path] = metadata
172 return metadata
174 def from_mscore(rawmeta):
175 metadata = {}
176 keys = {'title': ['Title'],
177 'description': ['Description', 'WM/SubTitleDescription'],
178 'episodeTitle': ['WM/SubTitle'],
179 'callsign': ['WM/MediaStationCallSign'],
180 'displayMajorNumber': ['WM/MediaOriginalChannel'],
181 'originalAirDate': ['WM/MediaOriginalBroadcastDateTime'],
182 'rating': ['WM/ParentalRating'],
183 'credits': ['WM/MediaCredits'], 'genre': ['WM/Genre']}
185 for tagname in keys:
186 for tag in keys[tagname]:
187 try:
188 if tag in rawmeta:
189 value = rawmeta[tag][0]
190 if type(value) not in (str, unicode):
191 value = str(value)
192 if value:
193 metadata[tagname] = value
194 except:
195 pass
197 if 'episodeTitle' in metadata and 'title' in metadata:
198 metadata['seriesTitle'] = metadata['title']
199 if 'genre' in metadata:
200 value = metadata['genre'].split(',')
201 metadata['vProgramGenre'] = value
202 metadata['vSeriesGenre'] = value
203 del metadata['genre']
204 if 'credits' in metadata:
205 value = [x.split('/') for x in metadata['credits'].split(';')]
206 if len(value) > 3:
207 metadata['vActor'] = [x for x in (value[0] + value[3]) if x]
208 metadata['vDirector'] = [x for x in value[1] if x]
209 del metadata['credits']
210 if 'rating' in metadata:
211 rating = metadata['rating']
212 if rating in TV_RATINGS:
213 metadata['tvRating'] = TV_RATINGS[rating]
214 del metadata['rating']
216 return metadata
218 def from_dvrms(full_path):
219 if full_path in dvrms_cache:
220 return dvrms_cache[full_path]
222 try:
223 rawmeta = mutagen.File(unicode(full_path, 'utf-8'))
224 assert(rawmeta)
225 except:
226 dvrms_cache[full_path] = {}
227 return {}
229 metadata = from_mscore(rawmeta)
230 dvrms_cache[full_path] = metadata
231 return metadata
233 def from_eyetv(full_path):
234 keys = {'TITLE': 'title', 'SUBTITLE': 'episodeTitle',
235 'DESCRIPTION': 'description', 'YEAR': 'movieYear',
236 'EPISODENUM': 'episodeNumber'}
237 metadata = {}
238 path = os.path.dirname(unicode(full_path, 'utf-8'))
239 eyetvp = [x for x in os.listdir(path) if x.endswith('.eyetvp')][0]
240 eyetvp = os.path.join(path, eyetvp)
241 eyetv = plistlib.readPlist(eyetvp)
242 if 'epg info' in eyetv:
243 info = eyetv['epg info']
244 for key in keys:
245 if info[key]:
246 metadata[keys[key]] = info[key]
247 if info['SUBTITLE']:
248 metadata['seriesTitle'] = info['TITLE']
249 if info['ACTORS']:
250 metadata['vActor'] = [x.strip() for x in info['ACTORS'].split(',')]
251 if info['DIRECTOR']:
252 metadata['vDirector'] = [info['DIRECTOR']]
254 for ptag, etag, ratings in [('tvRating', 'TV_RATING', TV_RATINGS),
255 ('mpaaRating', 'MPAA_RATING', MPAA_RATINGS),
256 ('starRating', 'STAR_RATING', STAR_RATINGS)]:
257 x = info[etag].upper()
258 if x and x in ratings:
259 metadata[ptag] = ratings[x]
261 # movieYear must be set for the mpaa/star ratings to work
262 if (('mpaaRating' in metadata or 'starRating' in metadata) and
263 'movieYear' not in metadata):
264 metadata['movieYear'] = eyetv['info']['start'].year
265 return metadata
267 def from_text(full_path):
268 metadata = {}
269 full_path = unicode(full_path, 'utf-8')
270 path, name = os.path.split(full_path)
271 title, ext = os.path.splitext(name)
273 search_paths = []
274 ptmp = full_path
275 while ptmp:
276 parent = os.path.dirname(ptmp)
277 if ptmp != parent:
278 ptmp = parent
279 else:
280 break
281 search_paths.append(os.path.join(ptmp, 'default.txt'))
283 search_paths.append(os.path.join(path, title) + '.properties')
284 search_paths.reverse()
286 search_paths += [full_path + '.txt',
287 os.path.join(path, '.meta', 'default.txt'),
288 os.path.join(path, '.meta', name) + '.txt']
290 for metafile in search_paths:
291 if os.path.exists(metafile):
292 sep = ':='[metafile.endswith('.properties')]
293 for line in file(metafile, 'U'):
294 if line.startswith(BOM):
295 line = line[3:]
296 if line.strip().startswith('#') or not sep in line:
297 continue
298 key, value = [x.strip() for x in line.split(sep, 1)]
299 if not key or not value:
300 continue
301 if key.startswith('v'):
302 if key in metadata:
303 metadata[key].append(value)
304 else:
305 metadata[key] = [value]
306 else:
307 metadata[key] = value
309 for rating, ratings in [('tvRating', TV_RATINGS),
310 ('mpaaRating', MPAA_RATINGS),
311 ('starRating', STAR_RATINGS)]:
312 x = metadata.get(rating, '').upper()
313 if x in ratings:
314 metadata[rating] = ratings[x]
315 else:
316 try:
317 x = int(x)
318 metadata[rating] = x
319 except:
320 pass
322 return metadata
324 def basic(full_path):
325 base_path, name = os.path.split(full_path)
326 title, ext = os.path.splitext(name)
327 mtime = os.stat(unicode(full_path, 'utf-8')).st_mtime
328 if (mtime < 0):
329 mtime = 0
330 originalAirDate = datetime.utcfromtimestamp(mtime)
332 metadata = {'title': title,
333 'originalAirDate': originalAirDate.isoformat()}
334 ext = ext.lower()
335 if ext in ['.mp4', '.m4v', '.mov']:
336 metadata.update(from_moov(full_path))
337 elif ext in ['.dvr-ms', '.asf', '.wmv']:
338 metadata.update(from_dvrms(full_path))
339 elif 'plistlib' in sys.modules and base_path.endswith('.eyetv'):
340 metadata.update(from_eyetv(full_path))
341 metadata.update(from_nfo(full_path))
342 metadata.update(from_text(full_path))
344 return metadata
346 def from_container(xmldoc):
347 metadata = {}
349 keys = {'title': 'Title', 'episodeTitle': 'EpisodeTitle',
350 'description': 'Description', 'programId': 'ProgramId',
351 'seriesId': 'SeriesId', 'episodeNumber': 'EpisodeNumber',
352 'tvRating': 'TvRating', 'displayMajorNumber': 'SourceChannel',
353 'callsign': 'SourceStation', 'showingBits': 'ShowingBits',
354 'mpaaRating': 'MpaaRating'}
356 details = xmldoc.getElementsByTagName('Details')[0]
358 for key in keys:
359 data = tag_data(details, keys[key])
360 if data:
361 if key == 'description':
362 data = data.replace(TRIBUNE_CR, '')
363 elif key == 'tvRating':
364 data = int(data)
365 elif key == 'displayMajorNumber':
366 if '-' in data:
367 data, metadata['displayMinorNumber'] = data.split('-')
368 metadata[key] = data
370 return metadata
372 def from_details(xml):
373 metadata = {}
375 xmldoc = minidom.parse(xml)
376 showing = xmldoc.getElementsByTagName('showing')[0]
377 program = showing.getElementsByTagName('program')[0]
379 items = {'description': 'program/description',
380 'title': 'program/title',
381 'episodeTitle': 'program/episodeTitle',
382 'episodeNumber': 'program/episodeNumber',
383 'programId': 'program/uniqueId',
384 'seriesId': 'program/series/uniqueId',
385 'seriesTitle': 'program/series/seriesTitle',
386 'originalAirDate': 'program/originalAirDate',
387 'isEpisode': 'program/isEpisode',
388 'movieYear': 'program/movieYear',
389 'partCount': 'partCount',
390 'partIndex': 'partIndex',
391 'time': 'time'}
393 for item in items:
394 data = tag_data(showing, items[item])
395 if data:
396 if item == 'description':
397 data = data.replace(TRIBUNE_CR, '')
398 metadata[item] = data
400 vItems = ['vActor', 'vChoreographer', 'vDirector',
401 'vExecProducer', 'vProgramGenre', 'vGuestStar',
402 'vHost', 'vProducer', 'vWriter']
404 for item in vItems:
405 data = _vtag_data(program, item)
406 if data:
407 metadata[item] = data
409 sb = showing.getElementsByTagName('showingBits')
410 if sb:
411 metadata['showingBits'] = sb[0].attributes['value'].value
413 #for tag in ['starRating', 'mpaaRating', 'colorCode']:
414 for tag in ['starRating', 'mpaaRating']:
415 value = _tag_value(program, tag)
416 if value:
417 metadata[tag] = value
419 rating = _tag_value(showing, 'tvRating')
420 if rating:
421 metadata['tvRating'] = rating
423 return metadata
425 def _nfo_vitems(source, metadata):
427 vItems = {'vGenre': 'genre',
428 'vWriter': 'credits',
429 'vDirector': 'director',
430 'vActor': 'actor/name'}
432 for key in vItems:
433 data = _vtag_data_alternate(source, vItems[key])
434 if data:
435 metadata.setdefault(key, [])
436 for dat in data:
437 if not dat in metadata[key]:
438 metadata[key].append(dat)
440 if 'vGenre' in metadata:
441 metadata['vSeriesGenre'] = metadata['vProgramGenre'] = metadata['vGenre']
443 return metadata
445 def _parse_nfo(nfo_path, nfo_data=None):
446 # nfo files can contain XML or a URL to seed the XBMC metadata scrapers
447 # It's also possible to have both (a URL after the XML metadata)
448 # pyTivo only parses the XML metadata, but we'll try to stip the URL
449 # from mixed XML/URL files. Returns `None` when XML can't be parsed.
450 if nfo_data is None:
451 nfo_data = [line.strip() for line in file(nfo_path, 'rU')]
452 xmldoc = None
453 try:
454 xmldoc = minidom.parseString(os.linesep.join(nfo_data))
455 except expat.ExpatError, err:
456 if expat.ErrorString(err.code) == expat.errors.XML_ERROR_INVALID_TOKEN:
457 # might be a URL outside the xml
458 while len(nfo_data) > err.lineno:
459 if len(nfo_data[-1]) == 0:
460 nfo_data.pop()
461 else:
462 break
463 if len(nfo_data) == err.lineno:
464 # last non-blank line contains the error
465 nfo_data.pop()
466 return _parse_nfo(nfo_path, nfo_data)
467 return xmldoc
469 def _from_tvshow_nfo(tvshow_nfo_path):
470 if tvshow_nfo_path in nfo_cache:
471 return nfo_cache[tvshow_nfo_path]
473 items = {'description': 'plot',
474 'title': 'title',
475 'seriesTitle': 'showtitle',
476 'starRating': 'rating',
477 'tvRating': 'mpaa'}
479 nfo_cache[tvshow_nfo_path] = metadata = {}
481 xmldoc = _parse_nfo(tvshow_nfo_path)
482 if not xmldoc:
483 return metadata
485 tvshow = xmldoc.getElementsByTagName('tvshow')
486 if tvshow:
487 tvshow = tvshow[0]
488 else:
489 return metadata
491 for item in items:
492 data = tag_data(tvshow, items[item])
493 if data:
494 metadata[item] = data
496 metadata = _nfo_vitems(tvshow, metadata)
498 nfo_cache[tvshow_nfo_path] = metadata
499 return metadata
501 def _from_episode_nfo(nfo_path, xmldoc):
502 metadata = {}
504 items = {'description': 'plot',
505 'episodeTitle': 'title',
506 'seriesTitle': 'showtitle',
507 'originalAirDate': 'aired',
508 'starRating': 'rating',
509 'tvRating': 'mpaa'}
511 # find tvshow.nfo
512 path = nfo_path
513 while True:
514 basepath = os.path.dirname(path)
515 if path == basepath:
516 break
517 path = basepath
518 tv_nfo = os.path.join(path, 'tvshow.nfo')
519 if os.path.exists(tv_nfo):
520 metadata.update(_from_tvshow_nfo(tv_nfo))
521 break
523 episode = xmldoc.getElementsByTagName('episodedetails')
524 if episode:
525 episode = episode[0]
526 else:
527 return metadata
529 metadata['isEpisode'] = 'true'
530 for item in items:
531 data = tag_data(episode, items[item])
532 if data:
533 metadata[item] = data
535 season = tag_data(episode, 'displayseason')
536 if not season or season == "-1":
537 season = tag_data(episode, 'season')
538 if not season:
539 season = 1
541 ep_num = tag_data(episode, 'displayepisode')
542 if not ep_num or ep_num == "-1":
543 ep_num = tag_data(episode, 'episode')
544 if ep_num and ep_num != "-1":
545 metadata['episodeNumber'] = "%d%02d" % (int(season), int(ep_num))
547 if 'originalAirDate' in metadata:
548 metadata['originalAirDate'] += 'T00:00:00Z'
550 metadata = _nfo_vitems(episode, metadata)
552 return metadata
554 def _from_movie_nfo(xmldoc):
555 metadata = {}
557 movie = xmldoc.getElementsByTagName('movie')
558 if movie:
559 movie = movie[0]
560 else:
561 return metadata
563 items = {'description': 'plot',
564 'title': 'title',
565 'movieYear': 'year',
566 'starRating': 'rating',
567 'mpaaRating': 'mpaa'}
569 metadata['isEpisode'] = 'false'
571 for item in items:
572 data = tag_data(movie, items[item])
573 if data:
574 metadata[item] = data
576 metadata['movieYear'] = "%04d" % int(metadata.get('movieYear', 0))
578 metadata = _nfo_vitems(movie, metadata)
579 return metadata
581 def from_nfo(full_path):
582 if full_path in nfo_cache:
583 return nfo_cache[full_path]
585 metadata = nfo_cache[full_path] = {}
587 nfo_path = "%s.nfo" % os.path.splitext(full_path)[0]
588 if not os.path.exists(nfo_path):
589 return metadata
591 xmldoc = _parse_nfo(nfo_path)
592 if not xmldoc:
593 return metadata
595 if xmldoc.getElementsByTagName('episodedetails'):
596 # it's an episode
597 metadata.update(_from_episode_nfo(nfo_path, xmldoc))
598 elif xmldoc.getElementsByTagName('movie'):
599 # it's a movie
600 metadata.update(_from_movie_nfo(xmldoc))
602 # common nfo cleanup
603 if 'starRating' in metadata:
604 # .NFO 0-10 -> TiVo 1-7
605 rating = int(float(metadata['starRating']) * 6 / 10 + 1.5)
606 metadata['starRating'] = rating
608 for key, mapping in [('mpaaRating', MPAA_RATINGS),
609 ('tvRating', TV_RATINGS)]:
610 if key in metadata:
611 rating = mapping.get(metadata[key], None)
612 if rating:
613 metadata[key] = str(rating)
614 else:
615 del metadata[key]
617 nfo_cache[full_path] = metadata
618 return metadata
620 def from_tivo(full_path):
621 if full_path in tivo_cache:
622 return tivo_cache[full_path]
624 tdcat_path = config.get_bin('tdcat')
625 tivo_mak = config.get_server('tivo_mak')
626 try:
627 assert(tdcat_path and tivo_mak)
628 fname = unicode(full_path, 'utf-8')
629 if mswindows:
630 fname = fname.encode('iso8859-1')
631 tcmd = [tdcat_path, '-m', tivo_mak, '-2', fname]
632 tdcat = subprocess.Popen(tcmd, stdout=subprocess.PIPE)
633 metadata = from_details(tdcat.stdout)
634 tivo_cache[full_path] = metadata
635 except:
636 metadata = {}
638 return metadata
640 def force_utf8(text):
641 if type(text) == str:
642 try:
643 text = text.decode('utf8')
644 except:
645 if sys.platform == 'darwin':
646 text = text.decode('macroman')
647 else:
648 text = text.decode('iso8859-1')
649 return text.encode('utf-8')
651 def dump(output, metadata):
652 for key in metadata:
653 value = metadata[key]
654 if type(value) == list:
655 for item in value:
656 output.write('%s: %s\n' % (key, item.encode('utf-8')))
657 else:
658 if key in HUMAN and value in HUMAN[key]:
659 output.write('%s: %s\n' % (key, HUMAN[key][value]))
660 else:
661 output.write('%s: %s\n' % (key, value.encode('utf-8')))
663 if __name__ == '__main__':
664 if len(sys.argv) > 1:
665 metadata = {}
666 config.init([])
667 logging.basicConfig()
668 fname = force_utf8(sys.argv[1])
669 ext = os.path.splitext(fname)[1].lower()
670 if ext == '.tivo':
671 metadata.update(from_tivo(fname))
672 elif ext in ['.mp4', '.m4v', '.mov']:
673 metadata.update(from_moov(fname))
674 elif ext in ['.dvr-ms', '.asf', '.wmv']:
675 metadata.update(from_dvrms(fname))
676 elif ext == '.wtv':
677 vInfo = plugins.video.transcode.video_info(fname)
678 metadata.update(from_mscore(vInfo['rawmeta']))
679 dump(sys.stdout, metadata)