Advertisement
Guest User

nfbca default.py

a guest
Oct 29th, 2021
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.01 KB | None | 0 0
  1. import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse
  2. import re, sys, http.cookiejar, os
  3. import xbmc, xbmcgui, xbmcplugin, xbmcaddon, xbmcvfs
  4. import json as json
  5. from xbmcgui import ListItem
  6.  
  7. qp = urllib.parse.quote_plus
  8. uqp = urllib.parse.unquote_plus
  9.  
  10. # plugin constants
  11. version = "0.0.2+matrix.1"
  12. plugin = "nfbca - " + version
  13.  
  14. __settings__ = xbmcaddon.Addon(id='plugin.video.nfbca')
  15. rootDir = __settings__.getAddonInfo('path')
  16. if rootDir[-1] == ';':
  17. rootDir = rootDir[0:-1]
  18. rootDir = xbmc.translatePath(rootDir)
  19. settingsDir = __settings__.getAddonInfo('profile')
  20. settingsDir = xbmc.translatePath(settingsDir)
  21. cacheDir = os.path.join(settingsDir, 'cache')
  22.  
  23. programs_thumb = os.path.join(__settings__.getAddonInfo('path'), 'resources', 'media', 'programs.png')
  24. topics_thumb = os.path.join(__settings__.getAddonInfo('path'), 'resources', 'media', 'topics.png')
  25. search_thumb = os.path.join(__settings__.getAddonInfo('path'), 'resources', 'media', 'search.png')
  26. next_thumb = os.path.join(__settings__.getAddonInfo('path'), 'resources', 'media', 'next.png')
  27.  
  28. pluginhandle = int(sys.argv[1])
  29.  
  30. ########################################################
  31. ## URLs
  32. ########################################################
  33. API_URL = 'http://www.nfb.ca/api/v2/json/%sapi_key=0f40a3cd-f7a4-5518-b49f-b6dee4ab8148&platform=mobile_android'
  34. SEARCHURL = 'search/%s/?search_keywords=%s&qte=24&at_index=%d&'
  35. CHANNELLIST = 'channel/all/?'
  36. CHANNEL = 'channel/content/%s/?qte=24&at_index=%d&'
  37. MEDIAINFO = 'film/get_info/%s/?'
  38. FEATURED = 'pagefeature/all/%s?'
  39.  
  40. ########################################################
  41. ## Modes
  42. ########################################################
  43. M_DO_NOTHING = 0
  44. M_BROWSE_CHANNELS = 10
  45. M_BROWSE_CHANNEL_CONTENTS = 20
  46. M_SEARCH = 30
  47. M_PLAY = 40
  48. M_FEATURED = 50
  49.  
  50. ##################
  51. ## Class for items
  52. ##################
  53. class MediaItem:
  54. def __init__(self):
  55. self.ListItem = ListItem()
  56. self.Image = ''
  57. self.Url = ''
  58. self.Isfolder = False
  59. self.Mode = ''
  60.  
  61. ## Get URL
  62. def getURL( url ):
  63. print(plugin + ' getURL :: url = ' + url)
  64. cj = http.cookiejar.LWPCookieJar()
  65. opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
  66. opener.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2;)')]
  67. usock=opener.open(url)
  68. response=usock.read()
  69. usock.close()
  70. return response
  71.  
  72. # Save page locally
  73. def save_web_page(url):
  74. f = open(os.path.join(cacheDir, 'docnet.html'), 'w')
  75. data = getURL(url)
  76. f.write(data)
  77. f.close()
  78. return data
  79.  
  80. # Read from locally save page
  81. def load_local_page():
  82. f = open(os.path.join(cacheDir, 'docnet.html'), 'r')
  83. data = f.read()
  84. f.close()
  85. return data
  86.  
  87. # Read local json - Temporary
  88. def load_local_json(filename):
  89. f = open(os.path.join(cacheDir, filename), 'r')
  90. data = f.read()
  91. f.close()
  92. return data
  93.  
  94. # Remove HTML codes
  95. def cleanHtml( dirty ):
  96. clean = re.sub('"', '\"', dirty)
  97. clean = re.sub(''', '\'', clean)
  98. clean = re.sub('×', 'x', clean)
  99. clean = re.sub('&', '&', clean)
  100. clean = re.sub('‘', '\'', clean)
  101. clean = re.sub('’', '\'', clean)
  102. clean = re.sub('–', '-', clean)
  103. clean = re.sub('“', '\"', clean)
  104. clean = re.sub('”', '\"', clean)
  105. clean = re.sub('—', '-', clean)
  106. clean = re.sub('&', '&', clean)
  107. clean = re.sub("`", '', clean)
  108. clean = re.sub('<em>', '[I]', clean)
  109. clean = re.sub('</em>', '[/I]', clean)
  110. clean = re.sub('<strong>', '', clean)
  111. clean = re.sub('</strong>', '', clean)
  112. return clean
  113.  
  114. ########################################################
  115. ## Mode = None
  116. ## Build the main directory
  117. ########################################################
  118. def BuildMainDirectory():
  119. MediaItems = []
  120. main = [
  121. (__settings__.getLocalizedString(30000), topics_thumb, str(M_FEATURED), 'en'),
  122. (__settings__.getLocalizedString(30001), topics_thumb, str(M_FEATURED), 'fr')
  123. ]
  124. for name, thumb, mode, lang in main:
  125. Mediaitem = MediaItem()
  126. Url = ''
  127. Mode = mode
  128. Title = name
  129. Thumb = thumb
  130. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mode) + "&lang=" + lang
  131. Mediaitem.ListItem.setArt({'icon': Thumb})
  132. Mediaitem.ListItem.setLabel(Title)
  133. Mediaitem.Isfolder = True
  134. MediaItems.append(Mediaitem)
  135.  
  136. addDir(MediaItems)
  137. # End of Directory
  138. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  139.  
  140. def Featured(lang):
  141. # set content type so library shows more views and info
  142. xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  143.  
  144. # Get featured homepage contents
  145. URL = API_URL % (FEATURED % lang)
  146. data = getURL(URL)
  147. #data = load_local_json('featured.json')
  148. items = json.loads(data)
  149. itemList = items['data']
  150. itemList = [item for item in itemList]
  151. MediaItems = []
  152. for item in itemList:
  153. Mediaitem = MediaItem()
  154. Title = item['title']
  155. Slug = item['film_slug']
  156. MedUrl = MEDIAINFO % Slug
  157. Url = API_URL % MedUrl
  158. #print(Url)
  159. Mediaitem.Image = item['img']
  160. Plot = cleanHtml(item['description'])
  161. Mediaitem.Mode = M_PLAY
  162. #print(Url)
  163. Title = Title.encode('utf-8')
  164. #print(Title)
  165. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mediaitem.Mode) + "&name=" + qp(Title)
  166. Mediaitem.ListItem.setInfo('video', { 'Title': Title, 'Plot': Plot})
  167. Mediaitem.ListItem.setArt({'icon:': Mediaitem.Image})
  168. Mediaitem.ListItem.setLabel(Title)
  169. Mediaitem.ListItem.setProperty('IsPlayable', 'true')
  170. #Mediaitem.Isfolder = True
  171. MediaItems.append(Mediaitem)
  172. # One Mediaitem for Channels
  173. Mediaitem = MediaItem()
  174. Url = ''
  175. Mode = M_BROWSE_CHANNELS
  176. Title = __settings__.getLocalizedString(30012)
  177. Thumb = topics_thumb
  178. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mode) + "&lang=" + lang
  179. Mediaitem.ListItem.setArt({'icon': Thumb})
  180. Mediaitem.ListItem.setLabel(Title)
  181. Mediaitem.Isfolder = True
  182. MediaItems.append(Mediaitem)
  183. # One Mediaitem for Search
  184. Mediaitem = MediaItem()
  185. Url = ''
  186. Mode = M_SEARCH
  187. Title = __settings__.getLocalizedString(30013)
  188. Thumb = search_thumb
  189. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mode) + "&lang=" + lang
  190. Mediaitem.ListItem.setArt({'icon': Thumb})
  191. Mediaitem.ListItem.setLabel(Title)
  192. Mediaitem.Isfolder = True
  193. MediaItems.append(Mediaitem)
  194. addDir(MediaItems)
  195.  
  196. # End of Directory
  197. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  198. ## Set Default View Mode. This might break with different skins. But who cares?
  199. #xbmc.executebuiltin("Container.SetViewMode(503)")
  200. SetViewMode()
  201.  
  202. ###########################################################
  203. ## Mode == M_BROWSE_CHANNELS
  204. ## BROWSE CHANNELS
  205. ###########################################################
  206. def BrowseChannels(lang):
  207. #print('Browse Channels')
  208. # set content type so library shows more views and info
  209. xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  210.  
  211. # Get featured homepage contents
  212. URL = API_URL % CHANNELLIST
  213. data = getURL(URL)
  214. #data = load_local_json('channels.json')
  215. items = json.loads(data)
  216. itemList = items['data']
  217. itemList = [item for item in itemList if item.get('language', '') == lang]
  218. MediaItems = []
  219. for item in itemList:
  220. Mediaitem = MediaItem()
  221. Title = item['title']
  222. Slug = item['slug']
  223. StartIndex = 0
  224. ChUrl = CHANNEL % (Slug, StartIndex)
  225. Url = API_URL % ChUrl
  226. #print(Url)
  227. Mediaitem.Image = item['thumbnail']
  228. Plot = cleanHtml(item['description'])
  229. Mediaitem.Mode = M_BROWSE_CHANNEL_CONTENTS
  230. #print(Url)
  231. Title = Title.encode('utf-8')
  232. #print(Title)
  233. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mediaitem.Mode) + "&lang=" + lang
  234. Mediaitem.ListItem.setInfo('video', { 'Title': Title, 'Plot': Plot})
  235. Mediaitem.ListItem.setArt({'icon': Mediaitem.Image})
  236. Mediaitem.ListItem.setLabel(Title)
  237. Mediaitem.Isfolder = True
  238. MediaItems.append(Mediaitem)
  239. addDir(MediaItems)
  240.  
  241. # End of Directory
  242. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  243. ## Set Default View Mode. This might break with different skins. But who cares?
  244. #xbmc.executebuiltin("Container.SetViewMode(503)")
  245. SetViewMode()
  246.  
  247.  
  248. ###########################################################
  249. ## Mode == M_BROWSE_CHANNEL_CONTENTS
  250. ## BROWSE CONTENTS
  251. ###########################################################
  252. def Browse(url, lang):
  253. #print('Browse Contents')
  254. # set content type so library shows more views and info
  255. xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  256.  
  257. # Get contents for given url
  258. #print(url)
  259. ItemsPerPage, StartIndex = re.compile('qte=(\d+)&at_index=(\d+)&').findall(url)[0]
  260. ItemsPerPageInt = int( ItemsPerPage )
  261. StartIndexInt = int( StartIndex )
  262. #URL = API_URL + HOMESLIDE
  263. data = getURL(url)
  264. #data = load_local_json('search.json')
  265. items = json.loads(data)
  266. ItemCount = int(items['data_length'])
  267. if ItemCount < 1:
  268. return
  269. itemList = items['data']
  270. itemList = [item for item in itemList]
  271. MediaItems = []
  272. for item in itemList:
  273. Mediaitem = MediaItem()
  274. Genre = item['genres']
  275. Year = item['year']
  276. Rating = item['rating']
  277. #Playcount = item['viewed']
  278. Director = item['director']
  279. Mpaa = item['pg_rating']
  280. Title = item['title']
  281. Slug = item['slug']
  282. MedUrl = MEDIAINFO % Slug
  283. Url = API_URL % MedUrl
  284. #print(Url)
  285. Mediaitem.Image = item['big_thumbnail']
  286. Plot = cleanHtml(item['description'])
  287. Mediaitem.Mode = M_PLAY
  288. #print(Url)
  289. Title = Title.encode('utf-8')
  290. #print(Title)
  291. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mediaitem.Mode) + "&name=" + qp(Title)
  292. Mediaitem.ListItem.setInfo('video', { 'Title': Title, 'Plot': Plot,
  293. 'Genre': Genre, 'Year': Year,
  294. 'Rating': Rating, #'Playcount': Playcount,
  295. 'Director': Director, 'Mpaa': Mpaa})
  296. Mediaitem.ListItem.setArt({'icon': Mediaitem.Image})
  297. Mediaitem.ListItem.setProperty('IsPlayable', 'true')
  298. Mediaitem.ListItem.setLabel(Title)
  299. MediaItems.append(Mediaitem)
  300. NextStart = StartIndexInt + ItemsPerPageInt
  301. if NextStart < ItemCount:
  302. # One Mediaitem for Channels
  303. Mediaitem = MediaItem()
  304. Url = url.replace('at_index='+StartIndex, 'at_index='+str(NextStart))
  305. Mode = M_BROWSE_CHANNEL_CONTENTS
  306. Title = __settings__.getLocalizedString(30014)
  307. Thumb = next_thumb
  308. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mode) + "&name=" + urllib.quote_plus(Title)
  309. Mediaitem.ListItem.setArt({'icon': Thumb})
  310. Mediaitem.ListItem.setLabel(Title)
  311. Mediaitem.Isfolder = True
  312. MediaItems.append(Mediaitem)
  313. # One Mediaitem for Channels
  314. Mediaitem = MediaItem()
  315. Url = ''
  316. Mode = M_BROWSE_CHANNELS
  317. Title = __settings__.getLocalizedString(30012)
  318. Thumb = topics_thumb
  319. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mode) + "&lang=" + lang
  320. Mediaitem.ListItem.setArt({'icon': Thumb})
  321. Mediaitem.ListItem.setLabel(Title)
  322. Mediaitem.Isfolder = True
  323. MediaItems.append(Mediaitem)
  324. # One Mediaitem for Search
  325. Mediaitem = MediaItem()
  326. Url = ''
  327. Mode = M_SEARCH
  328. Title = __settings__.getLocalizedString(30013)
  329. Thumb = search_thumb
  330. Mediaitem.Url = sys.argv[0] + "?url=" + qp(Url) + "&mode=" + str(Mode) + "&lang=" + lang
  331. Mediaitem.ListItem.setArt({'icon': Thumb})
  332. Mediaitem.ListItem.setLabel(Title)
  333. Mediaitem.Isfolder = True
  334. MediaItems.append(Mediaitem)
  335. addDir(MediaItems)
  336.  
  337. # End of Directory
  338. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  339. ## Set Default View Mode. This might break with different skins. But who cares?
  340. #xbmc.executebuiltin("Container.SetViewMode(503)")
  341. SetViewMode()
  342.  
  343. ###########################################################
  344. ## Mode == M_PLAY
  345. ## Try to get a list of playable items and play it.
  346. ###########################################################
  347. def Play(url):
  348. if url == None or url == '':
  349. return
  350. #print('Getting Media Information to play')
  351. # Get contents for given url
  352. #print(url)
  353. #URL = API_URL + HOMESLIDE
  354. data = getURL(url)
  355. #data = load_local_json('mediainfo.json')
  356. items = json.loads(data)
  357. item = items['data'].get('film', '')
  358. Genre = item['genres']
  359. Year = item['year']
  360. Rating = item['rating']
  361. #Playcount = item['viewed']
  362. Director = item['director']
  363. Mpaa = item['pg_rating']
  364. Title = item['title']
  365. HQ = item['mobile_urls_versions'].get('HQ', '')
  366. vanilla = item['mobile_urls_versions'].get('vanilla', '')
  367. if HQ:
  368. Url = HQ
  369. else:
  370. Url = vanilla
  371. #print(Url)
  372. Thumb = item['big_thumbnail']
  373. Plot = cleanHtml(item['description'])
  374. #print(Url)
  375. Title = Title.encode('utf-8')
  376. listitem = ListItem(Title, Thumb, Thumb)
  377. listitem.setInfo('video', { 'Title': Title, 'Plot': Plot,
  378. 'Genre': Genre, 'Year': Year,
  379. 'Rating': Rating, #'Playcount': Playcount,
  380. 'Director': Director, 'Mpaa': Mpaa})
  381. listitem.setPath(Url)
  382. #vid = xbmcgui.ListItem(path=url)
  383. #xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(url, vid)
  384. #xbmc.executebuiltin("xbmc.PlayMedia("+url+")")
  385. xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
  386.  
  387. # Set View Mode selected in the setting
  388. def SetViewMode():
  389. try:
  390. # if (xbmc.getSkinDir() == "skin.confluence"):
  391. if __settings__.getSetting('view_mode') == "1": # List
  392. xbmc.executebuiltin('Container.SetViewMode(502)')
  393. if __settings__.getSetting('view_mode') == "2": # Big List
  394. xbmc.executebuiltin('Container.SetViewMode(51)')
  395. if __settings__.getSetting('view_mode') == "3": # Thumbnails
  396. xbmc.executebuiltin('Container.SetViewMode(500)')
  397. if __settings__.getSetting('view_mode') == "4": # Poster Wrap
  398. xbmc.executebuiltin('Container.SetViewMode(501)')
  399. if __settings__.getSetting('view_mode') == "5": # Fanart
  400. xbmc.executebuiltin('Container.SetViewMode(508)')
  401. if __settings__.getSetting('view_mode') == "6": # Media info
  402. xbmc.executebuiltin('Container.SetViewMode(504)')
  403. if __settings__.getSetting('view_mode') == "7": # Media info 2
  404. xbmc.executebuiltin('Container.SetViewMode(503)')
  405. except:
  406. print("SetViewMode Failed: " + __settings__.getSetting('view_mode'))
  407. print("Skin: " + xbmc.getSkinDir())
  408.  
  409. # Search documentaries
  410. def SEARCH(url, lang):
  411. if url is None or url == '':
  412. keyb = xbmc.Keyboard('', 'Search NFB')
  413. keyb.doModal()
  414. if (keyb.isConfirmed() == False):
  415. return
  416. search = keyb.getText()
  417. if search is None or search == '':
  418. return
  419. #search = search.replace(" ", "+")
  420. encSrc = urllib.parse.quote(search)
  421. SearchIndex = 0
  422. Surl = SEARCHURL % (lang, encSrc, SearchIndex)
  423. url = API_URL % Surl
  424.  
  425. Browse(url, lang)
  426.  
  427. ## Get Parameters
  428. def get_params():
  429. param = []
  430. paramstring = sys.argv[2]
  431. if len(paramstring) >= 2:
  432. params = sys.argv[2]
  433. cleanedparams = params.replace('?', '')
  434. if (params[len(params) - 1] == '/'):
  435. params = params[0:len(params) - 2]
  436. pairsofparams = cleanedparams.split('&')
  437. param = {}
  438. for i in range(len(pairsofparams)):
  439. splitparams = {}
  440. splitparams = pairsofparams[i].split('=')
  441. if (len(splitparams)) == 2:
  442. param[splitparams[0]] = splitparams[1]
  443. return param
  444.  
  445. def addDir(Listitems):
  446. if Listitems is None:
  447. return
  448. Items = []
  449. for Listitem in Listitems:
  450. Item = Listitem.Url, Listitem.ListItem, Listitem.Isfolder
  451. Items.append(Item)
  452. handle = pluginhandle
  453. xbmcplugin.addDirectoryItems(handle, Items)
  454. #xbmcplugin.addDirectoryItem(handle=pluginhandle, url, listitem, isFolder)
  455. #print('adding items')
  456.  
  457. if not os.path.exists(settingsDir):
  458. os.mkdir(settingsDir)
  459. if not os.path.exists(cacheDir):
  460. os.mkdir(cacheDir)
  461.  
  462. params = get_params()
  463. url = None
  464. name = None
  465. mode = None
  466. titles = None
  467. lang = None
  468. try:
  469. url = uqp(params["url"])
  470. except:
  471. pass
  472. try:
  473. name = uqp(params["name"])
  474. except:
  475. pass
  476. try:
  477. mode = int(params["mode"])
  478. except:
  479. pass
  480. try:
  481. titles = uqp(params["titles"])
  482. except:
  483. pass
  484. try:
  485. lang = params['lang']
  486. except:
  487. pass
  488.  
  489. xbmc.log( "Mode: " + str(mode) )
  490. #print("URL: " + str(url))
  491. #print("Name: " + str(name))
  492. #print("Title: " + str(titles))
  493.  
  494. if mode == None:
  495. BuildMainDirectory()
  496. elif mode == M_DO_NOTHING:
  497. print('Doing Nothing')
  498. elif mode == M_SEARCH:
  499. SEARCH(url, lang)
  500. elif mode == M_BROWSE_CHANNELS:
  501. BrowseChannels(lang)
  502. elif mode == M_BROWSE_CHANNEL_CONTENTS:
  503. Browse(url, lang)
  504. elif mode == M_PLAY:
  505. Play(url)
  506. elif mode == M_FEATURED:
  507. Featured(lang)
  508.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement