12 import xml
.etree
.ElementTree
as ElementTree
15 import elementtree
.ElementTree
as ElementTree
17 warnings
.warn('Python 2.5 or higher or elementtree is ' +
18 'needed to use the TivoPush')
20 if 'ElementTree' not in locals():
23 def __init__(self
, *arg
, **karg
):
24 raise Exception('Python 2.5 or higher or elementtree is ' +
25 'needed to use the TivoPush')
30 def __init__(self
, username
, password
):
31 self
.__logger
= logging
.getLogger('pyTivo.mind')
32 self
.__username
= username
33 self
.__password
= password
34 self
.__mind
= config
.get_mind()
36 cj
= cookielib
.CookieJar()
37 cp
= urllib2
.HTTPCookieProcessor(cj
)
38 self
.__opener
= urllib2
.build_opener(cp
)
42 if not self
.__pcBodySearch
():
43 self
.__pcBodyStore
('pyTivo', True)
45 def pushVideo(self
, tsn
, url
, description
, duration
, size
,
46 title
, subtitle
, source
='', mime
='video/mpeg'):
47 # It looks like tivo only supports one pc per house
48 pc_body_id
= self
.__pcBodySearch
()[0]
54 'bodyId': 'tsn:' + tsn
,
55 'description': description
,
57 'partnerId': 'tivo:pt.3187',
58 'pcBodyId': pc_body_id
,
59 'publishDate': time
.strftime('%Y-%m-%d %H:%M%S', time
.gmtime()),
66 if mime
== 'video/mp4':
67 data
['encodingType'] = 'avcL41MP4'
68 elif mime
== 'video/bif':
69 data
['encodingType'] = 'vc1ApL3'
71 data
['encodingType'] = 'mpeg2ProgramStream'
73 data
['url'] = url
+ '?Format=' + mime
76 data
['subtitle'] = subtitle
78 offer_id
, content_id
= self
.__bodyOfferModify
(data
)
79 self
.__subscribe
(offer_id
, content_id
, tsn
)
81 def getDownloadRequests(self
):
97 # It looks like tivo only supports one pc per house
98 pc_body_id
= self
.__pcBodySearch
()[0]
101 offer_list
= self
.__bodyOfferSchedule
(pc_body_id
)
103 for offer
in offer_list
.findall('bodyOffer'):
105 if offer
.findtext('state') != 'scheduled':
108 for n
in NEEDED_VALUES
:
109 d
[n
] = offer
.findtext(n
)
114 def completeDownloadRequest(self
, request
, mime
='video/mpeg'):
115 if mime
== 'video/mp4':
116 request
['encodingType'] = 'avcL41MP4'
117 elif mime
== 'video/bif':
118 request
['encodingType'] = 'vc1ApL3'
120 request
['encodingType'] = 'mpeg2ProgramStream'
121 request
['url'] = url
+ '?Format=' + mime
122 request
['state'] = 'complete'
123 request
['type'] = 'bodyOfferModify'
124 request
['updateDate'] = time
.strftime('%Y-%m-%d %H:%M%S',
127 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
()[0]
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 if xml
.findtext('state') != 'complete':
189 raise Exception(ElementTree
.tostring(xml
))
191 offer_id
= xml
.findtext('offerId')
192 content_id
= offer_id
.replace('of','ct')
194 return offer_id
, content_id
197 def __subscribe(self
, offer_id
, content_id
, tsn
):
198 """Push the offer to the tivo"""
200 'bodyId': 'tsn:' + tsn
,
202 'contentId': content_id
,
204 'type': 'singleOfferSource'
206 'title': 'pcBodySubscription',
210 return self
.__dict
_request
(data
, 'subscribe&bodyId=tsn:' + tsn
)
212 def __bodyOfferSchedule(self
, pc_body_id
):
213 """Get pending stuff for this pc"""
215 data
= {'pcBodyId': pc_body_id
}
216 return self
.__dict
_request
(data
, 'bodyOfferSchedule')
218 def __pcBodySearch(self
):
221 xml
= self
.__dict
_request
({}, 'pcBodySearch')
223 return [id.text
for id in xml
.findall('pcBody/pcBodyId')]
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):
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
)
248 """Helper to create x-tivo/dict-binary"""
251 keys
= [str(k
) for k
in d
]
257 output
.append( varint( len(k
) ) )
260 if isinstance(v
, dict):
261 output
.append( chr(2) )
262 output
.append( dictcode(v
) )
269 if sys
.platform
== 'darwin':
270 v
= v
.decode('macroman')
272 v
= v
.decode('iso8859-1')
273 elif type(v
) != unicode:
275 v
= v
.encode('utf-8')
276 output
.append( chr(1) )
277 output
.append( varint( len(v
) ) )
280 output
.append( chr(0) )
282 output
.append( chr(0x80) )
284 return ''.join(output
)
289 output
.append( chr(i
& 0x7f) )
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
)