Skip to content

Commit

Permalink
Merge pull request #42 from peci1/matrix
Browse files Browse the repository at this point in the history
Python3/Kodi 19 compatibility
  • Loading branch information
brozikcz authored Jan 7, 2022
2 parents cbcc0c3 + 3be173f commit 00cb52e
Show file tree
Hide file tree
Showing 9 changed files with 613 additions and 185 deletions.
65 changes: 33 additions & 32 deletions addon.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
# -*- coding: utf-8 -*-
import httplib
import http.client
import json
import os
import random
import sys
import time
import traceback
import urllib
import urllib.request, urllib.parse, urllib.error
from collections import defaultdict
from datetime import datetime, timedelta
from urlparse import urlparse
from urllib.parse import urlparse

import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
import xbmcvfs
from xbmcplugin import addDirectoryItem

import ivysilani
Expand All @@ -35,7 +36,7 @@
###############################################################################

params = None
_addon_ = xbmcaddon.Addon('plugin.video.ivysilani')
_addon_ = xbmcaddon.Addon('plugin.video.ivysilani.cz')
_lang_ = _addon_.getLocalizedString
_scriptname_ = _addon_.getAddonInfo('name')
_version_ = _addon_.getAddonInfo('version')
Expand Down Expand Up @@ -66,7 +67,7 @@ def _exception_log(exc_type, exc_value, exc_traceback):
logErr(traceback.format_exception(exc_type, exc_value, exc_traceback))
xbmcgui.Dialog().notification(_scriptname_, _toString(exc_value), xbmcgui.NOTIFICATION_ERROR)
if not _first_error_:
if xbmcgui.Dialog().yesno(_scriptname_, _lang_(30500), _lang_(30501)):
if xbmcgui.Dialog().yesno(_scriptname_, _lang_(30500) + "\n" + _lang_(30501)):
_addon_.setSetting("send_errors", "true")
_send_errors_ = (_addon_.getSetting('send_errors') == "true")
_addon_.setSetting("first_error", "true")
Expand All @@ -87,7 +88,7 @@ def _exception_log(exc_type, exc_value, exc_traceback):
"auto_view_mode": "true",
"send_errors": "false",
"show_subtitles": "false"}
for setting in DEFAULT_SETTING_VALUES.keys():
for setting in list(DEFAULT_SETTING_VALUES.keys()):
val = _addon_.getSetting(setting)
if not val:
_addon_.setSetting(setting, DEFAULT_SETTING_VALUES[setting])
Expand All @@ -100,11 +101,11 @@ def _exception_log(exc_type, exc_value, exc_traceback):
_send_errors_ = (_addon_.getSetting('send_errors') == "true")
_auto_view_mode_ = (_addon_.getSetting('auto_view_mode') == "true")
_show_subtitles_ = (_addon_.getSetting('show_subtitles') == "true")
_subtitles_path_ = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('profile'), "subtitles.str"))
_icon_ = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'icon.png'))
_next_ = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'next.png'))
_previous_ = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'previous.png'))
_fanArt = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'fanart1.png'))
_subtitles_path_ = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('profile'), "subtitles.str"))
_icon_ = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'icon.png'))
_next_ = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'next.png'))
_previous_ = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'previous.png'))
_fanArt = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'fanart1.png'))
_handle_ = int(sys.argv[1])
_baseurl_ = sys.argv[0]

Expand Down Expand Up @@ -136,7 +137,7 @@ def _fanart():
listedDir = os.listdir(fanartFolder)
r = random.randint(0, len(listedDir) - 1)
selected = os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media', 'fanart', listedDir[r])
return xbmc.translatePath(selected)
return xbmcvfs.translatePath(selected)


