Exemplo n.º 1
0
 def parental_control_is_active():
     now = datetime.datetime.now()
     hour_start = get_setting_as_int('parental.control.start')
     hour_now = now.hour
     hour_end = get_setting_as_int('parental.control.end')
     return get_setting_as_bool(
         'parental.control.enabled') and hour_start <= hour_now <= hour_end
Exemplo n.º 2
0
    def onClick(self, controlID):
        if controlID == 9100:
            self.ClearAllListviews()
            sHost = kodiutils.get_setting('host')
            iPort = kodiutils.get_setting_as_int('port')
            bUseSSL = kodiutils.get_setting_as_bool('usessl')

            #Show error if we don't have any port or host
            if len(sHost) == 0:
                kodiutils.dialogok(__language__(30008), __language__(30009),
                                   __language__(30010), "")
                kodiutils.show_settings()
                return

            self.getControl(9002).setLabel(
                kodiutils.get_setting('host'))  #print the host we connect to
            log("Connecting to: " + sHost)
            self.WS.ConnectTo(sHost, iPort, bUseSSL, "directory")
        if controlID == 9102:
            self.ClearAllListviews()
            self.WS.terminate()
        if controlID == 6000:
            self.CleanUp()
            self.close()
        if controlID == 9500:
            self.SetSorting("NAME", True)
        if controlID == 9501:
            self.SetSorting("MODIFY", True)
        if controlID == 9502:
            self.SetSorting("SIZE", True)
        if controlID == 9503:
            self.SetCleanFilename(
                self.getControl(9503).isSelected() == 1, True)
        if controlID == 100:
            self.onClickDirectory()
        if controlID == 500:
            self.onClickFilelist()
        if controlID == 9101:
            kodiutils.show_settings()
            self.getControl(9002).setLabel(kodiutils.get_setting('host'))
        if controlID == 600:
            self.onClickQueue()
        if controlID == 601:
            if kodiutils.dialogyesno(__language__(30011),
                                     __language__(30012)) == True:
                self.WS.SendMOTRCommand(
                    "QUEUEMANAGEMENT", "-1;clear-finished"
                )  #QueueID = -1 when default commands are used
        if controlID == 602:
            if kodiutils.dialogyesno(__language__(30011),
                                     __language__(30013)) == True:
                self.WS.SendMOTRCommand(
                    "QUEUEMANAGEMENT", "-1;stop-all-running"
                )  #QueueID = -1 when default commands are used
        if controlID == 603:
            if kodiutils.dialogyesno(__language__(30011),
                                     __language__(30014)) == True:
                self.WS.SendMOTRCommand(
                    "QUEUEMANAGEMENT", "-1;remove-all"
                )  #QueueID = -1 when default commands are used
Exemplo n.º 3
0
def loop():
    monitor = xbmc.Monitor()

    while not monitor.abortRequested():
        # Sleep/wait for abort for 10 seconds
        if kodiutils.get_setting_as_bool("debug"):
            kodiutils.notification(kodiutils.get_string(30032), "Debug :: Timer set to %d" % kodiutils.get_setting_as_int("timer"),
                                   time=5000, icon=ADDON.getAddonInfo('icon'),
                                   sound=True)
        if monitor.waitForAbort(kodiutils.get_setting_as_int("timer")):
            # Abort was requested while waiting. We should exit
            break

        logger.debug("Edem.tv.parser is launched parse function at %s" % time.time())
        parse()
