/plugin.video.sdarot.tv/sdarottv.py

https://github.com/barakile/xbmc-israel · Python · 320 lines · 240 code · 60 blank · 20 comment · 54 complexity · c73a1bb713249568da418065237b3821 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """
  3. Plugin for streaming video content from www.sdarot.co.in
  4. """
  5. import urllib, urllib2, re, os, sys
  6. import xbmcaddon, xbmc, xbmcplugin, xbmcgui
  7. import HTMLParser
  8. import json
  9. import cookielib
  10. import unicodedata
  11. ADDON = xbmcaddon.Addon(id='plugin.video.sdarot.tv')
  12. ##General vars
  13. __plugin__ = "Sdarot.TV Video"
  14. __author__ = "Cubicle"
  15. __image_path__ = ''
  16. __settings__ = xbmcaddon.Addon(id='plugin.video.sdarot.tv')
  17. __language__ = __settings__.getLocalizedString
  18. __PLUGIN_PATH__ = __settings__.getAddonInfo('path')
  19. LIB_PATH = xbmc.translatePath( os.path.join( __PLUGIN_PATH__, 'resources', 'lib' ) )
  20. sys.path.append (LIB_PATH)
  21. dbg = False # used for simple downloader logging
  22. #DOMAIN='http://sdarot.wf'
  23. DOMAIN = __settings__.getSetting("domain")
  24. print "Sdarot Domain=" + DOMAIN
  25. from sdarotcommon import *
  26. path = xbmc.translatePath(__settings__.getAddonInfo("profile"))
  27. cookie_path = os.path.join(path, 'sdarot-cookiejar.txt')
  28. print("Loading cookies from :" + repr(cookie_path))
  29. cookiejar = cookielib.LWPCookieJar(cookie_path)
  30. if os.path.exists(cookie_path):
  31. try:
  32. cookiejar.load()
  33. except:
  34. pass
  35. elif not os.path.exists(path):
  36. os.makedirs(path)
  37. cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)
  38. opener = urllib2.build_opener(cookie_handler)
  39. urllib2.install_opener(opener)
  40. #print "built opener:" + str(opener)
  41. def LOGIN():
  42. #print("LOGIN is running now!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  43. loginurl = DOMAIN+'/login'
  44. if ADDON.getSetting('username')=='':
  45. dialog = xbmcgui.Dialog()
  46. xbmcgui.Dialog().ok('Sdarot','www.sdarot.tv התוסף דורש חשבון חינמי באתר' ,' במסך הבא יש להכניס את שם המשתמש והסיסמא')
  47. if ADDON.getSetting('username')=='':
  48. search_entered = ''
  49. keyboard = xbmc.Keyboard(search_entered, 'נא הקלד שם משתמש')
  50. keyboard.doModal()
  51. if keyboard.isConfirmed():
  52. search_entered = keyboard.getText()
  53. ADDON.setSetting('username',search_entered)
  54. if ADDON.getSetting('user_password')=='':
  55. search_entered = ''
  56. keyboard = xbmc.Keyboard(search_entered, 'נא הקלד סיסמא')
  57. keyboard.doModal()
  58. if keyboard.isConfirmed():
  59. search_entered = keyboard.getText()
  60. ADDON.setSetting('user_password',search_entered)
  61. username = ADDON.getSetting('username')
  62. password = ADDON.getSetting('user_password')
  63. if not username or not password:
  64. print "Sdarot tv:no credencials found skipping login"
  65. return
  66. print "Trying to login to sdarot tv site username:" + username
  67. page = getData(url=loginurl,timeout=0,postData="username=" + username + "&password=" + password +"&submit_login=התחבר",referer=DOMAIN+"/");
  68. def MAIN_MENU():
  69. # check's if login is required.
  70. print "check if logged in already"
  71. page = getData(DOMAIN,referer="")
  72. match = re.compile('<span class="blue" id="logout"><a href="/log(.*?)">').findall(page)
  73. if len(match)!= 1 :
  74. print "login required"
  75. LOGIN()
  76. else:
  77. print "already logged in."
  78. addDir("הכל א-ת","all-heb",2,'');
  79. addDir("הכל a-z","all-eng",2,'');
  80. addDir("חפש",DOMAIN+"/search",6,'')
  81. def SearchSdarot(url):
  82. search_entered = ''
  83. keyboard = xbmc.Keyboard(search_entered, "חפש כאן")
  84. keyboard.doModal()
  85. if keyboard.isConfirmed():
  86. search_entered = keyboard.getText()
  87. page = getData(url=url,timeout=0,postData="search=" + search_entered)
  88. # print page
  89. matches = re.compile('<a href="/watch/(\d+)-(.*?)">').findall(page)
  90. print matches
  91. #needs to remove duplicted result (originaly in site
  92. matches = [ matches[i] for i,x in enumerate(matches) if x not in matches[i+1:]]
  93. print matches
  94. for match in matches:
  95. series_id = match[0]
  96. link_name = match[1]
  97. image_link=DOMAIN+"/media/series/"+str(match[0])+".jpg"
  98. series_link=DOMAIN+"/watch/"+str(match[0])+"/"+match[1]
  99. addDir(link_name,series_link,"3&image="+urllib.quote(image_link)+"&series_id="+series_id+"&series_name="+urllib.quote(link_name),image_link)
  100. def INDEX_AZ(url):
  101. page = getData(DOMAIN+'/series');
  102. matches = re.compile('<a href="/watch/(\d+)-(.*?)">.*?</noscript>.*?<div>(.*?)</div>').findall(page)
  103. sr_arr = []
  104. idx = 0
  105. i=0
  106. if url == "all-eng":
  107. idx = 1
  108. for match in matches:
  109. series_id = match[0]
  110. link_name = match[1]
  111. name = HTMLParser.HTMLParser().unescape(match[2])
  112. m_arr = name.split(" / ")
  113. if (len(m_arr)>1) and (idx==1):
  114. sr_arr.append(( series_id, link_name, m_arr[1].strip() ))
  115. else:
  116. sr_arr.append(( series_id, link_name, m_arr[0].strip() ))
  117. i=i+1
  118. sr_sorted = sorted(sr_arr,key=lambda sr_arr: sr_arr[2])
  119. for key in sr_sorted:
  120. series_link=DOMAIN+"/watch/"+str(key[0])+"/"+key[1]
  121. image_link=DOMAIN+"/media/series/"+str(key[0])+".jpg"
  122. addDir(key[2],series_link,"3&image="+urllib.quote(image_link)+"&series_id="+str(key[0])+"&series_name="+urllib.quote(key[1]),image_link)
  123. xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
  124. def sdarot_series(url):
  125. series_id=urllib.unquote_plus(params["series_id"])
  126. series_name=urllib.unquote_plus(params["series_name"])
  127. image_link=urllib.unquote_plus(params["image"])
  128. downloadEnabled = False
  129. opener.addheaders = [('Referer',url)]
  130. opener.open(DOMAIN+'/landing/'+series_id).read()
  131. # print "sdarot_series: Fetching URL:"+url
  132. try:
  133. page = opener.open(url).read()
  134. print cookiejar
  135. except urllib2.URLError, e:
  136. print 'sdarot_season: got http error ' +str(e.code) + ' fetching ' + url + "\n"
  137. raise e
  138. #page = getData(url);
  139. #print "Page Follows:\n"
  140. #print page
  141. #<ul id="season">
  142. block_regexp='id="season">(.*?)</ul>'
  143. seasons_list = re.compile(block_regexp,re.I+re.M+re.U+re.S).findall(page)[0]
  144. regexp='>(\d+)</a'
  145. matches = re.compile(regexp).findall(seasons_list)
  146. for season in matches:
  147. downloadMenu = []
  148. if downloadEnabled:
  149. downloadUrl = "XBMC.RunPlugin(plugin://plugin.video.sdarot.tv/?mode=7&url=" + url + "&season_id="+str(season)+"&series_id="+str(series_id) + ")"
  150. downloadMenu.append(('הורד עונה', downloadUrl,))
  151. addDir("עונה "+ str(season),url,"5&image="+urllib.quote(image_link)+"&season_id="+str(season)+"&series_id="+str(series_id)+"&series_name="+urllib.quote(series_id),image_link,contextMenu=downloadMenu)
  152. xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
  153. def sdarot_season(url):
  154. series_id=urllib.unquote_plus(params["series_id"])
  155. series_name=urllib.unquote_plus(params["series_name"])
  156. season_id=urllib.unquote_plus(params["season_id"])
  157. image_link=urllib.unquote_plus(params["image"])
  158. page = getData(url=DOMAIN+"/ajax/watch",timeout=0,postData="episodeList=true&serie="+series_id+"&season="+season_id);
  159. episodes=json.loads(page)
  160. if episodes is None or (len(episodes)==0):
  161. xbmcgui.Dialog().ok('Error occurred',"לא נמצאו פרקים לעונה")
  162. return
  163. print episodes
  164. for i in range (0, len(episodes)) :
  165. epis= str(episodes[i]['episode'])
  166. addVideoLink("פרק "+epis, url, "4&episode_id="+epis+"&image="+urllib.quote(image_link)+"&season_id="+str(season_id)+"&series_id="+str(series_id)+"&series_name="+urllib.quote(series_id),image_link, '')
  167. xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
  168. def download_season(url):
  169. import SimpleDownloader as downloader
  170. downloader = downloader.SimpleDownloader()
  171. downloader.dbg = False
  172. series_id=urllib.unquote_plus(params["series_id"])
  173. season_id=urllib.unquote_plus(params["season_id"])
  174. page = getData(url=DOMAIN+"/ajax/watch",timeout=0,postData="episodeList=true&serie="+series_id+"&season="+season_id);
  175. episodes=json.loads(page)
  176. if episodes is None or (len(episodes)==0):
  177. xbmcgui.Dialog().ok('Error occurred',"לא נמצאו פרקים לעונה")
  178. return
  179. print "Download sdarot series=" + series_id + " season=" + season_id + " #episodes=" + str(len(episodes))
  180. for i in range (0, len(episodes)) :
  181. epis= str(episodes[i]['episode'])
  182. finalVideoUrl,VID = getFinalVideoUrl(series_id,season_id,epis,silent=True)
  183. if finalVideoUrl == None :
  184. continue
  185. print "Downloading:" + str(finalVideoUrl)
  186. fileName = 'S' + str(season_id).zfill(2) + 'E' + str(epis).zfill(2) + '_' + str(VID) + '.mp4'
  187. download_path = os.path.join(path,str(series_id))
  188. if not os.path.exists(download_path):
  189. os.makedirs(download_path)
  190. finalFileName = os.path.join(download_path,fileName)
  191. if not os.path.isfile(finalFileName):
  192. #progress = xbmcgui . DialogProgress ( )
  193. #progress.create ( "XBMC ISRAEL" , "Downloading " , '' , 'Please Wait' )
  194. try :
  195. #downloader . download ( finalVideoUrl , download_path , progress )
  196. downloaderParams = { "url": finalVideoUrl, "download_path": download_path }
  197. downloader.download(fileName, downloaderParams,async=True)
  198. except Exception, e:
  199. print str(e)
  200. pass
  201. def sdarot_movie(url):
  202. series_id=urllib.unquote_plus(params["series_id"])
  203. series_name=urllib.unquote_plus(params["series_name"])
  204. season_id=urllib.unquote_plus(params["season_id"])
  205. image_link=urllib.unquote_plus(params["image"])
  206. episode_id=urllib.unquote_plus(params["episode_id"])
  207. title = series_name + "עונה " + season_id + " פרק" + episode_id
  208. finalUrl,VID = getFinalVideoUrl(series_id,season_id,episode_id)
  209. print "finalUrl" + finalUrl
  210. player_url=DOMAIN+'/templates/frontend/blue_html5/player/jwplayer.flash.swf'
  211. liz = xbmcgui.ListItem(title, path=finalUrl, iconImage=params["image"], thumbnailImage=params["image"])
  212. liz.setInfo(type="Video", infoLabels={ "Title": title })
  213. liz.setProperty('IsPlayable', 'true')
  214. #print finalUrl
  215. xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=liz)
  216. ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=finalUrl, listitem=liz, isFolder=False)
  217. params = getParams(sys.argv[2])
  218. print "params:"
  219. print params
  220. url=None
  221. name=None
  222. mode=None
  223. module=None
  224. page=None
  225. try:
  226. url=urllib.unquote_plus(params["url"])
  227. except:
  228. pass
  229. try:
  230. name=urllib.unquote_plus(params["name"])
  231. except:
  232. pass
  233. try:
  234. mode=int(params["mode"])
  235. except:
  236. pass
  237. try:
  238. module=urllib.unquote_plus(params["module"])
  239. except:
  240. pass
  241. try:
  242. page=urllib.unquote_plus(params["page"])
  243. except:
  244. pass
  245. if mode==None or url==None or len(url)<1:
  246. MAIN_MENU()
  247. elif mode==2:
  248. INDEX_AZ(url)
  249. elif mode==3:
  250. sdarot_series(url)
  251. elif mode==4:
  252. sdarot_movie(url)
  253. elif mode==5:
  254. sdarot_season(url)
  255. elif mode==6:
  256. SearchSdarot(url)
  257. elif mode==7:
  258. download_season(url)
  259. xbmcplugin.setPluginFanart(int(sys.argv[1]),xbmc.translatePath( os.path.join( __PLUGIN_PATH__,"fanart.jpg") ))
  260. xbmcplugin.endOfDirectory(int(sys.argv[1]),cacheToDisc=0)