def _setViewMode(view_mode):
Expand Down Expand Up @@ -179,8 +180,8 @@ def addDirectoryItem(label, url, ID=None, related=False, episodes=False, plot=No
dt = datetime.fromtimestamp(time.mktime(time.strptime(date, "%d. %m. %Y")))
liVideo['premiered'] = dt.strftime("%Y-%m-%d")
if image:
li.setThumbnailImage(image)
li.setIconImage(icon)
li.setArt({'thumb': image})
li.setArt({'icon': icon})
li.setInfo("video", liVideo)
if not fanart:
fanart = _fanart()
Expand All @@ -189,11 +190,11 @@ def addDirectoryItem(label, url, ID=None, related=False, episodes=False, plot=No
url = _baseurl_ + "?episodes=" + ID
if ID:
cm = []
cm.append((_lang_(30013), "XBMC.Container.Update(" + _baseurl_ + "?play=" + ID + "&skip_auto=1)"))
cm.append((_lang_(30013), "Container.Update(" + _baseurl_ + "?play=" + ID + "&skip_auto=1)"))
if related:
cm.append((_lang_(30003), "XBMC.Container.Update(" + _baseurl_ + "?related=" + ID + ")"))
cm.append((_lang_(30004), "XBMC.Container.Update(" + _baseurl_ + "?episodes=" + ID + ")"))
cm.append((_lang_(30005), "XBMC.Container.Update(" + _baseurl_ + "?bonuses=" + ID + ")"))
cm.append((_lang_(30003), "Container.Update(" + _baseurl_ + "?related=" + ID + ")"))
cm.append((_lang_(30004), "Container.Update(" + _baseurl_ + "?episodes=" + ID + ")"))
cm.append((_lang_(30005), "Container.Update(" + _baseurl_ + "?bonuses=" + ID + ")"))
li.addContextMenuItems(cm)
xbmcplugin.addDirectoryItem(handle=_handle_, url=url, listitem=li, isFolder=isFolder)

Expand Down Expand Up @@ -282,8 +283,8 @@ def listLiveChannels():

def playUrl(title, url, image, subtitles=False):
li = xbmcgui.ListItem(title)
li.setThumbnailImage(image)
res = urllib.urlopen(url)
li.setArt({'thumb': image})
res = urllib.request.urlopen(url)
try:
url = res.geturl()
finally:
Expand All @@ -297,7 +298,7 @@ def playUrl(title, url, image, subtitles=False):


def playPlayable(playable, skipAutoQuality=False, forceQuality=None):
image = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media',
image = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media',
'logo_' + playable.ID.lower() + '_400x225.png'))
if isinstance(playable, ivysilani.Programme):
image = playable.imageURL
Expand All @@ -322,7 +323,7 @@ def playPlayable(playable, skipAutoQuality=False, forceQuality=None):


def playLiveChannel(liveChannel, skipAutoQuality=False):
image = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media',
image = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media',
'logo_' + liveChannel.ID.lower() + '_400x225.png'))
if _auto_quality_ and not skipAutoQuality:
url = autoSelectQuality(liveChannel)
Expand All @@ -344,13 +345,13 @@ def selectLiveChannel(ID):

def listAlphabet():
for letter in ivysilani.alphabet():
addDirectoryItem(letter.title, _baseurl_ + "?letter=" + urllib.quote_plus(_toString(letter.link)))
addDirectoryItem(letter.title, _baseurl_ + "?letter=" + urllib.parse.quote_plus(_toString(letter.link)))
xbmcplugin.endOfDirectory(_handle_, updateListing=False, cacheToDisc=False)


def listGenres():
for genre in ivysilani.genres():
addDirectoryItem(genre.title, _baseurl_ + "?genre=" + urllib.quote_plus(_toString(genre.link)))
addDirectoryItem(genre.title, _baseurl_ + "?genre=" + urllib.parse.quote_plus(_toString(genre.link)))
xbmcplugin.endOfDirectory(_handle_, updateListing=False, cacheToDisc=False)


Expand All @@ -365,7 +366,7 @@ def listDates():
pretty_date = day_names[dt.weekday()] + " " + dt.strftime("%d.%m.%Y")
formated_date = dt.strftime("%Y-%m-%d")
list_item = xbmcgui.ListItem(label=pretty_date)
listing.append((_baseurl_ + "?date=" + urllib.quote_plus(formated_date), list_item, True))
listing.append((_baseurl_ + "?date=" + urllib.parse.quote_plus(formated_date), list_item, True))
dt = dt - timedelta(days=1)
xbmcplugin.addDirectoryItems(_handle_, listing, len(listing))
xbmcplugin.endOfDirectory(_handle_, updateListing=False, cacheToDisc=False)
Expand All @@ -374,9 +375,9 @@ def listDates():
def listChannelsForDate(date):
for channel in ivysilani.LIVE_CHANNELS:
if channel.permanent:
image = xbmc.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media',
image = xbmcvfs.translatePath(os.path.join(_addon_.getAddonInfo('path'), 'resources', 'media',
'logo_' + channel.ID.lower() + '_400x225.png'))
url = _baseurl_ + "?date=" + urllib.quote_plus(date) + "&channel=" + channel.ID
url = _baseurl_ + "?date=" + urllib.parse.quote_plus(date) + "&channel=" + channel.ID
addDirectoryItem(_toString(channel.title), url, image=image)
xbmcplugin.endOfDirectory(_handle_, updateListing=False, cacheToDisc=False)

