13 import xml
.etree
.ElementTree
as ElementTree
16 import elementtree
.ElementTree
as ElementTree
18 warnings
.warn('Python 2.5 or higher or elementtree is ' +
19 'needed to use the TivoPush')
21 if 'ElementTree' not in locals():
24 def __init__(self
, *arg
, **karg
):
25 raise Exception('Python 2.5 or higher or elementtree is ' +
26 'needed to use the TivoPush')
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
)
43 def pushVideo(self
, tsn
, url
, description
, duration
, size
,
44 title
, subtitle
, source
='', mime
='video/mpeg',
46 # It looks like tivo only supports one pc per house
47 pc_body_id
= self
.__pcBodySearch
()
53 'bodyId': 'tsn:' + tsn
,
54 'description': description
,
56 'partnerId': 'tivo:pt.3187',
57 'pcBodyId': pc_body_id
,
58 'publishDate': time
.strftime('%Y-%m-%d %H:%M%S', time
.gmtime()),
65 rating
= metadata
.get_tv(tvrating
)
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
75 data
['subtitle'] = subtitle
77 offer_id
, content_id
= self
.__bodyOfferModify
(data
)
78 self
.__subscribe
(offer_id
, content_id
, tsn
)
80 def getDownloadRequests(self
):
96 # It looks like tivo only supports one pc per house
97 pc_body_id
= self
.__pcBodySearch
()
100 offer_list
= self
.__bodyOfferSchedule
(pc_body_id
)
102 for offer
in offer_list
.findall('bodyOffer'):
104 if offer
.findtext('state') != 'scheduled':
107 for n
in NEEDED_VALUES
:
108 d
[n
] = offer
.findtext(n
)
113 def completeDownloadRequest(self
, request
, status
, mime
='video/mpeg'):
115 mtypes
= {'video/mp4': 'avcL41MP4', 'video/bif': 'vc1ApL3'}
116 request
['encodingType'] = mtypes
.get(mime
, 'mpeg2ProgramStream')
117 request
['url'] += '?Format=' + mime
118 request
['state'] = 'complete'
120 request
['state'] = 'cancelled'
121 request
['cancellationReason'] = 'httpFileNotFound'
122 request
['type'] = 'bodyOfferModify'
123 request
['updateDate'] = time
.strftime('%Y-%m-%d %H:%M%S',
126 offer_id
, content_id
= self
.__bodyOfferModify
(request
)
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
)
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
)
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'
158 'https://%s/mind/login' % self
.__mind
,
159 urllib
.urlencode(data
)
162 result
= self
.__opener
.open(r
)
166 self
.__logger
.debug('__login\n%s' % (data
))
168 def __dict_request(self
, data
, req
):
170 'https://%s/mind/mind7?type=%s' % (self
.__mind
, req
),
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
)))
182 def __bodyOfferModify(self
, data
):
183 """Create an offer"""
185 xml
= self
.__dict
_request
(data
, 'bodyOfferModify&bodyId=' +
188 offer_id
= xml
.findtext('offerId')
190 content_id
= offer_id
.replace('of','ct')
192 return offer_id
, content_id
194 raise Exception(ElementTree
.tostring(xml
))
196 def __subscribe(self
, offer_id
, content_id
, tsn
):
197 """Push the offer to the tivo"""
199 'bodyId': 'tsn:' + tsn
,
201 'contentId': content_id
,
203 'type': 'singleOfferSource'
205 'title': 'pcBodySubscription',
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
):
220 xml
= self
.__dict
_request
({}, 'pcBodySearch')
221 id = xml
.findtext('.//pcBodyId')
223 xml
= self
.__pcBodyStore
('pyTivo', True)
224 id = xml
.findtext('.//pcBodyId')
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):
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
)
251 """Helper to create x-tivo/dict-binary"""
254 keys
= [str(k
) for k
in d
]
260 output
.append( varint( len(k
) ) )
263 if isinstance(v
, dict):
264 output
.append( chr(2) )
265 output
.append( dictcode(v
) )
272 if sys
.platform
== 'darwin':
273 v
= v
.decode('macroman')
275 v
= v
.decode('iso8859-1')
276 elif type(v
) != unicode:
278 v
= v
.encode('utf-8')
279 output
.append( chr(1) )
280 output
.append( varint( len(v
) ) )
283 output
.append( chr(0) )
285 output
.append( chr(0x80) )
287 return ''.join(output
)
292 output
.append( chr(i
& 0x7f) )
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
)