def get_videos(name,playlist_id,token="",page_num=1):
    items_per_page = kodiutils.get_setting_as_int("items_per_page")
    url_api = 'https://www.googleapis.com/youtube/v3/playlistItems?part=id,snippet,contentDetails&maxResults=%s&playlistId=%s&key=%s' \
              % (str(items_per_page), playlist_id, YOUTUBE_API_KEY)
    if page_num != 1:
        url_api += "&pageToken=%s" % (token)

    try:
        resp = requests.get(url_api).json()
    except ValueError:
        kodiutils.log(kodiutils.get_string(32004), xbmc.LOGERROR)
        resp = None

    if resp:
        nextpagetoken = resp["nextPageToken"] if "nextPageToken" in list(resp.keys()) else ""
        availablevideos = resp["pageInfo"]["totalResults"] if "pageInfo" in list(resp.keys()) and "totalResults" in list(resp["pageInfo"].keys()) else 1

        returnedVideos = resp["items"]
        totalpages = int(math.ceil((float(availablevideos) / items_per_page)))
        video_ids = []
        if returnedVideos:
            for video in returnedVideos:
                videoid = video["contentDetails"]["videoId"]
                video_ids.append(videoid)
            video_ids = ','.join(video_ids)
            url_api = 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s' % (video_ids,YOUTUBE_API_KEY)
            try:
                resp = requests.get(url_api).json()
            except ValueError:
                kodiutils.log(kodiutils.get_string(32005), xbmc.LOGERROR)
                resp = None

            if resp:
                returnedVideos = resp["items"]

                for video in returnedVideos:
                    title = video["snippet"]["title"]
                    plot = video["snippet"]["description"]
                    aired = video["snippet"]["publishedAt"]
                    thumb = video["snippet"]["thumbnails"]["high"]["url"]
                    videoid = video["id"]
                    # process duration
                    duration_string = video["contentDetails"]["duration"]
                    duration = addonutils.return_duration_as_seconds(duration_string)
                    try:
                        aired = re.compile('(.+?)-(.+?)-(.+?)T').findall(aired)[0]
                        date = aired[2] + '.' + aired[1] + '.' + aired[0]
                        aired = aired[0] + '-' + aired[1] + '-' + aired[2]
                    except IndexError:
                        aired = ''
                        date = ''

                    infolabels = {'plot': plot.encode('utf-8'), 'aired': aired, 'date': date, 'tvshowtitle': TVSHOWTITLE,
                                  'title': title.encode('utf-8'), 'originaltitle': title.encode('utf-8'), 'status': STATUS,
                                  'cast': CAST, 'duration': duration}

                    # Video and audio info
                    video_info = {'codec': 'avc1', 'aspect': 1.78}
                    audio_info = {'codec': 'aac', 'language': 'en'}
                    if video["contentDetails"]["definition"].lower() == 'hd':
                        video_info['width'] = 1280
                        video_info['height'] = 720
                        audio_info['channels'] = 2
                    else:
                        video_info['width'] = 854
                        video_info['height'] = 480
                        audio_info['channels'] = 1
                    if xbmcaddon.Addon(id='plugin.video.youtube').getSetting('kodion.video.quality.ask') == 'false' and xbmcaddon.Addon(
                                    id='plugin.video.youtube').getSetting('kodion.video.quality') != '3' and xbmcaddon.Addon(
                                    id='plugin.video.youtube').getSetting('kodion.video.quality') != '4':
                        video_info['width'] = 854
                        video_info['height'] = 480
                        audio_info['channels'] = 1

                    yield build_video_item(title.encode('utf-8'), thumb, videoid, infolabels, video_info, audio_info)

    if totalpages > 1 and (page_num + 1) <= totalpages:
        nextpage = ListItem("[B]%s[/B] (%s/%s)" % (kodiutils.get_string(32008), str(page_num), str(totalpages)))
        nextpage.setProperty("type", "next")
        nextpage.setProperty("page", str(page_num+1))
        nextpage.setProperty("token", str(nextpagetoken))
        nextpage.setInfo(type="video",infoLabels={"plot": kodiutils.get_string(32002)})
        yield nextpage
