示例#1
0
def login():
    loginData = json.dumps({"email": control.setting("email"), "password": control.setting("password"), "stayLoggedIn": True, "deviceToken": {"token": None, "platform": "web"}}).encode('utf-8')
    jwtToken = ""
    try:
        authAnswer = json.loads(client.request(auth_url, post=loginData, headers={"Content-Type": "application/json;charset=UTF-8", "Content-Length": len(loginData)}))
        if authAnswer["success"]:
            jwtToken = authAnswer["token"]
            res = json.loads(client.request(userinfo_url, cookie="jwt=%s" % jwtToken))
            if res["success"]:
                control.setSetting("hasPremium", str(res["isPremium"]))
    except:
        pass
    return jwtToken
def get_Tv():   
    m = client.request('https://player.mediaklikk.hu/playernew/player.php?video=' + url)
    m = m.replace('\\', '')
    direct_url = re.search('"file"\s*:\s*"([^"]+)', m).group(1)
    chunk_list = client.request('http:%s' % direct_url)
    chunk_list = chunk_list.replace('\n', '')
    chunk_list = re.compile('BANDWIDTH=([0-9]+)(.+?m3u8)').findall(chunk_list)
    if len(chunk_list) == 0: direct_url = direct_url[0]
    else:
        chunk_list = [(int(i[0]), i[1]) for i in chunk_list]
        chunk_list = sorted(chunk_list, reverse=True)
        q_list = [str(i[0]) for i in chunk_list]
        q_list = [q.replace('3000000', '720p').replace('1600000', '480p').replace('1200000', '360p').replace('800000', '290p').replace('400000', '180p') for q in q_list]
        auto_pick = control.setting('autopick') == '1'

        if auto_pick == True:
            stream = chunk_list[0][1]
        else:
            q = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', q_list)
            if q == -1:
                return
            else:
                stream = chunk_list[q][1]
        direct_url = direct_url.split('playlist')[0] + stream
    play_url('http:%s' % direct_url, iconimage, name)
示例#3
0
def error(msg, caller=None):
    func = inspect.currentframe().f_back.f_code

    if caller is not None:
        caller = "%s.%s()" % (caller, func.co_name)
    if control.setting('debug') == 'true':
        log('%s\n%s' % (msg, traceback.format_exc()), caller, level=LOGERROR)
示例#4
0
def apiRibbons():
    r = client.request("%s/ribbons/%s/%s" % (api_url, param, page))
    data = json.loads(r)
    dirType = 'videos'
    for card in data["cards"]:
        thumb = "%s/%s" % (
            base_url, card["imageUrl"]
        ) if "https://" not in card["imageUrl"] else card["imageUrl"]
        title = card["title"].encode('utf-8')
        if "contentLength" in card:
            plot = ""
            if control.setting('fillLead') == 'true':
                try:
                    r = client.request("%s/search/%s" %
                                       (api_url, card["slug"]))
                    episode = json.loads(r)
                    plot = episode["lead"] if "lead" in episode else ""
                    if plot.startswith("<p>"):
                        plot = plot[3:]
                    if plot.endswith("</p>"):
                        plot = plot[:-4]
                except:
                    pass
            if 'EPISODE' in card['cardType']:
                dirType = 'episodes'
            if 'MOVIE' in card['cardType']:
                dirType = 'movies'
            addDirectoryItem(title,
                             "playvideo&param=%s" % card["slug"],
                             thumb,
                             "DefaultFolder.png",
                             meta={
                                 'title': title,
                                 'duration': int(card["contentLength"]),
                                 'plot': plot
                             },
                             isFolder=False)
        else:
            if card["cardType"] != "ARTICLE":
                addDirectoryItem(
                    title,
                    "apisearch&param=%s" % quote_plus(card["slug"]),
                    thumb,
                    "DefaultFolder.png",
                    meta={
                        'title':
                        title,
                        'plot':
                        card["lead"].encode('utf-8') if "lead" in card else ''
                    })
    r = client.request("%s/ribbons/%s/%d" % (api_url, param, int(page) + 1))
    if r != None:
        addDirectoryItem(
            u'[I]K\u00F6vetkez\u0151 oldal >>[/I]',
            'apiribbons&param=%s&page=%d' % (param, int(page) + 1), '',
            'DefaultFolder.png')
    endDirectory(type=dirType)
