Advertisement
Guest User

Untitled

a guest
Jan 19th, 2019
1,840
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 31.39 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import sys
  4. import os
  5. import urllib
  6. import urllib2
  7. import json
  8. import xbmc
  9. import xbmcgui
  10. import xbmcplugin
  11. import xbmcaddon
  12. import xbmcvfs
  13. import base64
  14. import time
  15. import inputstreamhelper
  16. import ssl
  17. import uuid
  18. import requests
  19.  
  20. __addon_id__= 'plugin.video.hbogopl'
  21. __Addon = xbmcaddon.Addon(__addon_id__)
  22. __settings__ = xbmcaddon.Addon(id='plugin.video.hbogopl')
  23.  
  24. UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36'
  25. MUA = 'Dalvik/2.1.0 (Linux; U; Android 8.0.0; Nexus 5X Build/OPP3.170518.006)'
  26. xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  27. se = __settings__.getSetting('se')
  28. language = __settings__.getSetting('language')
  29. if language == '0':
  30.     lang = 'Polish'
  31.     Code = 'POL'
  32.     srtsubs_path = xbmc.translatePath('special://temp/hbogo.Polish.Forced.srt')
  33. elif language == '1':
  34.     lang = 'Polish'
  35.     Code = 'POL'
  36.     srtsubs_path = xbmc.translatePath('special://temp/hbogo.Polish.Forced.srt')
  37. elif language == '2':
  38.     lang = 'English'
  39.     Code = 'ENG'
  40.     srtsubs_path = xbmc.translatePath('special://temp/hbogo.English.Forced.srt')
  41.    
  42.  
  43. md = xbmc.translatePath(__Addon.getAddonInfo('path') + "/resources/media/")
  44. search_string = urllib.unquote_plus(__settings__.getSetting('lastsearch'))
  45.  
  46. operator = __settings__.getSetting('operator')
  47. op_ids = [
  48. '00000000-0000-0000-0000-000000000000', # Anonymous NonAuthenticated
  49. '07b113ce-1c12-4bfd-9823-db951a6b4e87', # nc+
  50. 'a35f8cd2-05d7-4c0f-832f-0ddfad3b585d', # Plus
  51. 'c5ff7517-8ef8-4346-86c7-0fb328848671', # UPC
  52. '7021fee7-bab1-4b4b-b91c-a2dc4fdd7a05', # Vectra
  53. '22eaaeb6-1575-419f-9f1b-af797e86b9ee', # PLAY
  54. '598a984f-bc08-4e77-896b-a82d8d6ea8de', # Multimedia Polska
  55. 'c454b13c-5c82-4a01-854f-c34b2901d1b2', # Netia
  56. '48b81f9b-cb72-48cd-85d2-e952f78137c0', # Orange
  57. '82ae5dfd-9d29-4059-a843-2aa16449c42a', # INEA
  58. '357890f0-2698-445b-8712-b82f715b0648', # TOYA
  59. '5eb57ea8-9cd7-4bbf-8c6c-e56b186dd5c0', # JAMBOX
  60. '2e0325fa-d4b3-41eb-a9e4-0a36ee59aec5', # PROMAX
  61. '892771be-a48c-46ab-a0d0-3f51cdc50cf2', # Asta-Net
  62. '6a47f04f-cdd6-428b-abb5-135e38a43b38', # TK Chopin
  63. '36f365ac-4ca2-4e8b-9b21-14479e5fe6bb', # ELSAT
  64. '99eed640-107c-4732-81d0-59305ff6b520', # Eltronik
  65. 'f7f4d300-23ab-4b79-bb35-49568eb7cd4a', # SatFilm
  66. '5893f3c1-0bcd-4ae3-b434-45666925b5d1', # Master
  67. '8f34fcd8-3b74-4c16-b91c-c8375ab3ffdb', # STANSAT
  68. '878e69aa-be98-4a7d-a08e-b11c7330d8b3', # Dialog
  69. 'b49a6c5d-033d-4bf1-b273-37ba188aef97', # Internetia
  70. '62f7b31b-c866-4ff3-a7a1-800fac10de16', # Petrotel
  71. '1366289b-86ae-4695-8d4b-a6b14eacdd8b', # Cinema City – promocja
  72. '64d88671-b490-44b9-b1ee-e145347732b3', # Samsung - promocja
  73. '57332e2f-958c-4a83-86cc-e569842868a2', # Player+
  74. 'b7018ed3-1858-4436-8e7f-d92a6d0b9bfc', # HBO GO Vip/Club Poland
  75. 'dbaf3435-6ee2-4a79-af13-dac5a1c550a3', # HBO Polska
  76. ]
  77. op_id = op_ids[int(operator)];
  78.  
  79.  
  80. username = __settings__.getSetting('username')
  81. password = __settings__.getSetting('password')
  82.  
  83. individualization = __settings__.getSetting('individualization')
  84. goToken = ""
  85. customerId = __settings__.getSetting('customerId')
  86. GOcustomerId = ""
  87. sessionId = '00000000-0000-0000-0000-000000000000'
  88.  
  89. loggedin_headers = {
  90.     'User-Agent': UA,
  91.     'Accept': '*/*',
  92.     'Accept-Language': 'en-US,en;q=0.5',
  93.     'Referer': 'https://www.hbogo.pl/',
  94.     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  95.     'Origin': 'https://www.hbogo.pl',
  96.     'X-Requested-With': 'XMLHttpRequest',
  97.     'GO-Language': 'POL',
  98.     'GO-requiredPlatform': 'CHBR',
  99.     'GO-Token': '',
  100.     'GO-SessionId': '',
  101.     'GO-swVersion': '4.8.0',
  102.     'GO-CustomerId': '',
  103.     'Connection': 'keep-alive',
  104.     'Accept-Encoding': ''
  105. }
  106.  
  107. loggedviahbo_headers = {
  108. 'GO-requiredPlatform': 'CHBR',
  109. 'Origin': 'https://hbogo.pl',
  110. 'Accept-Encoding': '',
  111. 'Accept-Language': 'en-US,en;q=0.9',
  112. 'User-Agent': UA,
  113. 'Content-Type': 'application/json',
  114. 'Accept': '*/*',
  115. 'Referer': 'https://hbogo.pl/',
  116. 'GO-swVersion': '4.7.4',
  117. 'Connection': 'keep-alive',
  118. 'GO-CustomerId': ''
  119. }
  120.  
  121. def LOGINVIAHBOPAYLOAD(indiv):
  122.     return {
  123. 'Id':'',
  124. 'Action':'L',
  125. 'IsPromo':False,
  126. 'OperatorId':op_id,
  127. 'IsAnonymus':False,
  128. 'EmailAddress':username,
  129. 'Password':password,
  130. 'Nick':'',
  131. 'BirthYear':0,
  132. 'SubscribeForNewsletter':False,
  133. 'IpAddress':'',
  134. 'OperatorName':'HBO Poland',
  135. 'Language':'POL',
  136. 'CustomerCode':'',
  137. 'ServiceCode':'HBO_Premium',
  138. 'CountryName':'Poland',
  139. 'AppLanguage':'POL',
  140. 'AudioLanguage':'POL',
  141. 'DefaultSubtitleLanguage':'POL',
  142. 'AutoPlayNext':False,
  143. 'ProfileName':'',
  144. 'SubtitleSize':'MEDIUM',
  145. 'IsDefaultProfile':True,
  146. 'Gender':0,
  147. 'ZipCode':'',
  148. 'FirstName':'',
  149. 'LastName':'',
  150. 'SubscState':'VALID',
  151. 'CurrentDevice':{
  152.     'Id':'',
  153.     'Individualization':indiv,
  154.     'Name':'COMP',
  155.     'Platform':'COMP',
  156.     'CreatedDate':time.strftime('%d/%m/%Y'),
  157.     'IsDeleted':False,
  158.     'OSName':'Linux',
  159.     'Brand':'Chrome',
  160.     'Modell':'61.0.3163',
  161.     'SWVersion':'4.7.4'
  162. }}
  163.  
  164.  
  165. # Zapisz dane uwierzytelniania na stałe; jest wykonywane raz
  166. def storeIndiv(indiv, custid):
  167.     global individualization
  168.     global customerId
  169.     individualization = __settings__.getSetting('individualization')
  170.     if individualization == "":
  171.         __settings__.setSetting('individualization', indiv)
  172.         individualization = indiv
  173.  
  174.     customerId = __settings__.getSetting('customerId')
  175.     if customerId == "":
  176.         __settings__.setSetting('customerId', custid)
  177.         customerId = custid
  178.  
  179.  
  180. # Zarejestruj urządzenie na platformie; jest wykonywane raz
  181. def SILENTREGISTER():
  182.     global goToken
  183.     global individualization
  184.     global customerId
  185.     global sessionId
  186.    
  187.     #За HBO Polska
  188.     if op_id =='dbaf3435-6ee2-4a79-af13-dac5a1c550a3':
  189.         payload = LOGINVIAHBOPAYLOAD("")
  190.         req = urllib2.Request('https://api.ugw.hbogo.eu/v3.0/Authentication/POL/JSON/POL/COMP', json.dumps(payload), loggedviahbo_headers)
  191.         opener = urllib2.build_opener()
  192.         f = opener.open(req)
  193.         jsonrsp = json.loads(f.read())
  194.         try:
  195.             if jsonrsp['ErrorMessage']:
  196.                 xbmcgui.Dialog().ok('Błąd', jsonrsp['Error'])
  197.         except:
  198.             #goToken = jsonrsp['Token']
  199.             sessionId = jsonrsp['SessionId']
  200.             custid = jsonrsp['Customer']['Id']
  201.             indiv = jsonrsp['Customer']['CurrentDevice']['Individualization']
  202.             storeIndiv(indiv, custid)
  203.        
  204.     #За inni operatorzy
  205.     else:
  206.         storeIndiv(str(uuid.uuid1()), '00000000-0000-0000-0000-000000000000')
  207.  
  208.  
  209. # Uwierzytelnianie; jest wykonywane przed otwarciem wideo
  210. def LOGIN():
  211.     global sessionId
  212.     global goToken
  213.     global customerId
  214.     global GOcustomerId
  215.     global individualization
  216.     global loggedin_headers
  217.  
  218.     customerId = __settings__.getSetting('customerId')
  219.     individualization = __settings__.getSetting('individualization')
  220.  
  221.     if (individualization == ""):
  222.         SILENTREGISTER()
  223.  
  224.     if (username=="" or password=="")
  225.         xbmcgui.Dialog().ok('HBO GO', 'Podaj dane logowania w ustawieniach wtyczki.')
  226.         xbmcaddon.Addon(id='plugin.video.hbogopl').openSettings("Konto")
  227.         xbmc.executebuiltin("Container.Refresh")
  228.         return False
  229.  
  230.     #За HBO Polska
  231.     if op_id =='dbaf3435-6ee2-4a79-af13-dac5a1c550a3':
  232.         payload = LOGINVIAHBOPAYLOAD(individualization)
  233.         req = urllib2.Request('https://api.ugw.hbogo.eu/v3.0/Authentication/POL/JSON/POL/COMP', json.dumps(payload), loggedviahbo_headers)
  234.         opener = urllib2.build_opener()
  235.         f = opener.open(req)
  236.         jsonrspl = json.loads(f.read())
  237.        
  238.         try:
  239.             if jsonrspl['Data']['ErrorMessage']:
  240.                 xbmcgui.Dialog().ok('Błąd', jsonrspl['Data']['ErrorMessage'])
  241.         except:
  242.             pass
  243.        
  244.         sessionId = jsonrspl['SessionId']
  245.         if sessionId == '00000000-0000-0000-0000-000000000000':
  246.             xbmcgui.Dialog().ok('Logowanie nie powiodło się','Sprawdź, czy poprawnie wpisałeś dane logowania w ustawieniach i spróbuj ponownie.')
  247.             xbmcaddon.Addon(id='plugin.video.hbogopl').openSettings("Konto")
  248.             xbmc.executebuiltin("Action(Back)")
  249.         else:
  250.             #xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(username,'Czas na popcorn!', 4000, md+'DefaultUser.png'))
  251.        
  252.             goToken = jsonrspl['Token']
  253.             GOcustomerId = jsonrspl['Customer']['Id']
  254.        
  255.             loggedin_headers['GO-SessionId'] = str(sessionId)
  256.             loggedin_headers['GO-Token'] = str(goToken)
  257.             loggedin_headers['GO-CustomerId'] = str(GOcustomerId)
  258.        
  259.        
  260.     #За inni operatorzy
  261.     else:
  262.         sn_headers = {
  263.             'Host': 'plgwapi.hbogo.eu',
  264.             'User-Agent': UA,
  265.             'Accept': 'application/json',
  266.             'Accept-Language': 'pl-pl',
  267.             'Accept-Encoding': 'br, gzip, deflate',
  268.             'Referer': 'https://gateway.hbogo.eu/signin/form',
  269.             'Content-Type': 'application/json',
  270.             'GO-CustomerId': '00000000-0000-0000-0000-000000000000',
  271.             'Origin': 'https://gateway.hbogo.eu',
  272.             'Connection': 'keep-alive'
  273.             }
  274.  
  275.         payload = {
  276.             "Action": "L",
  277.             "AppLanguage": None,
  278.             "ActivationCode": None,
  279.             "AllowedContents": [],
  280.             "AudioLanguage": None,
  281.             "AutoPlayNext": False,
  282.             "BirthYear": 0,
  283.             "CurrentDevice": {
  284.                 "AppLanguage": "",
  285.                 "AutoPlayNext": False,
  286.                 "Brand": "Chrome",
  287.                 "CreatedDate": "",
  288.                 "DeletedDate": "",
  289.                 "Id": "00000000-0000-0000-0000-000000000000",
  290.                 "Individualization": individualization,
  291.                 "IsDeleted": False,
  292.                 "LastUsed": "",
  293.                 "Modell": "61.0.3163",
  294.                 "Name": "",
  295.                 "OSName": "Linux",
  296.                 "OSVersion": "",
  297.                 "Platform": "COMP",
  298.                 "SWVersion": "3.1.19.6338.281",
  299.                 "SubtitleSize": ""
  300.             },
  301.             "CustomerCode": "",
  302.             "DebugMode": False,
  303.             "DefaultSubtitleLanguage": None,
  304.             "EmailAddress": "",
  305.             "FirstName": "",
  306.             "Gender": 0,
  307.             "Id": "00000000-0000-0000-0000-000000000000",
  308.             "IsAnonymus": True,
  309.             "IsPromo": False,
  310.             "Language": "POL",
  311.             "LastName": "",
  312.             "Nick": "",
  313.             "NotificationChanges": 0,
  314.             "OperatorId": op_id,
  315.             "OperatorName": "",
  316.             "OperatorToken": "",
  317.             "ParentalControl": {
  318.                 "Active": False,
  319.                 "Password": "",
  320.                 "Rating": 0,
  321.                 "ReferenceId": "00000000-0000-0000-0000-000000000000"
  322.             },
  323.             "Password": password,
  324.             "PromoCode": "",
  325.             "ReferenceId": "00000000-0000-0000-0000-000000000000",
  326.             "SecondaryEmailAddress": "",
  327.             "SecondarySpecificData": None,
  328.             "ServiceCode": "",
  329.             "SpecificData": None,
  330.             "SubscribeForNewsletter": False,
  331.             "SubscState": None,
  332.             "SubtitleSize": "",
  333.             "TVPinCode": "",
  334.             "ZipCode": "",
  335.             "PromoId": ""
  336.         }
  337.        
  338.         usernamekey = 'EmailAddress'
  339.        
  340.         # UPC
  341.         if op_id =='c5ff7517-8ef8-4346-86c7-0fb328848671':
  342.             payload['Nick'] = username
  343.         else:
  344.             payload['EmailAddress'] = username
  345.  
  346.         response = requests.post(
  347.             'https://plgwapi.hbogo.eu/v2.1/Authentication/json/POL/COMP',
  348.             json=payload,
  349.             verify=False,
  350.             headers=sn_headers
  351.         )
  352.  
  353.         jsonrspl = response.json()
  354.         print jsonrspl
  355.  
  356.         try:
  357.             if jsonrspl['Data']['ErrorMessage']:
  358.                 xbmcgui.Dialog().ok('Błąd', jsonrspl['Data']['ErrorMessage'])
  359.         except:
  360.             pass
  361.  
  362.         sessionId = jsonrspl['SessionId']
  363.         if sessionId == '00000000-0000-0000-0000-000000000000':
  364.             xbmcgui.Dialog().ok('Logowanie nie powiodło się','Sprawdź, czy poprawnie wpisałeś dane logowania w ustawieniach i spróbuj ponownie.')
  365.             xbmcaddon.Addon(id='plugin.video.hbogopl').openSettings("Konto")
  366.             xbmc.executebuiltin("Action(Back)")
  367.         else:
  368.             #xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(username,'Czas na popcorn!', 4000, md+'DefaultUser.png'))
  369.        
  370.             goToken = jsonrspl['Token']
  371.             GOcustomerId = jsonrspl['Customer']['Id']
  372.        
  373.             loggedin_headers['GO-SessionId'] = str(sessionId)
  374.             loggedin_headers['GO-Token'] = str(goToken)
  375.             loggedin_headers['GO-CustomerId'] = str(GOcustomerId)
  376.  
  377.  
  378.  
  379.  
  380. #Kategorie
  381. def CATEGORIES():
  382.     addDir('Wyszukiwanie filmów, seriali ...','search','',4,md+'DefaultAddonsSearch.png')
  383.     #Pobieranie kategorii
  384.     req = urllib2.Request('http://plapi.hbogo.eu/v7/Groups/json/POL/ANMO/0/True', None, loggedin_headers)
  385.     opener = urllib2.build_opener()
  386.     f = opener.open(req)
  387.     jsonrsp = json.loads(f.read())
  388.  
  389.     try:
  390.         if jsonrsp['ErrorMessage']:
  391.             xbmcgui.Dialog().ok('Błąd', jsonrsp['ErrorMessage'])
  392.     except:
  393.         pass
  394.     #Lista kategorii
  395.     for cat in range(0, 3): #Do 3, aby uwzględnić fałszywą kategorię Kids oraz moja lista
  396.         addDir(jsonrsp['Items'][cat]['Name'].encode('utf-8', 'ignore'),jsonrsp['Items'][cat]['ObjectUrl'],'',1,md+'DefaultFolder.png')
  397.     #Ręcznie dodana kategoria Kids
  398.     addDir(jsonrsp['Items'][3]['Name'].encode('utf-8', 'ignore'),'http://plapi.hbogo.eu/v7/Group/json/POL/ANMO/b071fcca-7b15-459d-9b2a-53b108d1df6c/0/0/0/0/0/0/True','',1,md+'DefaultFolder.png')
  399.     addDir('Moja lista','http://plapi.hbogo.eu/v7/CustomerGroup/json/POL/ANMO/c79efa9f-be92-4bfd-90d8-31a9c30d4b80/0/0/0/0/0/0/false','',1,md+'DefaultFolder.png')
  400.  
  401.  
  402. #Zawartosc kategorii
  403. def LIST(url):
  404.     groupid = url.find("c79efa9f-be92-4bfd-90d8-31a9c30d4b80", 0, len(url))
  405.     if groupid > -1 and sessionId == '00000000-0000-0000-0000-000000000000':
  406.         if LOGIN() == False:
  407.             return
  408.  
  409.     req = urllib2.Request(url, None, loggedin_headers)
  410.     opener = urllib2.build_opener()
  411.     f = opener.open(req)
  412.     jsonrsp = json.loads(f.read())
  413.     try:
  414.         if jsonrsp['ErrorMessage']:
  415.             xbmcgui.Dialog().ok('Błąd', jsonrsp['ErrorMessage'])
  416.     except:
  417.         pass
  418.     #Jeśli istnieje podkategoria / gatunki
  419.     if len(jsonrsp['Container']) > 1:
  420.         for Container in range(0, len(jsonrsp['Container'])):
  421.             addDir(jsonrsp['Container'][Container]['Name'].encode('utf-8', 'ignore'),jsonrsp['Container'][Container]['ObjectUrl'],'',1,md+'DefaultFolder.png')
  422.     else:
  423.         xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
  424.         xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_DATE)
  425.         xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_TITLE)
  426.         #Jeśli nie ma podkategorii / gatunków
  427.         for titles in range(0, len(jsonrsp['Container'][0]['Contents']['Items'])):
  428.  
  429.             allowplay = jsonrsp['Container'][0]['Contents']['Items'][titles].get( 'AllowPlay', None )
  430.             if allowplay is None:
  431.                 allowplay = False
  432.  
  433.             if jsonrsp['Container'][0]['Contents']['Items'][titles]['ContentType'] == 1: #1=MOVIE/EXTRAS, 2=SERIES(serial), 3=SERIES(episode)
  434.                 #Film
  435.                 xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  436.                 plot = jsonrsp['Container'][0]['Contents']['Items'][titles].get( 'Description', None )
  437.                 if plot is None:
  438.                     plot = jsonrsp['Container'][0]['Contents']['Items'][titles].get( 'Abstract', None )
  439.                 if plot is None:
  440.                     plot = ''
  441.                 plot.encode('utf-8', 'ignore')
  442.                 firstGenre = jsonrsp['Container'][0]['Contents']['Items'][titles]['Genre']
  443.                 secondGenre = jsonrsp['Container'][0]['Contents']['Items'][titles]['SecondaryGenre']
  444.                 genre = [firstGenre.capitalize(), secondGenre.capitalize()]
  445.                 date = jsonrsp['Container'][0]['Contents']['Items'][titles]['AvailabilityFrom']
  446.                 addLink(jsonrsp['Container'][0]['Contents']['Items'][titles]['ObjectUrl'],plot,jsonrsp['Container'][0]['Contents']['Items'][titles]['AgeRating'],jsonrsp['Container'][0]['Contents']['Items'][titles]['ImdbRate'],jsonrsp['Container'][0]['Contents']['Items'][titles]['BackgroundUrl'],[jsonrsp['Container'][0]['Contents']['Items'][titles]['Cast'].split(', ')][0],jsonrsp['Container'][0]['Contents']['Items'][titles]['Director'],jsonrsp['Container'][0]['Contents']['Items'][titles]['Writer'],jsonrsp['Container'][0]['Contents']['Items'][titles]['Duration'],genre,jsonrsp['Container'][0]['Contents']['Items'][titles]['Name'].encode('utf-8', 'ignore'),jsonrsp['Container'][0]['Contents']['Items'][titles]['OriginalName'],jsonrsp['Container'][0]['Contents']['Items'][titles]['ProductionYear'],5,date,allowplay)
  447.                 #xbmc.log("GO: FILMI: DUMP: " + jsonrsp['Container'][0]['Contents']['Items'][titles]['ObjectUrl'], xbmc.LOGNOTICE)
  448.                
  449.             elif jsonrsp['Container'][0]['Contents']['Items'][titles]['ContentType'] == 3:
  450.                 #Odcinek serialu
  451.                 xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
  452.                 plot = jsonrsp['Container'][0]['Contents']['Items'][titles].get( 'Abstract', None )
  453.                 if plot is None:
  454.                     plot = ''
  455.                 plot.encode('utf-8', 'ignore')
  456.                 firstGenre = jsonrsp['Container'][0]['Contents']['Items'][titles]['Genre']
  457.                 secondGenre = jsonrsp['Container'][0]['Contents']['Items'][titles]['SecondaryGenre']
  458.                 genre = [firstGenre.capitalize(), secondGenre.capitalize()]
  459.                 date = jsonrsp['Container'][0]['Contents']['Items'][titles]['AvailabilityFrom']
  460.                 addLink(jsonrsp['Container'][0]['Contents']['Items'][titles]['ObjectUrl'],plot,jsonrsp['Container'][0]['Contents']['Items'][titles]['AgeRating'],jsonrsp['Container'][0]['Contents']['Items'][titles]['ImdbRate'],jsonrsp['Container'][0]['Contents']['Items'][titles]['BackgroundUrl'],[jsonrsp['Container'][0]['Contents']['Items'][titles]['Cast'].split(', ')][0],jsonrsp['Container'][0]['Contents']['Items'][titles]['Director'],jsonrsp['Container'][0]['Contents']['Items'][titles]['Writer'],jsonrsp['Container'][0]['Contents']['Items'][titles]['Duration'],genre,jsonrsp['Container'][0]['Contents']['Items'][titles]['SeriesName'].encode('utf-8', 'ignore')+' Sezon '+str(jsonrsp['Container'][0]['Contents']['Items'][titles]['SeasonIndex'])+' odc. '+str(jsonrsp['Container'][0]['Contents']['Items'][titles]['Index']),jsonrsp['Container'][0]['Contents']['Items'][titles]['OriginalName'],jsonrsp['Container'][0]['Contents']['Items'][titles]['ProductionYear'],5,date,allowplay)
  461.             else:
  462.                 #Seria
  463.                 xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
  464.                 plot = jsonrsp['Container'][0]['Contents']['Items'][titles].get( 'Description', None )
  465.                 if plot is None:
  466.                     plot = jsonrsp['Container'][0]['Contents']['Items'][titles].get( 'Abstract', None )
  467.                 if plot is None:
  468.                     plot = ''
  469.                 plot.encode('utf-8', 'ignore')
  470.                 addDir(jsonrsp['Container'][0]['Contents']['Items'][titles]['Name'].encode('utf-8', 'ignore'),jsonrsp['Container'][0]['Contents']['Items'][titles]['ObjectUrl'],plot,2,jsonrsp['Container'][0]['Contents']['Items'][titles]['BackgroundUrl'])
  471.  
  472.  
  473.  
  474. #Serie
  475. def SEASON(url):
  476.     xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  477.     req = urllib2.Request(url, None, loggedin_headers)
  478.     opener = urllib2.build_opener()
  479.     f = opener.open(req)
  480.     jsonrsp = json.loads(f.read())
  481.  
  482.     try:
  483.         if jsonrsp['ErrorMessage']:
  484.             xbmcgui.Dialog().ok('Błąd', jsonrsp['ErrorMessage'])
  485.     except:
  486.         pass
  487.     for season in range(0, len(jsonrsp['Parent']['ChildContents']['Items'])):
  488.         plot = jsonrsp['Parent']['ChildContents']['Items'][season].get( 'Description', None )
  489.         if plot is None:
  490.             plot = jsonrsp['Parent']['ChildContents']['Items'][season].get( 'Abstract', None )
  491.         if plot is None:
  492.             plot = ''
  493.         plot.encode('utf-8', 'ignore')
  494.         addDir(jsonrsp['Parent']['ChildContents']['Items'][season]['Name'].encode('utf-8', 'ignore'),jsonrsp['Parent']['ChildContents']['Items'][season]['ObjectUrl'],plot,3,jsonrsp['Parent']['ChildContents']['Items'][season]['BackgroundUrl'])
  495.  
  496.  
  497.  
  498.  
  499. #Odcinki
  500. def EPISODE(url):
  501.     xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
  502.     xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_DATE)
  503.     xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_TITLE)
  504.     xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
  505.     req = urllib2.Request(url, None, loggedin_headers)
  506.     opener = urllib2.build_opener()
  507.     f = opener.open(req)
  508.     jsonrsp = json.loads(f.read())
  509.  
  510.     try:
  511.         if jsonrsp['ErrorMessage']:
  512.             xbmcgui.Dialog().ok('Błąd', jsonrsp['ErrorMessage'])
  513.     except:
  514.         pass
  515.  
  516.     for episode in range(0, len(jsonrsp['ChildContents']['Items'])):
  517.         plot = jsonrsp['ChildContents']['Items'][episode].get( 'Abstract', None )
  518.         if plot is None:
  519.             plot = ''
  520.         plot.encode('utf-8', 'ignore')
  521.         firstGenre = jsonrsp['Genre']
  522.         secondGenre = jsonrsp['SecondaryGenre']
  523.         genre = [firstGenre.capitalize(), secondGenre.capitalize()]
  524.         date = jsonrsp['AvailabilityFrom']
  525.         allowplay = jsonrsp['ChildContents']['Items'][episode].get( 'AllowPlay', None )
  526.         if allowplay is None:
  527.             allowplay = False
  528.         addLink(jsonrsp['ChildContents']['Items'][episode]['ObjectUrl'],plot,jsonrsp['ChildContents']['Items'][episode]['AgeRating'],jsonrsp['ChildContents']['Items'][episode]['ImdbRate'],jsonrsp['ChildContents']['Items'][episode]['BackgroundUrl'],[jsonrsp['ChildContents']['Items'][episode]['Cast'].split(', ')][0],jsonrsp['ChildContents']['Items'][episode]['Director'],jsonrsp['ChildContents']['Items'][episode]['Writer'],jsonrsp['ChildContents']['Items'][episode]['Duration'],genre,jsonrsp['ChildContents']['Items'][episode]['SeriesName'].encode('utf-8', 'ignore')+' Sezon '+str(jsonrsp['ChildContents']['Items'][episode]['SeasonIndex'])+' '+jsonrsp['ChildContents']['Items'][episode]['Name'].encode('utf-8', 'ignore'),jsonrsp['ChildContents']['Items'][episode]['OriginalName'],jsonrsp['ChildContents']['Items'][episode]['ProductionYear'],5,date,allowplay)
  529.  
  530.  
  531. #Ładowanie wideo
  532. def PLAY(url):
  533.     global goToken
  534.     global individualization
  535.     global customerId
  536.     global GOcustomerId
  537.     global sessionId
  538.     global loggedin_headers
  539.  
  540.     #Logowanie, jeśli użytkownik jest anonimowy
  541.     if sessionId == '00000000-0000-0000-0000-000000000000':
  542.         if LOGIN() == False:
  543.             return
  544.            
  545.     #Napisy
  546.     if se=='true':
  547.         try:
  548.             req = urllib2.Request('http://plapi.hbogo.eu/v7/Content/json/POL/ANMO/'+cid, None, loggedin_headers)
  549.             req.add_header('User-Agent', MUA)
  550.             opener = urllib2.build_opener()
  551.             f = opener.open(req)
  552.             jsonrsps = json.loads(f.read())
  553.            
  554.             #Pobieramy oficjalne napisy do odcinka w formacie TTML i konwertujemy je na SRT
  555.             try:
  556.                 if jsonrsps['Subtitles'][0]['Code']==Code:
  557.                     slink = jsonrsps['Subtitles'][0]['Url']
  558.                 elif jsonrsps['Subtitles'][1]['Code']==Code:
  559.                     slink = jsonrsps['Subtitles'][1]['Url']
  560.                 req = urllib2.Request(slink, None, loggedin_headers)
  561.                 response = urllib2.urlopen(req)
  562.                 data=response.read()
  563.                 response.close()
  564.                    
  565.                 subs = re.compile('<p[^>]+begin="([^"]+)\D(\d+)"[^>]+end="([^"]+)\D(\d+)"[^>]*>([\w\W]+?)</p>').findall(data)
  566.                 row = 0
  567.                 buffer = ''
  568.                 for sub in subs:
  569.                     row = row + 1
  570.                     buffer += str(row) +'\n'
  571.                     buffer += "%s,%03d" % (sub[0], int(sub[1])) + ' --> ' + "%s,%03d" % (sub[2], int(sub[3])) + '\n'
  572.                     buffer += urllib.unquote_plus(sub[4]).replace('<br/>','\n').replace('<br />','\n').replace("\r\n", "").replace("&lt;", "<").replace("&gt;", ">").replace("\n    ","").strip()
  573.                     buffer += '\n\n'
  574.                     sub = 'true'
  575.                     with open(srtsubs_path, "w") as subfile:
  576.                         subfile.write(buffer)
  577.                 #Wyjątek dla niepoprawnych napisow
  578.                 if sub != 'true':
  579.                     raise Exception()
  580.                    
  581.             except:
  582.                 sub = 'false'
  583.         except:
  584.             sub = 'false'
  585.    
  586.    
  587.     #Zadanie manifestu ism
  588.     purchase_payload = '<Purchase xmlns="go:v7:interop" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><AllowHighResolution>true</AllowHighResolution><ContentId>'+cid+'</ContentId><CustomerId>'+GOcustomerId+'</CustomerId><Individualization>'+individualization+'</Individualization><OperatorId>'+op_id+'</OperatorId><IsFree>false</IsFree><RequiredPlatform>COMP</RequiredPlatform><UseInteractivity>false</UseInteractivity></Purchase>'
  589.  
  590.     purchase_headers = {
  591.         'Accept': 'application/json, text/javascript, */*; q=0.01',
  592.         'Accept-Encoding': '',
  593.         'Accept-Language': 'en-US,en;q=0.8',
  594.         'Connection': 'keep-alive',
  595.         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  596.         'GO-CustomerId': str(GOcustomerId),
  597.         'GO-requiredPlatform': 'CHBR',
  598.         'GO-SessionId': str(sessionId),
  599.         'GO-swVersion': '4.7.4',
  600.         'GO-Token': str(goToken),
  601.         'Origin': 'https://www.hbogo.pl',
  602.         'User-Agent': UA
  603.         }
  604.  
  605.     req = urllib2.Request('https://plapi.hbogo.eu/v7/Purchase/Json/POL/COMP', purchase_payload, purchase_headers)
  606.     opener = urllib2.build_opener()
  607.     f = opener.open(req)
  608.     jsonrspp = json.loads(f.read())
  609.  
  610.     try:
  611.         if jsonrspp['ErrorMessage']:
  612.             xbmcgui.Dialog().ok('Błąd',jsonrspp['ErrorMessage'])
  613.     except:
  614.         pass
  615.  
  616.     MediaUrl = jsonrspp['Purchase']['MediaUrl'] + "/Manifest"
  617.  
  618.     PlayerSessionId = jsonrspp['Purchase']['PlayerSessionId']
  619.     x_dt_auth_token = jsonrspp['Purchase']['AuthToken']
  620.     dt_custom_data = base64.b64encode("{\"userId\":\"" + GOcustomerId + "\",\"sessionId\":\"" + PlayerSessionId + "\",\"merchant\":\"hboeurope\"}")
  621.  
  622.     #Odtwórz wideo
  623.     is_helper = inputstreamhelper.Helper('mpd', drm='com.widevine.alpha')
  624.     if not is_helper.check_inputstream():
  625.         return False
  626.  
  627.     li = xbmcgui.ListItem(iconImage=thumbnail, thumbnailImage=thumbnail, path=MediaUrl)
  628.     if (se=='true' and sub=='true'): #Ustaw zewnętrzne napisy, jeśli wybrany jest ten tryb
  629.         li.setSubtitles([srtsubs_path])
  630.     license_server = 'https://lic.drmtoday.com/license-proxy-widevine/cenc/'
  631.     license_headers = 'dt-custom-data=' + dt_custom_data + '&x-dt-auth-token=' + x_dt_auth_token + '&Origin=https://www.hbogo.pl&Content-Type='
  632.     license_key = license_server + '|' + license_headers + '|R{SSM}|JBlicense'
  633.  
  634.     li.setProperty('inputstreamaddon', 'inputstream.adaptive')
  635.     li.setProperty('inputstream.adaptive.manifest_type', 'ism')
  636.     li.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha')
  637.     li.setProperty('inputstream.adaptive.license_data', 'ZmtqM2xqYVNkZmFsa3Izag==')
  638.     li.setProperty('inputstream.adaptive.license_key', license_key)
  639.  
  640.     print MediaUrl
  641.     print "---"
  642.     print license_headers
  643.  
  644.     xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li)
  645.  
  646.  
  647. #Wyszukiwarka
  648. def SEARCH():
  649.     keyb = xbmc.Keyboard(search_string, 'Wyszukiwanie filmów, seriali ...')
  650.     keyb.doModal()
  651.     searchText = ''
  652.     if (keyb.isConfirmed()):
  653.         searchText = urllib.quote_plus(keyb.getText())
  654.         if searchText == "":
  655.             addDir('Wróć - nie ma wyników pasujących do wyszukiwania','','','',md+'DefaultFolderBack.png')
  656.         else:
  657.             #Zapis ostatniego zapytania
  658.             __settings__.setSetting('lastsearch', searchText)
  659.             #Wyszukaj
  660.             req = urllib2.Request('https://plapi.hbogo.eu/v7/Search/Json/POL/ANMO/'+searchText.decode('utf-8', 'ignore').encode('utf-8', 'ignore')+'/0/0/0/0/0/3', None, loggedin_headers)
  661.             opener = urllib2.build_opener()
  662.             f = opener.open(req)
  663.             jsonrsp = json.loads(f.read())        
  664.  
  665.             try:
  666.                 if jsonrsp['ErrorMessage']:
  667.                     xbmcgui.Dialog().ok('Błąd', jsonrsp['ErrorMessage'])
  668.             except:
  669.                 pass
  670.  
  671.             br=0
  672.             for index in range(0, len(jsonrsp['Container'][0]['Contents']['Items'])):
  673.                 allowplay = jsonrsp['Container'][0]['Contents']['Items'][index].get( 'AllowPlay', None )
  674.                 if (jsonrsp['Container'][0]['Contents']['Items'][index]['ContentType'] == 1 or jsonrsp['Container'][0]['Contents']['Items'][index]['ContentType'] == 7): #1,7=MOVIE/EXTRAS, 2=SERIES(serial), 3=SERIES(episode)
  675.                     #Film
  676.                     addLink(jsonrsp['Container'][0]['Contents']['Items'][index]['ObjectUrl'],'',jsonrsp['Container'][0]['Contents']['Items'][index]['AgeRating'],jsonrsp['Container'][0]['Contents']['Items'][index]['ImdbRate'],jsonrsp['Container'][0]['Contents']['Items'][index]['BackgroundUrl'],[jsonrsp['Container'][0]['Contents']['Items'][index]['Cast'].split(', ')][0],jsonrsp['Container'][0]['Contents']['Items'][index]['Director'],jsonrsp['Container'][0]['Contents']['Items'][index]['Writer'],jsonrsp['Container'][0]['Contents']['Items'][index]['Duration'],jsonrsp['Container'][0]['Contents']['Items'][index]['Genre'],jsonrsp['Container'][0]['Contents']['Items'][index]['Name'].encode('utf-8', 'ignore'),jsonrsp['Container'][0]['Contents']['Items'][index]['OriginalName'],jsonrsp['Container'][0]['Contents']['Items'][index]['ProductionYear'],5,'',True)
  677.                 elif jsonrsp['Container'][0]['Contents']['Items'][index]['ContentType'] == 3:
  678.                     #Odcinek
  679.                     addLink(jsonrsp['Container'][0]['Contents']['Items'][index]['ObjectUrl'],'',jsonrsp['Container'][0]['Contents']['Items'][index]['AgeRating'],jsonrsp['Container'][0]['Contents']['Items'][index]['ImdbRate'],jsonrsp['Container'][0]['Contents']['Items'][index]['BackgroundUrl'],[jsonrsp['Container'][0]['Contents']['Items'][index]['Cast'].split(', ')][0],jsonrsp['Container'][0]['Contents']['Items'][index]['Director'],jsonrsp['Container'][0]['Contents']['Items'][index]['Writer'],jsonrsp['Container'][0]['Contents']['Items'][index]['Duration'],jsonrsp['Container'][0]['Contents']['Items'][index]['Genre'],jsonrsp['Container'][0]['Contents']['Items'][index]['SeriesName'].encode('utf-8', 'ignore')+' '+jsonrsp['Container'][0]['Contents']['Items'][index]['Name'].encode('utf-8', 'ignore'),jsonrsp['Container'][0]['Contents']['Items'][index]['OriginalName'],jsonrsp['Container'][0]['Contents']['Items'][index]['ProductionYear'],5,'',True)
  680.                 else:
  681.                     #Seria
  682.                     addDir(jsonrsp['Container'][0]['Contents']['Items'][index]['Name'].encode('utf-8', 'ignore'),jsonrsp['Container'][0]['Contents']['Items'][index]['ObjectUrl'],'',2,jsonrsp['Container'][0]['Contents']['Items'][index]['BackgroundUrl'])
  683.                 br=br+1
  684.             if br==0:
  685.                 addDir('Wróć - nie ma wyników pasujących do wyszukiwania','','','',md+'DefaultFolderBack.png')
  686.  
  687.  
  688. def addLink(ou,plot,ar,imdb,bu,cast,director,writer,duration,genre,name,on,py,mode,date,playble):
  689.     cid = ou.rsplit('/',2)[1]
  690.     u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&cid="+cid+"&thumbnail="+bu
  691.     ok=True
  692.     if playble:
  693.         playble = 'true'
  694.     else:
  695.         playble = 'false'
  696.         u = ''
  697.         name = name + ' - Wkrótce'
  698.     liz=xbmcgui.ListItem(name, iconImage=bu, thumbnailImage=bu)
  699.     liz.setProperty("IsPlayable" , playble)
  700.     liz.setArt({ 'thumb': bu,'poster': bu, 'banner' : bu, 'fanart': bu })
  701.     liz.setInfo( type="Video", infoLabels={'plot': plot, "mpaa": str(ar)+'+', "rating": imdb, "cast": cast, "director": director, "writer": writer, "duration": duration, "genre": genre, "title": name, "originaltitle": on, "year": py, "date": date, 'sorttitle': name , 'aired': date} )
  702.     liz.addStreamInfo('video', { 'width': 1280, 'height': 720 })
  703.     liz.addStreamInfo('video', { 'aspect': 1.78, 'codec': 'h264' })
  704.     liz.addStreamInfo('audio', { 'codec': 'aac', 'channels': 2 })
  705.  
  706.     contextmenu = []
  707.     contextmenu.append(('Informacje', 'XBMC.Action(Info)'))
  708.     liz.addContextMenuItems(contextmenu)
  709.     ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
  710.     return ok
  711.  
  712.  
  713.  
  714. #Moduł do dodawania oddzielnego katalogu i jego atrybutów do zawartości wyswietlanego katalogu Kodi
  715. def addDir(name,url,plot,mode,iconimage):
  716.     u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
  717.     ok=True
  718.     liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  719.     liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": plot } )
  720.  
  721.     print("plot: "+str(plot.count))
  722.     if len(plot)>0:
  723.         contextmenu = []
  724.         contextmenu.append(('Informacje', 'XBMC.Action(Info)'))
  725.         liz.addContextMenuItems(contextmenu)
  726.  
  727.     ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  728.     return ok
  729.  
  730.  
  731. def get_params():
  732.     param=[]
  733.     paramstring=sys.argv[2]
  734.     if len(paramstring)>=2:
  735.         params=sys.argv[2]
  736.         cleanedparams=params.replace('?','')
  737.         if (params[len(params)-1]=='/'):
  738.             params=params[0:len(params)-2]
  739.         pairsofparams=cleanedparams.split('&')
  740.         param={}
  741.         for i in range(len(pairsofparams)):
  742.             splitparams={}
  743.             splitparams=pairsofparams[i].split('=')
  744.             if (len(splitparams))==2:
  745.                 param[splitparams[0]]=splitparams[1]
  746.     return param
  747.  
  748. params=get_params()
  749. url=None
  750. name=None
  751. iconimage=None
  752. mode=None
  753. ssl._create_default_https_context = ssl._create_unverified_context
  754. try:
  755.         url=urllib.unquote_plus(params["url"])
  756. except:
  757.         pass
  758. try:
  759.         name=urllib.unquote_plus(params["name"])
  760. except:
  761.         pass
  762. try:
  763.         thumbnail=str(params["thumbnail"])
  764. except:
  765.         pass
  766. try:
  767.         mode=int(params["mode"])
  768. except:
  769.         pass
  770. try:
  771.         cid=str(params["cid"])
  772. except:
  773.         pass
  774.  
  775.  
  776. #Lista poszczególnych modułów w tej wtyczce - musi w pełni odpowiadać powyższemu kodowi
  777. if mode==None or url==None or len(url)<1:
  778.         CATEGORIES()
  779.  
  780. elif mode==1:
  781.         LIST(url)
  782.  
  783. elif mode==2:
  784.         SEASON(url)
  785.  
  786. elif mode==3:
  787.         EPISODE(url)
  788.        
  789. elif mode==4:
  790.         SEARCH()
  791.  
  792. elif mode==5:
  793.         PLAY(url)
  794.  
  795. elif mode==6:
  796.         SILENTREGISTER()
  797.  
  798. elif mode==7:
  799.         LOGIN()
  800.  
  801.  
  802. xbmcplugin.endOfDirectory(int(sys.argv[1]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement