updated XBMC NFO support, added movies, ratings, stars
[pyTivo/wmcbrine/lucasnz.git] / mind.py
blob5a0784be381aad60d9e4af0d4e83ee78fc3dac45
1 import cookielib
2 import logging
3 import sys
4 import time
5 import urllib2
6 import urllib
7 import warnings
9 import config
10 import metadata
12 try:
13 import xml.etree.ElementTree as ElementTree
14 except ImportError:
15 try:
16 import elementtree.ElementTree as ElementTree
17 except ImportError:
18 warnings.warn('Python 2.5 or higher or elementtree is ' +
19 'needed to use the TivoPush')
21 if 'ElementTree' not in locals():
23 class Mind:
24 def __init__(self, *arg, **karg):
25 raise Exception('Python 2.5 or higher or elementtree is ' +
26 'needed to use the TivoPush')
28 else:
30 class Mind:
31 def __init__(self, username, password, tsn):
32 self.__logger = logging.getLogger('pyTivo.mind')
33 self.__username = username
34 self.__password = password
35 self.__mind = config.get_mind(tsn)
37 cj = cookielib.CookieJar()
38 cp = urllib2.HTTPCookieProcessor(cj)
39 self.__opener = urllib2.build_opener(cp)
41 self.__login()
43 def pushVideo(self, tsn, url, description, duration, size,
44 title, subtitle, source='', mime='video/mpeg',
45 tvrating=None):
46 # It looks like tivo only supports one pc per house
47 pc_body_id = self.__pcBodySearch()
49 if not source:
50 source = title
52 data = {
53 'bodyId': 'tsn:' + tsn,
54 'description': description,
55 'duration': duration,
56 'partnerId': 'tivo:pt.3187',
57 'pcBodyId': pc_body_id,
58 'publishDate': time.strftime('%Y-%m-%d %H:%M%S', time.gmtime()),
59 'size': size,
60 'source': source,
61 'state': 'complete',
62 'title': title
65 rating = metadata.get_tv(tvrating)
66 if rating:
67 data['tvRating'] = rating.lower()
69 mtypes = {'video/mp4': 'avcL41MP4', 'video/bif': 'vc1ApL3'}
70 data['encodingType'] = mtypes.get(mime, 'mpeg2ProgramStream')
72 data['url'] = url + '?Format=' + mime
74 if subtitle:
75 data['subtitle'] = subtitle
77 offer_id, content_id = self.__bodyOfferModify(data)
78 self.__subscribe(offer_id, content_id, tsn)
80 def getDownloadRequests(self):
81 NEEDED_VALUES = [
82 'bodyId',
83 'bodyOfferId',
84 'description',
85 'partnerId',
86 'pcBodyId',
87 'publishDate',
88 'source',
89 'state',
90 'subscriptionId',
91 'subtitle',
92 'title',
93 'url'
96 # It looks like tivo only supports one pc per house
97 pc_body_id = self.__pcBodySearch()
99 requests = []
100 offer_list = self.__bodyOfferSchedule(pc_body_id)
102 for offer in offer_list.findall('bodyOffer'):
103 d = {}
104 if offer.findtext('state') != 'scheduled':
105 continue
107 for n in NEEDED_VALUES:
108 d[n] = offer.findtext(n)
109 requests.append(d)
111 return requests
113 def completeDownloadRequest(self, request, status, mime='video/mpeg'):
114 if status:
115 mtypes = {'video/mp4': 'avcL41MP4', 'video/bif': 'vc1ApL3'}
116 request['encodingType'] = mtypes.get(mime, 'mpeg2ProgramStream')
117 request['url'] += '?Format=' + mime
118 request['state'] = 'complete'
119 else:
120 request['state'] = 'cancelled'
121 request['cancellationReason'] = 'httpFileNotFound'
122 request['type'] = 'bodyOfferModify'
123 request['updateDate'] = time.strftime('%Y-%m-%d %H:%M%S',
124 time.gmtime())
126 offer_id, content_id = self.__bodyOfferModify(request)
127 if status:
128 self.__subscribe(offer_id, content_id, request['bodyId'][4:])
130 def getXMPPLoginInfo(self):
131 # It looks like tivo only supports one pc per house
132 pc_body_id = self.__pcBodySearch()
134 xml = self.__bodyXmppInfoGet(pc_body_id)
136 results = {
137 'server': xml.findtext('server'),
138 'port': int(xml.findtext('port')),
139 'username': xml.findtext('xmppId')
142 for sendPresence in xml.findall('sendPresence'):
143 results.setdefault('presence_list',[]).append(sendPresence.text)
145 return results
147 def __login(self):
149 data = {
150 'cams_security_domain': 'tivocom',
151 'cams_login_config': 'http',
152 'cams_cb_username': self.__username,
153 'cams_cb_password': self.__password,
154 'cams_original_url': '/mind/mind7?type=infoGet'
157 r = urllib2.Request(
158 'https://%s/mind/login' % self.__mind,
159 urllib.urlencode(data)
161 try:
162 result = self.__opener.open(r)
163 except:
164 pass
166 self.__logger.debug('__login\n%s' % (data))
168 def __dict_request(self, data, req):
169 r = urllib2.Request(
170 'https://%s/mind/mind7?type=%s' % (self.__mind, req),
171 dictcode(data),
172 {'Content-Type': 'x-tivo/dict-binary'}
174 result = self.__opener.open(r)
176 xml = ElementTree.parse(result).find('.')
178 self.__logger.debug('%s\n%s\n\n%sg' % (req, data,
179 ElementTree.tostring(xml)))
180 return xml
182 def __bodyOfferModify(self, data):
183 """Create an offer"""
185 xml = self.__dict_request(data, 'bodyOfferModify&bodyId=' +
186 data['bodyId'])
188 offer_id = xml.findtext('offerId')
189 if offer_id:
190 content_id = offer_id.replace('of','ct')
192 return offer_id, content_id
193 else:
194 raise Exception(ElementTree.tostring(xml))
196 def __subscribe(self, offer_id, content_id, tsn):
197 """Push the offer to the tivo"""
198 data = {
199 'bodyId': 'tsn:' + tsn,
200 'idSetSource': {
201 'contentId': content_id,
202 'offerId': offer_id,
203 'type': 'singleOfferSource'
205 'title': 'pcBodySubscription',
206 'uiType': 'cds'
209 return self.__dict_request(data, 'subscribe&bodyId=tsn:' + tsn)
211 def __bodyOfferSchedule(self, pc_body_id):
212 """Get pending stuff for this pc"""
214 data = {'pcBodyId': pc_body_id}
215 return self.__dict_request(data, 'bodyOfferSchedule')
217 def __pcBodySearch(self):
218 """Find PCS"""
220 xml = self.__dict_request({}, 'pcBodySearch')
221 id = xml.findtext('.//pcBodyId')
222 if not id:
223 xml = self.__pcBodyStore('pyTivo', True)
224 id = xml.findtext('.//pcBodyId')
226 return id
228 def __collectionIdSearch(self, url):
229 """Find collection ids"""
231 xml = self.__dict_request({'url': url}, 'collectionIdSearch')
232 return xml.findtext('collectionId')
234 def __pcBodyStore(self, name, replace=False):
235 """Setup a new PC"""
237 data = {
238 'name': name,
239 'replaceExisting': str(replace).lower()
242 return self.__dict_request(data, 'pcBodyStore')
244 def __bodyXmppInfoGet(self, body_id):
246 return self.__dict_request({'bodyId': body_id},
247 'bodyXmppInfoGet&bodyId=' + body_id)
250 def dictcode(d):
251 """Helper to create x-tivo/dict-binary"""
252 output = []
254 keys = [str(k) for k in d]
255 keys.sort()
257 for k in keys:
258 v = d[k]
260 output.append( varint( len(k) ) )
261 output.append( k )
263 if isinstance(v, dict):
264 output.append( chr(2) )
265 output.append( dictcode(v) )
267 else:
268 if type(v) == str:
269 try:
270 v = v.decode('utf8')
271 except:
272 if sys.platform == 'darwin':
273 v = v.decode('macroman')
274 else:
275 v = v.decode('iso8859-1')
276 elif type(v) != unicode:
277 v = str(v)
278 v = v.encode('utf-8')
279 output.append( chr(1) )
280 output.append( varint( len(v) ) )
281 output.append( v )
283 output.append( chr(0) )
285 output.append( chr(0x80) )
287 return ''.join(output)
289 def varint(i):
290 output = []
291 while i > 0x7f:
292 output.append( chr(i & 0x7f) )
293 i >>= 7
294 output.append( chr(i | 0x80) )
295 return ''.join(output)
297 def getMind(tsn=None):
298 username = config.get_tsn('tivo_username', tsn)
299 password = config.get_tsn('tivo_password', tsn)
301 if not username or not password:
302 raise Exception("tivo_username and tivo_password required")
304 return Mind(username, password, tsn)