audio_lang code tidy up
[pyTivo/wmcbrine/lucasnz.git] / mind.py
blobb16e840e46904c2675114455246dc10f8bbf8214
1 import cookielib
2 import logging
3 import sys
4 import time
5 import urllib2
6 import urllib
7 import warnings
9 import config
11 try:
12 import xml.etree.ElementTree as ElementTree
13 except ImportError:
14 try:
15 import elementtree.ElementTree as ElementTree
16 except ImportError:
17 warnings.warn('Python 2.5 or higher or elementtree is ' +
18 'needed to use the TivoPush')
20 if 'ElementTree' not in locals():
22 class Mind:
23 def __init__(self, *arg, **karg):
24 raise Exception('Python 2.5 or higher or elementtree is ' +
25 'needed to use the TivoPush')
27 else:
29 class Mind:
30 def __init__(self, username, password, tsn):
31 self.__logger = logging.getLogger('pyTivo.mind')
32 self.__username = username
33 self.__password = password
34 self.__mind = config.get_mind(tsn)
36 cj = cookielib.CookieJar()
37 cp = urllib2.HTTPCookieProcessor(cj)
38 self.__opener = urllib2.build_opener(cp)
40 self.__login()
42 def pushVideo(self, tsn, url, description, duration, size,
43 title, subtitle, source='', mime='video/mpeg',
44 tvrating=None):
45 # It looks like tivo only supports one pc per house
46 pc_body_id = self.__pcBodySearch()
48 if not source:
49 source = title
51 data = {
52 'bodyId': 'tsn:' + tsn,
53 'description': description,
54 'duration': duration,
55 'partnerId': 'tivo:pt.3187',
56 'pcBodyId': pc_body_id,
57 'publishDate': time.strftime('%Y-%m-%d %H:%M%S', time.gmtime()),
58 'size': size,
59 'source': source,
60 'state': 'complete',
61 'title': title
64 ratings = {'x1': 'y7', 'x2': 'y', 'x3': 'g', 'x4': 'pg',
65 'x5': '14', 'x6': 'ma', 'x7': 'nr'}
66 if tvrating in ratings:
67 data['tvRating'] = ratings[tvrating]
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 content_id = offer_id.replace('of','ct')
191 return offer_id, content_id
193 def __subscribe(self, offer_id, content_id, tsn):
194 """Push the offer to the tivo"""
195 data = {
196 'bodyId': 'tsn:' + tsn,
197 'idSetSource': {
198 'contentId': content_id,
199 'offerId': offer_id,
200 'type': 'singleOfferSource'
202 'title': 'pcBodySubscription',
203 'uiType': 'cds'
206 return self.__dict_request(data, 'subscribe&bodyId=tsn:' + tsn)
208 def __bodyOfferSchedule(self, pc_body_id):
209 """Get pending stuff for this pc"""
211 data = {'pcBodyId': pc_body_id}
212 return self.__dict_request(data, 'bodyOfferSchedule')
214 def __pcBodySearch(self):
215 """Find PCS"""
217 xml = self.__dict_request({}, 'pcBodySearch')
218 id = xml.findtext('.//pcBodyId')
219 if not id:
220 xml = self.__pcBodyStore('pyTivo', True)
221 id = xml.findtext('.//pcBodyId')
223 return id
225 def __collectionIdSearch(self, url):
226 """Find collection ids"""
228 xml = self.__dict_request({'url': url}, 'collectionIdSearch')
229 return xml.findtext('collectionId')
231 def __pcBodyStore(self, name, replace=False):
232 """Setup a new PC"""
234 data = {
235 'name': name,
236 'replaceExisting': str(replace).lower()
239 return self.__dict_request(data, 'pcBodyStore')
241 def __bodyXmppInfoGet(self, body_id):
243 return self.__dict_request({'bodyId': body_id},
244 'bodyXmppInfoGet&bodyId=' + body_id)
247 def dictcode(d):
248 """Helper to create x-tivo/dict-binary"""
249 output = []
251 keys = [str(k) for k in d]
252 keys.sort()
254 for k in keys:
255 v = d[k]
257 output.append( varint( len(k) ) )
258 output.append( k )
260 if isinstance(v, dict):
261 output.append( chr(2) )
262 output.append( dictcode(v) )
264 else:
265 if type(v) == str:
266 try:
267 v = v.decode('utf8')
268 except:
269 if sys.platform == 'darwin':
270 v = v.decode('macroman')
271 else:
272 v = v.decode('iso8859-1')
273 elif type(v) != unicode:
274 v = str(v)
275 v = v.encode('utf-8')
276 output.append( chr(1) )
277 output.append( varint( len(v) ) )
278 output.append( v )
280 output.append( chr(0) )
282 output.append( chr(0x80) )
284 return ''.join(output)
286 def varint(i):
287 output = []
288 while i > 0x7f:
289 output.append( chr(i & 0x7f) )
290 i >>= 7
291 output.append( chr(i | 0x80) )
292 return ''.join(output)
294 def getMind(tsn=None):
295 username = config.get_tsn('tivo_username', tsn)
296 password = config.get_tsn('tivo_password', tsn)
298 if not username or not password:
299 raise Exception("tivo_username and tivo_password required")
301 return Mind(username, password, tsn)