Ejemplo n.º 1
0
    def onAVStarted(self):
        self._up_next = None
        self._callback = None
        self._playlist = None

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        up_next = get_kodi_string('_slyguy_play_next')
        if up_next:
            set_kodi_string('_slyguy_play_next')
            up_next = json.loads(up_next)
            if up_next['playing_file'] == self.getPlayingFile():
                if up_next['next_file']:
                    self._playlist.remove(up_next['next_file'])
                    self._playlist.add(up_next['next_file'],
                                       index=self._playlist.getposition() + 1)

                if up_next['time']:
                    self._up_next = up_next

        callback = get_kodi_string('_slyguy_play_callback')
        if callback:
            set_kodi_string('_slyguy_play_callback')
            callback = json.loads(callback)
            if callback['playing_file'] == self.getPlayingFile(
            ) and callback['callback']:
                self._callback = callback

        if self._up_next or self._callback:
            self._thread = Thread(target=self.playback,
                                  args=(self.getPlayingFile(), ))
            self._thread.start()
    def onAVStarted(self):
        self._callback = None
        self._play_skips = []
        self._playing_file = self.getPlayingFile()

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        play_skips = []
        up_next = get_kodi_string('_slyguy_play_next')
        if up_next:
            set_kodi_string('_slyguy_play_next')
            up_next = json.loads(up_next)
            if up_next['playing_file'] == self._playing_file:
                if up_next['next_file']:
                    self._playlist.remove(up_next['next_file'])
                    self._playlist.add(up_next['next_file'],
                                       index=self._playlist.getposition() + 1)

                #legacy
                if up_next['time']:
                    play_skips.append({'from': up_next['time'], 'to': 0})

        _skips = get_kodi_string('_slyguy_play_skips')
        if _skips:
            set_kodi_string('_slyguy_play_skips')
            data = json.loads(_skips)
            if data['playing_file'] == self._playing_file:
                play_skips.extend(data['skips'])

        for skip in play_skips:
            if not skip.get('to'):
                skip['to'] = int(self.getTotalTime()) + 1
            else:
                if skip['to'] < 0:
                    self.seekTime(self.getTotalTime() + skip['to'] - 3)
                    continue

                skip['to'] -= 3

            if not skip.get('from'):
                continue

            self._play_skips.append(skip)

        callback = get_kodi_string('_slyguy_play_callback')
        if callback:
            set_kodi_string('_slyguy_play_callback')
            callback = json.loads(callback)
            if callback['playing_file'] == self._playing_file and callback[
                    'callback']:
                self._callback = callback

        if self._callback or self._play_skips:
            self._thread = Thread(target=self.playback)
            self._thread.start()
Ejemplo n.º 3
0
    def Playlist_Size(self):
        playlistId = xbmc.PLAYLIST_VIDEO
        if xbmc.PlayList(1).size() > 0:
            playlistId = 1
        elif xbmc.PlayList(0).size() > 0:
            playlistId = 0

        pl = xbmc.PlayList(playlistId)
        return pl.size()
Ejemplo n.º 4
0
    def onAVStarted(self):
        try:
            play_data = json.loads(get_kodi_string('_slyguy_play_data'))
        except:
            return

        set_kodi_string('_slyguy_play_data')

        self._callback = None
        self._play_skips = []
        self._playing_file = self.getPlayingFile()

        if play_data['playing_file'] != self._playing_file:
            return

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        play_skips = play_data['skips']

        if play_data['next']['next_file']:
            self._playlist.remove(play_data['next']['next_file'])
            self._playlist.add(play_data['next']['next_file'],
                               index=self._playlist.getposition() + 1)

        #legacy
        if play_data['next']['time']:
            play_skips.append({'from': play_data['next']['time'], 'to': 0})

        for skip in play_skips:
            if not skip.get('to'):
                skip['to'] = int(self.getTotalTime()) + 1
            else:
                if skip['to'] < 0:
                    self.seekTime(self.getTotalTime() + skip['to'] - 3)
                    continue

                skip['to'] -= 3

            if not skip.get('from'):
                continue

            self._play_skips.append(skip)

        ## Workaround for suspect IA bug: https://github.com/xbmc/inputstream.adaptive/issues/821
        # if int(self.getTime()) < 0:
        #     self.seekTime(0)

        if play_data['callback']['callback']:
            self._callback = play_data['callback']

        if self._callback or self._play_skips:
            self._thread = Thread(target=self.playback)
            self._thread.start()
Ejemplo n.º 5
0
def failed_playback():
    handle = _handle()
    xbmcplugin.setResolvedUrl(handle, False, Item(path='http').get_li())
    xbmcplugin.endOfDirectory(handle,
                              succeeded=True,
                              updateListing=False,
                              cacheToDisc=False)
    if KODI_VERSION < 18:
        xbmc.PlayList(xbmc.PLAYLIST_MUSIC).clear()
        xbmc.PlayList(xbmc.PLAYLIST_VIDEO).clear()
Ejemplo n.º 6
0
    def onAVStarted(self):
        self._up_next = None
        self._callback = None
        self._playlist = None

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        up_next = get_kodi_string('_slyguy_play_next')
        if up_next:
            set_kodi_string('_slyguy_play_next')
            up_next = json.loads(up_next)
            if up_next['playing_file'] == self.getPlayingFile():
                if up_next['next_file']:
                    self._playlist.remove(up_next['next_file'])
                    self._playlist.add(up_next['next_file'], index=self._playlist.getposition()+1)

                if up_next['time']:
                    self._up_next = up_next

        callback = get_kodi_string('_slyguy_play_callback')
        if callback:
            set_kodi_string('_slyguy_play_callback')
            callback = json.loads(callback)
            if callback['playing_file'] == self.getPlayingFile() and callback['callback']:
                self._callback = callback

        if self._up_next or self._callback:
            self._thread = Thread(target=self.playback, args=(self.getPlayingFile(),))
            self._thread.start()

    # def onPlayBackEnded(self):
    #     vid_playlist   = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    #     music_playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    #     position       = vid_playlist.getposition()+1

    #     if (vid_playlist.size() <= 1 or vid_playlist.size() == position) and (music_playlist.size() <= 1 or music_playlist.size() == position):
    #         self.onPlayBackStopped()

    # def onPlayBackStopped(self):
    #     set_kodi_string('_slyguy_last_quality')

    # def onPlayBackStarted(self):
    #     pass

    # def onPlayBackPaused(self):
    #     print("AV PAUSED")

    # def onPlayBackResumed(self):
    #     print("AV RESUME")

    # def onPlayBackError(self):
    #     self.onPlayBackStopped()
Ejemplo n.º 7
0
    def Playlist_Left(self):
        playlistId = xbmc.PLAYLIST_VIDEO
        if xbmc.PlayList(1).size() > 0:
            playlistId = 1
        elif xbmc.PlayList(0).size() > 0:
            playlistId = 0

        pl = xbmc.PlayList(playlistId)
        if pl.size() == 0:
            return 0
        elif pl.getposition() <= 0:
            return 0
        else:
            return pl.size() - pl.getposition()
Ejemplo n.º 8
0
def shuffle_category(key):
    """Generate a shuffled playlist and start playing"""

    data = get_json('https://data.jw-api.org/mediator/v1/categories/' +
                    global_lang + '/' + key + '?&detailed=1')
    data = data['category']
    all_media = data.get('media', [])
    for sc in data.get('subcategories', []):  # type: dict
        # Don't include things like Featured, because that would become duplicate
        if 'AllowShuffleInCategoryHeader' in sc.get('tags', []):
            all_media += sc.get('media', [])

    # Shuffle in place, we don't want to mess with Kodi's settings
    random.shuffle(all_media)

    pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    pl.clear()

    for md in all_media:
        media = Media()
        media.parse_media(md, censor_hidden=False)
        if media.url and not media.hidden:
            pl.add(media.resolved_url, media.listitem())

    xbmc.Player().play(pl)
Ejemplo n.º 9
0
 def resolveURL(self, id, opt):
     log('resolveURL, id = %s, opt = %s' % (id, opt))
     #todo if opt == live extra meta parse else pvr return link only
     self.listitems = []
     self.playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     self.playlist.clear()
     programmes = self.getGuidedata()
     data = [
         program for program in programmes
         if program['Channel']['Number'] == id
     ]
     channel = list(
         filter(lambda channel: channel['number'] == id,
                self.getChannels()))[0]
     self.poolList(self.buildPlayItem, data, ('play', False))
     liz = xbmcgui.ListItem(channel['name'], path=channel['url'])
     liz.setProperty('IsPlayable', 'true')
     if opt != 'pvr':
         [
             self.playlist.add(channel['url'], lz, idx)
             for idx, lz in enumerate(self.listitems)
         ]
         liz = self.listitems.pop(0)
         liz.setPath(path=channel['url'])
     return liz
Ejemplo n.º 10
0
 def resolveURL(self, tunerkey, channel, opt=None):
     log('resolveURL, channel = %s, opt = %s'%(channel,opt)) 
     self.listitems = []
     self.playlist  = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     self.playlist.clear()
     liz = xbmcgui.ListItem('')
     self.setDevice(tunerkey)
     info  = self.pyHDHR.getLiveTVChannelInfo(channel)
     url   = info.getURL()
     tuner = info.getTuner()
     if tuner.getModelNumber() == "HDTC-2US":
         if self.transcode == 'default': tranOPT = (tuner.getTranscodeOption() or 'none')
         else: tranOPT = self.transcode
         log("resolveURL, Tuner transcode option: " + tranOPT)
         if tranOPT != "none": video = {'codec': 'h264'}
         url = "%s?transcode=%s"%(url,tranOPT)
     else: liz.setMimeType('video/mpeg')
     liz.setProperty('IsPlayable','true') 
     
     if opt != 'pvr':
         chan  = self.getChannelInfo(channel)
         progs = chan.getProgramInfos()
         for prog in progs: self.buildChannelListItem(tunerkey, channel, prog, 'play')
         [self.playlist.add(url,lz,idx) for idx,lz in enumerate(self.listitems)]
         liz = self.listitems.pop(0)
         liz.setPath(path=url)
     else: liz.setPath(url)
     return liz
Ejemplo n.º 11
0
 def resolveURL(self, id, opt):
     log('resolveURL, id = %s, opt = %s' % (id, opt))
     self.listitems = []
     self.playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     self.playlist.clear()
     '''{u'dma': 501, u'streamUrl': u'https://acdn.locastnet.org/variant/E27GYubZwfUs.m3u8', u'name': u'WNBCDT2', u'sequence': 50, u'stationId': u'44936', u'callSign': u'4.2 COZITV', u'logo226Url': u'https://fans.tmsimg.com/assets/s78851_h3_aa.png', u'logoUrl': u'https://fans.tmsimg.com/assets/s78851_h3_aa.png', u'active': True, u'id': 1574529688491L}'''
     data = self.getURL(BASE_API + '/watch/station/%s/%s/%s' %
                        (id, self.lat, self.lon),
                        header=self.buildHeader(),
                        life=datetime.timedelta(seconds=5))
     url = data.get('streamUrl')
     liz = xbmcgui.ListItem(data.get('name'), path=url)
     liz.setProperty('IsPlayable', 'true')
     liz.setProperty('IsInternetStream', 'true')
     if opt != 'pvr':
         self.getStations(data.get('dma'),
                          name=data.get('name'),
                          opt='play')
         [
             self.playlist.add(url, lz, idx)
             for idx, lz in enumerate(self.listitems)
         ]
         liz = self.listitems.pop(0)
         liz.setPath(path=url)
     return liz
Ejemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
     if DISABLE_TRAKT: xbmcgui.Window(10000).setProperty('script.trakt.paused','true')
     self.playList  = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)        
     self.fileCount = 0
     self.cache     = SimpleCache()
     self.myPlayer  = Player()
     self.myPlayer.myBackground = self
Ejemplo n.º 13
0
def process_tracks(context, url, tree=None):
    xbmcplugin.addSortMethod(get_handle(), xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(get_handle(),
                             xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE)
    xbmcplugin.addSortMethod(get_handle(), xbmcplugin.SORT_METHOD_DURATION)
    xbmcplugin.addSortMethod(get_handle(), xbmcplugin.SORT_METHOD_SONG_RATING)
    xbmcplugin.addSortMethod(get_handle(), xbmcplugin.SORT_METHOD_TRACKNUM)

    tree = get_xml(context, url, tree)
    if tree is None:
        return

    playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    playlist.clear()

    server = context.plex_network.get_server_from_url(url)

    content_counter = {
        'photo': 0,
        'track': 0,
        'video': 0,
    }
    items = []
    append_item = items.append
    if PY3:
        branches = tree.iter()
    else:
        branches = tree.getiterator()

    for branch in branches:
        tag = branch.tag.lower()
        item = Item(server, url, tree, branch)
        if tag == 'track':
            append_item(create_track_item(context, item))
        elif tag == 'photo':  # mixed content audio playlist
            append_item(create_photo_item(context, item))
        elif tag == 'video':  # mixed content audio playlist
            append_item(create_movie_item(context, item))

        if isinstance(content_counter.get(tag), int):
            content_counter[tag] += 1

    if items:
        content_type = 'songs'
        if context.settings.mixed_content_type() == 'majority':
            majority = max(content_counter, key=content_counter.get)
            if majority == 'photo':
                content_type = 'images'
            elif majority == 'video':
                content_type = 'movies'

        xbmcplugin.setContent(get_handle(), content_type)
        xbmcplugin.addDirectoryItems(get_handle(), items, len(items))

    xbmcplugin.endOfDirectory(get_handle(),
                              cacheToDisc=context.settings.cache_directory())
Ejemplo n.º 14
0
 def playAlbum(self, album, startpos=-1, fanart=None):
     self.handler = AudioPlayerHandler(self)
     plist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
     plist.clear()
     index = 1
     for track in album.tracks():
         url, li = self.createTrackListItem(track, fanart, index=index)
         plist.add(url, li)
         index += 1
     xbmc.executebuiltin('PlayerControl(RandomOff)')
     self.stopAndWait()
     self.play(plist, startpos=startpos)
Ejemplo n.º 15
0
    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        if DISABLE_TRAKT:
            xbmcgui.Window(10000).setProperty('script.trakt.paused', 'true')
        self.playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        self.fileCount = 0
        self.cache = SimpleCache()
        self.myPlayer = Player()
        self.myPlayer.myBackground = self

        if saveVolume():
            setVolume(int(REAL_SETTINGS.getSetting('SetVolume')))
        setRepeat('all')
Ejemplo n.º 16
0
    def generate(self):
        with ProgressDialog(i18n('Generating Playlist'), i18n('This may take a while...')) as \
                progress_dialog:

            progress_dialog.update(0, i18n('Retrieving server list...'))
            servers = self._get_servers()
            if progress_dialog.is_canceled():
                return None

            progress_dialog.update(10, i18n('Retrieving server sections...'))
            sections = self._get_sections(servers, progress_dialog)
            if progress_dialog.is_canceled():
                return None

            progress_dialog.update(20, i18n('Retrieving content metadata...'))
            item_collections = self._get_item_collections(
                sections, progress_dialog)
            if progress_dialog.is_canceled():
                return None

            progress_dialog.update(60, i18n('Retrieving final sample...'))
            items = self._get_sample(item_collections)
            if progress_dialog.is_canceled():
                return None

            progress_dialog.update(70, i18n('Adding items to playlist...'))
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()

            _divisor, _percent_value = self._get_progress_data(items, 29)
            _percent = progress_dialog.percent

            for index, item in enumerate(items):
                if progress_dialog.is_canceled():
                    return None

                if index % _divisor == 0:
                    _percent += _percent_value
                progress_dialog.update(
                    _percent,
                    i18n('Adding %s to playlist...') % item[1].getLabel())

                playlist.add(*item)

            if progress_dialog.is_canceled():
                return None

            progress_dialog.update(100, i18n('Completed.'))
            xbmc.sleep(500)
            return items[0]
Ejemplo n.º 17
0
    def playQueueCallback(self, **kwargs):
        plist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        # plist.clear()
        try:
            citem = kodijsonrpc.rpc.Player.GetItem(playerid=0,
                                                   properties=['comment'
                                                               ])['item']
            plexID = citem['comment'].split(':', 1)[0]
        except:
            util.ERROR()
            return

        current = plist.getposition()
        size = plist.size()

        # Remove everything but the current track
        for x in range(size - 1, current,
                       -1):  # First everything with a greater position
            kodijsonrpc.rpc.Playlist.Remove(playlistid=xbmc.PLAYLIST_MUSIC,
                                            position=x)
        for x in range(current):  # Then anything with a lesser position
            kodijsonrpc.rpc.Playlist.Remove(playlistid=xbmc.PLAYLIST_MUSIC,
                                            position=0)

        swap = None
        for idx, track in enumerate(self.playQueue.items()):
            tid = 'PLEX-{0}'.format(track.ratingKey)
            if tid == plexID:
                # Save the position of the current track in the pq
                swap = idx

            url, li = self.player.createTrackListItem(track, index=idx + 1)

            plist.add(url, li)

        plist[0].setInfo('music', {
            'playcount': swap + 1,
        })

        # Now swap the track to the correct position. This seems to be the only way to update the kodi playlist position to the current track's new position
        if swap is not None:
            kodijsonrpc.rpc.Playlist.Swap(playlistid=xbmc.PLAYLIST_MUSIC,
                                          position1=0,
                                          position2=swap + 1)
            kodijsonrpc.rpc.Playlist.Remove(playlistid=xbmc.PLAYLIST_MUSIC,
                                            position=0)

        self.player.trigger('playlist.changed')
Ejemplo n.º 18
0
def play_track(pubdata, track, resolve=False):
    # type: (PublicationData, int, bool) -> None
    """Start playback of a track in a publication"""

    try:
        pub, media_list = download_pub_data(pubdata)
        item = next(MediaItem(m) for m in media_list if m.track == track)
        if resolve:
            xbmcplugin.setResolvedUrl(addon_handle, True, item.listitem_with_resolved_url())
        else:
            pl = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            pl.clear()
            pl.add(item.resolved_url, item.listitem())
            xbmc.Player().play(pl)
    except (NotFoundError, StopIteration):
        xbmcgui.Dialog().ok('', S.NOT_AVAIL)
Ejemplo n.º 19
0
    def playAudioPlaylist(self, playlist, startpos=-1, fanart=None):
        self.handler = AudioPlayerHandler(self)
        plist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        plist.clear()
        index = 1
        for track in playlist.items():
            url, li = self.createTrackListItem(track, fanart, index=index)
            plist.add(url, li)
            index += 1

        if playlist.isRemote:
            self.handler.setPlayQueue(playlist)
        else:
            if playlist.startShuffled:
                plist.shuffle()
                xbmc.executebuiltin('PlayerControl(RandomOn)')
            else:
                xbmc.executebuiltin('PlayerControl(RandomOff)')
        self.stopAndWait()
        self.play(plist, startpos=startpos)
def play_playlist(context, server, data):
    LOG.debug('Creating new playlist')
    playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    playlist.clear()

    url = server.join_url(server.get_url_location(),
                          data['extra'].get('album'), 'children')
    tree = get_xml(context, url)

    if tree is None:
        return

    track_tags = tree.findall('Track')
    add_to_playlist = playlist.add
    item_constructor = xbmcgui.ListItem

    for track in track_tags:
        LOG.debug('Adding playlist item')
        item = Item(server, None, tree, track)
        track = create_track_item(context, item, listing=False)
        url = track[0]
        details = track[1]
        if CONFIG['kodi_version'] >= 18:
            list_item = item_constructor(details.get('title', i18n('Unknown')),
                                         offscreen=True)
        else:
            list_item = item_constructor(details.get('title', i18n('Unknown')))

        thumb = data['full_data'].get('thumbnail', CONFIG['icon'])
        if 'thumbnail' in data['full_data']:
            del data['full_data']['thumbnail']  # not a valid info label

        list_item.setArt({'icon': thumb, 'thumb': thumb})
        list_item.setInfo(type='music', infoLabels=details)
        add_to_playlist(url, list_item)

    index = int(data['extra'].get('index', 0)) - 1
    LOG.debug(
        'Playlist complete.  Starting playback from track %s [playlist index %s] '
        % (data['extra'].get('index', 0), index))
    xbmc.Player().playselected(index)
Ejemplo n.º 21
0
 def resolveURL(self, id, opt):
     log('resolveURL, id = %s, opt = %s' % (id, opt))
     self.listitems = []
     self.playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     self.playlist.clear()
     channel = list(
         filter(lambda k: k.get('_id', '') == id, self.getGuidedata()))[0]
     urls = channel.get('stitched', {}).get('urls', [])
     if isinstance(urls, list):
         urls = [
             url['url'] for url in urls if url['type'].lower() == 'hls'
         ][0]
     liz = xbmcgui.ListItem(channel.get('name'), path=urls)
     liz.setProperty('IsPlayable', 'true')
     liz.setProperty('IsInternetStream', 'true')
     if opt != 'pvr':
         self.browseGuide(opt='play', data=[channel])
         [
             self.playlist.add(urls, lz, idx)
             for idx, lz in enumerate(self.listitems)
         ]
         liz = self.listitems.pop(0)
         liz.setPath(path=urls)
     return liz
Ejemplo n.º 22
0
 def Playlist_Clear(self):
     playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     return playlist.clear()
Ejemplo n.º 23
0
 def Playlist_Add(self, url, item):
     playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     # playlist.clear()
     return playlist.add(url=url, listitem=item)
Ejemplo n.º 24
0
def run(context):
    context.plex_network = plex.Plex(context.settings, load=True)
    play = composite_playlist(context) and wait_for_busy_dialog()
    if play:
        xbmc.Player().play(item=xbmc.PlayList(xbmc.PLAYLIST_VIDEO), startpos=0)
Ejemplo n.º 25
0
 def get_position(self):
     playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
     position = playlist.getposition()
     return playlist, position
Ejemplo n.º 26
0
    def get_playlist(self, item):

        if item['Type'] == 'Audio':
            return xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        return xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
Ejemplo n.º 27
0
getCurrentDialogId = xbmcgui.getCurrentWindowDialogId()

getCurrentWinId = xbmcgui.getCurrentWindowId()

keyboard = xbmc.Keyboard

monitor = xbmc.Monitor()

execute = xbmc.executebuiltin

skin = xbmc.getSkinDir()

player = xbmc.Player()

playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)

