7 from datetime
import datetime
8 from xml
.dom
import minidom
9 from xml
.parsers
import expat
16 from lrucache
import LRUCache
19 import plugins
.video
.transcode
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,
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',
41 'tvRating': {1: 'Y7', 2: 'Y', 3: 'G', 4: 'PG', 5: '14',
43 'starRating': {1: '1', 2: '1.5', 3: '2', 4: '2.5', 5: '3',
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")
56 return HUMAN
['mpaaRating'].get(rating
, 'NR')
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('/'):
67 for new_element
in element
.childNodes
:
68 if new_element
.nodeName
== name
:
74 if not element
.firstChild
:
76 return element
.firstChild
.data
78 def _vtag_data(element
, tag
):
79 for name
in tag
.split('/'):
80 new_element
= element
.getElementsByTagName(name
)
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
):
89 for name
in tag
.split('/'):
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
)
99 value
= item
[0].attributes
['value'].value
102 def from_moov(full_path
):
103 if full_path
in mp4_cache
:
104 return mp4_cache
[full_path
]
110 mp4meta
= mutagen
.File(unicode(full_path
, 'utf-8'))
113 mp4_cache
[full_path
] = {}
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:
125 metadata
['isEpisode'] = ['false', 'true'][value
== 'TV Show']
127 metadata
[keys
[key
]] = value
128 # These keys begin with the copyright symbol \xA9
129 elif key
== '\xa9day':
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'):
137 metadata
[k
].append(value
)
139 metadata
[k
] = [value
]
140 elif key
== '\xa9nam':
141 if 'tvsh' in mp4meta
:
142 metadata
['episodeTitle'] = value
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
)
169 metadata
[items
[item
]] = [x
['name'] for x
in data
[item
]]
171 mp4_cache
[full_path
] = metadata
174 def from_mscore(rawmeta
):
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']}
186 for tag
in keys
[tagname
]:
189 value
= rawmeta
[tag
][0]
190 if type(value
) not in (str, unicode):
193 metadata
[tagname
] = value
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(';')]
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']
218 def from_dvrms(full_path
):
219 if full_path
in dvrms_cache
:
220 return dvrms_cache
[full_path
]
223 rawmeta
= mutagen
.File(unicode(full_path
, 'utf-8'))
226 dvrms_cache
[full_path
] = {}
229 metadata
= from_mscore(rawmeta
)
230 dvrms_cache
[full_path
] = metadata
233 def from_eyetv(full_path
):
234 keys
= {'TITLE': 'title', 'SUBTITLE': 'episodeTitle',
235 'DESCRIPTION': 'description', 'YEAR': 'movieYear',
236 'EPISODENUM': 'episodeNumber'}
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']
246 metadata
[keys
[key
]] = info
[key
]
248 metadata
['seriesTitle'] = info
['TITLE']
250 metadata
['vActor'] = [x
.strip() for x
in info
['ACTORS'].split(',')]
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
267 def from_text(full_path
):
269 full_path
= unicode(full_path
, 'utf-8')
270 path
, name
= os
.path
.split(full_path
)
271 title
, ext
= os
.path
.splitext(name
)
276 parent
= os
.path
.dirname(ptmp
)
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
):
296 if line
.strip().startswith('#') or not sep
in line
:
298 key
, value
= [x
.strip() for x
in line
.split(sep
, 1)]
299 if not key
or not value
:
301 if key
.startswith('v'):
303 metadata
[key
].append(value
)
305 metadata
[key
] = [value
]
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()
314 metadata
[rating
] = ratings
[x
]
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
330 originalAirDate
= datetime
.utcfromtimestamp(mtime
)
332 metadata
= {'title': title
,
333 'originalAirDate': originalAirDate
.isoformat()}
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
))
346 def from_container(xmldoc
):
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]
359 data
= tag_data(details
, keys
[key
])
361 if key
== 'description':
362 data
= data
.replace(TRIBUNE_CR
, '')
363 elif key
== 'tvRating':
365 elif key
== 'displayMajorNumber':
367 data
, metadata
['displayMinorNumber'] = data
.split('-')
372 def from_details(xml
):
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',
394 data
= tag_data(showing
, items
[item
])
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']
405 data
= _vtag_data(program
, item
)
407 metadata
[item
] = data
409 sb
= showing
.getElementsByTagName('showingBits')
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
)
417 metadata
[tag
] = value
419 rating
= _tag_value(showing
, 'tvRating')
421 metadata
['tvRating'] = rating
425 def _nfo_vitems(source
, metadata
):
427 vItems
= {'vGenre': 'genre',
428 'vWriter': 'credits',
429 'vDirector': 'director',
430 'vActor': 'actor/name'}
433 data
= _vtag_data_alternate(source
, vItems
[key
])
435 metadata
.setdefault(key
, [])
437 if not dat
in metadata
[key
]:
438 metadata
[key
].append(dat
)
440 if 'vGenre' in metadata
:
441 metadata
['vSeriesGenre'] = metadata
['vProgramGenre'] = metadata
['vGenre']
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.
451 nfo_data
= [line
.strip() for line
in file(nfo_path
, 'rU')]
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:
463 if len(nfo_data
) == err
.lineno
:
464 # last non-blank line contains the error
466 return _parse_nfo(nfo_path
, nfo_data
)
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',
475 'seriesTitle': 'showtitle',
476 'starRating': 'rating',
479 nfo_cache
[tvshow_nfo_path
] = metadata
= {}
481 xmldoc
= _parse_nfo(tvshow_nfo_path
)
485 tvshow
= xmldoc
.getElementsByTagName('tvshow')
492 data
= tag_data(tvshow
, items
[item
])
494 metadata
[item
] = data
496 metadata
= _nfo_vitems(tvshow
, metadata
)
498 nfo_cache
[tvshow_nfo_path
] = metadata
501 def _from_episode_nfo(nfo_path
, xmldoc
):
504 items
= {'description': 'plot',
505 'episodeTitle': 'title',
506 'seriesTitle': 'showtitle',
507 'originalAirDate': 'aired',
508 'starRating': 'rating',
514 basepath
= os
.path
.dirname(path
)
518 tv_nfo
= os
.path
.join(path
, 'tvshow.nfo')
519 if os
.path
.exists(tv_nfo
):
520 metadata
.update(_from_tvshow_nfo(tv_nfo
))
523 episode
= xmldoc
.getElementsByTagName('episodedetails')
529 metadata
['isEpisode'] = 'true'
531 data
= tag_data(episode
, items
[item
])
533 metadata
[item
] = data
535 season
= tag_data(episode
, 'displayseason')
536 if not season
or season
== "-1":
537 season
= tag_data(episode
, 'season')
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
)
554 def _from_movie_nfo(xmldoc
):
557 movie
= xmldoc
.getElementsByTagName('movie')
563 items
= {'description': 'plot',
566 'starRating': 'rating',
567 'mpaaRating': 'mpaa'}
569 metadata
['isEpisode'] = 'false'
572 data
= tag_data(movie
, items
[item
])
574 metadata
[item
] = data
576 metadata
['movieYear'] = "%04d" % int(metadata
.get('movieYear', 0))
578 metadata
= _nfo_vitems(movie
, 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
):
591 xmldoc
= _parse_nfo(nfo_path
)
595 if xmldoc
.getElementsByTagName('episodedetails'):
597 metadata
.update(_from_episode_nfo(nfo_path
, xmldoc
))
598 elif xmldoc
.getElementsByTagName('movie'):
600 metadata
.update(_from_movie_nfo(xmldoc
))
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
)]:
611 rating
= mapping
.get(metadata
[key
], None)
613 metadata
[key
] = str(rating
)
617 nfo_cache
[full_path
] = 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')
627 assert(tdcat_path
and tivo_mak
)
628 fname
= unicode(full_path
, 'utf-8')
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
640 def force_utf8(text
):
641 if type(text
) == str:
643 text
= text
.decode('utf8')
645 if sys
.platform
== 'darwin':
646 text
= text
.decode('macroman')
648 text
= text
.decode('iso8859-1')
649 return text
.encode('utf-8')
651 def dump(output
, metadata
):
653 value
= metadata
[key
]
654 if type(value
) == list:
656 output
.write('%s: %s\n' % (key
, item
.encode('utf-8')))
658 if key
in HUMAN
and value
in HUMAN
[key
]:
659 output
.write('%s: %s\n' % (key
, HUMAN
[key
][value
]))
661 output
.write('%s: %s\n' % (key
, value
.encode('utf-8')))
663 if __name__
== '__main__':
664 if len(sys
.argv
) > 1:
667 logging
.basicConfig()
668 fname
= force_utf8(sys
.argv
[1])
669 ext
= os
.path
.splitext(fname
)[1].lower()
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
))
677 vInfo
= plugins
.video
.transcode
.video_info(fname
)
678 metadata
.update(from_mscore(vInfo
['rawmeta']))
679 dump(sys
.stdout
, metadata
)