Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

[6ca465]: plugin.video.twit / default.py Maximize Restore History

Download this file

default.py    491 lines (438 with data), 18.8 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import urllib
import urllib2
import re
import os
import xbmcplugin
import xbmcgui
import xbmcaddon
import StorageServer
from datetime import datetime
from pyamf import remoting
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
try:
import json
except:
import simplejson as json
addon = xbmcaddon.Addon(id='plugin.video.twit')
__language__ = addon.getLocalizedString
addon_version = addon.getAddonInfo('version')
home = xbmc.translatePath(addon.getAddonInfo('path'))
fanart = os.path.join(home, 'fanart.jpg')
icon = os.path.join(home, 'icon.png')
live_icon = 'http://twit-xbmc.googlecode.com/svn/images/live_icon.png'
cache = StorageServer.StorageServer("twit", 2)
debug = addon.getSetting('debug')
first_run = addon.getSetting('first_run')
def addon_log(string):
if debug == 'true':
xbmc.log("[addon.TWiT-%s]: %s" %(addon_version, string))
def cache_shows_file():
''' creates an initial cache from the shows file '''
show_file = os.path.join(home, 'resources', 'shows')
cache.set("shows", open(show_file, 'r').read())
def make_request(url):
try:
headers = {'User-agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0',
'Referer' : 'http://twit.tv'}
req = urllib2.Request(url,None,headers)
response = urllib2.urlopen(req)
data = response.read()
response.close()
return data
except urllib2.URLError, e:
addon_log( 'We failed to open "%s".' % url)
if hasattr(e, 'reason'):
addon_log('We failed to reach a server.')
addon_log('Reason: ', e.reason)
if hasattr(e, 'code'):
addon_log('We failed with error code - %s.' % e.code)
def shows_cache(shows):
''' this function checks for new shows that haven't been cached '''
url = 'http://twit.tv/shows'
soup = BeautifulSoup(make_request(url), convertEntities=BeautifulSoup.HTML_ENTITIES)
show_items = soup.findAll('div', attrs={'class' : 'item-list'})[2]('li')
for i in show_items:
name = str(i('a')[-1].string)
try:
show = shows['active'][name]
except:
addon_log('Show not in cache: '+name)
show_url = ('http://twit.tv/show/'+name.replace("'",'').replace('.','').replace(' ','-').lower()
.replace('-for-the','').replace('the-giz-wiz','weekly-daily-giz-wiz'))
new_show = cache_show(name, show_url)
if new_show:
addon_log('Cached new show: '+name)
return "True"
def cache_show(name, url):
''' a helper function to cache new shows '''
shows = eval(cache.get('shows'))
soup = BeautifulSoup(make_request(url), convertEntities=BeautifulSoup.HTML_ENTITIES)
try:
desc = soup.find('div', attrs={'class': "field-content"}).getText()
if desc == None: raise
except:
addon_log('description exception: '+name)
desc = ''
try:
thumb = soup.find('div', attrs={'class' : "views-field views-field-field-cover-art-fid"})('img')['src']
if thumb == None: raise
except:
addon_log('thumb exception: '+name)
thumb = icon
shows['active'][name] = {'show_url': url, 'thumb': thumb, 'description': desc}
cache.set("shows", repr(shows))
return True
def get_shows(shows):
''' loads the main directory '''
addDir(__language__(30000), 'latest_episodes', 4, icon)
addLink(__language__(30001), 'twit_live', '', '', 3, live_icon)
cache_shows = eval(cache.cacheFunction(shows_cache, shows))
if not cache_shows:
addon_log('shows_cache FAILED')
items = sorted(shows['active'].keys(), key=str.lower)
for i in items:
if i == 'Radio Leo': continue
addDir(i, shows['active'][i]['show_url'], 1, shows['active'][i]['thumb'], shows['active'][i]['description'])
addDir('Retired Shows', 'retired_shows', 6, icon)
def get_retired_shows():
''' mode 6, loads the retired shows directory '''
shows = eval(cache.get('shows'))
items = sorted(shows['retired'].keys(), key=str.lower)
for i in items:
if i == 'Radio Leo': continue
addDir(i, shows['retired'][i]['show_url'], 1, shows['retired'][i]['thumb'], shows['retired'][i]['description'])
def index(url, iconimage):
''' mode 1, loads episodes of a specific show '''
soup = BeautifulSoup(make_request(url), convertEntities=BeautifulSoup.HTML_ENTITIES)
items = soup.findAll('div', attrs={'id' : "primary"})[0]('div', attrs={'class' : 'field-content'})
for i in items:
try:
url = i.a['href']
except TypeError:
continue
if url.startswith('http://twit.tv/show/'):
name = i.a.string.encode('ascii', 'ignore')
try:
description = i.p.string
except:
description = ''
try:
date = i.findPrevious('span').string
except:
date = ''
addLink(name,url,description,date,2,iconimage)
try:
page = 'http://twit.tv'+soup('li', attrs={'class' : "pager-next"})[0].a['href']
addDir('Next Page',page,1,iconimage)
except:
pass
def cache_latest_episods():
shows = eval(cache.get('shows'))
url = 'http://twit.tv/'
soup = BeautifulSoup(make_request(url), convertEntities=BeautifulSoup.HTML_ENTITIES)
h_tag = soup.find('h2', attrs={'class': 'block-title'}, text='Most Recent Episodes')
items_string = str(h_tag.findNext('div', attrs={'class': "view-content"})('div'))
items_string = items_string.replace('\n','').replace('> <','><').replace('>, <','><')
pattern = (
'<span class="field-content">(.+?)</span></div><div class=".+?"><span class=".+?">'
'<div class="coverart"><img src="(.+?)" alt="" title="" width=".+?" height=".+?" class=".+?" />'
'</div><div class="show-info"><a href="(.+?)">(.+?)</a>(.+?) </div></span></div><div class=".+?">'
'<div class="field-content"><p>(.+?)</p>'
)
items_list = re.findall(pattern, items_string)
episode_list = []
episodes = ''
for show, thumb, href, episode, date, desc in items_list:
if episode in episodes:
addon_log('episode already in list')
continue
name = '%s - %s' %(show, episode)
try:
thumbnail = shows['active'][show]['thumb']
except:
addon_log('thumbnail exception: '+show)
thumbnail = thumb
episode_list.append((name,href,desc,date,thumbnail))
episodes += episode+', '
return episode_list
def get_latest_episodes():
episodes = cache.cacheFunction(cache_latest_episods)
for i in episodes:
addLink(i[0], i[1], i[2], i[3], 2, i[4])
def set_media_url(url):
playback_settings = {
'0': 'hd download',
'1': 'sd download',
'2': 'download',
'3': 'audio download'
}
soup = BeautifulSoup(make_request(url), convertEntities=BeautifulSoup.HTML_ENTITIES)
media_urls = {}
for i in soup('span', attrs={'class' : "download"}):
media_urls[i.a['class']] = i.a['href']
if content_type == 'audio':
playback_setting = '3'
playback_type = 'audio download'
else:
playback_setting = addon.getSetting('playback')
playback_type = playback_settings[playback_setting]
playback_url = None
if media_urls.has_key(playback_type):
playback_url = media_urls[playback_type]
else:
p_set = int(playback_setting)
if (p_set + 1) <= 3:
for i in range(len(playback_settings)):
p_set += 1
if p_set < 3:
try:
playback_url = media_urls[playback_settings[str(p_set)]]
break
except: continue
if not playback_url:
dialog = xbmcgui.Dialog()
ret = dialog.select(__language__(30002), media_urls.keys())
if ret >= 0:
playback_url = media_urls.values()[ret]
if playback_url:
success = True
else:
success = False
playback_url = ''
item = xbmcgui.ListItem(path=playback_url)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), success, item)
def twit_live():
live_streams = [
'http://twit.live-s.cdn.bitgravity.com/cdn-live-s1/_definst_/twit/live/high/playlist.m3u8',
'http://twit.live-s.cdn.bitgravity.com/cdn-live-s1/_definst_/twit/live/low/playlist.m3u8',
'http://bglive-a.bitgravity.com/twit/live/high?noprefix',
'http://bglive-a.bitgravity.com/twit/live/low?noprefix',
'ustream',
'justintv',
'http://hls.cdn.flosoft.biz/flosoft/smil:twitStreamAll.smil/playlist.m3u8',
'http://hls.cdn.flosoft.biz/flosoft/mp4:twitStream_720/playlist.m3u8',
'http://hls.cdn.flosoft.biz/flosoft/mp4:twitStream_540/playlist.m3u8',
'http://hls.cdn.flosoft.biz/flosoft/mp4:twitStream_360/playlist.m3u8',
'http://twit.am/listen'
]
if content_type == 'audio':
link = 'http://twit.am/listen'
else:
link = live_streams[int(addon.getSetting('twit_live'))]
if link == 'justintv':
link = get_jtv()
elif link == 'ustream':
link = get_ustream()
success = False
if link:
success = True
else: link = ''
item = xbmcgui.ListItem(path=link)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), success, item)
def get_ustream():
def getSwf():
url = 'http://www.ustream.tv/flash/viewer.swf'
req = urllib2.Request(url)
response = urllib2.urlopen(req)
swfUrl = response.geturl()
return swfUrl
data = make_request('http://cgw.ustream.tv/Viewer/getStream/1/1524.amf')
amf_data = remoting.decode(data).bodies[0][1].body
if amf_data['success']:
hls_url = None
if amf_data.has_key('liveHttpUrl'):
try: hls_url = amf_data['liveHttpUrl']
except: pass
if hls_url:
return hls_url
else:
streams = None
try:
streams = amf_data['streamVersions']['streams/live_1']['streamVersionCdn']
except: pass
if streams:
for i in streams.keys():
rtmp = streams[i].values()[0]
path = streams[i].values()[1]
break
playpath = ' playpath='+path
swf = ' swfUrl='+getSwf()
pageUrl = ' pageUrl=http://live.twit.tv'
url = rtmp + playpath + swf + pageUrl + ' swfVfy=1 live=true'
return url
else:
return None
def get_jtv():
try:
soup = BeautifulSoup(make_request('http://usher.justin.tv/find/twit.xml?type=live'))
token = ' jtv='+soup.token.string.replace('\\','\\5c').replace(' ','\\20').replace('"','\\22')
rtmp = soup.connect.string+'/'+soup.play.string
Pageurl = ' Pageurl=http://www.justin.tv/twit'
swf = ' swfUrl=http://www.justin.tv/widgets/live_embed_player.swf?channel=twit live=true'
url = rtmp+token+swf+Pageurl
return url
except:
return None
def get_params():
param=[]
paramstring=sys.argv[2]
if len(paramstring)>=2:
params=sys.argv[2]
cleanedparams=params.replace('?','')
if (params[len(params)-1]=='/'):
params=params[0:len(params)-2]
pairsofparams=cleanedparams.split('&')
param={}
for i in range(len(pairsofparams)):
splitparams={}
splitparams=pairsofparams[i].split('=')
if (len(splitparams))==2:
param[splitparams[0]]=splitparams[1]
return param
def addLink(name,url,description,date,mode,iconimage):
u=(sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+
"&iconimage="+urllib.quote_plus(iconimage)+"&content_type="+content_type)
episode = None
try: episode = int(re.findall('#(.+?):', name)[0])
except:
try: episode = int(name.split(' ')[-1])
except: pass
liz=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
liz.setInfo(type="Video", infoLabels={"Title": name, "Plot":description, "Aired": date, "episode": episode})
liz.setProperty("Fanart_Image", fanart)
liz.setProperty('IsPlayable', 'true')
if name == __language__(30001):
contextMenu = [('Run IrcChat', "RunPlugin(plugin://plugin.video.twit/?mode=5)")]
liz.addContextMenuItems(contextMenu)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
def addDir(name,url,mode,iconimage,description=None):
u=(sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+
"&iconimage="+urllib.quote_plus(iconimage)+"&content_type="+content_type)
liz=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
liz.setInfo(type="Video", infoLabels={"Title": name, "Plot":description})
liz.setProperty( "Fanart_Image", fanart )
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
def run_ircchat():
# check_chat_args
nickname = addon.getSetting('nickname')
username = addon.getSetting('username')
try:
ok = nickname
if ok is None or ok == '': raise
ok = username
if ok is None or ok == '': raise
except:
xbmc.executebuiltin("XBMC.Notification(%s, %s,10000,%s)"
%('IrcChat', language(30024), icon))
addon.openSettings()
nickname = addon.getSetting('nickname')
username = addon.getSetting('username')
try:
ok = nickname
if ok is None or ok == '': raise
ok = username
if ok is None or ok == '': raise
except:
return
# run ircchat script
xbmc.executebuiltin(
"RunScript(script.ircchat, run_irc=True&nickname=%s&username=%s&password=%s&host=irc.twit.tv&channel=twitlive)"
%(nickname, username, addon.getSetting('password'))
)
def setViewMode():
if not addon.getSetting('view_mode') == "0":
try:
if addon.getSetting('view_mode') == "1": # List
xbmc.executebuiltin('Container.SetViewMode(502)')
elif addon.getSetting('view_mode') == "2": # Big List
xbmc.executebuiltin('Container.SetViewMode(51)')
elif addon.getSetting('view_mode') == "3": # Thumbnails
xbmc.executebuiltin('Container.SetViewMode(500)')
elif addon.getSetting('view_mode') == "4": # Poster Wrap
xbmc.executebuiltin('Container.SetViewMode(501)')
elif addon.getSetting('view_mode') == "5": # Fanart
xbmc.executebuiltin('Container.SetViewMode(508)')
elif addon.getSetting('view_mode') == "6": # Media info
xbmc.executebuiltin('Container.SetViewMode(504)')
elif addon.getSetting('view_mode') == "7": # Media info 2
xbmc.executebuiltin('Container.SetViewMode(503)')
elif addon.getSetting('view_mode') == "8": # Media info 3
xbmc.executebuiltin('Container.SetViewMode(515)')
except:
addon_log("SetViewMode Failed: "+addon.getSetting('view_mode'))
addon_log("Skin: "+xbmc.getSkinDir())
if debug == 'true':
cache.dbg = True
if first_run != addon_version:
cache_shows_file()
addon_log('first_run, caching shows file')
xbmc.sleep(1000)
addon.setSetting('first_run', addon_version)
params=get_params()
url=None
name=None
mode=None
content_type='video'
try:
url=urllib.unquote_plus(params["url"])
except:
pass
try:
name=urllib.unquote_plus(params["name"])
except:
pass
try:
iconimage=urllib.unquote_plus(params["iconimage"])
except:
pass
try:
mode=int(params["mode"])
except:
pass
try:
content_type=str(params["content_type"])
except:
pass
addon_log("Mode: "+str(mode))
addon_log("URL: "+str(url))
addon_log("Name: "+str(name))
if mode==None:
try:
shows = eval(cache.get('shows'))
if isinstance(shows, dict):
get_shows(shows)
else: raise
except:
addon_log('"shows" cache missing')
cache_shows_file()
addon_log('caching shows file, this should only happen if common cache db is reset')
xbmc.sleep(1000)
shows = eval(cache.get('shows'))
if isinstance(shows, dict):
get_shows(shows)
else:
addon_log('"shows" cache ERROR')
xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode==1:
index(url,iconimage)
xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
setViewMode()
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode==2:
set_media_url(url)
elif mode==3:
twit_live()
xbmc.sleep(1000)
if addon.getSetting('run_chat') == 'true':
run_ircchat()
elif mode==4:
get_latest_episodes()
xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode==5:
run_ircchat()
elif mode==6:
get_retired_shows()
xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
xbmcplugin.endOfDirectory(int(sys.argv[1]))