def get_liveTv():
    from resources.lib import m3u8_parser
    
    title = name.split('-')[0].strip()
    
    if not title.lower() == 'm3':
        r = client.request(url)
        streamid = re.search('"streamId"\s*:\s*"([^"]+)', r).group(1)

        drm_info = client.request('https://player.mediaklikk.hu/playernew/public/stream/%s.json' % streamid)
        drm_info = json.loads(drm_info)
        drm_info = drm_info['drm']

        if drm_info == True:
            control.infoDialog(u'Lej\u00E1tsz\u00E1s sikertelen. Az \u00E9l\u0151 ad\u00E1s DRM v\u00E9delemmel van ell\u00E1tva.', icon='')
            return

        r = client.request('https://player.mediaklikk.hu/playernew/player.php?video=%s' % streamid)
        r = r.replace('\\', '').replace('\n', '')
        direct_url = re.findall('"file"\s*:\s*"([^"]+)', r)
        direct_url = [i for i in direct_url if not 'FWC2018' in i][0]

        direct_url = direct_url.replace('\\', '')
        if not direct_url.startswith('http'): direct_url = 'http:' + direct_url
        result = client.request(direct_url)
        url_list = m3u8_parser.parse(result)['playlists']
        url_list = [(i['stream_info']['resolution'].split('x')[1], i['uri']) for i in url_list]
        url_list = sorted(url_list, key=lambda tup: int(tup[0]), reverse=True)
        q_list = [x[0] + 'p' for x in url_list]
        
        auto_pick = control.setting('autopick') == '1'

        if len(url_list) == 1 or auto_pick == True:
            stream = url_list[0][1]
        else:
            q = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', q_list)
            if q == -1:
                return
            else:
                stream = url_list[q][1]
        
        stream = direct_url.split('index.m3u8')[0] + stream
    
    else:
        m3_cookie = client.request(url, output = 'cookie')
        m3_token = re.search('Token=([a-zA-Z0-9]+)', m3_cookie).group(1)
        m3_streamUrl = client.request('https://archivum.mtva.hu/m3/stream?target=live')
        m3_streamUrl = json.loads(m3_streamUrl).get('live')
        stream = m3_streamUrl.replace('[sessid]', m3_token)
        
        '''direct_url = 'https://stream.nava.hu:443/m3_live_drm/smil:m3.smil/playlist.m3u8'''
 
    play_url(stream, iconimage, title)
示例#6
0
def getJWTToken():
    if control.setting("email") and control.setting("password"):
        jwtToken =  control.setting("jwtToken")
        if jwtToken:
            m = re.search('(.*)\.(.*)\.(.*)', base64.b64decode(jwtToken).decode("utf-8"))
            if m:
                errMsg = ""
                try:
                    errMsg = "TV2 Play: cannot base64 decode the group 2: %s" % m.group(2)
                    decodedToken=base64.b64decode(m.group(2)+"===")
                    if sys.version_info[0] == 3:
                        errMsg = "TV2 Play: utf-8 decode error: %s" % decodedToken
                        decodedToken = decodedToken.decode("utf-8", "ignore")
                    errMsg = "TV2 Play: decodedToken is not a json object: %s" % decodedToken
                    jsObj = json.loads(decodedToken)
                    if "exp" in jsObj:
                        if jsObj["exp"]-int(time.time())>0:
                            return jwtToken
                        else:
                            xbmc.log("TV2 Play: jwtToken expired, request a new one.", xbmc.LOGINFO)
                    else:
                        xbmc.log("TV2 Play: match group 2 does not contains exp key: %s" % m.group(2), xbmc.LOGERROR)
                except:
                    xbmc.log(errMsg, xbmc.LOGERROR)
            else:
                xbmc.log("TV2 Play: jwtToken not match to (.*)\.(.*)\.(.*). jwtToken: %s" % jwtToken, xbmc.LOGERROR)
        jwtToken = login()
        if jwtToken:
            control.setSetting("loggedIn", "true")
            control.setSetting("jwtToken", jwtToken)
        else:
            control.setSetting("loggedIn", "false")
            control.setSetting("jwtToken", "")
            control.setSetting("hasPremium", "false")
            xbmcgui.Dialog().ok("TV2 Play", "Bejelentkezés sikerelen!")
        return jwtToken
    else:
        doLogout()
    return None
