Merge branch 'master' of git://repo.or.cz/pyTivo/wmcbrine.git
[pyTivo/wmcbrine/lucasnz.git] / metadata.py
blobf48f84b3696aecc388be131706766e9974e19ccd
1 #!/usr/bin/env python
3 import os
4 import subprocess
5 import sys
6 from datetime import datetime
7 from xml.dom import minidom
8 from xml.parsers import expat
9 try:
10 import plistlib
11 except:
12 pass
14 import mutagen
15 from lrucache import LRUCache
17 import config
18 import plugins.video.transcode
20 # Something to strip
21 TRIBUNE_CR = ' Copyright Tribune Media Services, Inc.'
23 TV_RATINGS = {'TV-Y7': 1, 'TV-Y': 2, 'TV-G': 3, 'TV-PG': 4, 'TV-14': 5,
24 'TV-MA': 6, 'TV-NR': 7, 'TVY7': 1, 'TVY': 2, 'TVG': 3,
25 'TVPG': 4, 'TV14': 5, 'TVMA': 6, 'TVNR': 7, 'Y7': 1,
26 'Y': 2, 'G': 3, 'PG': 4, '14': 5, 'MA': 6, 'NR': 7,
27 'UNRATED': 7, 'X1': 1, 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5,
28 'X6': 6, 'X7': 7, '01': 1, '02': 2, '03': 3, '04': 4,
29 '05': 5, '06': 6, '07': 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]
316 return metadata
318 def basic(full_path):
319 base_path, name = os.path.split(full_path)
320 title, ext = os.path.splitext(name)
321 mtime = os.stat(unicode(full_path, 'utf-8')).st_mtime
322 if (mtime < 0):
323 mtime = 0
324 originalAirDate = datetime.utcfromtimestamp(mtime)
326 metadata = {'title': title,
327 'originalAirDate': originalAirDate.isoformat()}
328 ext = ext.lower()
329 if ext in ['.mp4', '.m4v', '.mov']:
330 metadata.update(from_moov(full_path))
331 elif ext in ['.dvr-ms', '.asf', '.wmv']:
332 metadata.update(from_dvrms(full_path))
333 elif 'plistlib' in sys.modules and base_path.endswith('.eyetv'):
334 metadata.update(from_eyetv(full_path))
335 metadata.update(from_nfo(full_path))
336 metadata.update(from_text(full_path))
338 return metadata
340 def from_container(xmldoc):
341 metadata = {}
343 keys = {'title': 'Title', 'episodeTitle': 'EpisodeTitle',
344 'description': 'Description', 'programId': 'ProgramId',
345 'seriesId': 'SeriesId', 'episodeNumber': 'EpisodeNumber',
346 'tvRating': 'TvRating', 'displayMajorNumber': 'SourceChannel',
347 'callsign': 'SourceStation', 'showingBits': 'ShowingBits',
348 'mpaaRating': 'MpaaRating'}
350 details = xmldoc.getElementsByTagName('Details')[0]
352 for key in keys:
353 data = tag_data(details, keys[key])
354 if data:
355 if key == 'description':
356 data = data.replace(TRIBUNE_CR, '')
357 elif key == 'tvRating':
358 data = int(data)
359 elif key == 'displayMajorNumber':
360 if '-' in data:
361 data, metadata['displayMinorNumber'] = data.split('-')
362 metadata[key] = data
364 return metadata
366 def from_details(xml):
367 metadata = {}
369 xmldoc = minidom.parse(xml)
370 showing = xmldoc.getElementsByTagName('showing')[0]
371 program = showing.getElementsByTagName('program')[0]
373 items = {'description': 'program/description',
374 'title': 'program/title',
375 'episodeTitle': 'program/episodeTitle',
376 'episodeNumber': 'program/episodeNumber',
377 'programId': 'program/uniqueId',
378 'seriesId': 'program/series/uniqueId',
379 'seriesTitle': 'program/series/seriesTitle',
380 'originalAirDate': 'program/originalAirDate',
381 'isEpisode': 'program/isEpisode',
382 'movieYear': 'program/movieYear',
383 'partCount': 'partCount',
384 'partIndex': 'partIndex',
385 'time': 'time'}
387 for item in items:
388 data = tag_data(showing, items[item])
389 if data:
390 if item == 'description':
391 data = data.replace(TRIBUNE_CR, '')
392 metadata[item] = data
394 vItems = ['vActor', 'vChoreographer', 'vDirector',
395 'vExecProducer', 'vProgramGenre', 'vGuestStar',
396 'vHost', 'vProducer', 'vWriter']
398 for item in vItems:
399 data = _vtag_data(program, item)
400 if data:
401 metadata[item] = data
403 sb = showing.getElementsByTagName('showingBits')
404 if sb:
405 metadata['showingBits'] = sb[0].attributes['value'].value
407 #for tag in ['starRating', 'mpaaRating', 'colorCode']:
408 for tag in ['starRating', 'mpaaRating']:
409 value = _tag_value(program, tag)
410 if value:
411 metadata[tag] = value
413 rating = _tag_value(showing, 'tvRating')
414 if rating:
415 metadata['tvRating'] = rating
417 return metadata
419 def _nfo_vitems(source, metadata):
421 vItems = {'vGenre': 'genre',
422 'vWriter': 'credits',
423 'vDirector': 'director',
424 'vActor': 'actor/name'}
426 for key in vItems:
427 data = _vtag_data_alternate(source, vItems[key])
428 if data:
429 metadata.setdefault(key, [])
430 for dat in data:
431 if not dat in metadata[key]:
432 metadata[key].append(dat)
434 if 'vGenre' in metadata:
435 metadata['vSeriesGenre'] = metadata['vProgramGenre'] = metadata['vGenre']
437 return metadata
439 def _parse_nfo(nfo_path, nfo_data=None):
440 # nfo files can contain XML or a URL to seed the XBMC metadata scrapers
441 # It's also possible to have both (a URL after the XML metadata)
442 # pyTivo only parses the XML metadata, but we'll try to stip the URL
443 # from mixed XML/URL files. Returns `None` when XML can't be parsed.
444 if nfo_data is None:
445 nfo_data = [line.strip() for line in file(nfo_path, 'rU')]
446 xmldoc = None
447 try:
448 xmldoc = minidom.parseString(os.linesep.join(nfo_data))
449 except expat.ExpatError, err:
450 if expat.ErrorString(err.code) == expat.errors.XML_ERROR_INVALID_TOKEN:
451 # might be a URL outside the xml
452 while len(nfo_data) > err.lineno:
453 if len(nfo_data[-1]) == 0:
454 nfo_data.pop()
455 else:
456 break
457 if len(nfo_data) == err.lineno:
458 # last non-blank line contains the error
459 nfo_data.pop()
460 return _parse_nfo(nfo_path, nfo_data)
461 return xmldoc
463 def _from_tvshow_nfo(tvshow_nfo_path):
464 if tvshow_nfo_path in nfo_cache:
465 return nfo_cache[tvshow_nfo_path]
467 items = {'description': 'plot',
468 'title': 'title',
469 'seriesTitle': 'showtitle',
470 'starRating': 'rating',
471 'tvRating': 'mpaa'}
473 nfo_cache[tvshow_nfo_path] = metadata = {}
475 xmldoc = _parse_nfo(tvshow_nfo_path)
476 if not xmldoc:
477 return metadata
479 tvshow = xmldoc.getElementsByTagName('tvshow')
480 if tvshow:
481 tvshow = tvshow[0]
482 else:
483 return metadata
485 for item in items:
486 data = tag_data(tvshow, items[item])
487 if data:
488 metadata[item] = data
490 metadata = _nfo_vitems(tvshow, metadata)
492 nfo_cache[tvshow_nfo_path] = metadata
493 return metadata
495 def _from_episode_nfo(nfo_path, xmldoc):
496 metadata = {}
498 items = {'description': 'plot',
499 'episodeTitle': 'title',
500 'seriesTitle': 'showtitle',
501 'originalAirDate': 'aired',
502 'starRating': 'rating',
503 'tvRating': 'mpaa'}
505 # find tvshow.nfo
506 path = nfo_path
507 while True:
508 basepath = os.path.dirname(path)
509 if path == basepath:
510 break
511 path = basepath
512 tv_nfo = os.path.join(path, 'tvshow.nfo')
513 if os.path.exists(tv_nfo):
514 metadata.update(_from_tvshow_nfo(tv_nfo))
515 break
517 episode = xmldoc.getElementsByTagName('episodedetails')
518 if episode:
519 episode = episode[0]
520 else:
521 return metadata
523 metadata['isEpisode'] = 'true'
524 for item in items:
525 data = tag_data(episode, items[item])
526 if data:
527 metadata[item] = data
529 season = tag_data(episode, 'displayseason')
530 if not season or season == "-1":
531 season = tag_data(episode, 'season')
532 if not season:
533 season = 1
535 ep_num = tag_data(episode, 'displayepisode')
536 if not ep_num or ep_num == "-1":
537 ep_num = tag_data(episode, 'episode')
538 if ep_num and ep_num != "-1":
539 metadata['episodeNumber'] = "%d%02d" % (int(season), int(ep_num))
541 if 'originalAirDate' in metadata:
542 metadata['originalAirDate'] += 'T00:00:00Z'
544 metadata = _nfo_vitems(episode, metadata)
546 return metadata
548 def _from_movie_nfo(xmldoc):
549 metadata = {}
551 movie = xmldoc.getElementsByTagName('movie')
552 if movie:
553 movie = movie[0]
554 else:
555 return metadata
557 items = {'description': 'plot',
558 'title': 'title',
559 'movieYear': 'year',
560 'starRating': 'rating',
561 'mpaaRating': 'mpaa'}
563 metadata['isEpisode'] = 'false'
565 for item in items:
566 data = tag_data(movie, items[item])
567 if data:
568 metadata[item] = data
570 metadata['movieYear'] = "%04d" % int(metadata.get('movieYear', 0))
572 metadata = _nfo_vitems(movie, metadata)
573 return metadata
575 def from_nfo(full_path):
576 if full_path in nfo_cache:
577 return nfo_cache[full_path]
579 metadata = nfo_cache[full_path] = {}
581 nfo_path = "%s.nfo" % os.path.splitext(full_path)[0]
582 if not os.path.exists(nfo_path):
583 return metadata
585 xmldoc = _parse_nfo(nfo_path)
586 if not xmldoc:
587 return metadata
589 if xmldoc.getElementsByTagName('episodedetails'):
590 # it's an episode
591 metadata.update(_from_episode_nfo(nfo_path, xmldoc))
592 elif xmldoc.getElementsByTagName('movie'):
593 # it's a movie
594 metadata.update(_from_movie_nfo(xmldoc))
596 # common nfo cleanup
597 if 'starRating' in metadata:
598 # .NFO 0-10 -> TiVo 1-7
599 rating = int(float(metadata['starRating']) * 6 / 10 + 1.5)
600 metadata['starRating'] = rating
602 for key, mapping in [('mpaaRating', MPAA_RATINGS),
603 ('tvRating', TV_RATINGS)]:
604 if key in metadata:
605 rating = mapping.get(metadata[key], None)
606 if rating:
607 metadata[key] = str(rating)
608 else:
609 del metadata[key]
611 nfo_cache[full_path] = metadata
612 return metadata
614 def from_tivo(full_path):
615 if full_path in tivo_cache:
616 return tivo_cache[full_path]
618 tdcat_path = config.get_bin('tdcat')
619 tivo_mak = config.get_server('tivo_mak')
620 try:
621 assert(tdcat_path and tivo_mak)
622 fname = unicode(full_path, 'utf-8')
623 if mswindows:
624 fname = fname.encode('iso8859-1')
625 tcmd = [tdcat_path, '-m', tivo_mak, '-2', fname]
626 tdcat = subprocess.Popen(tcmd, stdout=subprocess.PIPE)
627 metadata = from_details(tdcat.stdout)
628 tivo_cache[full_path] = metadata
629 except:
630 metadata = {}
632 return metadata
634 def force_utf8(text):
635 if type(text) == str:
636 try:
637 text = text.decode('utf8')
638 except:
639 if sys.platform == 'darwin':
640 text = text.decode('macroman')
641 else:
642 text = text.decode('iso8859-1')
643 return text.encode('utf-8')
645 def dump(output, metadata):
646 for key in metadata:
647 value = metadata[key]
648 if type(value) == list:
649 for item in value:
650 output.write('%s: %s\n' % (key, item.encode('utf-8')))
651 else:
652 if key in HUMAN and value in HUMAN[key]:
653 output.write('%s: %s\n' % (key, HUMAN[key][value]))
654 else:
655 output.write('%s: %s\n' % (key, value.encode('utf-8')))
657 if __name__ == '__main__':
658 if len(sys.argv) > 1:
659 metadata = {}
660 fname = force_utf8(sys.argv[1])
661 ext = os.path.splitext(fname)[1].lower()
662 if ext == '.tivo':
663 config.init([])
664 metadata.update(from_tivo(fname))
665 elif ext in ['.mp4', '.m4v', '.mov']:
666 metadata.update(from_moov(fname))
667 elif ext in ['.dvr-ms', '.asf', '.wmv']:
668 metadata.update(from_dvrms(fname))
669 elif ext == '.wtv':
670 vInfo = plugins.video.transcode.video_info(fname)
671 metadata.update(from_mscore(vInfo['rawmeta']))
672 dump(sys.stdout, metadata)