PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/IPTVPlayer/hosts/hostwrestlingnetwork.py

https://gitlab.com/zatoshi/iptvplayer-for-e2
Python | 337 lines | 303 code | 17 blank | 17 comment | 8 complexity | 4b962b96978c19157925f58b7d6ea7fe MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. ###################################################
  3. # LOCAL import
  4. ###################################################
  5. from Plugins.Extensions.IPTVPlayer.components.iptvplayerinit import TranslateTXT as _, SetIPTVPlayerLastHostError
  6. from Plugins.Extensions.IPTVPlayer.components.ihost import CHostBase, CBaseHostClass, CDisplayListItem, ArticleContent, RetHost, CUrlItem
  7. from Plugins.Extensions.IPTVPlayer.tools.iptvtools import CSelOneLink, printDBG, printExc, CSearchHistoryHelper, GetLogoDir, GetCookieDir
  8. from Plugins.Extensions.IPTVPlayer.libs.urlparserhelper import getDirectM3U8Playlist
  9. from Plugins.Extensions.IPTVPlayer.libs.urlparser import urlparser
  10. from Plugins.Extensions.IPTVPlayer.libs.youtube_dl.utils import clean_html
  11. from Plugins.Extensions.IPTVPlayer.libs.crypto.hash.sha1Hash import SHA1
  12. ###################################################
  13. ###################################################
  14. # FOREIGN import
  15. ###################################################
  16. from Components.config import config, ConfigInteger, ConfigSelection, ConfigYesNo, ConfigText, getConfigListEntry
  17. from datetime import timedelta
  18. from binascii import hexlify
  19. import re
  20. import urllib
  21. import time
  22. import random
  23. try: import simplejson as json
  24. except: import json
  25. ###################################################
  26. ###################################################
  27. # E2 GUI COMMPONENTS
  28. ###################################################
  29. from Plugins.Extensions.IPTVPlayer.components.asynccall import MainSessionWrapper
  30. from Screens.MessageBox import MessageBox
  31. from Components.config import config, ConfigSelection, getConfigListEntry
  32. ###################################################
  33. ###################################################
  34. # Config options for HOST
  35. ###################################################
  36. def GetConfigList():
  37. optionList = []
  38. return optionList
  39. ###################################################
  40. def gettytul():
  41. return 'http://wrestlingnetwork.tv/'
  42. class WrestlingNet(CBaseHostClass):
  43. MAIN_URL = 'http://wrestlingnetwork.tv/'
  44. MAIN_CAT_TAB = [{'category':'search', 'title':_('Search'), 'search_item':True},
  45. {'category':'search_history', 'title':_('Search history')} ]
  46. def __init__(self):
  47. printDBG("WrestlingNet.__init__")
  48. CBaseHostClass.__init__(self, {'history':'wrestling-network.net'})
  49. self.DEFAULT_ICON = 'http://static-server1.wrestling-network.net/images/layout/wnhd_5years_bug.png'
  50. self.cacheSubCategory = {}
  51. def _getFullUrl(self, url):
  52. if 0 < len(url) and not url.startswith('http'):
  53. url = self.MAIN_URL + url
  54. return url
  55. def listsTab(self, tab, cItem):
  56. printDBG("WrestlingNet.listsMainMenu")
  57. for item in tab:
  58. params = dict(cItem)
  59. params.update(item)
  60. params['name'] = 'category'
  61. self.addDir(params)
  62. def listsMainMenu(self, cItem, subNextCategory, nextCategory):
  63. printDBG("listsMainMenu")
  64. self.cacheSubCategory = {}
  65. sts, data = self.cm.getPage(cItem['url'])
  66. if not sts: return
  67. subCatsUrls = []
  68. catsData = self.cm.ph.getAllItemsBeetwenMarkers(data, '<ul class="sub-menu">', '</ul>', withMarkers=False)
  69. for catItem in catsData:
  70. tmp = re.compile('<a[^>]*?href="([^"]+?)"[^>]*?>([^<]+?)<').findall(catItem)
  71. for item in tmp:
  72. url = self._getFullUrl(item[0])
  73. title = self.cleanHtmlStr(item[1])
  74. catUrl = '/'.join( url.split('/')[:-1] )
  75. if catUrl not in self.cacheSubCategory:
  76. self.cacheSubCategory[catUrl] = []
  77. self.cacheSubCategory[catUrl].append({'url':url, 'title':title})
  78. subCatsUrls.append(url)
  79. data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="menu-main-menu', '</div>')[1]
  80. data = re.compile('<a[^>]*?href="([^"]+?)"[^>]*?>([^<]+?)<').findall(data)
  81. prevUrl = ''
  82. categories = []
  83. for item in data:
  84. url = self._getFullUrl(item[0])
  85. if url in subCatsUrls: continue
  86. title = self.cleanHtmlStr(item[1])
  87. if url in self.cacheSubCategory:
  88. category = subNextCategory
  89. else:
  90. category = nextCategory
  91. params = dict(cItem)
  92. params.update({'url':url, 'title':title})
  93. params['category'] = category
  94. self.addDir(params)
  95. def listSubCategory(self, cItem, nextCategory):
  96. printDBG("listSubCategory")
  97. tab = self.cacheSubCategory.get(cItem['url'], [])
  98. params = dict(cItem)
  99. params['category'] = nextCategory
  100. self.listsTab(tab, params)
  101. def listVideosByCategory(self, cItem, category):
  102. printDBG("WrestlingNet.listVideosByCategory")
  103. self._listVideos(cItem)
  104. def listSearchResult(self, cItem, searchPattern, searchType):
  105. printDBG("WrestlingNet.listSearchResult cItem[%s], searchPattern[%s] searchType[%s]" % (cItem, searchPattern, searchType))
  106. searchPattern = urllib.quote_plus(searchPattern)
  107. cItem.update({'url':self.MAIN_URL, 'srch':'?s=%s&submit=Search' % searchPattern})
  108. self._listVideos(cItem)
  109. def _listVideos(self, cItem):
  110. printDBG("WrestlingNet._listVideos")
  111. page = cItem.get('page', 1)
  112. url = cItem.get('url', '')
  113. if page > 1:
  114. url += '/page/%s' % page
  115. url += cItem.get('srch', '')
  116. sts, data = self.cm.getPage(url)
  117. if not sts: return
  118. if ('/page/%s?' % (page+1)) in data or ('/page/%s/' % (page+1)) in data:
  119. nextPage = True
  120. else: nextPage = False
  121. data = self.cm.ph.getAllItemsBeetwenMarkers(data, '<div class="content-container">', '<!-- close .content-container -->', withMarkers=False)
  122. for item in data:
  123. url = self.cm.ph.getSearchGroups(item, 'href="([^"]+?)"')[0]
  124. if '/contact' in url: continue
  125. icon = self.cm.ph.getSearchGroups(item, 'src="([^"]+?)"')[0]
  126. title = self.cm.ph.getDataBeetwenMarkers(item, '<h3', '</h3>')[1]
  127. if '' != url and '' != title:
  128. params = dict(cItem)
  129. params.update( {'title':self.cleanHtmlStr( title ), 'url':self._getFullUrl(url), 'desc':self.cleanHtmlStr( item ), 'icon':self._getFullUrl(icon)} )
  130. self.addVideo(params)
  131. if nextPage:
  132. params = params = dict(cItem)
  133. params.update({'title':_("Next page"), 'page':page+1})
  134. self.addDir(params)
  135. def getLinksForVideo(self, cItem):
  136. printDBG("WrestlingNet.getLinksForVideo [%s]" % cItem)
  137. urlTab = []
  138. sts, data = self.cm.getPage(cItem['url'])
  139. if not sts: return urlTab
  140. sts, data = self.cm.ph.getDataBeetwenMarkers(data, '<div class="solar-main-content">', '<!-- close .content-container -->', True)
  141. if not sts:
  142. SetIPTVPlayerLastHostError(_("Please visit '%s' from using web-browser form the PC. If links are available please report this problem.\nEmail: samsamsam@o2.pl") % cItem['url'])
  143. return urlTab
  144. data = data.split('<h2 style="text-align: center;">')
  145. if len(data): del data[0]
  146. re_links = re.compile('<a[^>]+?href="([^"]+?)"[^>]*?>([^<]+?)</a>')
  147. for item in data:
  148. type = self.cleanHtmlStr( item.split('</h2>')[0] )
  149. links = re_links.findall(item)
  150. for link in links:
  151. urlTab.append({'name':type + ' ' + link[1], 'url':link[0]})
  152. return urlTab
  153. def getResolvedURL(self, url):
  154. printDBG("WrestlingNet.getResolvedURL [%s]" % url)
  155. urlTab = []
  156. sts, data = self.cm.getPage(url)
  157. if not sts: return urlTab
  158. videoUrl = self.cm.ph.getSearchGroups(data, '<iframe[^>]+?src="([^"]+?)"')[0]
  159. if not videoUrl:
  160. videoUrl = self.cm.ph.getSearchGroups(data, "file: '([^']+?)'")[0]
  161. if '.m3u8' in videoUrl:
  162. urlTab = getDirectM3U8Playlist(videoUrl, checkExt=True)
  163. urlTab = self.up.getVideoLinkExt( videoUrl )
  164. return urlTab
  165. def getFavouriteData(self, cItem):
  166. return cItem['url']
  167. def getLinksForFavourite(self, fav_data):
  168. return self.getLinksForVideo({'url':fav_data})
  169. def handleService(self, index, refresh=0, searchPattern='', searchType=''):
  170. printDBG('WrestlingNet.handleService start')
  171. CBaseHostClass.handleService(self, index, refresh, searchPattern, searchType)
  172. name = self.currItem.get("name", None)
  173. category = self.currItem.get("category", '')
  174. printDBG( "WrestlingNet.handleService: ---------> name[%s], category[%s] " % (name, category) )
  175. searchPattern = self.currItem.get("search_pattern", searchPattern)
  176. self.currList = []
  177. #MAIN MENU
  178. if None == name:
  179. cItem = {'name':'category', 'url':self.MAIN_URL, 'icon':self.DEFAULT_ICON}
  180. self.listsMainMenu(cItem, 'list_subcategory', 'list_category')
  181. self.listsTab(WrestlingNet.MAIN_CAT_TAB, cItem)
  182. elif 'list_subcategory' == category:
  183. self.listSubCategory(self.currItem, 'list_category')
  184. #CATEGORY
  185. elif 'list_category' == category:
  186. self.listVideosByCategory(self.currItem, '')
  187. #WYSZUKAJ
  188. elif category in ["search", "search_next_page"]:
  189. cItem = dict(self.currItem)
  190. cItem.update({'search_item':False, 'name':'category'})
  191. self.listSearchResult(cItem, searchPattern, searchType)
  192. #HISTORIA WYSZUKIWANIA
  193. elif category == "search_history":
  194. self.listsHistory({'name':'history', 'category': 'search'}, 'desc', _("Type: "))
  195. else:
  196. printExc()
  197. CBaseHostClass.endHandleService(self, index, refresh)
  198. class IPTVHost(CHostBase):
  199. def __init__(self):
  200. CHostBase.__init__(self, WrestlingNet(), True)
  201. def getLogoPath(self):
  202. return RetHost(RetHost.OK, value = [GetLogoDir('wrestlingnetworklogo.png')])
  203. def getLinksForVideo(self, Index = 0, selItem = None):
  204. retCode = RetHost.ERROR
  205. retlist = []
  206. if not self.isValidIndex(Index): return RetHost(retCode, value=retlist)
  207. urlList = self.host.getLinksForVideo(self.host.currList[Index])
  208. for item in urlList:
  209. need_resolve = 1
  210. retlist.append(CUrlItem(item["name"], item["url"], need_resolve))
  211. return RetHost(RetHost.OK, value = retlist)
  212. # end getLinksForVideo
  213. def getResolvedURL(self, url):
  214. # resolve url to get direct url to video file
  215. retlist = []
  216. urlList = self.host.getResolvedURL(url)
  217. for item in urlList:
  218. need_resolve = 0
  219. retlist.append(CUrlItem(item["name"], item["url"], need_resolve))
  220. return RetHost(RetHost.OK, value = retlist)
  221. def convertList(self, cList):
  222. hostList = []
  223. searchTypesOptions = [] # ustawione alfabetycznie
  224. #searchTypesOptions.append(("Filmy", "filmy"))
  225. #searchTypesOptions.append(("Seriale","seriale"))
  226. for cItem in cList:
  227. hostLinks = []
  228. type = CDisplayListItem.TYPE_UNKNOWN
  229. possibleTypesOfSearch = None
  230. if 'category' == cItem['type']:
  231. if cItem.get('search_item', False):
  232. type = CDisplayListItem.TYPE_SEARCH
  233. possibleTypesOfSearch = searchTypesOptions
  234. else:
  235. type = CDisplayListItem.TYPE_CATEGORY
  236. elif cItem['type'] == 'video':
  237. type = CDisplayListItem.TYPE_VIDEO
  238. elif 'more' == cItem['type']:
  239. type = CDisplayListItem.TYPE_MORE
  240. elif 'audio' == cItem['type']:
  241. type = CDisplayListItem.TYPE_AUDIO
  242. if type in [CDisplayListItem.TYPE_AUDIO, CDisplayListItem.TYPE_VIDEO]:
  243. url = cItem.get('url', '')
  244. if '' != url:
  245. hostLinks.append(CUrlItem("Link", url, 1))
  246. title = self.host.cleanHtmlStr( cItem.get('title', '') )
  247. description = self.host.cleanHtmlStr( cItem.get('desc', '') )
  248. icon = self.host.cleanHtmlStr( cItem.get('icon', '') )
  249. hostItem = CDisplayListItem(name = title,
  250. description = description,
  251. type = type,
  252. urlItems = hostLinks,
  253. urlSeparateRequest = 1,
  254. iconimage = icon,
  255. possibleTypesOfSearch = possibleTypesOfSearch)
  256. hostList.append(hostItem)
  257. return hostList
  258. # end convertList
  259. def getSearchItemInx(self):
  260. try:
  261. list = self.host.getCurrList()
  262. for i in range( len(list) ):
  263. if list[i]['category'] == 'search':
  264. return i
  265. except:
  266. printDBG('getSearchItemInx EXCEPTION')
  267. return -1
  268. def setSearchPattern(self):
  269. try:
  270. list = self.host.getCurrList()
  271. if 'history' == list[self.currIndex]['name']:
  272. pattern = list[self.currIndex]['title']
  273. search_type = list[self.currIndex]['search_type']
  274. self.host.history.addHistoryItem( pattern, search_type)
  275. self.searchPattern = pattern
  276. self.searchType = search_type
  277. except:
  278. printDBG('setSearchPattern EXCEPTION')
  279. self.searchPattern = ''
  280. self.searchType = ''
  281. return