示例#7
0
def playVideo():
    from resources.lib import m3u8_parser
    try:
        r = client.request("%s/search/%s" % (api_url, param))
        data = json.loads(r)
        playerId = data["playerId"]
        title = data["title"]
        thumb = "%s/%s" % (
            base_url, data["imageUrl"]
        ) if "https://" not in data["imageUrl"] else data["imageUrl"]
        r = client.request("%s/streaming-url?playerId=%s" %
                           (api_url, playerId))
        data = json.loads(r)
        r = client.request(data["url"])
        json_data = json.loads(r)
        m3u_url = json_data['bitrates']['hls']
        m3u_url = json_url = re.sub('^//', 'https://', m3u_url)
        r = client.request(m3u_url)

        root = os.path.dirname(m3u_url)
        sources = m3u8_parser.parse(r)
        try:
            sources.sort(key=lambda x: int(x['resolution'].split('x')[0]),
                         reverse=True)
        except:
            pass

        auto_pick = control.setting('autopick') == '1'

        if len(sources) == 1 or auto_pick == True:
            source = sources[0]['uri']
        else:
            result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [
                str(source['resolution'])
                if 'resolution' in source else 'Unknown' for source in sources
            ])
            if result == -1:
                source = sources[0]['uri']
            else:
                source = sources[result]['uri']
        stream_url = root + '/' + source
        item = control.item(path=stream_url)
        item.setArt({'icon': thumb, 'thumb': thumb})
        item.setInfo(type='Video', infoLabels={'Title': title})
        control.resolve(int(sys.argv[1]), True, item)
    except:
        xbmcgui.Dialog().notification(
            "TV2 Play", "Hiba a forrás elérésekor! Nem található?",
            xbmcgui.NOTIFICATION_ERROR)
        return
示例#8
0
def playVideo():
    from resources.lib import m3u8_parser
    try:
        splittedParam = param.split("/")
        splittedParam[-1] = quote_plus(splittedParam[-1])
        joinedParam = "/".join(splittedParam)
        r = client.request("%s%s/search/%s" % (api_url, "/premium" if ispremium else "", joinedParam), cookie="jwt=%s" % jwtToken if jwtToken else None)
        data = json.loads(r)
        playerId = data["playerId"]
        title = data["title"]
        plot = data["lead"] if "lead" in data else ""
        thumb = "%s/%s" % (base_url, data["imageUrl"]) if "https://" not in data["imageUrl"] else data["imageUrl"]
        r = client.request("%s%s/streaming-url?playerId=%s&stream=undefined" % (api_url, "/premium" if ispremium else "", playerId), cookie="jwt=%s" % jwtToken if jwtToken else None)
        data = json.loads(r)
        if (data["geoBlocked"] != False):
            xbmcgui.Dialog().notification("TV2 Play", "A tartalom a tartózkodási helyedről sajnos nem elérhető!", xbmcgui.NOTIFICATION_ERROR)
            return
        r = client.request(data["url"])
        json_data = json.loads(r)
        m3u_url = json_data['bitrates']['hls']
        m3u_url = json_url = re.sub('^//', 'https://', m3u_url)
        r = client.request(m3u_url)

        root = os.path.dirname(m3u_url)
        sources = m3u8_parser.parse(r)
        try: 
            sources.sort(key=lambda x: int(x['resolution'].split('x')[0]), reverse=True)
        except: 
            pass

        auto_pick = control.setting('autopick') == '1'

        if len(sources) == 1 or auto_pick == True:
            source = sources[0]['uri']
        else:
            result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [str(source['resolution']) if 'resolution' in source else 'Unknown' for source in sources])
            if result == -1:
                source = sources[0]['uri']
            else:
                source = sources[result]['uri']
        stream_url = root + '/' + source
        item = control.item(path=stream_url)
        item.setArt({'icon': thumb, 'thumb': thumb})
        item.setInfo(type='Video', infoLabels = {'Title': title, 'Plot': plot})
        control.resolve(int(sys.argv[1]), True, item)
    except:
        xbmcgui.Dialog().notification("TV2 Play", "Hiba a forrás elérésekor! Nem található?", xbmcgui.NOTIFICATION_ERROR)