Exemplo n.º 5
0
def legacy_root_menu():
    include_premium = adobe_activate_api.is_authenticated()
    channel_list = events.get_channel_list(include_premium)
    curdate = datetime.utcnow()
    upcoming = get_setting_as_int('upcoming') + 1
    days = (curdate + timedelta(days=upcoming)).strftime("%Y%m%d")
    # Live
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(live_events_mode,
                       espn_url=events.get_live_events_url(channel_list)),
        make_list_item(get_string(30029)), True)
    # Upcoming
    espn_url = events.get_upcoming_events_url(channel_list) + '&endDate=' + days \
        + '&startDate=' + curdate.strftime("%Y%m%d")
    addDirectoryItem(plugin.handle,
                     plugin.url_for(list_sports, espn_url=espn_url),
                     make_list_item(get_string(30030)), True)
    enddate = '&endDate=' + (curdate + timedelta(days=1)).strftime("%Y%m%d")
    replays1 = [5, 10, 15, 20, 25]
    replays1 = replays1[get_setting_as_int('replays1')]
    start1 = (curdate - timedelta(days=replays1)).strftime("%Y%m%d")
    replays2 = [10, 20, 30, 40, 50]
    replays2 = replays2[get_setting_as_int('replays2')]
    start2 = (curdate - timedelta(days=replays2)).strftime("%Y%m%d")
    replays3 = [30, 60, 90, 120]
    replays3 = replays3[get_setting_as_int('replays3')]
    start3 = (curdate - timedelta(days=replays3)).strftime("%Y%m%d")
    replays4 = [60, 90, 120, 240]
    replays4 = replays4[get_setting_as_int('replays4')]
    start4 = (curdate - timedelta(days=replays4)).strftime("%Y%m%d")
    start_all = (curdate - timedelta(days=365)).strftime("%Y%m%d")
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start1),
        make_list_item(get_string(30031) % replays1), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start2),
        make_list_item(get_string(30031) % replays2), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start3),
        make_list_item(get_string(30031) % replays3), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       '&endDate=' + start3 + '&startDate=' + start4),
        make_list_item(get_string(30033) % (replays3, replays4)), True)
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(list_sports,
                       espn_url=events.get_replay_events_url(channel_list) +
                       enddate + '&startDate=' + start_all),
        make_list_item(get_string(30032)), True)
    xbmcplugin.endOfDirectory(plugin.handle)
