9 from datetime
import datetime
10 from xml
.dom
import minidom
11 from xml
.parsers
import expat
18 from lrucache
import LRUCache
21 import plugins
.video
.transcode
25 TRIBUNE_CR
= ' Copyright Tribune Media Services, Inc.'
27 TV_RATINGS
= {'TV-Y7': 1, 'TV-Y': 2, 'TV-G': 3, 'TV-PG': 4, 'TV-14': 5,
28 'TV-MA': 6, 'TV-NR': 7, 'TVY7': 1, 'TVY': 2, 'TVG': 3,
29 'TVPG': 4, 'TV14': 5, 'TVMA': 6, 'TVNR': 7, 'Y7': 1,
30 'Y': 2, 'G': 3, 'PG': 4, '14': 5, 'MA': 6, 'NR': 7,
31 'UNRATED': 7, 'X1': 1, 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5,
34 MPAA_RATINGS
= {'G': 1, 'PG': 2, 'PG-13': 3, 'PG13': 3, 'R': 4, 'X': 5,
35 'NC-17': 6, 'NC17': 6, 'NR': 8, 'UNRATED': 8, 'G1': 1,
36 'P2': 2, 'P3': 3, 'R4': 4, 'X5': 5, 'N6': 6, 'N8': 8}
38 STAR_RATINGS
= {'1': 1, '1.5': 2, '2': 3, '2.5': 4, '3': 5, '3.5': 6,
39 '4': 7, '*': 1, '**': 3, '***': 5, '****': 7, 'X1': 1,
40 'X2': 2, 'X3': 3, 'X4': 4, 'X5': 5, 'X6': 6, 'X7': 7}
42 HUMAN
= {'mpaaRating': {1: 'G', 2: 'PG', 3: 'PG-13', 4: 'R', 5: 'X',
44 'tvRating': {1: 'Y7', 2: 'Y', 3: 'G', 4: 'PG', 5: '14',
46 'starRating': {1: '1', 2: '1.5', 3: '2', 4: '2.5', 5: '3',
55 tivo_cache
= LRUCache(50)
56 mp4_cache
= LRUCache(50)
57 dvrms_cache
= LRUCache(50)
58 nfo_cache
= LRUCache(50)
60 mswindows
= (sys
.platform
== "win32")
63 return HUMAN
['mpaaRating'].get(rating
, 'NR')
66 return HUMAN
['tvRating'].get(rating
, 'NR')
68 def get_stars(rating
):
69 return HUMAN
['starRating'].get(rating
, '')
74 tsize
= '%.2f GB' % (raw
/ GB
)
76 tsize
= '%.2f MB' % (raw
/ MB
)
78 tsize
= '%.2f KB' % (raw
/ KB
)
80 tsize
= '%d Bytes' % raw
83 def tag_data(element
, tag
):
84 for name
in tag
.split('/'):
86 for new_element
in element
.childNodes
:
87 if new_element
.nodeName
== name
:
93 if not element
.firstChild
:
95 return element
.firstChild
.data
97 def _vtag_data(element
, tag
):
98 for name
in tag
.split('/'):
99 new_element
= element
.getElementsByTagName(name
)
102 element
= new_element
[0]
103 elements
= element
.getElementsByTagName('element')
104 return [x
.firstChild
.data
for x
in elements
if x
.firstChild
]
106 def _vtag_data_alternate(element
, tag
):
108 for name
in tag
.split('/'):
110 for elmt
in elements
:
111 new_elements
+= elmt
.getElementsByTagName(name
)
112 elements
= new_elements
113 return [x
.firstChild
.data
for x
in elements
if x
.firstChild
]
115 def _tag_value(element
, tag
):
116 item
= element
.getElementsByTagName(tag
)
118 value
= item
[0].attributes
['value'].value
121 def from_moov(full_path
):
122 if full_path
in mp4_cache
:
123 return mp4_cache
[full_path
]
129 mp4meta
= mutagen
.File(unicode(full_path
, 'utf-8'))
132 mp4_cache
[full_path
] = {}
135 # The following 1-to-1 correspondence of atoms to pyTivo
136 # variables is TV-biased
137 keys
= {'tvnn': 'callsign', 'tven': 'episodeNumber',
138 'tvsh': 'seriesTitle'}
140 for key
, value
in mp4meta
.items():
141 if type(value
) == list:
144 metadata
['isEpisode'] = ['false', 'true'][value
== 'TV Show']
146 metadata
[keys
[key
]] = value
147 # These keys begin with the copyright symbol \xA9
148 elif key
== '\xa9day':
150 value
+= '-01-01T16:00:00Z'
151 metadata
['originalAirDate'] = value
152 #metadata['time'] = value
153 elif key
in ['\xa9gen', 'gnre']:
154 for k
in ('vProgramGenre', 'vSeriesGenre'):
156 metadata
[k
].append(value
)
158 metadata
[k
] = [value
]
159 elif key
== '\xa9nam':
160 if 'tvsh' in mp4meta
:
161 metadata
['episodeTitle'] = value
163 metadata
['title'] = value
165 # Description in desc, cmt, and/or ldes tags. Keep the longest.
166 elif key
in ['desc', '\xa9cmt', 'ldes'] and len(value
) > len_desc
:
167 metadata
['description'] = value
168 len_desc
= len(value
)
170 # A common custom "reverse DNS format" tag
171 elif (key
== '----:com.apple.iTunes:iTunEXTC' and
172 ('us-tv' in value
or 'mpaa' in value
)):
173 rating
= value
.split("|")[1].upper()
174 if rating
in TV_RATINGS
and 'us-tv' in value
:
175 metadata
['tvRating'] = TV_RATINGS
[rating
]
176 elif rating
in MPAA_RATINGS
and 'mpaa' in value
:
177 metadata
['mpaaRating'] = MPAA_RATINGS
[rating
]
179 # Actors, directors, producers, AND screenwriters may be in a long
180 # embedded XML plist.
181 elif (key
== '----:com.apple.iTunes:iTunMOVI' and
182 'plistlib' in sys
.modules
):
183 items
= {'cast': 'vActor', 'directors': 'vDirector',
184 'producers': 'vProducer', 'screenwriters': 'vWriter'}
186 data
= plistlib
.readPlistFromString(value
)
192 metadata
[items
[item
]] = [x
['name'] for x
in data
[item
]]
194 mp4_cache
[full_path
] = metadata
197 def from_mscore(rawmeta
):
199 keys
= {'title': ['Title'],
200 'description': ['Description', 'WM/SubTitleDescription'],
201 'episodeTitle': ['WM/SubTitle'],
202 'callsign': ['WM/MediaStationCallSign'],
203 'displayMajorNumber': ['WM/MediaOriginalChannel'],
204 'originalAirDate': ['WM/MediaOriginalBroadcastDateTime'],
205 'rating': ['WM/ParentalRating'],
206 'credits': ['WM/MediaCredits'], 'genre': ['WM/Genre']}
209 for tag
in keys
[tagname
]:
212 value
= rawmeta
[tag
][0]
213 if type(value
) not in (str, unicode):
216 metadata
[tagname
] = value
220 if 'episodeTitle' in metadata
and 'title' in metadata
:
221 metadata
['seriesTitle'] = metadata
['title']
222 if 'genre' in metadata
:
223 value
= metadata
['genre'].split(',')
224 metadata
['vProgramGenre'] = value
225 metadata
['vSeriesGenre'] = value
226 del metadata
['genre']
227 if 'credits' in metadata
:
228 value
= [x
.split('/') for x
in metadata
['credits'].split(';')]
230 metadata
['vActor'] = [x
for x
in (value
[0] + value
[3]) if x
]
231 metadata
['vDirector'] = [x
for x
in value
[1] if x
]
232 del metadata
['credits']
233 if 'rating' in metadata
:
234 rating
= metadata
['rating']
235 if rating
in TV_RATINGS
:
236 metadata
['tvRating'] = TV_RATINGS
[rating
]
237 del metadata
['rating']
241 def from_dvrms(full_path
):
242 if full_path
in dvrms_cache
:
243 return dvrms_cache
[full_path
]
246 rawmeta
= mutagen
.File(unicode(full_path
, 'utf-8'))
249 dvrms_cache
[full_path
] = {}
252 metadata
= from_mscore(rawmeta
)
253 dvrms_cache
[full_path
] = metadata
256 def from_eyetv(full_path
):
257 keys
= {'TITLE': 'title', 'SUBTITLE': 'episodeTitle',
258 'DESCRIPTION': 'description', 'YEAR': 'movieYear',
259 'EPISODENUM': 'episodeNumber'}
261 path
= os
.path
.dirname(unicode(full_path
, 'utf-8'))
262 eyetvp
= [x
for x
in os
.listdir(path
) if x
.endswith('.eyetvp')][0]
263 eyetvp
= os
.path
.join(path
, eyetvp
)
265 eyetv
= plistlib
.readPlist(eyetvp
)
268 if 'epg info' in eyetv
:
269 info
= eyetv
['epg info']
272 metadata
[keys
[key
]] = info
[key
]
274 metadata
['seriesTitle'] = info
['TITLE']
276 metadata
['vActor'] = [x
.strip() for x
in info
['ACTORS'].split(',')]
278 metadata
['vDirector'] = [info
['DIRECTOR']]
280 for ptag
, etag
, ratings
in [('tvRating', 'TV_RATING', TV_RATINGS
),
281 ('mpaaRating', 'MPAA_RATING', MPAA_RATINGS
),
282 ('starRating', 'STAR_RATING', STAR_RATINGS
)]:
283 x
= info
[etag
].upper()
284 if x
and x
in ratings
:
285 metadata
[ptag
] = ratings
[x
]
287 # movieYear must be set for the mpaa/star ratings to work
288 if (('mpaaRating' in metadata
or 'starRating' in metadata
) and
289 'movieYear' not in metadata
):
290 metadata
['movieYear'] = eyetv
['info']['start'].year
293 def from_text(full_path
):
295 full_path
= unicode(full_path
, 'utf-8')
296 path
, name
= os
.path
.split(full_path
)
297 title
, ext
= os
.path
.splitext(name
)
302 parent
= os
.path
.dirname(ptmp
)
307 search_paths
.append(os
.path
.join(ptmp
, 'default.txt'))
309 search_paths
.append(os
.path
.join(path
, title
) + '.properties')
310 search_paths
.reverse()
312 search_paths
+= [full_path
+ '.txt',
313 os
.path
.join(path
, '.meta', 'default.txt'),
314 os
.path
.join(path
, '.meta', name
) + '.txt']
316 for metafile
in search_paths
:
317 if os
.path
.exists(metafile
):
318 sep
= ':='[metafile
.endswith('.properties')]
319 for line
in file(metafile
, 'U'):
320 if line
.startswith(BOM
):
322 if line
.strip().startswith('#') or not sep
in line
:
324 key
, value
= [x
.strip() for x
in line
.split(sep
, 1)]
325 if not key
or not value
:
327 if key
.startswith('v'):
329 metadata
[key
].append(value
)
331 metadata
[key
] = [value
]
333 metadata
[key
] = value
335 for rating
, ratings
in [('tvRating', TV_RATINGS
),
336 ('mpaaRating', MPAA_RATINGS
),
337 ('starRating', STAR_RATINGS
)]:
338 x
= metadata
.get(rating
, '').upper()
340 metadata
[rating
] = ratings
[x
]
350 def basic(full_path
):
351 base_path
, name
= os
.path
.split(full_path
)
352 title
, ext
= os
.path
.splitext(name
)
353 mtime
= os
.stat(unicode(full_path
, 'utf-8')).st_mtime
356 originalAirDate
= datetime
.utcfromtimestamp(mtime
)
358 metadata
= {'title': title
,
359 'originalAirDate': originalAirDate
.isoformat()}
361 if ext
in ['.mp4', '.m4v', '.mov']:
362 metadata
.update(from_moov(full_path
))
363 elif ext
in ['.dvr-ms', '.asf', '.wmv']:
364 metadata
.update(from_dvrms(full_path
))
365 elif 'plistlib' in sys
.modules
and base_path
.endswith('.eyetv'):
366 metadata
.update(from_eyetv(full_path
))
367 metadata
.update(from_nfo(full_path
))
368 metadata
.update(from_text(full_path
))
372 def from_container(xmldoc
):
375 keys
= {'title': 'Title', 'episodeTitle': 'EpisodeTitle',
376 'description': 'Description', 'programId': 'ProgramId',
377 'seriesId': 'SeriesId', 'episodeNumber': 'EpisodeNumber',
378 'tvRating': 'TvRating', 'displayMajorNumber': 'SourceChannel',
379 'callsign': 'SourceStation', 'showingBits': 'ShowingBits',
380 'mpaaRating': 'MpaaRating'}
382 details
= xmldoc
.getElementsByTagName('Details')[0]
385 data
= tag_data(details
, keys
[key
])
387 if key
== 'description':
388 data
= data
.replace(TRIBUNE_CR
, '')
389 elif key
== 'tvRating':
391 elif key
== 'displayMajorNumber':
393 data
, metadata
['displayMinorNumber'] = data
.split('-')
398 def from_details(xml
):
401 xmldoc
= minidom
.parseString(xml
)
402 showing
= xmldoc
.getElementsByTagName('showing')[0]
403 program
= showing
.getElementsByTagName('program')[0]
405 items
= {'description': 'program/description',
406 'title': 'program/title',
407 'episodeTitle': 'program/episodeTitle',
408 'episodeNumber': 'program/episodeNumber',
409 'programId': 'program/uniqueId',
410 'seriesId': 'program/series/uniqueId',
411 'seriesTitle': 'program/series/seriesTitle',
412 'originalAirDate': 'program/originalAirDate',
413 'isEpisode': 'program/isEpisode',
414 'movieYear': 'program/movieYear',
415 'partCount': 'partCount',
416 'partIndex': 'partIndex',
420 data
= tag_data(showing
, items
[item
])
422 if item
== 'description':
423 data
= data
.replace(TRIBUNE_CR
, '')
424 metadata
[item
] = data
426 vItems
= ['vActor', 'vChoreographer', 'vDirector',
427 'vExecProducer', 'vProgramGenre', 'vGuestStar',
428 'vHost', 'vProducer', 'vWriter']
431 data
= _vtag_data(program
, item
)
433 metadata
[item
] = data
435 sb
= showing
.getElementsByTagName('showingBits')
437 metadata
['showingBits'] = sb
[0].attributes
['value'].value
439 #for tag in ['starRating', 'mpaaRating', 'colorCode']:
440 for tag
in ['starRating', 'mpaaRating']:
441 value
= _tag_value(program
, tag
)
443 metadata
[tag
] = value
445 rating
= _tag_value(showing
, 'tvRating')
447 metadata
['tvRating'] = rating
451 def _nfo_vitems(source
, metadata
):
453 vItems
= {'vGenre': 'genre',
454 'vWriter': 'credits',
455 'vDirector': 'director',
456 'vActor': 'actor/name'}
459 data
= _vtag_data_alternate(source
, vItems
[key
])
461 metadata
.setdefault(key
, [])
463 if not dat
in metadata
[key
]:
464 metadata
[key
].append(dat
)
466 if 'vGenre' in metadata
:
467 metadata
['vSeriesGenre'] = metadata
['vProgramGenre'] = metadata
['vGenre']
471 def _parse_nfo(nfo_path
, nfo_data
=None):
472 # nfo files can contain XML or a URL to seed the XBMC metadata scrapers
473 # It's also possible to have both (a URL after the XML metadata)
474 # pyTivo only parses the XML metadata, but we'll try to stip the URL
475 # from mixed XML/URL files. Returns `None` when XML can't be parsed.
477 nfo_data
= [line
.strip() for line
in file(nfo_path
, 'rU')]
480 xmldoc
= minidom
.parseString(os
.linesep
.join(nfo_data
))
481 except expat
.ExpatError
, err
:
482 if expat
.ErrorString(err
.code
) == expat
.errors
.XML_ERROR_INVALID_TOKEN
:
483 # might be a URL outside the xml
484 while len(nfo_data
) > err
.lineno
:
485 if len(nfo_data
[-1]) == 0:
489 if len(nfo_data
) == err
.lineno
:
490 # last non-blank line contains the error
492 return _parse_nfo(nfo_path
, nfo_data
)
495 def _from_tvshow_nfo(tvshow_nfo_path
):
496 if tvshow_nfo_path
in nfo_cache
:
497 return nfo_cache
[tvshow_nfo_path
]
499 items
= {'description': 'plot',
501 'seriesTitle': 'showtitle',
502 'starRating': 'rating',
505 nfo_cache
[tvshow_nfo_path
] = metadata
= {}
507 xmldoc
= _parse_nfo(tvshow_nfo_path
)
511 tvshow
= xmldoc
.getElementsByTagName('tvshow')
518 data
= tag_data(tvshow
, items
[item
])
520 metadata
[item
] = data
522 metadata
= _nfo_vitems(tvshow
, metadata
)
524 nfo_cache
[tvshow_nfo_path
] = metadata
527 def _from_episode_nfo(nfo_path
, xmldoc
):
530 items
= {'description': 'plot',
531 'episodeTitle': 'title',
532 'seriesTitle': 'showtitle',
533 'originalAirDate': 'aired',
534 'starRating': 'rating',
540 basepath
= os
.path
.dirname(path
)
544 tv_nfo
= os
.path
.join(path
, 'tvshow.nfo')
545 if os
.path
.exists(tv_nfo
):
546 metadata
.update(_from_tvshow_nfo(tv_nfo
))
549 episode
= xmldoc
.getElementsByTagName('episodedetails')
555 metadata
['isEpisode'] = 'true'
557 data
= tag_data(episode
, items
[item
])
559 metadata
[item
] = data
561 season
= tag_data(episode
, 'displayseason')
562 if not season
or season
== "-1":
563 season
= tag_data(episode
, 'season')
567 ep_num
= tag_data(episode
, 'displayepisode')
568 if not ep_num
or ep_num
== "-1":
569 ep_num
= tag_data(episode
, 'episode')
570 if ep_num
and ep_num
!= "-1":
571 metadata
['episodeNumber'] = "%d%02d" % (int(season
), int(ep_num
))
573 if 'originalAirDate' in metadata
:
574 metadata
['originalAirDate'] += 'T00:00:00Z'
576 metadata
= _nfo_vitems(episode
, metadata
)
580 def _from_movie_nfo(xmldoc
):
583 movie
= xmldoc
.getElementsByTagName('movie')
589 items
= {'description': 'plot',
592 'starRating': 'rating',
593 'mpaaRating': 'mpaa'}
595 metadata
['isEpisode'] = 'false'
598 data
= tag_data(movie
, items
[item
])
600 metadata
[item
] = data
602 metadata
['movieYear'] = "%04d" % int(metadata
.get('movieYear', 0))
604 metadata
= _nfo_vitems(movie
, metadata
)
607 def from_nfo(full_path
):
608 if full_path
in nfo_cache
:
609 return nfo_cache
[full_path
]
611 metadata
= nfo_cache
[full_path
] = {}
613 nfo_path
= "%s.nfo" % os
.path
.splitext(full_path
)[0]
614 if not os
.path
.exists(nfo_path
):
617 xmldoc
= _parse_nfo(nfo_path
)
621 if xmldoc
.getElementsByTagName('episodedetails'):
623 metadata
.update(_from_episode_nfo(nfo_path
, xmldoc
))
624 elif xmldoc
.getElementsByTagName('movie'):
626 metadata
.update(_from_movie_nfo(xmldoc
))
629 if 'starRating' in metadata
:
630 # .NFO 0-10 -> TiVo 1-7
631 rating
= int(float(metadata
['starRating']) * 6 / 10 + 1.5)
632 metadata
['starRating'] = rating
634 for key
, mapping
in [('mpaaRating', MPAA_RATINGS
),
635 ('tvRating', TV_RATINGS
)]:
637 rating
= mapping
.get(metadata
[key
], None)
639 metadata
[key
] = str(rating
)
643 nfo_cache
[full_path
] = metadata
646 def _tdcat_bin(tdcat_path
, full_path
, tivo_mak
):
647 fname
= unicode(full_path
, 'utf-8')
649 fname
= fname
.encode('iso8859-1')
650 tcmd
= [tdcat_path
, '-m', tivo_mak
, '-2', fname
]
651 tdcat
= subprocess
.Popen(tcmd
, stdout
=subprocess
.PIPE
)
652 return tdcat
.stdout
.read()
654 def _tdcat_py(full_path
, tivo_mak
):
657 tfile
= open(full_path
, 'rb')
658 header
= tfile
.read(16)
659 offset
, chunks
= struct
.unpack('>LH', header
[10:])
660 rawdata
= tfile
.read(offset
- 16)
664 for i
in xrange(chunks
):
665 chunk_size
, data_size
, id, enc
= struct
.unpack('>LLHH',
666 rawdata
[count
:count
+ 12])
668 data
= rawdata
[count
:count
+ data_size
]
669 xml_data
[id] = {'enc': enc
, 'data': data
, 'start': count
+ 16}
670 count
+= chunk_size
- 12
673 details
= chunk
['data']
675 xml_key
= xml_data
[3]['data']
677 hexmak
= hashlib
.md5('tivo:TiVo DVR:' + tivo_mak
).hexdigest()
678 key
= hashlib
.sha1(hexmak
+ xml_key
).digest()[:16] + '\0\0\0\0'
680 turkey
= hashlib
.sha1(key
[:17]).digest()
681 turiv
= hashlib
.sha1(key
).digest()
683 details
= turing
.Turing(turkey
, turiv
).crypt(details
, chunk
['start'])
687 def from_tivo(full_path
):
688 if full_path
in tivo_cache
:
689 return tivo_cache
[full_path
]
691 tdcat_path
= config
.get_bin('tdcat')
692 tivo_mak
= config
.get_server('tivo_mak')
696 details
= _tdcat_bin(tdcat_path
, full_path
, tivo_mak
)
698 details
= _tdcat_py(full_path
, tivo_mak
)
699 metadata
= from_details(details
)
700 tivo_cache
[full_path
] = metadata
707 def force_utf8(text
):
708 if type(text
) == str:
710 text
= text
.decode('utf8')
712 if sys
.platform
== 'darwin':
713 text
= text
.decode('macroman')
715 text
= text
.decode('iso8859-1')
716 return text
.encode('utf-8')
718 def dump(output
, metadata
):
720 value
= metadata
[key
]
721 if type(value
) == list:
723 output
.write('%s: %s\n' % (key
, item
.encode('utf-8')))
725 if key
in HUMAN
and value
in HUMAN
[key
]:
726 output
.write('%s: %s\n' % (key
, HUMAN
[key
][value
]))
728 output
.write('%s: %s\n' % (key
, value
.encode('utf-8')))
730 if __name__
== '__main__':
731 if len(sys
.argv
) > 1:
734 logging
.basicConfig()
735 fname
= force_utf8(sys
.argv
[1])
736 ext
= os
.path
.splitext(fname
)[1].lower()
738 metadata
.update(from_tivo(fname
))
739 elif ext
in ['.mp4', '.m4v', '.mov']:
740 metadata
.update(from_moov(fname
))
741 elif ext
in ['.dvr-ms', '.asf', '.wmv']:
742 metadata
.update(from_dvrms(fname
))
744 vInfo
= plugins
.video
.transcode
.video_info(fname
)
745 metadata
.update(from_mscore(vInfo
['rawmeta']))
746 dump(sys
.stdout
, metadata
)