示例#9
0
def getVideo():
    from resources.lib import m3u8_parser
    r = client.request(url)
    try:
        try:
            json_url = re.search('jsonUrl\s*=\s*[\'"]([^\'"]+)', r).group(1)
            json_url = re.sub('^//', 'https://', json_url)
        except:
            json_url = re.findall(r'&q;originalUrl&q;:&q;([^}]*)&q;', r)
            json_url = json_url[len(json_url) - 1].replace("&a;", "&")
        r = client.request(json_url)
        json_data = json.loads(r)
        m3u_url = json_data['bitrates']['hls']
        m3u_url = json_url = re.sub('^//', 'https://', m3u_url)
        r = client.request(m3u_url)

        root = os.path.dirname(m3u_url)
        sources = m3u8_parser.parse(r)
        try:
            sources.sort(key=lambda x: int(x['resolution'].split('x')[0]),
                         reverse=True)
        except:
            pass

        auto_pick = control.setting('autopick') == '1'

        if len(sources) == 1 or auto_pick == True:
            source = sources[0]['uri']
        else:
            result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [
                str(source['resolution'])
                if 'resolution' in source else 'Unknown' for source in sources
            ])
            if result == -1:
                source = sources[0]['uri']
            else:
                source = sources[result]['uri']
        stream_url = root + '/' + source

        item = control.item(path=stream_url)
        item.setArt({'icon': iconimage, 'thumb': iconimage})
        item.setInfo(type='Video', infoLabels={'Title': name})
        control.resolve(int(sys.argv[1]), True, item)
    except:
        return
示例#10
0
                xbmc.log("TV2 Play: jwtToken not match to (.*)\.(.*)\.(.*). jwtToken: %s" % jwtToken, xbmc.LOGERROR)
        jwtToken = login()
        if jwtToken:
            control.setSetting("loggedIn", "true")
            control.setSetting("jwtToken", jwtToken)
        else:
            control.setSetting("loggedIn", "false")
            control.setSetting("jwtToken", "")
            control.setSetting("hasPremium", "false")
            xbmcgui.Dialog().ok("TV2 Play", "Bejelentkezés sikerelen!")
        return jwtToken
    else:
        doLogout()
    return None

if control.setting("firstStart") in ["true", "True"]:
    if control.yesnoDialog("A [COLOR gold]PRÉMIUM[/COLOR] tartalmak eléréséhez [B]TV2 Play Prémium[/B] csomag szükséges! A kiegészítő beállításaiban megadhatod a bejelentkezési adataidat.", nolabel='Bezárás', yeslabel='Beállítások megnyitása') == True:
        control.openSettings()
    control.setSetting('firstStart', "false")

jwtToken = getJWTToken()
hasPremium = control.setting("hasPremium") == "true"

params = dict(parse_qsl(sys.argv[2].replace('?', '')))

action = params.get('action')
param = params.get('param')
page = params.get('page')
ispremium = True if params.get('ispremium') in ["true", "True"] else False

if action == None:
示例#11
0
def constructor():

    _list_ = []
    groups = []

    if control.setting('local_or_remote') == '0':
        try:
            with open(control.setting('local')) as _file_:
                text = _file_.read()
                _file_.close()
        except IOError:
            return 'null'
    elif control.setting('local_or_remote') == '2':
        return 'Youtube'
    else:
        try:
            text = client.request(control.setting('remote'))
            if text is None:
                raise ValueError
        except ValueError:
            text = client.request(control.setting('remote'), close=False)
            if text is None:
                return 'null'

    result = text.replace('\r\n', '\n')
    items = re.compile('EXTINF:(-?\d*)(,| |.*?)\n#',
                       re.U + re.S).findall(result + '\n#')

    for duration, item in items:

        title = re.findall('[^\d*?],(.*?)\\n', ' ' + item, re.U)[0]
        link = re.findall('\\n(.*?)$', item, re.U)[0]

        if not control.condVisibility(
                'System.HasAddon(script.module.urlresolver)'):
            link = link.replace(
                'https://www.youtube.com/watch?v=',
                'plugin://plugin.video.youtube/play/?video_id=')
            link = link.replace(
                'https://youtu.be/',
                'plugin://plugin.video.youtube/play/?video_id=')

        duration = int(duration)

        if 'tvg-logo' in item:
            icon = re.findall('tvg-logo="(.*?)"', item, re.U)[0]
        elif 'icon' in item:
            icon = re.findall('icon="(.*?)"', item, re.U)[0]
        elif 'image' in item:
            icon = re.findall('image="(.*?)"', item, re.U)[0]
        else:
            icon = control.addonInfo('icon')

        if 'group-title' in item:
            group = re.findall('group-title="(.*?)"', item, re.U)[0]
        else:
            group = ''

        data = ({
            'title': title.decode('utf-8'),
            'image': icon,
            'group': 'NULL' if group == '' else group.decode('utf-8'),
            'url': link,
            'duration': duration if duration > 0 else None
        })
        _list_.append(data)
        groups.append(group.decode('utf-8'))

    trimmed_groups = list(ordereddict.OrderedDict.fromkeys(groups))

    trimmed_groups.sort()

    if len(trimmed_groups) == 1:
        control.setSetting('group', 'ALL')

    if not text.startswith('#EXTM3U'):
        return
    else:
        return _list_, trimmed_groups
