6 from datetime
import datetime
7 from xml
.dom
import minidom
8 from xml
.parsers
import expat
15 from lrucache
import LRUCache
18 import plugins
.video
.transcode
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,
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',
39 'tvRating': {1: 'Y7', 2: 'Y', 3: 'G', 4: 'PG', 5: '14',
41 'starRating': {1: '1', 2: '1.5', 3: '2', 4: '2.5', 5: '3',
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")
54 return HUMAN
['mpaaRating'].get(rating
, 'NR')
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
)
67 element
= new_element
[0]
68 if not element
.firstChild
:
70 return element
.firstChild
.data
72 def _vtag_data(element
, tag
):
73 for name
in tag
.split('/'):
74 new_element
= element
.getElementsByTagName(name
)
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
):
83 for name
in tag
.split('/'):
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
)
93 value
= item
[0].attributes
['value'].value
96 def from_moov(full_path
):
97 if full_path
in mp4_cache
:
98 return mp4_cache
[full_path
]
104 mp4meta
= mutagen
.File(unicode(full_path
, 'utf-8'))
107 mp4_cache
[full_path
] = {}
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:
119 metadata
['isEpisode'] = ['false', 'true'][value
== 'TV Show']
121 metadata
[keys
[key
]] = value
122 # These keys begin with the copyright symbol \xA9
123 elif key
== '\xa9day':
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'):
131 metadata
[k
].append(value
)
133 metadata
[k
] = [value
]
134 elif key
== '\xa9nam':
135 if 'tvsh' in mp4meta
:
136 metadata
['episodeTitle'] = value
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
)
163 metadata
[items
[item
]] = [x
['name'] for x
in data
[item
]]
165 mp4_cache
[full_path
] = metadata
168 def from_mscore(rawmeta
):
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']}
180 for tag
in keys
[tagname
]:
183 value
= rawmeta
[tag
][0]
184 if type(value
) not in (str, unicode):
187 metadata
[tagname
] = value
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(';')]
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']
212 def from_dvrms(full_path
):
213 if full_path
in dvrms_cache
:
214 return dvrms_cache
[full_path
]
217 rawmeta
= mutagen
.File(unicode(full_path
, 'utf-8'))
220 dvrms_cache
[full_path
] = {}
223 metadata
= from_mscore(rawmeta
)
224 dvrms_cache
[full_path
] = metadata
227 def from_eyetv(full_path
):
228 keys
= {'TITLE': 'title', 'SUBTITLE': 'episodeTitle',
229 'DESCRIPTION': 'description', 'YEAR': 'movieYear',
230 'EPISODENUM': 'episodeNumber'}
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']
240 metadata
[keys
[key
]] = info
[key
]
242 metadata
['seriesTitle'] = info
['TITLE']
244 metadata
['vActor'] = [x
.strip() for x
in info
['ACTORS'].split(',')]
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
261 def from_text(full_path
):
263 full_path
= unicode(full_path
, 'utf-8')
264 path
, name
= os
.path
.split(full_path
)
265 title
, ext
= os
.path
.splitext(name
)
270 parent
= os
.path
.dirname(ptmp
)
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
):
290 if line
.strip().startswith('#') or not sep
in line
:
292 key
, value
= [x
.strip() for x
in line
.split(sep
, 1)]
293 if not key
or not value
:
295 if key
.startswith('v'):
297 metadata
[key
].append(value
)
299 metadata
[key
] = [value
]
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()
308 metadata
[rating
] = ratings
[x
]
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
318 originalAirDate
= datetime
.utcfromtimestamp(mtime
)
320 metadata
= {'title': title
,
321 'originalAirDate': originalAirDate
.isoformat()}
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
))
334 def from_container(xmldoc
):
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]
346 data
= tag_data(details
, keys
[key
])
348 if key
== 'description':
349 data
= data
.replace(TRIBUNE_CR
, '')
350 elif key
== 'tvRating':
352 elif key
== 'displayMajorNumber':
354 data
, metadata
['displayMinorNumber'] = data
.split('-')
359 def from_details(xml
):
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',
380 data
= tag_data(showing
, items
[item
])
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']
391 data
= _vtag_data(program
, item
)
393 metadata
[item
] = data
395 sb
= showing
.getElementsByTagName('showingBits')
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
)
403 metadata
[tag
] = value
405 rating
= _tag_value(showing
, 'tvRating')
407 metadata
['tvRating'] = rating
411 def _nfo_vitems(source
, metadata
):
413 vItems
= {'vGenre': 'genre',
414 'vWriter': 'credits',
415 'vDirector': 'director',
416 'vActor': 'actor/name'}
419 data
= _vtag_data_alternate(source
, vItems
[key
])
421 metadata
.setdefault(key
, [])
423 if not dat
in metadata
[key
]:
424 metadata
[key
].append(dat
)
426 if 'vGenre' in metadata
:
427 metadata
['vSeriesGenre'] = metadata
['vProgramGenre'] = metadata
['vGenre']
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.
437 nfo_data
= [line
.strip() for line
in file(nfo_path
, 'rU')]
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:
450 if len(nfo_data
) == err
.lineno
:
451 # last non-blank line contains the error
453 return _parse_nfo(nfo_path
, nfo_data
)
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',
462 'seriesTitle': 'showtitle',
463 'starRating': 'rating',
466 nfo_cache
[tvshow_nfo_path
] = metadata
= {}
468 xmldoc
= _parse_nfo(tvshow_nfo_path
)
472 tvshow
= xmldoc
.getElementsByTagName('tvshow')
479 data
= tag_data(tvshow
, items
[item
])
481 metadata
[item
] = data
483 metadata
= _nfo_vitems(tvshow
, metadata
)
485 nfo_cache
[tvshow_nfo_path
] = metadata
488 def _from_episode_nfo(nfo_path
, xmldoc
):
491 items
= {'description': 'plot',
492 'episodeTitle': 'title',
493 'seriesTitle': 'showtitle',
494 'originalAirDate': 'aired',
495 'starRating': 'rating',
501 basepath
= os
.path
.dirname(path
)
505 tv_nfo
= os
.path
.join(path
, 'tvshow.nfo')
506 if os
.path
.exists(tv_nfo
):
507 metadata
.update(_from_tvshow_nfo(tv_nfo
))
510 episode
= xmldoc
.getElementsByTagName('episodedetails')
516 metadata
['isEpisode'] = 'true'
518 data
= tag_data(episode
, items
[item
])
520 metadata
[item
] = data
522 season
= tag_data(episode
, 'displayseason')
523 if not season
or season
== "-1":
524 season
= tag_data(episode
, 'season')
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
)
541 def _from_movie_nfo(xmldoc
):
544 movie
= xmldoc
.getElementsByTagName('movie')
550 items
= {'description': 'plot',
553 'starRating': 'rating',
554 'mpaaRating': 'mpaa'}
556 metadata
['isEpisode'] = 'false'
559 data
= tag_data(movie
, items
[item
])
561 metadata
[item
] = data
563 metadata
['movieYear'] = "%04d" % int(metadata
.get('movieYear', 0))
565 metadata
= _nfo_vitems(movie
, 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
):
578 xmldoc
= _parse_nfo(nfo_path
)
582 if xmldoc
.getElementsByTagName('episodedetails'):
584 metadata
.update(_from_episode_nfo(nfo_path
, xmldoc
))
585 elif xmldoc
.getElementsByTagName('movie'):
587 metadata
.update(_from_movie_nfo(xmldoc
))
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
)]:
598 rating
= mapping
.get(metadata
[key
], None)
600 metadata
[key
] = str(rating
)
604 nfo_cache
[full_path
] = 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')
614 assert(tdcat_path
and tivo_mak
)
615 fname
= unicode(full_path
, 'utf-8')
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
627 def force_utf8(text
):
628 if type(text
) == str:
630 text
= text
.decode('utf8')
632 if sys
.platform
== 'darwin':
633 text
= text
.decode('macroman')
635 text
= text
.decode('iso8859-1')
636 return text
.encode('utf-8')
638 def dump(output
, metadata
):
640 value
= metadata
[key
]
641 if type(value
) == list:
643 output
.write('%s: %s\n' % (key
, item
.encode('utf-8')))
645 if key
in HUMAN
and value
in HUMAN
[key
]:
646 output
.write('%s: %s\n' % (key
, HUMAN
[key
][value
]))
648 output
.write('%s: %s\n' % (key
, value
.encode('utf-8')))
650 if __name__
== '__main__':
651 if len(sys
.argv
) > 1:
653 fname
= force_utf8(sys
.argv
[1])
654 ext
= os
.path
.splitext(fname
)[1].lower()
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
))
663 vInfo
= plugins
.video
.transcode
.video_info(fname
)
664 metadata
.update(from_mscore(vInfo
['rawmeta']))
665 dump(sys
.stdout
, metadata
)