resolve = xbmcplugin.setResolvedUrl

legalFilename = xbmc.makeLegalFilename if getKodiVersion() < 19 else xbmcvfs.makeLegalFilename

openFile = xbmcvfs.File

makeFile = xbmcvfs.mkdir

deleteFile = xbmcvfs.delete

deleteDir = xbmcvfs.rmdir

listDir = xbmcvfs.listdir
Ejemplo n.º 28
0
def playlist(mode=1):
    """
    # mode=1 for video and mode=0 for music/audio
    """

    return xbmc.PlayList(mode)
Ejemplo n.º 29
0
def queueVideo(url, name):
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    listitem = xbmcgui.ListItem(name)
    playlist.add(url, listitem)
Ejemplo n.º 30
0
def parse(item, quality=None, geolock=None):
    if quality is None:
        quality = get_quality()
        if quality == QUALITY_CUSTOM:
            quality = int(settings.getFloat('max_bandwidth') * 1000000)
    else:
        quality = int(quality)

    if quality in (QUALITY_DISABLED, QUALITY_SKIP):
        return

    url = item.path.split('|')[0]
    parse = urlparse(url.lower())

    if 'http' not in parse.scheme:
        return

    parser = None
    if item.inputstream and item.inputstream.check():
        is_ia = True
        if item.inputstream.manifest_type == 'mpd':
            parser = MPD()
        elif item.inputstream.manifest_type == 'hls':
            parser = M3U8()
    else:
        is_ia = False
        if parse.path.endswith('.m3u') or parse.path.endswith('.m3u8'):
            parser = M3U8()

    if not parser:
        return

    if item.use_proxy:
        url = gui.PROXY_PATH + url

    try:
        resp = Session().get(url,
                             headers=item.headers,
                             cookies=item.cookies,
                             attempts=1,
                             timeout=30)
    except Exception as e:
        log.exception(e)
        return False
    else:
        result = resp.ok

    if not result:
        error = require_country(geolock)
        if not error:
            error = _(_.QUALITY_PARSE_ERROR,
                      error=_(_.QUALITY_HTTP_ERROR, code=resp.status_code))

        gui.ok(error)
        return False

    try:
        parser.parse(resp.text, proxy_enabled=item.use_proxy)
        qualities = parser.qualities()
    except Exception as e:
        log.exception(e)
        gui.ok(_(_.QUALITY_PARSE_ERROR, error=e))
        return

    if len(qualities) < 2:
        log.debug('Only found {} quality, skipping quality select'.format(
            len(qualities)))
        return

    qualities = sorted(qualities, key=lambda s: s[0], reverse=True)

    if quality == QUALITY_ASK:
        quality = get_kodi_string('_slyguy_last_quality')
        addon = get_kodi_string('_slyguy_last_addon')
        playlist_pos = xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition()

        if quality and addon == ADDON_ID and (playlist_pos > 0 or
                                              (xbmc.Player().isPlaying()
                                               and playlist_pos == -1)):
            quality = int(quality)
        else:
            quality = select_quality(qualities)

        set_kodi_string('_slyguy_last_quality', quality)
        set_kodi_string('_slyguy_last_addon', ADDON_ID)

        if quality == QUALITY_SKIP:
            return

    if quality == QUALITY_BEST:
        quality = qualities[0][0]
    elif quality == QUALITY_LOWEST:
        quality = qualities[-1][0]

    min_bandwidth, max_bandwidth, stream = parser.bandwidth_range(quality)
    if stream['adaption_set'] > 0 and item.use_proxy:
        item.headers['_proxy_adaption_set'] = str(stream['adaption_set'])

    set_settings(min_bandwidth, max_bandwidth, is_ia)