示例#12
0
def main_menu():

    _list_ = []

    root_menu = [{
        'title': control.lang(30011),
        'image': control.join(control.addonmedia('settings.png')),
        'url': '{0}?action={1}'.format(sysurl, 'settings')
    }, {
        'title':
        control.lang(30015).format(
            control.lang(30016) if control.setting('group') ==
            'ALL' else control.setting('group').decode('utf-8')),
        'image':
        control.join(control.addonmedia('switcher.png')),
        'url':
        '{0}?action={1}'.format(sysurl, 'switcher')
    }]

    try:
        if constructor() == 'Youtube':
            if 'playlist?list=' in control.setting('youtube_url'):
                _items_ = root_menu + cache.get(
                    youtube.youtube(
                        key='AIzaSyA8k1OyLGf03HBNl0byD511jr9cFWo2GR4').
                    playlist,
                    int(control.setting('caching'))
                    if int(control.setting('caching')) > 0 else 0,
                    control.setting('youtube_url').partition('list=')[2])
                del _items_[1]
            elif not bool(control.setting('youtube_url')):
                raise TypeError
            else:
                raise ValueError
        elif constructor() == 'null':
            raise TypeError
        elif not constructor()[0] == []:
            if len(constructor()[1]) == 1:
                del root_menu[1]
            if control.setting('group') not in constructor()[1]:
                control.setSetting('group', 'ALL')
            filtered = [
                item for item in constructor()[0] if any(
                    item['group'] == selected
                    for selected in [control.setting('group').decode('utf-8')])
            ] if not control.setting('group') == 'ALL' else constructor()[0]
            _items_ = root_menu + filtered
        else:
            raise ValueError
    except ValueError:
        _items_ = root_menu + nullify(30013)
        del _items_[1]
    except TypeError:
        _items_ = root_menu + nullify(30026)
        del _items_[1]

    for item in _items_:

        li = control.item(label=item['title'])
        li.setInfo('video', {'title': item['title']})
        li.setArt({
            'icon': item['image'],
            'thumb': item['image'],
            'fanart': control.addonInfo('fanart')
        })
        li.setProperty('IsPlayable', 'true')
        li.addContextMenuItems([
            (control.lang(30012),
             'RunPlugin({0}?action=refresh)'.format(sysurl))
        ])
        _url_ = '{0}?action=play&url={1}'.format(sysurl, item['url'])
        isFolder = False
        if control.setting('youtube') == 'true' and item['url'].startswith(
                'plugin://plugin.video.youtube/play/?video_id='):
            _url_ = '{0}?action=play&url={1}'.format(sysurl, item['url'])
        if control.setting('youtube') == 'false' and item['url'].startswith(
                'plugin://plugin.video.youtube/play/?video_id='):
            _url_ = item['url']
        if item['url'].startswith('plugin://'):
            _url_ = item['url']
        if item['url'].endswith(('settings', 'switcher')):
            li.setProperty('IsPlayable', 'false')
        _list_.append((_url_, li, isFolder))

    control.addItems(syshandle, _list_)
    control.directory(syshandle, cacheToDisc=True)
示例#13
0
# -*- coding: utf-8 -*-

import os, xbmc, re, datetime, time
from resources.lib import client, control, cache

gmt_offset = int(control.setting('gmt.offset'))
local_time = datetime.datetime.now()
local_time = local_time + datetime.timedelta(hours=gmt_offset)
current_time = local_time.strftime("%H:%M")
current_date = local_time.strftime("%Y-%m-%d")
broadcast = {
    'm1': '1',
    'm2': '2',
    'm4 sport': '30',
    'm5': '33',
    'duna': '3',
    'duna world': '4'
}


def list_cache(channel):
    r = client.request(
        'http://www.mediaklikk.hu/iface/broadcast/%s/broadcast_%s.xml' %
        (current_date, broadcast[channel.lower()]))
    items = client.parseDOM(r, 'Item')
    return items


def get_list(channel):
    try:
        items = cache.get(list_cache, 15, channel)