Use 'ts' = 'on' in server section instead of togo_mpegts to align
[pyTivo/wmcbrine/lucasnz.git] / metadata.py
blob4a211a4323bfc61072b7edf792231ef20bf04f83
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}
30 MPAA_RATINGS = {'G': 1, 'PG': 2, 'PG-13': 3, 'PG13': 3, 'R': 4, 'X': 5,
31 'NC-17': 6, 'NC17': 6, 'NR': 8, 'UNRATED': 8, 'G1': 1,
32 'P2': 2, 'P3': 3, 'R4': 4, 'X5': 5, 'N6': 6, 'N8': 8}
34 STAR_RATINGS = {'1': 1, '1.5': 2, '2': 3, '2.5': 4, '3': 5, '3.5': 6,
35 '4': 7, '*': 1, '**': 3, '***': 5, '****': 7}
37 HUMAN = {'mpaaRating': {1: 'G', 2: 'PG', 3: 'PG-13', 4: 'R', 5: 'X',
38 6: 'NC-17', 8: 'NR'},
39 'tvRating': {1: 'Y7', 2: 'Y', 3: 'G', 4: 'PG', 5: '14',
40 6: 'MA', 7: 'NR'},
41 'starRating': {1: '1', 2: '1.5', 3: '2', 4: '2.5', 5: '3',
42 6: '3.5', 7: '4'}}
44 BOM = '\xef\xbb\xbf'
46 tivo_cache = LRUCache(50)
47 mp4_cache = LRUCache(50)
48 dvrms_cache = LRUCache(50)
49 nfo_cache = LRUCache(50)
51 mswindows = (sys.platform == "win32")
53 def get_mpaa(rating):
54 return HUMAN['mpaaRating'].get(rating, 'NR')
56 def get_tv(rating):
57 return HUMAN['tvRating'].get(rating, 'NR')
59 def get_stars(rating):
60 return HUMAN['starRating'].get(rating, '')
62 def tag_data(element, tag):
63 for name in tag.split('/'):
64 new_element = element.getElementsByTagName(name)
65 if not new_element:
66 return ''
67 element = new_element[0]
68 if not element.firstChild:
69 return ''
70 return element.firstChild.data
72 def _vtag_data(element, tag):
73 for name in tag.split('/'):
74 new_element = element.getElementsByTagName(name)
75 if not new_element:
76 return []
77 element = new_element[0]
78 elements = element.getElementsByTagName('element')
79 return [x.firstChild.data for x in elements if x.firstChild]
81 def _vtag_data_alternate(element, tag):
82 elements = [element]
83 for name in tag.split('/'):
84 new_elements = []
85 for elmt in elements:
86 new_elements += elmt.getElementsByTagName(name)
87 elements = new_elements
88 return [x.firstChild.data for x in elements if x.firstChild]
90 def _tag_value(element, tag):
91 item = element.getElementsByTagName(tag)
92 if item:
93 value = item[0].attributes['value'].value
94 return int(value[0])
96 def from_moov(full_path):
97 if full_path in mp4_cache:
98 return mp4_cache[full_path]
100 metadata = {}
101 len_desc = 0
103 try:
104 mp4meta = mutagen.File(unicode(full_path, 'utf-8'))
105 assert(mp4meta)
106 except:
107 mp4_cache[full_path] = {}
108 return {}
110 # The following 1-to-1 correspondence of atoms to pyTivo
111 # variables is TV-biased
112 keys = {'tvnn': 'callsign', 'tven': 'episodeNumber',
113 'tvsh': 'seriesTitle'}
115 for key, value in mp4meta.items():
116 if type(value) == list:
117 value = value[0]
118 if key == 'stik':
119 metadata['isEpisode'] = ['false', 'true'][value == 'TV Show']
120 elif key in keys:
121 metadata[keys[key]] = value
122 # These keys begin with the copyright symbol \xA9
123 elif key == '\xa9day':
124 if len(value) == 4:
125 value += '-01-01T16:00:00Z'
126 metadata['originalAirDate'] = value
127 #metadata['time'] = value
128 elif key in ['\xa9gen', 'gnre']:
129 for k in ('vProgramGenre', 'vSeriesGenre'):
130 if k in metadata:
131 metadata[k].append(value)
132 else:
133 metadata[k] = [value]
134 elif key == '\xa9nam':
135 if 'tvsh' in mp4meta:
136 metadata['episodeTitle'] = value
137 else:
138 metadata['title'] = value
140 # Description in desc, cmt, and/or ldes tags. Keep the longest.
141 elif key in ['desc', '\xa9cmt', 'ldes'] and len(value) > len_desc:
142 metadata['description'] = value
143 len_desc = len(value)
145 # A common custom "reverse DNS format" tag
146 elif (key == '----:com.apple.iTunes:iTunEXTC' and
147 ('us-tv' in value or 'mpaa' in value)):
148 rating = value.split("|")[1].upper()
149 if rating in TV_RATINGS and 'us-tv' in value:
150 metadata['tvRating'] = TV_RATINGS[rating]
151 elif rating in MPAA_RATINGS and 'mpaa' in value:
152 metadata['mpaaRating'] = MPAA_RATINGS[rating]
154 # Actors, directors, producers, AND screenwriters may be in a long
155 # embedded XML plist.
156 elif (key == '----:com.apple.iTunes:iTunMOVI' and
157 'plistlib' in sys.modules):
158 items = {'cast': 'vActor', 'directors': 'vDirector',
159 'producers': 'vProducer', 'screenwriters': 'vWriter'}
160 data = plistlib.readPlistFromString(value)
161 for item in items:
162 if item in data:
163 metadata[items[item]] = [x['name'] for x in data[item]]
165 mp4_cache[full_path] = metadata
166 return metadata
168 def from_mscore(rawmeta):
169 metadata = {}
170 keys = {'title': ['Title'],
171 'description': ['Description', 'WM/SubTitleDescription'],
172 'episodeTitle': ['WM/SubTitle'],
173 'callsign': ['WM/MediaStationCallSign'],
174 'displayMajorNumber': ['WM/MediaOriginalChannel'],
175 'originalAirDate': ['WM/MediaOriginalBroadcastDateTime'],
176 'rating': ['WM/ParentalRating'],
177 'credits': ['WM/MediaCredits'], 'genre': ['WM/Genre']}
179 for tagname in keys:
180 for tag in keys[tagname]:
181 try:
182 if tag in rawmeta:
183 value = rawmeta[tag][0]
184 if type(value) not in (str, unicode):
185 value = str(value)
186 if value:
187 metadata[tagname] = value
188 except:
189 pass
191 if 'episodeTitle' in metadata and 'title' in metadata:
192 metadata['seriesTitle'] = metadata['title']
193 if 'genre' in metadata:
194 value = metadata['genre'].split(',')
195 metadata['vProgramGenre'] = value
196 metadata['vSeriesGenre'] = value
197 del metadata['genre']
198 if 'credits' in metadata:
199 value = [x.split('/') for x in metadata['credits'].split(';')]
200 if len(value) > 3:
201 metadata['vActor'] = [x for x in (value[0] + value[3]) if x]
202 metadata['vDirector'] = [x for x in value[1] if x]
203 del metadata['credits']
204 if 'rating' in metadata:
205 rating = metadata['rating']
206 if rating in TV_RATINGS:
207 metadata['tvRating'] = TV_RATINGS[rating]
208 del metadata['rating']
210 return metadata
212 def from_dvrms(full_path):
213 if full_path in dvrms_cache:
214 return dvrms_cache[full_path]
216 try:
217 rawmeta = mutagen.File(unicode(full_path, 'utf-8'))
218 assert(rawmeta)
219 except:
220 dvrms_cache[full_path] = {}
221 return {}
223 metadata = from_mscore(rawmeta)
224 dvrms_cache[full_path] = metadata
225 return metadata
227 def from_eyetv(full_path):
228 keys = {'TITLE': 'title', 'SUBTITLE': 'episodeTitle',
229 'DESCRIPTION': 'description', 'YEAR': 'movieYear',
230 'EPISODENUM': 'episodeNumber'}
231 metadata = {}
232 path = os.path.dirname(unicode(full_path, 'utf-8'))
233 eyetvp = [x for x in os.listdir(path) if x.endswith('.eyetvp')][0]
234 eyetvp = os.path.join(path, eyetvp)
235 eyetv = plistlib.readPlist(eyetvp)
236 if 'epg info' in eyetv:
237 info = eyetv['epg info']
238 for key in keys:
239 if info[key]:
240 metadata[keys[key]] = info[key]
241 if info['SUBTITLE']:
242 metadata['seriesTitle'] = info['TITLE']
243 if info['ACTORS']:
244 metadata['vActor'] = [x.strip() for x in info['ACTORS'].split(',')]
245 if info['DIRECTOR']:
246 metadata['vDirector'] = [info['DIRECTOR']]
248 for ptag, etag, ratings in [('tvRating', 'TV_RATING', TV_RATINGS),
249 ('mpaaRating', 'MPAA_RATING', MPAA_RATINGS),
250 ('starRating', 'STAR_RATING', STAR_RATINGS)]:
251 x = info[etag].upper()
252 if x and x in ratings:
253 metadata[ptag] = ratings[x]
255 # movieYear must be set for the mpaa/star ratings to work
256 if (('mpaaRating' in metadata or 'starRating' in metadata) and
257 'movieYear' not in metadata):
258 metadata['movieYear'] = eyetv['info']['start'].year
259 return metadata
261 def from_text(full_path):
262 metadata = {}
263 full_path = unicode(full_path, 'utf-8')
264 path, name = os.path.split(full_path)
265 title, ext = os.path.splitext(name)
267 search_paths = []
268 ptmp = full_path
269 while ptmp:
270 parent = os.path.dirname(ptmp)
271 if ptmp != parent:
272 ptmp = parent
273 else:
274 break
275 search_paths.append(os.path.join(ptmp, 'default.txt'))
277 search_paths.append(os.path.join(path, title) + '.properties')
278 search_paths.reverse()
280 search_paths += [full_path + '.txt',
281 os.path.join(path, '.meta', 'default.txt'),
282 os.path.join(path, '.meta', name) + '.txt']
284 for metafile in search_paths:
285 if os.path.exists(metafile):
286 sep = ':='[metafile.endswith('.properties')]
287 for line in file(metafile, 'U'):
288 if line.startswith(BOM):
289 line = line[3:]
290 if line.strip().startswith('#') or not sep in line:
291 continue
292 key, value = [x.strip() for x in line.split(sep, 1)]
293 if not key or not value:
294 continue
295 if key.startswith('v'):
296 if key in metadata:
297 metadata[key].append(value)
298 else:
299 metadata[key] = [value]
300 else:
301 metadata[key] = value
303 for rating, ratings in [('tvRating', TV_RATINGS),
304 ('mpaaRating', MPAA_RATINGS),
305 ('starRating', STAR_RATINGS)]:
306 x = metadata.get(rating, '').upper()
307 if x in ratings:
308 metadata[rating] = ratings[x]
310 return metadata
312 def basic(full_path):
313 base_path, name = os.path.split(full_path)
314 title, ext = os.path.splitext(name)
315 mtime = os.stat(unicode(full_path, 'utf-8')).st_mtime
316 if (mtime < 0):
317 mtime = 0
318 originalAirDate = datetime.utcfromtimestamp(mtime)
320 metadata = {'title': title,
321 'originalAirDate': originalAirDate.isoformat()}
322 ext = ext.lower()
323 if ext in ['.mp4', '.m4v', '.mov']:
324 metadata.update(from_moov(full_path))
325 elif ext in ['.dvr-ms', '.asf', '.wmv']:
326 metadata.update(from_dvrms(full_path))
327 elif 'plistlib' in sys.modules and base_path.endswith('.eyetv'):
328 metadata.update(from_eyetv(full_path))
329 metadata.update(from_nfo(full_path))
330 metadata.update(from_text(full_path))
332 return metadata
334 def from_container(xmldoc):
335 metadata = {}
337 keys = {'title': 'Title', 'episodeTitle': 'EpisodeTitle',
338 'description': 'Description', 'seriesId': 'SeriesId',
339 'episodeNumber': 'EpisodeNumber', 'tvRating': 'TvRating',
340 'displayMajorNumber': 'SourceChannel', 'callsign': 'SourceStation',
341 'showingBits': 'ShowingBits', 'mpaaRating': 'MpaaRating'}
343 details = xmldoc.getElementsByTagName('Details')[0]
345 for key in keys:
346 data = tag_data(details, keys[key])
347 if data:
348 if key == 'description':
349 data = data.replace(TRIBUNE_CR, '')
350 elif key == 'tvRating':
351 data = int(data)
352 elif key == 'displayMajorNumber':
353 if '-' in data:
354 data, metadata['displayMinorNumber'] = data.split('-')
355 metadata[key] = data
357 return metadata
359 def from_details(xml):
360 metadata = {}
362 xmldoc = minidom.parse(xml)
363 showing = xmldoc.getElementsByTagName('showing')[0]
364 program = showing.getElementsByTagName('program')[0]
366 items = {'description': 'program/description',
367 'title': 'program/title',
368 'episodeTitle': 'program/episodeTitle',
369 'episodeNumber': 'program/episodeNumber',
370 'seriesId': 'program/series/uniqueId',
371 'seriesTitle': 'program/series/seriesTitle',
372 'originalAirDate': 'program/originalAirDate',
373 'isEpisode': 'program/isEpisode',
374 'movieYear': 'program/movieYear',
375 'partCount': 'partCount',
376 'partIndex': 'partIndex',
377 'time': 'time'}
379 for item in items:
380 data = tag_data(showing, items[item])
381 if data:
382 if item == 'description':
383 data = data.replace(TRIBUNE_CR, '')
384 metadata[item] = data
386 vItems = ['vActor', 'vChoreographer', 'vDirector',
387 'vExecProducer', 'vProgramGenre', 'vGuestStar',
388 'vHost', 'vProducer', 'vWriter']
390 for item in vItems:
391 data = _vtag_data(program, item)
392 if data:
393 metadata[item] = data
395 sb = showing.getElementsByTagName('showingBits')
396 if sb:
397 metadata['showingBits'] = sb[0].attributes['value'].value
399 #for tag in ['starRating', 'mpaaRating', 'colorCode']:
400 for tag in ['starRating', 'mpaaRating']:
401 value = _tag_value(program, tag)
402 if value:
403 metadata[tag] = value
405 rating = _tag_value(showing, 'tvRating')
406 if rating:
407 metadata['tvRating'] = rating
409 return metadata
411 def _nfo_vitems(source, metadata):
413 vItems = {'vGenre': 'genre',
414 'vWriter': 'credits',
415 'vDirector': 'director',
416 'vActor': 'actor/name'}
418 for key in vItems:
419 data = _vtag_data_alternate(source, vItems[key])
420 if data:
421 metadata.setdefault(key, [])
422 for dat in data:
423 if not dat in metadata[key]:
424 metadata[key].append(dat)
426 if 'vGenre' in metadata:
427 metadata['vSeriesGenre'] = metadata['vProgramGenre'] = metadata['vGenre']
429 return metadata
431 def _parse_nfo(nfo_path, nfo_data=None):
432 # nfo files can contain XML or a URL to seed the XBMC metadata scrapers
433 # It's also possible to have both (a URL after the XML metadata)
434 # pyTivo only parses the XML metadata, but we'll try to stip the URL
435 # from mixed XML/URL files. Returns `None` when XML can't be parsed.
436 if nfo_data is None:
437 nfo_data = [line.strip() for line in file(nfo_path, 'rU')]
438 xmldoc = None
439 try:
440 xmldoc = minidom.parseString(os.linesep.join(nfo_data))
441 except expat.ExpatError, err:
442 import ipdb; ipdb.set_trace()
443 if expat.ErrorString(err.code) == expat.errors.XML_ERROR_INVALID_TOKEN:
444 # might be a URL outside the xml
445 while len(nfo_data) > err.lineno:
446 if len(nfo_data[-1]) == 0:
447 nfo_data.pop()
448 else:
449 break
450 if len(nfo_data) == err.lineno:
451 # last non-blank line contains the error
452 nfo_data.pop()
453 return _parse_nfo(nfo_path, nfo_data)
454 return xmldoc
456 def _from_tvshow_nfo(tvshow_nfo_path):
457 if tvshow_nfo_path in nfo_cache:
458 return nfo_cache[tvshow_nfo_path]
460 items = {'description': 'plot',
461 'title': 'title',
462 'seriesTitle': 'showtitle',
463 'starRating': 'rating',
464 'tvRating': 'mpaa'}
466 nfo_cache[tvshow_nfo_path] = metadata = {}
468 xmldoc = _parse_nfo(tvshow_nfo_path)
469 if not xmldoc:
470 return metadata
472 tvshow = xmldoc.getElementsByTagName('tvshow')
473 if tvshow:
474 tvshow = tvshow[0]
475 else:
476 return metadata
478 for item in items:
479 data = tag_data(tvshow, items[item])
480 if data:
481 metadata[item] = data
483 metadata = _nfo_vitems(tvshow, metadata)
485 nfo_cache[tvshow_nfo_path] = metadata
486 return metadata
488 def _from_episode_nfo(nfo_path, xmldoc):
489 metadata = {}
491 items = {'description': 'plot',
492 'episodeTitle': 'title',
493 'seriesTitle': 'showtitle',
494 'originalAirDate': 'aired',
495 'starRating': 'rating',
496 'tvRating': 'mpaa'}
498 # find tvshow.nfo
499 path = nfo_path
500 while True:
501 basepath = os.path.dirname(path)
502 if path == basepath:
503 break
504 path = basepath
505 tv_nfo = os.path.join(path, 'tvshow.nfo')
506 if os.path.exists(tv_nfo):
507 metadata.update(_from_tvshow_nfo(tv_nfo))
508 break
510 episode = xmldoc.getElementsByTagName('episodedetails')
511 if episode:
512 episode = episode[0]
513 else:
514 return metadata
516 metadata['isEpisode'] = 'true'
517 for item in items:
518 data = tag_data(episode, items[item])
519 if data:
520 metadata[item] = data
522 season = tag_data(episode, 'displayseason')
523 if not season or season == "-1":
524 season = tag_data(episode, 'season')
525 if not season:
526 season = 1
528 ep_num = tag_data(episode, 'displayepisode')
529 if not ep_num or ep_num == "-1":
530 ep_num = tag_data(episode, 'episode')
531 if ep_num and ep_num != "-1":
532 metadata['episodeNumber'] = "%d%02d" % (int(season), int(ep_num))
534 if 'originalAirDate' in metadata:
535 metadata['originalAirDate'] += 'T00:00:00Z'
537 metadata = _nfo_vitems(episode, metadata)
539 return metadata
541 def _from_movie_nfo(xmldoc):
542 metadata = {}
544 movie = xmldoc.getElementsByTagName('movie')
545 if movie:
546 movie = movie[0]
547 else:
548 return metadata
550 items = {'description': 'plot',
551 'title': 'title',
552 'movieYear': 'year',
553 'starRating': 'rating',
554 'mpaaRating': 'mpaa'}
556 metadata['isEpisode'] = 'false'
558 for item in items:
559 data = tag_data(movie, items[item])
560 if data:
561 metadata[item] = data
563 metadata['movieYear'] = "%04d" % int(metadata.get('movieYear', 0))
565 metadata = _nfo_vitems(movie, metadata)
566 return metadata
568 def from_nfo(full_path):
569 if full_path in nfo_cache:
570 return nfo_cache[full_path]
572 metadata = nfo_cache[full_path] = {}
574 nfo_path = "%s.nfo" % os.path.splitext(full_path)[0]
575 if not os.path.exists(nfo_path):
576 return metadata
578 xmldoc = _parse_nfo(nfo_path)
579 if not xmldoc:
580 return metadata
582 if xmldoc.getElementsByTagName('episodedetails'):
583 # it's an episode
584 metadata.update(_from_episode_nfo(nfo_path, xmldoc))
585 elif xmldoc.getElementsByTagName('movie'):
586 # it's a movie
587 metadata.update(_from_movie_nfo(xmldoc))
589 # common nfo cleanup
590 if 'starRating' in metadata:
591 # .NFO 0-10 -> TiVo 1-7
592 rating = int(float(metadata['starRating']) * 6 / 10 + 1.5)
593 metadata['starRating'] = rating
595 for key, mapping in [('mpaaRating', MPAA_RATINGS),
596 ('tvRating', TV_RATINGS)]:
597 if key in metadata:
598 rating = mapping.get(metadata[key], None)
599 if rating:
600 metadata[key] = str(rating)
601 else:
602 del metadata[key]
604 nfo_cache[full_path] = metadata
605 return metadata
607 def from_tivo(full_path):
608 if full_path in tivo_cache:
609 return tivo_cache[full_path]
611 tdcat_path = config.get_bin('tdcat')
612 tivo_mak = config.get_server('tivo_mak')
613 try:
614 assert(tdcat_path and tivo_mak)
615 fname = unicode(full_path, 'utf-8')
616 if mswindows:
617 fname = fname.encode('iso8859-1')
618 tcmd = [tdcat_path, '-m', tivo_mak, '-2', fname]
619 tdcat = subprocess.Popen(tcmd, stdout=subprocess.PIPE)
620 metadata = from_details(tdcat.stdout)
621 tivo_cache[full_path] = metadata
622 except:
623 metadata = {}
625 return metadata
627 def force_utf8(text):
628 if type(text) == str:
629 try:
630 text = text.decode('utf8')
631 except:
632 if sys.platform == 'darwin':
633 text = text.decode('macroman')
634 else:
635 text = text.decode('iso8859-1')
636 return text.encode('utf-8')
638 def dump(output, metadata):
639 for key in metadata:
640 value = metadata[key]
641 if type(value) == list:
642 for item in value:
643 output.write('%s: %s\n' % (key, item.encode('utf-8')))
644 else:
645 if key in HUMAN and value in HUMAN[key]:
646 output.write('%s: %s\n' % (key, HUMAN[key][value]))
647 else:
648 output.write('%s: %s\n' % (key, value.encode('utf-8')))
650 if __name__ == '__main__':
651 if len(sys.argv) > 1:
652 metadata = {}
653 fname = force_utf8(sys.argv[1])
654 ext = os.path.splitext(fname)[1].lower()
655 if ext == '.tivo':
656 config.init([])
657 metadata.update(from_tivo(fname))
658 elif ext in ['.mp4', '.m4v', '.mov']:
659 metadata.update(from_moov(fname))
660 elif ext in ['.dvr-ms', '.asf', '.wmv']:
661 metadata.update(from_dvrms(fname))
662 elif ext == '.wtv':
663 vInfo = plugins.video.transcode.video_info(fname)
664 metadata.update(from_mscore(vInfo['rawmeta']))
665 dump(sys.stdout, metadata)