Expand Down Expand Up @@ -410,8 +411,8 @@ def listContext(what, ID, page):
def _sendError(params, exc_type, exc_value, exc_traceback):
status = "no status"
try:
conn = httplib.HTTPSConnection('script.google.com')
req_data = urllib.urlencode(
conn = http.client.HTTPSConnection('script.google.com')
req_data = urllib.parse.urlencode(
{'addon': _scriptname_, 'version': _version_, 'params': _toString(params), 'type': exc_type,
'value': exc_value,
'traceback': _toString(traceback.format_exception(exc_type, exc_value, exc_traceback))})
Expand All @@ -423,7 +424,7 @@ def _sendError(params, exc_type, exc_value, exc_traceback):
location = resp.getheader('Location')
o = urlparse(location, allow_fragments=True)
host = o.netloc
conn = httplib.HTTPSConnection(host)
conn = http.client.HTTPSConnection(host)
url = o.path + "?" + o.query
conn.request(method='GET', url=url)
resp = conn.getresponse()
Expand Down Expand Up @@ -462,7 +463,7 @@ def get_params():
def assign_params(params):
for param in params:
try:
globals()[param] = urllib.unquote_plus(params[param])
globals()[param] = urllib.parse.unquote_plus(params[param])
except:
pass

Expand Down Expand Up @@ -544,7 +545,7 @@ def assign_params(params):
logErr(traceback.format_exception(exc_type, exc_value, exc_traceback))
found = False
for wnm in well_known_error_messages:
if ex.message == wnm[0]:
if str(ex) == wnm[0]:
xbmcgui.Dialog().notification(_scriptname_, _lang_(wnm[1]), xbmcgui.NOTIFICATION_ERROR)
found = True
if not found:
Expand Down
10 changes: 6 additions & 4 deletions addon.xml
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="plugin.video.ivysilani" name="iVysílání — Česká televize" version="1.3.8" provider-name="Štěpán Ort">
<addon id="plugin.video.ivysilani.cz" name="iVysílání — Česká televize" version="1.4.0" provider-name="Štěpán Ort">
<requires>
<import addon="xbmc.python" version="2.1.0"/>
<import addon="script.module.stream.resolver" version="1.6.13"/>
<import addon="xbmc.python" version="3.0.0"/>
<import addon="script.module.stream.resolver" version="1.7.0"/>
<import addon="script.module.web-pdb" />
</requires>
<extension point="xbmc.python.pluginsource" library="addon.py">
<provides>video</provides>
</extension>
<extension point="xbmc.addon.metadata">
<summary>iVysílání — Česká televize</summary>
<description>Plugin to play videos and live TV from Czech Television's iVysilani</description>
<description lang="cs">Plugin nabízí přístup do archivu České televize iVysílání i přehrávání kanálů živě.
<description lang="cs_CZ">Plugin nabízí přístup do archivu České televize iVysílání i přehrávání kanálů živě.
</description>
<platform>all</platform>
<language>cs en sk</language>
</extension>
</addon>
30 changes: 16 additions & 14 deletions ivysilani.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@
"""Wrapper pro iVysílání České televize
"""

import httplib
import http.client
import time
import urllib
import urllib2
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta

from StringIO import StringIO
from io import StringIO, BytesIO
import gzip

import util
import sys

__author__ = "Štěpán Ort"
__license__ = "MIT"
Expand Down Expand Up @@ -145,15 +146,15 @@ def available_qualities(self):
try:
quality = Quality(quality_label)
url = self.url(quality)
import urlparse
par = urlparse.parse_qs(urlparse.urlparse(url).query)
import urllib.parse
par = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
label = _toString(par['quality'][0])
quality = Quality(label)
if quality not in self._links():
self._links()[quality] = url
except:
pass
qualities = self._links().keys()
qualities = list(self._links().keys())
sorted_qualities = sorted(qualities, key=lambda quality: quality.height, reverse=True)
return sorted_qualities

Expand All @@ -177,13 +178,14 @@ def url(self, quality):
data = None
try:
data = _fetch(PLAYLISTURL_URL, params)
except:
except Exception as ex:
print(str(ex), file=sys.stderr)
return None
root = ET.fromstring(data)
if root.tag == "errors":
raise Exception(', '.join([e.text for e in root]))
playlist_url = root.text
resp = urllib2.urlopen(playlist_url)
resp = urllib.request.urlopen(playlist_url)
playlist_data = resp.read()
root = ET.fromstring(playlist_data)
videos = root.findall("smilRoot/body//video")
Expand All @@ -196,9 +198,9 @@ def url(self, quality):
if switchItem:
url = switchItem.get("base") + "/" + url
try:
if urllib2.urlopen(url).getcode() == 200:
if urllib.request.urlopen(url).getcode() == 200:
self._links()[quality] = url
except urllib2.HTTPError:
except urllib.error.HTTPError:
return None
return url

Expand Down Expand Up @@ -330,12 +332,12 @@ def _https_ceska_televize_fetch(url, params):
"Accept-encoding": "gzip",
"Connection": "Keep-Alive",
"User-Agent": "Dalvik/1.6.0 (Linux; U; Android 4.4.4; Nexus 7 Build/KTU84P)"}
conn = httplib.HTTPSConnection("www.ceskatelevize.cz")
conn.request("POST", url, urllib.urlencode(params), headers)
conn = http.client.HTTPSConnection("www.ceskatelevize.cz")
conn.request("POST", url, urllib.parse.urlencode(params), headers)
response = conn.getresponse()
if response.status == 200:
if response.getheader('Content-Encoding') == 'gzip':
data = gzip.GzipFile(fileobj = StringIO(response.read())).read()
data = gzip.GzipFile(fileobj = BytesIO(response.read())).read()
else:
data = response.read()
conn.close()
Expand Down
45 changes: 0 additions & 45 deletions resources/language/Czech/strings.xml

This file was deleted.

Loading

0 comments on commit 00cb52e

Please sign in to comment.