Exemplo n.º 6
0
def play_video(video_id, channel):
    # remove channel number if available
    if "_" in video_id:
        video_id = video_id.split("_")[1]
    config_url = ""
    if channel == "All Channels Feed" or channel == "":
        # no channel info guess by id
        if not video_id.isdigit():
            #probalby a video from puls4 or atv
            config_url = ids.get_livestream_config_url("puls4_and_atv_at")
        else:
            config_url = ids.get_livestream_config_url("austrian_tv")
    else:
        if channel == "PULS 4" or channel == "ATV":
            config_url = ids.get_livestream_config_url("puls4_and_atv_at")
        else:
            config_url = ids.get_livestream_config_url("austrian_tv")
    config = json.loads(get_url(config_url, cache=True, critical=True))
    mdsV2 = config["mdsclient"]["mdsV2"]
    sources_request_url = mdsV2["baseUrl"]+"vas/live/v2/videos?access_token=%s&client_location=null&client_name=%s&ids=%s" % (mdsV2["accessToken"], mdsV2["clientName"], video_id)
    sources_request = json.loads(get_url(sources_request_url, critical=True))
    log("sources_request: " + str(sources_request))
    protected = sources_request[0]["is_protected"]
    mpd_id = 0
    m3u8_id = 0
    ism_id = 0
    mp4_id = 0
    protocol = ""
    for source in sources_request[0]["sources"]:
        if source["mimetype"] == "text/xml":
            ism_id = source["id"]
        if source["mimetype"] == "application/x-mpegURL":
            m3u8_id = source["id"]
        if source["mimetype"] == "application/dash+xml":
            mpd_id = source["id"]
        if source["mimetype"] == "video/mp4":
            mp4_id = source["id"]
    drm = None
    if not protected:
        if kodiutils.get_setting_as_int('non_drm_format') == 0:
            source_id = mpd_id
            protocol = "mpd"
        elif kodiutils.get_setting_as_int('non_drm_format') == 3:
            source_id = mp4_id
            protocol = "mp4"
        else:
            source_id = m3u8_id
            protocol = "hls"
    else:
        if kodiutils.get_setting("drm") == "0":
            source_id = mpd_id
            protocol = "mpd"
            drm_name = "widevine"
            drm = 'com.widevine.alpha'
        else:
            source_id = ism_id
            protocol = "ism"
            drm_name = "playready"
            drm = 'com.microsoft.playready'

    if protected and LooseVersion('18.0') > LooseVersion(xbmc.getInfoLabel('System.BuildVersion')):
        log("version is: " + xbmc.getInfoLabel('System.BuildVersion'))
        kodiutils.notification('ERROR', kodiutils.get_string(32025))
        setResolvedUrl(plugin.handle, False, ListItem('none'))
        return

    server_request_token = get_video_server_request_token(access_token=mdsV2["accessToken"], client_location="null", client_name=mdsV2["clientName"], video_id=video_id, salt=mdsV2["salt"])
    server_request_url = mdsV2["baseUrl"]+"vas/live/v2/videos/%s/sources?access_token=%s&client_id=%s&client_location=null&client_name=%s" % (video_id, mdsV2["accessToken"], server_request_token, mdsV2["clientName"])
    server_request = json.loads(get_url(server_request_url, critical=True))
    server_id = server_request["server_id"]

    start = ""
    end = ""
    if protected and kodiutils.get_setting("drm") == "0" and kodiutils.get_setting_as_bool("oldformat"):
        start = "0"
        end = "999999999"

    source_url_request_token = get_video_source_request_token(access_token=mdsV2["accessToken"], client_location="null", client_name=mdsV2["clientName"], server_id= server_id, source_id=source_id, video_id=video_id, salt=mdsV2["salt"], start=start, end=end)
    source_url_request_url = mdsV2["baseUrl"]+"vas/live/v2/videos/%s/sources/url?access_token=%s&client_id=%s&client_location=null&client_name=%s&secure_delivery=true&server_id=%s&source_ids=%s" % (video_id, mdsV2["accessToken"], source_url_request_token, mdsV2["clientName"], server_id, source_id)

    if protected and kodiutils.get_setting("drm") == "0"and kodiutils.get_setting_as_bool("oldformat"):
        source_url_request_url += "&subclip_start=0&subclip_end=999999999"

    source_url_request = json.loads(get_url(source_url_request_url, critical=True))
    if not "status_code" in source_url_request or source_url_request["status_code"] != 0:
        log("error on video request: " + str(source_url_request))
        return sys.exit(0)

    playitem = ListItem('none')
    log("selected non drm format: " + kodiutils.get_setting('non_drm_format'))
    log("media url: " + source_url_request["sources"][0]["url"])
    if not protected and (kodiutils.get_setting_as_int('non_drm_format') == 2 or kodiutils.get_setting_as_int('non_drm_format') == 3):
        playitem = ListItem(label=xbmc.getInfoLabel('Container.ShowTitle'), path=source_url_request["sources"][0]["url"]+"|User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
        setResolvedUrl(plugin.handle, True, playitem)
    else:
        is_helper = None
        try:
            is_helper = inputstreamhelper.Helper(protocol, drm=drm)
        except Exception as e:
            if str(e) == 'UnsupportedDRMScheme' and drm == 'com.microsoft.playready':
                is_helper = inputstreamhelper.Helper(protocol, drm=None)
                pass
            else:
                kodiutils.notification('ERROR', kodiutils.get_string(32018).format(drm))
        #check for inputstream_addon
        inputstream_installed = False
        if is_helper:
            inputstream_installed = is_helper._has_inputstream()

        if is_helper and not inputstream_installed:
            # ask to install inputstream
            xbmc.executebuiltin('InstallAddon({})'.format(is_helper.inputstream_addon), True)
            inputstream_installed = is_helper._has_inputstream()

        if is_helper and inputstream_installed and is_helper.check_inputstream():
            version = xbmcaddon.Addon('inputstream.adaptive').getAddonInfo('version')
            if not protected and kodiutils.get_setting_as_int('non_drm_format') == 0 and LooseVersion(version) < LooseVersion("2.2.2"):
                # inputstream to old cannot play mpd
                # switch to hls
                kodiutils.set_setting('non_drm_format', 1)
                play_video(video_id, channel)
            elif protected and LooseVersion(version) < LooseVersion("2.2.2"):
                # inputstream to old cannot play mpd
                xbmcgui.Dialog().ok(heading=kodiutils.get_string(32023), line1=kodiutils.get_string(32024))
                setResolvedUrl(plugin.handle, False, ListItem(label='none'))
            else:
                playitem = ListItem(label=xbmc.getInfoLabel('Container.ShowTitle'), path=source_url_request["sources"][0]["url"]+"|User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                playitem.setProperty('inputstreamaddon', is_helper.inputstream_addon)
                playitem.setProperty('inputstream.adaptive.manifest_type', protocol)
                if protected:
                    playitem.setProperty('inputstream.adaptive.license_type', drm)
                    playitem.setProperty('inputstream.adaptive.license_key', source_url_request["drm"]["licenseAcquisitionUrl"] + "?token=" + source_url_request["drm"]["token"] +"|User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" +'|R{SSM}|')
                setResolvedUrl(plugin.handle, True, playitem)
        else:
            if drm:
                kodiutils.notification('ERROR', kodiutils.get_string(32019).format(drm))
                setResolvedUrl(plugin.handle, False, playitem)
            else:
                if xbmcgui.Dialog().yesno(heading=kodiutils.get_string(32020), line1=kodiutils.get_string(32021), line2=kodiutils.get_string(32022).format(kodiutils.get_string(32110))):
                    if LooseVersion('18.0') > LooseVersion(xbmc.getInfoLabel('System.BuildVersion')):
                        kodiutils.set_setting('non_drm_format', 3)
                    else:
                        kodiutils.set_setting('non_drm_format', 2)
                    play_video(video_id, channel)
                else:
                    setResolvedUrl(plugin.handle, False, playitem)
Exemplo n.º 7
0
    def video_score(self, score, pos, s):
        megabit = 1e6
        speed = settings.get_setting_as_int('stream.adv.speedtest')
        if speed > 0:
            debug('set max_bitrate from speedtest: {}Mbps'.format(
                int(speed * 0.8 / megabit)))
            max_bitrate = int(speed * 0.8)
        else:
            max_bitrate = get_setting_as_int('stream.max.bitrate') * megabit
        debug('video max_bitrate: {}'.format(max_bitrate))

        quality = s.get('quality', 'SD')
        max_quality = get_setting('stream.max.quality')
        debug('qualita {} vs {} | {} >= {}'.format(
            quality, max_quality, self.QUALITY_LIST[max_quality],
            self.QUALITY_LIST[quality]))
        if quality in self.QUALITY_LIST:
            if max_quality == '-':
                score[pos] += self.QUALITY_LIST[quality]
                debug('quality point 1: {} / {}'.format(
                    self.QUALITY_LIST[quality], score[pos]))
            elif self.QUALITY_LIST[max_quality] >= self.QUALITY_LIST[quality]:
                w = self.QUALITY_LIST[max_quality] - (
                    self.QUALITY_LIST[max_quality] -
                    self.QUALITY_LIST[quality] - 1)
                score[pos] += w
                debug('quality point 2: {} / {}'.format(w, score[pos]))
            else:
                debug('nehodnotime rozlisenie 1')
        else:
            debug('nehodnotime rozlisenie 2')

        bitrate = int(s.get('bitrate', 0))
        if max_bitrate >= 100 * megabit:
            score[pos] += 1
            debug('vsetky bitrate su dobre, bitrate {} / {}'.format(
                bitrate, score[pos]))
        elif bitrate < max_bitrate:
            score[pos] += 1
            debug('nizsi bitrate {} < {} / {}'.format(bitrate, max_bitrate,
                                                      score[pos]))
        else:
            score[pos] -= 10
            debug('prilis velky bitrate {} > {} / {}'.format(
                bitrate, max_bitrate, score[pos]))

        stream_info = s.get('stream_info', {})
        video = stream_info.get('video', {})
        vcodec = video.get('codec')

        if get_setting_as_bool('stream.adv'):
            if vcodec in get_setting('stream.adv.blacklist.codec'):
                score[pos] -= 10
                debug('blacklist codec {} / {}'.format(vcodec, score[pos]))

            if vcodec in get_setting('stream.adv.whitelist.codec'):
                score[pos] += 1
                debug('whitelist codec {} / {}'.format(vcodec, score[pos]))

            if get_setting_as_bool(
                    'stream.adv.exclude.3d') and '3D' in quality:
                score[pos] -= 10
                debug('penalize 3D content {}'.format(score[pos]))

            if get_setting_as_bool(
                    'stream.adv.exclude.hdr') and stream_info.get('HDR'):
                score[pos] -= 10
                debug('penalize HDR content {}'.format(score[pos]))

            if get_setting_as_bool(
                    'stream.adv.prefer.hdr') and stream_info.get('HDR'):
                score[pos] += 1
                debug('prefer HDR {}'.format(score[pos]))

        return score
Exemplo n.º 8
0
    def filter(self):
        speedtest_last = get_setting_as_int('stream.adv.speedtest.last')
        now = time.time()
        force = True if speedtest_last is None or (
            speedtest_last + (24 * 3600 * 2)) < now else False

        isp = self.isp()
        asn = settings.get_setting('stream.adv.speedtest.asn')
        asn_changed = str(isp.get('a')) != str(asn)
        wrong_speed = settings.get_setting_as_int('stream.adv.speedtest') < 1
        debug('Force: {} ASN: {} / {} [{}] / SPEED: {} [{}]'.format(
            force, asn, isp.get('a'), asn_changed,
            settings.get_setting_as_int('stream.adv.speedtest'), wrong_speed))
        if force is True or (get_setting_as_int('stream.max.bitrate') == 100
                             and (asn_changed or wrong_speed)):
            smin, smax, dur = self.speedtest(isp)
            debug('smin {} / smax {} / dur {}'.format(smin, smax, dur))

        # @todo autoselect / filtrovanie nechcenych streamov
        if not get_setting_as_bool('stream.autoselect') \
                or SC.ACTION_SELECT_STREAM in self.params or SC.ACTION_DOWNLOAD in self.params:
            debug(
                'nieje autoselect, alebo je vynuteny vyber streamu alebo download'
            )
            return

        if get_setting_as_bool('stream.autoselect'):

            lang1 = get_setting('stream.lang1').lower()
            lang2 = get_setting('stream.lang2').lower()
            if Sc.parental_control_is_active():
                lang1 = get_setting('parental.control.lang1').lower()
                lang2 = get_setting('parental.control.lang2').lower()

            score = {pos: 0 for pos, s in enumerate(self.streams)}
            for pos, s in enumerate(self.streams):
                debug(
                    '-----------------------------------------------------------------------------------------------'
                )
                debug('stream: bitrate: {} quality: {} lang: {}'.format(
                    s.get('bitrate', 0), s.get('quality', 'N/A'),
                    s.get('linfo', 'N/A')))
                self.video_score(score, pos, s)

                stream_info = s.get('stream_info', {})
                linfo = s.get('linfo', [])
                if lang1 in linfo:
                    score = self.audio_score(lang1, pos, score, stream_info, 3)
                elif lang2 in linfo:
                    score = self.audio_score(lang2, pos, score, stream_info, 1)
                else:
                    debug('Nemame primarny, ani sekundarny jazyk')

                debug(
                    '-----------------------------------------------------------------------------------------------'
                )
                debug('final score: {}'.format(score[pos]))

            score = {
                k: v
                for k, v in sorted(
                    score.items(), key=lambda item: item[1], reverse=True)
            }
            sel = list(score.keys())[0]
            debug('score: {} / {}'.format(score, sel))
            self.selected = self.streams[sel]
            self.streams = [self.selected]
            return

        debug('autoselect nic nevybral, tak nechame usera vybrat')