[8a757e]: plugin.video.watson / default.py Maximize Restore History

Download this file

default.py    724 lines (583 with data), 27.0 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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# -*- coding: utf-8 -*-
#!/usr/bin/python
#
#
#
# Auth: Jarkko Vesiluoma
# jvesiluoma@gmail.com
#
# Version history:
# [B]2.0.1[/B] - Watson 2.0 release, plugin fixed to work with new Watson.
# [B]1.1.1[/B] - Download function improved, will now download to single file, some minor updates. New icon.
# [B]1.1.0[/B] - Beta, programs can now be removed from recordings / favourites.
# [B]1.0.9[/B] - Beta, Context menu to save program to recordings / favourites added, tmp dirs now selectable from settings
# [B]1.0.8[/B] - Beta, Search for recordings added
# [B]1.0.7[/B] - Beta, Download and Plot context menus added
# [B]1.0.6[/B] - Beta, Minor fixes
# [B]1.0.5[/B] - Beta, LiveTV added
# [B]1.0.4[/B] - Pre-Alpha2, Video stop now fixed, started to code "LiveTV" option
# [B]1.0.3[/B] - Pre-Alpha2, tmpfile location check (os-check)
# [B]1.0.2[/B] - Pre-Alpha2, minor modifications
# [B]1.0.1[/B] - Pre-Alpha2, modified menu structure
# [B]1.0.0[/B] - Initial version for XBMC
#
#
#
# Watson 1 API description:
#
# User recordings (user archive):
# http://www.watson.fi/pctv/RSS?action=getfavoriterecordings
#
# XML format:
# TITLE = Program title
# DESC = Program description
# AIRDATE = Program airdate
# LINK = Program link to RSS, e.g: http://www.watson.fi/pctv/rss/recordings/1382979
# PLINK = Program permanent link, e.g: 1382979
# SOURCEURL = Program source url, e.g: http://www.watson.fi/pctv/rss/channels/317994
# SRCURLINF = Program source url info, e.g: 317994 - HLS/Unknown
# DURL = Program download url, if bitrate is '-1', then program is scheduled for recording, but not yet in archive e.g: http://www.watson.fi/pctv/Download?id=1382979&format=HLS&bitrate=-1
# If bitrate is for example 1974558, program is recorded and of course, state is 'active and reason is 'Completed' instead of 'blocked' and 'Queued'.
# THUMBNAIL = Program thumbnail url, e.g: http://www.watson.fi/pctv/resources/recordings/screengrabs/1375085.jpg
#
# <item>
# <title>TITLE</title>
# <description>DESC</description>
# <dc:date>AIRDATE</dc:date>
# <link>LINK</link>
# <guid isPermaLink="false">PLINK</guid>
# <source url="SOURCEURL">SRCURLINF</source>
# <media:content url="DURL" medium="video" type="video/mp4" expression="full" duration="1980"/>
# <media:status state="blocked" reason="Queued" />
# <media:community><media:starRating average="0" min="0" max="5"/></media:community>
# </item>
#
# This is how few last line looks, when program is already recorded, notice that 'content url' - line has video type, medium, filesize etc. and state is now 'active' and reason is changed to 'Complete'
#
# <media:content url="http://www.watson.fi/pctv/Download?id=1375085&amp;format=HLS&amp;bitrate=1974558" medium="video" type="video/mp4" fileSize="1091264424" expression="full" duration="3180"/>
# <media:status state="active" reason="Completed" />
# <media:community><media:starRating average="0" min="0" max="5"/></media:community>
# <media:thumbnail url="THUMBNAIL" height="72" width="96"/>
#
#
# EPG from last 120 hours:
# http://www.watson.fi/pctv/RSS?action=getprograms&hours=120
#
#
# Users scheduled recordings:
# http://www.watson.fi/pctv/RSS?action=getscheduledrecordings
#
# XML format:
# NAME = Program name, e.g: Paljastavat valheet
# CHANID = Channel Id, e.g: 1011
# LINK = Program link, e.g: http://www.watson.fi/pctv/rss/scheduledrecordings/756093
# PLINK = Program permanent link, e.g: 756093
# SURL = Source URL: http://www.watson.fi/pctv/rss/channels/1011
#
# <item>
# <title>NAME</title>
# <description>Scheduled Recording for Program Title NAME, Every Day from Channel ID CHANID</description>
# <link>LINK</link>
# <guid isPermaLink="false">PLINK</guid>
# <source url="SURL">CHANID</source>
# </item>
#
# Add recording to favorites:
# RECORDINGID = 7 digit recodring id (permlink), e.g: 1264516
# http://www.watson.fi/pctv/RSS?action=addfavorite&amp;id=RECORDINGID
#
#
# Remove program from recordings / favorites:
# RECORDINGID = 7 digit recodring id (permlink), e.g: 1264516
# http://www.watson.fi/pctv/RSS?action=removerecording&id=RECORDINGID
#
#
# Search recordings and programs:
# SEARCHSTRING = Search string to find recordings and programs
# http://www.watson.fi/pctv/RSS?action=search&type=all&field=all&term=SEARCHSTRING
#
#
#
#
# TV channel Id list:
# 1006 = Jim
# 1007 = Yle something???
# 1008 = Nelonen
# 1010 = TV1
# 1011 = MTV3
# 1012 = TV2
# 1013 = SVT1
# 1014 = TV5
# 1015 = Sub
# 161260 = ???
# 629149 = AVA
# 642360 = MTV?
# 317994 = FOX
# Global variables
VERSION = "2.1.0"
MYHEADERS = { 'User-Agent': "Watson-XBMC version "+VERSION+";" }
DEBUG=1
# 1=low, 2=high, any other ==> low
QUALITY=2
# Imports
import locale
locale.setlocale(locale.LC_ALL, 'C')
import urllib, urllib2, cookielib , re, os, sys, time, linecache, StringIO, time, xbmcplugin, xbmcaddon, xbmcgui, socket, operator, httplib, base64
#import CommonFunctions as common
from xml.dom import minidom
from urlparse import urlparse
watson_addon = xbmcaddon.Addon("plugin.video.watson");
channeldict={'1006':'Jim','1007':'Yle?','1008':'Nelonen','1010':'TV1','1011':'MTV3','1012':'TV2','1013':'SVT1','1014':'TV5','1015':'Sub','629149':'AVA','317994':'Fox'}
url_archive='http://www.watson.fi/pctv/RSS?action=getfavoriterecordings'
tmpfile=watson_addon.getSetting("tempdir")+"tmp_m3u8a"
tmpfile2=watson_addon.getSetting("tempdir")+"tmp_m3u8b"
# Check settings
def settings():
# Is account setup properly? Well...at least something given?
if watson_addon.getSetting("username") != '' and watson_addon.getSetting("password") != '' and tmpfile != "" and tmpfile2 != "":
INDEX()
else:
u=sys.argv[0]+"?url=Settings&mode=5"
listfolder = xbmcgui.ListItem(watson_addon.getLocalizedString(32005))
listfolder.setInfo('video', {'Title': watson_addon.getLocalizedString(32006)})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, listfolder, isFolder=1)
u=sys.argv[0]+"?url=Settings&mode=5"
listfolder = xbmcgui.ListItem(watson_addon.getLocalizedString(32007))
listfolder.setInfo('video', {'Title': watson_addon.getLocalizedString(32007)})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, listfolder, isFolder=1)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Get first selection list and display items from tuples
def INDEX():
# Live TV
u=sys.argv[0]+"?url=LiveTV&mode=1"
listfolder = xbmcgui.ListItem(watson_addon.getLocalizedString(32001))
listfolder.setInfo('video', {'Title': watson_addon.getLocalizedString(32001)})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, listfolder, isFolder=1)
# Archive
u=sys.argv[0]+"?url=Archive&mode=2"
listfolder = xbmcgui.ListItem(watson_addon.getLocalizedString(32002))
listfolder.setInfo('video', {'Title': watson_addon.getLocalizedString(32002)})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, listfolder, isFolder=1)
# Search recordings
u=sys.argv[0]+"?url=SearchRec&mode=7"
listfolder = xbmcgui.ListItem(watson_addon.getLocalizedString(32003))
listfolder.setInfo('video', {'Title': watson_addon.getLocalizedString(32003)})
xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, listfolder, isFolder=1)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Ask search string from user
def search(url):
keyboard = xbmc.Keyboard('', watson_addon.getLocalizedString(32004))
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText():
search_string = keyboard.getText().replace(" ","+")
searchrec("https://www.watson.fi/pctv/RSS?action=search&type=all&field=all&term="+search_string)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Search from programs *** Not in use ***
def searchproc(url):
auth_handler = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler.add_password(None, "http://www.watson.fi", watson_addon.getSetting("username"), watson_addon.getSetting("password"))
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth_handler))
request = urllib2.Request(url, headers=MYHEADERS)
searchcontent = opener.open(request).read()
# Save everyhing we need to tuples...
procsearchmatch=re.compile('<title>(.+?)</title>\n <description>(.+?)</description>\n <dc:date>(.+?)</dc:date>\n <guid isPermaLink="false">(.+?)</guid>\n <link>(.+?)</link>\n <source url="(.+?)">(.+?)</source>\n <media:content duration="(.+?)"/>\n').findall(searchcontent)
procsearchmatch.sort(key=operator.itemgetter(0), reverse=True)
# Add search results
for matchitem in procsearchmatch:
sendurl=matchitem[4]
sendday=matchitem[2].split("T")[0]
sendtime=matchitem[2][matchitem[2].find("T")+1:matchitem[2].find("+")]
sendname=matchitem[0]+" - "+sendday+" "+sendtime
sendname=sendname.replace("&#228;","a")
senddesc=matchitem[1].replace("&#228;","a")
senddesc=senddesc.replace("&#246;","o")
senddesc=senddesc.replace("&amp;","&")
#Format: addDir(name,url,mode,thumbnail, description, permlink)
addDir(sendname,sendurl.replace("&amp;","&"),4,"",senddesc, "")
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Add recording to 'favourites' by plink (seven digit recording id)
def addrecording(name, plink):
# Compile url
url="http://www.watson.fi/pctv/RSS?action=addfavorite&id="+plink
auth_handler = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler.add_password(None, "http://www.watson.fi", watson_addon.getSetting("username"), watson_addon.getSetting("password"))
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth_handler))
request = urllib2.Request(url, headers=MYHEADERS)
searchcontent = opener.open(request).read()
xbmcgui.Dialog().ok("Info","Recording %s \n added to recordings."%(name))
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def removerecording(url,name):
# Compile url
url="http://www.watson.fi/pctv/RSS?action=removerecording&id="+plink
auth_handler = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler.add_password(None, "http://www.watson.fi", watson_addon.getSetting("username"), watson_addon.getSetting("password"))
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth_handler))
request = urllib2.Request(url, headers=MYHEADERS)
searchcontent = opener.open(request).read()
xbmcgui.Dialog().ok("Info","Recording %s \n removed from recordings."%(name))
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def searchrec(url):
auth_handler = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler.add_password(None, "http://www.watson.fi", watson_addon.getSetting("username"), watson_addon.getSetting("password"))
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth_handler))
request = urllib2.Request(url, headers=MYHEADERS)
searchcontent = opener.open(request).read()
# Save everyhing we need to tuples...
recsearchmatch=re.compile('<title\>(.+?)<\/title\>\n <description\>(.+?)<\/description\>\n <dc:date\>(.+?)<\/dc:date\>\n <link\>(.+?)<\/link\>\n <guid isPermaLink="(.+?)"\>(.+?)<\/guid\>\n <source url="(.+?)"\>(.+?)<\/source\>\n <media:content url="(.+?)" medium="(.+?)" type="(.+?)" fileSize="(.+?)" expression="(.+?)" duration="(.+?)"\/\>\n <media:status state="(.+?)" reason="(.+?)" \/\>\n <media:community\><media:starRating average="(.+?)" min="(.+?)" max="(.+?)"\/\><\/media:community\>\n <media:thumbnail url="(.+?)" height="(.+?)" width="(.+?)"\/\>').findall(searchcontent)
recsearchmatch.sort(key=operator.itemgetter(2), reverse=True)
# Add search results
for matchitem in recsearchmatch:
sendurl=matchitem[8]
sendday=matchitem[2].split("T")[0]
sendtime=matchitem[2][matchitem[2].find("T")+1:matchitem[2].find("+")]
sendname=matchitem[0]+" - "+sendday+" "+sendtime
sendname=sendname.replace("&#228;","a")
senddesc=matchitem[1].replace("&#228;","a")
senddesc=senddesc.replace("&#246;","o")
senddesc=senddesc.replace("&amp;","&")
#Format: addDir(name,url,mode,thumbnail, description, permlink)
addDir(sendname,sendurl.replace("&amp;","&"),4,matchitem[17]+"?width=640&height=480",senddesc, matchitem[5])
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Fetch XML and parse channel list from there and make list of channels
def livetv(url):
auth_handler = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handler.add_password(None, "https://www.watson.fi", watson_addon.getSetting("username"), watson_addon.getSetting("password"))
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth_handler))
request = urllib2.Request(url, headers=MYHEADERS)
content = opener.open(request).read()
dom = minidom.parseString(content)
items = dom.getElementsByTagName('item')
for i in items:
programtitle=i.getElementsByTagName('title')[0].childNodes[0].nodeValue
programdesc=i.getElementsByTagName('description')[0].childNodes[0].nodeValue
programstream1=i.getElementsByTagName('media:content')[0].getAttribute("url")
programthumb=i.getElementsByTagName('media:thumbnail')[0].getAttribute("url")
addDir(programtitle,programstream1,6,programthumb+"?width=320&height=240",programdesc,"NoContext")
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Get first selection list and display items from tuples
def programs(url):
checked = []
ie=0
if LoginError==False:
for e in match:
if e[0].split("(")[0].rstrip() not in checked:
#print "e: "+e[0].split("(")[0]+", length: "+str(len(e[0].split("(")[0]))
checked.append(e[0].split("(")[0].rstrip())
checked.sort()
i=0
for item in checked:
#Format: addDir(name,url,mode,thumbnail, description, permlink)
itemname=item.replace("&#228;","a")
itemname=itemname.replace("&#196;","A")
itemname=itemname.replace("&#246;","o")
itemname=itemname.replace("&apos;","'")
itemname=itemname.replace("&amp;","&")
addDir(itemname,item,3,"","","NoContext")
i+=1
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Get first selection list and display items from tuples
def episodelist (url,name):
i=0
name=url
# Sort results by time
match.sort(key=operator.itemgetter(2), reverse=True)
#print "name: "+name.split("(")[0].rstrip()+", length: "+str(len(name.split("(")[0].rstrip()))
for matchitem in match:
if matchitem[0].split("(")[0].rstrip()==name.split("(")[0].rstrip():
#adddir uniques
sendurl=matchitem[8]
sendday=matchitem[2].split("T")[0]
sendtime=matchitem[2][matchitem[2].find("T")+1:matchitem[2].find("+")]
# sendchan=matchitem[7].split(" ")[0]
sendname=matchitem[0]+" - "+channeldict[matchitem[7].split(" ")[0]]+" - "+sendday+" "+sendtime
sendname=sendname.replace("&#228;","a")
sendname=sendname.replace("&#196;","A")
sendname=sendname.replace("&#246;","�")
sendname=sendname.replace("&amp;","&")
senddesc=matchitem[1].replace("&#228;","a")
senddesc=senddesc.replace("&#246;","o")
senddesc=senddesc.replace("&amp;","&")
#Format: addDir(name,url,mode,thumbnail, description, permlink)
addDir(sendname,sendurl.replace("&amp;","&"),4,matchitem[17]+"?width=640&height=480",senddesc, matchitem[5])
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Add item to XBMC display list
def addDir(name,url,mode,iconimage,pdesc,plink):
u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
contextMenuItems = []
if url.startswith("http"):
# Create context menu if needed
if plink != "NoContext":
contextMenuItems.append(('Download Video', 'XBMC.RunPlugin(%s?url=%s&name=%s&mode=9)'%(sys.argv[0],url, name)))
contextMenuItems.append(( "Plot", "XBMC.Action(Info)", ))
contextMenuItems.append(('Remove from recordings', 'XBMC.RunPlugin(%s?url=%s&name=%s&plink=%s&mode=10)'%(sys.argv[0],"removerecording",name,plink)))
if plink != "":
contextMenuItems.append(('Add to recordings', 'XBMC.RunPlugin(%s?url=%s&name=%s&plink=%s&mode=8)'%(sys.argv[0],"addrecording",name,plink)))
liz.addContextMenuItems( contextMenuItems )
liz.setInfo( type="Video", infoLabels={ "Title": name, 'Plot': pdesc } )
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
else:
liz.setInfo( type="Video", infoLabels={ "Title": name, 'Plot': pdesc } )
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
# Play LiveTV, url can be played directly
def playlive(url):
# Play selected video
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
# Read playlist
try:
response = urllib2.urlopen(url)
except urllib2.HTTPError as e:
print "DEBUG: ERROR; Can't open url "+url+". Code: "+str(e.code)
try:
firstplaylist=str(response.read())
except urllib2.HTTPError as e:
print "DEBUG: ERROR; Can't fetch channel playlist. Code: "+str(e.code)
try:
redirurl=str(response.geturl())
except urllib2.HTTPError as e:
print "DEBUG: ERROR; Can't get channel redirection url from headers. Code: "+str(e.code)
# Get correct urls for streams..playlist contains current program files???.
playurl={}
i=0
for line in firstplaylist.split("\n"):
if "m3u8" in line:
if i==0:
playurl["Lo"]=line
else:
playurl["Hi"]=line
i+=1
tmpstring1=redirurl.rpartition('/')
try:
liveplayurl=tmpstring1[0]+tmpstring1[1]+playurl["Hi"]+"?"+tmpstring1[2].split('?')[1]
#Format: addDir(name,url,mode,thumbnail, description, permlink)
except:
print "DEBUG: ERROR; creating final playlist url."
# Clear playlist before adding new stuff...
playlist.clear()
playlist.add(liveplayurl)
xbmc.Player().play( playlist)
while xbmc.Player().isPlaying():
xbmc.sleep(250)
# if xbmc.Player().onPlayBackStopped():
xbmc.Player().stop()
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Retrieve m3u8 file, the dirty, dirty, dirty way, parse it and get and create real playlist
def playlocal(file):
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
# Clear playlist before adding new stuff...
playlist.clear()
#playlist.add(file)
# Play from playlist
xbmc.Player().play(file)
while xbmc.Player().isPlaying():
xbmc.sleep(250)
xbmc.Player().stop()
xbmcplugin.endOfDirectory(int(sys.argv[1]))
# Retrieve m3u8 file, the dirty, dirty, dirty way, parse it and get and create real playlist
def playurl(url):
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
# Clear playlist before adding new stuff...
playlist.clear()
playlist.add(getplaylisturl(url))
# Play from playlist
xbmc.Player().play( playlist)
while xbmc.Player().isPlaying():
xbmc.sleep(250)
xbmc.Player().stop()
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def getplaylisturl(urlin):
playurllow=""
playurlhigh=""
# Compile and retrieve redirection and right npvr server
compiledurl='https://'+watson_addon.getSetting("username")+':'+watson_addon.getSetting("password")+'@'+urlin.split("//")[1]
try:
compiledurl='https://'+watson_addon.getSetting("username")+':'+watson_addon.getSetting("password")+'@'+urlin.split("//")[1]
urllib.urlretrieve(compiledurl, tmpfile)
except:
print "DEBUG: Error; Error creating playlist download URL."
# Read playlist
try:
fdbc=urllib.urlopen(compiledurl)
redirection=urlparse(fdbc.url)
redirectionNEW=redirection.geturl()
except:
e = sys.exc_info()[0]
print "DEBUG: Exception: "+str(e)
redirection=""
playurl={}
if "H264" in urlin:
linestring=open(tmpfile, 'r').read()
for line in linestring.split("\n"):
if "01.m3u8" in line:
playurl["Lo"]=line
elif "02.m3u8" in line:
playurl["Hi"]=line
tmpstring1=redirectionNEW.rpartition('/')
try:
finalplaylist=tmpstring1[0]+tmpstring1[1]+playurl["Hi"]+"?"+tmpstring1[2].split('?')[1]
#Format: addDir(name,url,mode,thumbnail, description, permlink)
except:
print "DEBUG: ERROR; creating final archive playlist url."
else:
linestring=open(tmpfile, 'r').read()
for line in linestring.split("\n"):
if "01.m3u8?session" in line:
playurllow=line
elif "02.m3u8?session" in line:
playurlhigh=line
if watson_addon.getSetting("bitrate") == 1:
finalplaylist="http://"+watson_addon.getSetting("username")+":"+watson_addon.getSetting("password")+"@"+redirection.netloc+"/recorder/resources/"+playurllow
elif watson_addon.getSetting("bitrate") == 0:
finalplaylist="http://"+watson_addon.getSetting("username")+":"+watson_addon.getSetting("password")+"@"+redirection.netloc+"/recorder/resources/"+playurlhigh
else:
finalplaylist="http://"+watson_addon.getSetting("username")+":"+watson_addon.getSetting("password")+"@"+redirection.netloc+"/recorder/resources/"+playurlhigh
return finalplaylist
# Download selected video
def downloadvideo(durl,dname):
downloadurl=getplaylisturl(durl)
ddir=watson_addon.getSetting("savedir")+dname.replace(':','-')
ddir=ddir.replace(' ','_')
# # Try to make download dir..
# try:
# os.makedirs(ddir)
# except:
# print "downloadvideo: download dir already exists or permission denied..."
# Get download url (playlist)
try:
urllib.urlretrieve(downloadurl, tmpfile2)
linestring=open(tmpfile2, 'r').read()
xbmcgui.Dialog().ok("Status","Downloading %s in background, \n file is saved to %s."%(dname.replace(':','-'), ddir))
except:
xbmcgui.Dialog().ok("Status","Error getting download url!")
# Fetch video files and create playlist from files.
savedir=watson_addon.getSetting("savedir")+dname.replace(':','-')
savedir=savedir.replace('(','')
savedir=savedir.replace(')','')
savedir=savedir.replace(' ','_')+".ts"
savedir=savedir.replace('&#228;','a')
savedir=savedir.replace("&#246;","o")
savedir=savedir.replace('&amp;','_')
playing=0
try:
for line in linestring.split("\n"):
if "session=" in line:
print "1"
# Open remote file for reading...
wwwfile=urllib.urlopen("https://"+downloadurl.split("/")[2]+"/recorder/resources/"+line)
print "2"
# Open local file for writing (append)...
localfile=open(savedir, 'ab+')
print "3"
# Write remote file to local file...
localfile.write(wwwfile.read())
print "...downloading..."
localfile.close()
print "ddir:"+ddir
print "savedir:"+savedir
print "4"
playlocal(savedir)
playing=1
print "5"
print "...downloading completed!"
#xbmcgui.Dialog().ok("Status","Download completed for %s !"%(savedir))
except:
print "Status","Error fetching video files!"
# added 9.2
xbmcplugin.endOfDirectory(int(sys.argv[1]))
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]
if paramstring.endswith("mode=9"):
downloadurl=paramstring.split('=')[1]+"="+paramstring.split('=')[2]+"="+paramstring.split('=')[3]+"="+paramstring.split('=')[4].split('&')[0]
param.update({'url' : downloadurl })
return param
# Main program
params=get_params()
url=None
name=None
mode=None
plink=None
LoginError=True
# Try to get XML list
try:
cookiejar=cookielib.CookieJar()
auth_handlerb = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth_handlerb.add_password(None, "http://www.watson.fi", watson_addon.getSetting("username"), watson_addon.getSetting("password"))
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(auth_handlerb),urllib2.HTTPCookieProcessor(cookiejar))
request = urllib2.Request(url_archive, headers=MYHEADERS)
urllib2.install_opener(opener)
content = opener.open(request).read()
# Save everyhing we need to tuples...
match=re.compile('<title\>(.+?)<\/title\>\n <description\>(.+?)<\/description\>\n <dc:date\>(.+?)<\/dc:date\>\n <link\>(.+?)<\/link\>\n <guid isPermaLink="(.+?)"\>(.+?)<\/guid\>\n <source url="(.+?)"\>(.+?)<\/source\>\n <media:content url="(.+?)" medium="(.+?)" type="(.+?)" fileSize="(.+?)" expression="(.+?)" duration="(.+?)"\/\>\n <media:status state="(.+?)" reason="(.+?)" \/\>\n <media:community\><media:starRating average="(.+?)" min="(.+?)" max="(.+?)"\/\><\/media:community\>\n <media:thumbnail url="(.+?)" height="(.+?)" width="(.+?)"\/\>').findall(content)
LoginError=False
except:
print "Error opening XML"
LoginError=True
# Get 'url'
try:
url=urllib.unquote_plus(params["url"])
except:
pass
# Get 'name'
try:
name=urllib.unquote_plus(params["name"])
except:
pass
try:
plink=urllib.unquote_plus(params["plink"])
except:
pass
try:
mode=int(params["mode"])
except:
pass
if mode==None or url==None or len(url)<1:
settings()
# Show main menu, livetv / archive / search programs / search recordings
elif mode==0:
INDEX()
# LiveTV
elif mode==1:
livetv('https://www.watson.fi/pctv/RSS?action=getavailableretvchannels')
# Archive
elif mode==2:
programs('https://www.watson.fi/pctv/RSS?action=getfavoriterecordings')
# Archive episodelist
elif mode==3:
episodelist(url,name)
# Play from download url...
elif mode==4:
playurl(url)
# Show settings if not defined or something wrong...
elif mode==5:
watson_addon.openSettings(url=sys.argv[0])
# Play live feed
elif mode==6:
playlive(url)
# Search records
elif mode==7:
search(url)
# Add recording to favorites / recordings
elif mode==8:
addrecording(name,plink)
# Download video
elif mode==9:
downloadvideo(url,name)
# Download video
elif mode==10:
removerecording(name,plink)
xbmcplugin.endOfDirectory(int(sys.argv[1]))