Пример #1
0
    def create_ctrl_map(self, dialog, map_file):
        """
        :type dialog:   DialogProgress
        :type map_file: str
        """
        mapping_proc = subprocess.Popen(
                ['stdbuf', '-oL', self.config_helper.get_binary(), 'map', map_file, '-input',
                 self.plugin.get_setting('input_device', unicode)], stdout=subprocess.PIPE)

        lines_iterator = iter(mapping_proc.stdout.readline, b"")

        mapping_thread = threading.Thread(target=loop_lines, args=(dialog, lines_iterator))
        mapping_thread.start()

        success = False

        # TODO: Make a method or function from this
        while True:
            xbmc.sleep(1000)
            if not mapping_thread.isAlive():
                dialog.close()
                success = True
                break
            if dialog.iscanceled():
                mapping_proc.kill()
                dialog.close()
                success = False
                break

        if os.path.isfile(map_file) and success:

            return True
        else:

            return False
Пример #2
0
    def _populate(self):
        xbmc.sleep(500)  # Delay population to let ui settle
        self.label.setLabel(self.title)
        for result in self.populator():
            self.step()

            if not result:
                continue

            with self.lock:
                # Remember selected item
                selectedItem = None
                if self.insideIndex == -1:
                    selectedIndex = self.list.getSelectedPosition()
                else:
                    selectedIndex = self.insideIndex
                if selectedIndex >= 0:
                    selectedItem = self.items[selectedIndex]

                # Add new item
                self.items.append(result)
                self.items.sort()

                # Retrived new selection-index
                if selectedItem is not None:
                    selectedIndex = self.items.index(selectedItem)
                    if self.insideIndex != -1:
                        self.insideIndex = selectedIndex

                # Update only if in root
                if self.insideIndex == -1:
                    self._inside_root(select=selectedIndex)
                    self.setFocus(self.list)

        pass
Пример #3
0
    def _populate(self):
        xbmc.sleep(500) # Delay population to let ui settle
        self.label.setLabel(self.title)
        for result in self.populator():
            self.step()
            
            if not result:
                continue
            
            with self.lock:
                # Remember selected item
                selectedItem = None
                if self.insideIndex == -1:
                    selectedIndex = self.list.getSelectedPosition()
                else:
                    selectedIndex = self.insideIndex   
                if selectedIndex >= 0:
                    selectedItem = self.items[selectedIndex]

                # Add new item
                self.items.append(result)
                self.items.sort()

                # Retrived new selection-index
                if selectedItem is not None:
                    selectedIndex = self.items.index(selectedItem)
                    if self.insideIndex != -1:
                        self.insideIndex = selectedIndex
                
                # Update only if in root
                if self.insideIndex == -1:
                    self._inside_root(select=selectedIndex)
                    self.setFocus(self.list)
        
        pass
Пример #4
0
def movies_batch_add_to_library():
    """ Batch add movies to library """
    movie_batch_file = plugin.get_setting(SETTING_MOVIES_BATCH_ADD_FILE_PATH)
    if xbmcvfs.exists(movie_batch_file):
        try:
            f = open(xbmc.translatePath(movie_batch_file), 'r')
            r = f.read()
            f.close()
            ids = r.split('\n')
        except: return plugin.notify(msg='Movies Batch Add File', title='Not found', delay=3000, image=get_icon_path("movies"))
        library_folder = setup_library(plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER))
        import_tmdb()
        for id in ids:
            if "," in id:
                csvs = id.split(',')
                for csv in csvs:
                    if not str(csv).startswith("tt") and csv != "":
                        movie = tmdb.Movies(csv).info()
                        id = movie.get('imdb_id')
                    batch_add_movies_to_library(library_folder, id)
            else:
                if not str(id).startswith("tt") and id != "":
                    movie = tmdb.Movies(id).info()
                    id = movie.get('imdb_id')
                batch_add_movies_to_library(library_folder, id)
        os.remove(xbmc.translatePath(movie_batch_file))
        if xbmcvfs.exists(plugin.get_setting(SETTING_TV_BATCH_ADD_FILE_PATH)): 
            xbmc.executebuiltin("RunPlugin(plugin://plugin.video.metalliq/tv/batch_add_to_library)")
            return True
        else:
            xbmc.sleep(1000)
            plugin.notify(msg='Added movie strm-files', title='Starting library scan', delay=3000, image=get_icon_path("movies"))
            scan_library(type="video")
            return True
    elif xbmcvfs.exists(plugin.get_setting(SETTING_TV_BATCH_ADD_FILE_PATH)): xbmc.executebuiltin("RunPlugin(plugin://plugin.video.metalliq/tv/batch_add_to_library)")
Пример #5
0
    def create_ctrl_map(self, dialog, map_file):
        mapping_proc = subprocess.Popen([
            'stdbuf', '-oL',
            self.config_helper.get_binary(), 'map', map_file, '-input',
            self.plugin.get_setting('input_device', unicode)
        ],
                                        stdout=subprocess.PIPE)

        lines_iterator = iter(mapping_proc.stdout.readline, b"")

        mapping_thread = threading.Thread(target=loop_lines,
                                          args=(dialog, lines_iterator))
        mapping_thread.start()

        success = False

        # TODO: Make a method or function from this
        while True:
            xbmc.sleep(1000)
            if not mapping_thread.isAlive():
                dialog.close()
                success = True
                break
            if dialog.iscanceled():
                mapping_proc.kill()
                dialog.close()
                success = False
                break

        if os.path.isfile(map_file) and success:

            return True
        else:

            return False
Пример #6
0
def scan_library(type="video"):
    while not xbmc.abortRequested and \
     (xbmc.getCondVisibility('Library.IsScanning') or \
     xbmc.getCondVisibility('Window.IsActive(progressdialog)')):
        xbmc.sleep(1000)
    xbmc.executebuiltin('UpdateLibrary(video)')
    xbmc.executebuiltin('UpdateLibrary(music)')
Пример #7
0
def movies_batch_add_to_library():
    """ Batch add movies to library """
    movie_batch_file = plugin.get_setting(SETTING_MOVIES_BATCH_ADD_FILE_PATH, unicode)
    if xbmcvfs.exists(movie_batch_file):
        try:
            f = open(xbmc.translatePath(movie_batch_file), 'r')
            r = f.read()
            f.close()
            ids = r.split('\n')
        except: return dialogs.notify(msg='Movies Batch Add File', title=_("%s not found").replace("%s ",""), delay=3000, image=get_icon_path("movies"))
        library_folder = setup_library(plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER, unicode))
        import_tmdb()
        for id in ids:
            if "," in id:
                csvs = id.split(',')
                for csv in csvs:
                    if not str(csv).startswith("tt") and csv != "":
                        movie = tmdb.Movies(csv).info()
                        csv = movie.get('imdb_id')
                    batch_add_movies_to_library(library_folder, csv)
            else:
                if not str(id).startswith("tt") and id != "":
                    movie = tmdb.Movies(id).info()
                    id = movie.get('imdb_id')
                batch_add_movies_to_library(library_folder, id)
        os.remove(xbmc.translatePath(movie_batch_file))
        if xbmcvfs.exists(plugin.get_setting(SETTING_TV_BATCH_ADD_FILE_PATH, unicode)):
            xbmc.executebuiltin("RunPlugin(plugin://plugin.video.chappaai/tv/batch_add_to_library)")
            return True
        else:
            xbmc.sleep(1000)
            dialogs.notify(msg='Added movie strm-files', title='Starting library scan', delay=3000, image=get_icon_path("movies"))
            scan_library(type="video")
            return True
    if xbmcvfs.exists(plugin.get_setting(SETTING_TV_BATCH_ADD_FILE_PATH, unicode)): xbmc.executebuiltin("RunPlugin(plugin://plugin.video.chappaai/tv/batch_add_to_library)")
Пример #8
0
def scan_library(type="video"):
    while not xbmc.abortRequested and \
     (xbmc.getCondVisibility('Library.IsScanning') or \
     xbmc.getCondVisibility('Window.IsActive(progressdialog)')):
        xbmc.sleep(1000)
    xbmc.executebuiltin('UpdateLibrary(video)')
    xbmc.executebuiltin('UpdateLibrary(music)')
Пример #9
0
def search():
    keyboard = xbmc.Keyboard('', '请输入关键字 (片名/AV)')
    xbmc.sleep(1500)
    keyboard.doModal()
    if keyboard.isConfirmed():
        keyword = keyboard.getText()
        return searchResult(page=1, keyword=keyword)
Пример #10
0
def i1IIi11111i():
    o000o0o00o0Oo("Login", "/login")
    xbmc.executebuiltin('Dialog.Close(busydialog)')
    try:
        oo = requests.get(
            "http://echipstore.com/get-code/?nocache=true").json()
        IiII1I1i1i1ii = oo["message"] % oo["user_code"].upper()
        IIIII = xbmcgui.DialogProgress()
        IIIII.create('Login', IiII1I1i1i1ii)
        if 26 - 26: O00OoOoo00.iiiI11 / oooOOOOO * IiiIII111ii / i1iIIi1
        ii11iIi1I = 0
        while ii11iIi1I < 60:
            iI111I11I1I1 = int((ii11iIi1I / 60.0) * 100)
            if IIIII.iscanceled():
                break
            IIIII.update(iI111I11I1I1, "")
            ii11iIi1I = ii11iIi1I + 1
            xbmc.sleep(5000)
            i1I11i = requests.get(
                "http://echipstore.com/device?device_code=%s&nocache=true" %
                urllib.quote_plus(oo["device_code"]))
            if "token" in i1I11i.text:
                Oo0Ooo.setSetting("token", i1I11i.json()["token"])
                Oo0Ooo.setSetting("email", i1I11i.json()["email"])
                break
        IIIII.close()
        del IIIII
        xbmc.executebuiltin('XBMC.Container.Update(%s)' % O0O0OO0O0O0)
    except:
        OOooO0OOoo = xbmcgui.Dialog()
        OOooO0OOoo.ok("Oops!",
                      "Có lỗi xảy ra. Xin quý vị vui lòng login vào dịp khác")
        if 29 - 29: o00o / IiI1I1
Пример #11
0
def o0o00o0():
    i1IIi11111i("Login", "/login")
    xbmc.executebuiltin('Dialog.Close(busydialog)')
    try:
        iIi1ii1I1 = requests.get(
            "http://echipstore.com/get-code/?nocache=true").json()
        o0 = iIi1ii1I1["message"] % iIi1ii1I1["user_code"].upper()
        I11II1i = xbmcgui.DialogProgress()
        I11II1i.create('Login', o0)
        if 23 - 23: ooO00oOoo / iiI1i1 + i1iIIII + i1iIIII / Iii1IIIiiI
        iiI1 = 0
        while iiI1 < 60:
            i11Iiii = int((iiI1 / 60.0) * 100)
            if I11II1i.iscanceled():
                break
            I11II1i.update(i11Iiii, "")
            iiI1 = iiI1 + 1
            xbmc.sleep(5000)
            iII1i1I1II = requests.get(
                "http://echipstore.com/device?device_code=%s&nocache=true" %
                urllib.quote_plus(iIi1ii1I1["device_code"]))
            if "token" in iII1i1I1II.text:
                o0O.setSetting("token", iII1i1I1II.json()["token"])
                o0O.setSetting("email", iII1i1I1II.json()["email"])
                break
        I11II1i.close()
        del I11II1i
        xbmc.executebuiltin('XBMC.Container.Update(%s)' % iI11I1II1I1I)
    except:
        i1 = xbmcgui.Dialog()
        i1.ok("Oops!", "Có lỗi xảy ra. Xin quý vị vui lòng login vào dịp khác")
        if 48 - 48: ooO0OO000o + ooO0OO000o - ooO00oOoo.i1iIIIiI1I / I11i11Ii
Пример #12
0
def input_keyword():
    keyboard = Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        keyword = keyboard.getText()
        url = plugin.url_for("search_title", title=keyword)
        plugin.redirect(url)
Пример #13
0
def input_keyword():
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        keyword = keyboard.getText()
        url = url_for('search', title=keyword, page=1)
        plugin.redirect(url)
Пример #14
0
def input_keyword():
    keyboard = Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        keyword = keyboard.getText()
        url = plugin.url_for("search_title", title=keyword)
        plugin.redirect(url)
Пример #15
0
def action_prerun(link):
#    xbmc.executebuiltin('ActivateWindow(10025,addons://user/xbmc.addon.video/plugin.video.zen/,return)')
    if link.startswith("plugin://"):
        id = link.split("/")
        xbmc.executebuiltin('RunAddon(%s)' % id[2])
        while xbmc.getInfoLabel('Container.PluginName') != id[2] or xbmc.getCondVisibility('Window.IsActive(busydialog)'): xbmc.sleep(250)
        xbmc.sleep(250)
        xbmc.executebuiltin('Container.Update("%s")' % link)
Пример #16
0
def search():
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        keyword = keyboard.getText()
        url = HOST_URL + '/index.php?m=vod-search&wd=' + keyword
        return category(url)
Пример #17
0
    def show_countdown(self, time_to_wait, title='', text=''):
        '''
        Show a countdown dialog with a progress bar for XBMC while delaying 
        execution. Necessary for some filehosters eg. megaupload
        
        The original version of this code came from Anarchintosh.
        
        Args:
            time_to_wait (int): number of seconds to pause for.
            
        Kwargs:
            title (str): Displayed in the title of the countdown dialog. Default
            is blank.
                         
            text (str): A line of text to be displayed in the dialog. Default
            is blank.
            
        Returns: 
            ``True`` if countdown is allowed to complete, ``False`` if the 
            user cancelled the countdown.
        '''
        
        dialog = xbmcgui.DialogProgress()
        ret = dialog.create(title)

        self.log_notice('waiting %d secs' % time_to_wait)
        
        secs = 0
        increment = 100 / time_to_wait

        cancelled = False
        while secs <= time_to_wait:

            if (dialog.iscanceled()):
                cancelled = True
                break

            if secs != 0: 
                xbmc.sleep(1000)

            secs_left = time_to_wait - secs
            if secs_left == 0: 
                percent = 100
            else: 
                percent = increment * secs
            
            remaining_display = ('Wait %d seconds for the ' +
                    'video stream to activate...') % secs_left
            dialog.update(percent, text, remaining_display)

            secs += 1

        if cancelled == True:     
            self.log_notice('countdown cancelled')
            return False
        else:
            self.log_debug('countdown finished waiting')
            return True        
Пример #18
0
def wait_for_dialog(dialog_id, timeout=None, interval=500):
    start = time.time()

    while not xbmc.getCondVisibility("Window.IsActive(%s)" % dialog_id):
        if xbmc.abortRequested or (timeout and time.time() - start >= timeout):
            return False
        xbmc.sleep(interval)

    return True
Пример #19
0
def delete_path(userid, path):
    api = get_api(userid)
    try:
        plugin.notify('正在删除文件,请稍候...', delay=2000)
        api.delete(path)
    except PCSApiError as e:
        xbmcutils.show_msg(str(e), '错误')
    else:
        xbmc.sleep(1000)
        xbmcutils.refresh()
def action_prerun(link):
    #    xbmc.executebuiltin('ActivateWindow(10025,addons://user/xbmc.addon.video/plugin.video.zen/,return)')
    if link.startswith("plugin://"):
        id = link.split("/")
        xbmc.executebuiltin('RunAddon(%s)' % id[2])
        while xbmc.getInfoLabel('Container.PluginName') != id[
                2] or xbmc.getCondVisibility('Window.IsActive(busydialog)'):
            xbmc.sleep(250)
        xbmc.sleep(250)
        xbmc.executebuiltin('Container.Update("%s")' % link)
Пример #21
0
def delete_path(userid, path):
    api = get_api(userid)
    try:
        plugin.notify('正在删除文件,请稍候...', delay=2000)
        api.delete(path)
    except PCSApiError as e:
        xbmcutils.show_msg(str(e), '错误')
    else:
        xbmc.sleep(1000)
        xbmcutils.refresh()
Пример #22
0
def wait_for_dialog(dialog_id, timeout=None, interval=500):
    start = time.time()
    
    while not xbmc.getCondVisibility("Window.IsActive(%s)" % dialog_id):
        if xbmc.abortRequested or \
         (timeout and time.time() - start >= timeout):
            return False
        xbmc.sleep(interval)
        
    return True
Пример #23
0
def search():
    plugin.set_content('TVShows')
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if not keyboard.isConfirmed():
        return

    keyword = keyboard.getText()
    p_url = 'http://so.tv.sohu.com/mts?chl=&tvType=-2&wd='
    url = p_url + quote_plus(keyword)

    # construct url based on user selected item
    page = 1
    p_url = url + '&fee=0&whole=1&m=1&box=1&p=%d' % page
    link = get_html(p_url)

    #########################################################################
    # Video listing for all found related episode title
    tree = BeautifulSoup(link, 'html.parser')
    soup = tree.find_all('div', {'class': 'ssItem cfix'})

    #########################################################################
    items = []
    for page in soup[0]:
        try:
            p_url = httphead(page.a['href'])
        except:
            continue
        p_name = page.a['title'].encode('utf-8')
        img = httphead(page.img['src'])
        infop = page.find('p', {'class': 'des'})
        try:
            info = infop.text
        except:
            info = ''
        items.append({
            'label': p_name,
            'path': url_for('episodelist1', url=p_url),
            'thumbnail': httphead(page.img['src']),
            'info': {'title': p_name, 'plot': info}
        })

        album = page.find_all('a', {'class': 'ts'})
        for series in album:
            items.append({
                'label': series['title'],
                'path': url_for('playvideo', name=series['title'],
                                url=httphead(series['href']),
                                image=httphead(page.img['src'])),
                'is_playable': True,
                'info': {'title': series['title']},
            })

    return items
Пример #24
0
def search():
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if not keyboard.isConfirmed():
        return

    keyword = keyboard.getText()
    url = HOST_URL + '/x/search/?q=' + quote_plus(keyword)
    url += '&stag=0'

    link = get_html(url)
    items = []
    if link is None:
        xbmcgui.Dialog().ok(plugin.addon.getAddonInfo('name'),
                            ' 抱歉,没有找到[COLOR FFFF0000] ' + keyword
                            + ' [/COLOR]的相关视频')
        return items

    items.append({
        'label': '[COLOR FFFF0000]当前搜索:(' + keyword + ')[/COLOR]',
    })

    # fetch and build the video series episode list
    content = BeautifulSoup(link, 'html.parser')
    soup = content.find_all('div', {'class': 'result_item'})

    for item in soup:
        href = httphead(item.a['href'])
        img = httphead(item.img['src'])
        title = item.img['alt']

        info = item.find('span', {'class': 'desc_text'})
        try:
            info = info.text
        except:
            info = ''
        items.append({
            'label': title,
            'path': url_for('episodelist', url=href),
            'thumbnail': img,
            'info': {'title': title, 'plot': info}
        })

        list = item.find_all('div', {'class': 'item'})
        for series in list:
            subtitle = series.a.text
            href = httphead(series.a['href'])
            items.append({
                'label': subtitle,
                'path': url_for('playvideo', vid=href),
                'is_playable': True,
                'info': {'title': subtitle}
            })
    return items
Пример #25
0
    def create_ctrl_map_new(self, dialog, map_file, device):
        # TODO: Implementation detail which should be hidden?
        input_queue = Queue.Queue()
        input_map = InputMap(map_file)
        input_device = None

        for handler in device.handlers:
            if handler[:-1] == 'js':
                input_device = os.path.join('/dev/input', handler)

        if not input_device:
            return False

        input_wrapper = InputWrapper(input_device, device.name, input_queue,
                                     input_map)
        input_wrapper.build_controller_map()

        print 'num buttons: %s' % input_wrapper.num_buttons
        print 'num_axes: %s' % input_wrapper.num_axes
        expected_input_number = input_wrapper.num_buttons + (
            input_wrapper.num_axes * 2)

        js = StoppableJSHandler(input_wrapper, input_map)
        it = StoppableInputHandler(input_queue, input_map, dialog,
                                   expected_input_number)

        success = False

        while True:
            xbmc.sleep(1000)
            if not it.isAlive():
                js.stop()
                dialog.close()
                js.join(timeout=2)
                if input_map.status == InputMap.STATUS_DONE:
                    success = True
                if input_map.status == InputMap.STATUS_PENDING or input_map.status == InputMap.STATUS_ERROR:
                    success = False
                break
            if dialog.iscanceled():
                it.stop()
                js.stop()
                success = False
                it.join(timeout=2)
                js.join(timeout=2)
                dialog.close()
                break

        if os.path.isfile(map_file) and success:

            return True
        else:

            return False
Пример #26
0
def keyboard(default='', heading='', hidden=False):

    if hidden:
        kb = _xbmc.Keyboard(default, heading, hidden)
    else:
        kb = xbmc.Keyboard(default, heading)

    xbmc.sleep(1000)
    kb.doModal()
    if (kb.isConfirmed()):
        return kb.getText()
Пример #27
0
 def background_task(self):
     xbmc.sleep(1000)
     while not xbmc.abortRequested and self.active:
         if self.hide_progress:
             active_window = xbmcgui.getCurrentWindowDialogId()
             if active_window in [10101,10151]:
                 xbmc.executebuiltin("Dialog.Close(%d, true)" % active_window)
         if self.hide_info:
             if xbmc.getCondVisibility("Window.IsActive(infodialog)"):
                 xbmc.executebuiltin('Dialog.Close(infodialog, true)')                
         xbmc.sleep(100)
Пример #28
0
 def background_task(self):
     xbmc.sleep(1000)
     while not xbmc.abortRequested and self.active:
         if self.hide_progress:
             active_window = xbmcgui.getCurrentWindowDialogId()
             if active_window in [10101, 10151]:
                 xbmc.executebuiltin("Dialog.Close(%d, true)" %
                                     active_window)
         if self.hide_info:
             if xbmc.getCondVisibility("Window.IsActive(infodialog)"):
                 xbmc.executebuiltin('Dialog.Close(infodialog, true)')
         xbmc.sleep(100)
def list_library():
    while not xbmc.abortRequested and \
     (xbmc.getCondVisibility('Library.IsScanning') or \
     xbmc.getCondVisibility('Window.IsActive(progressdialog)') or \
     xbmc.getCondVisibility('Window.IsActive(extendedprogressdialog)')):
        xbmc.sleep(100)
    xbmc.sleep(5000)
    library = {}
    medias = ["movies", "tvshows"]
    #    medias = ["movies", "tvshows", "musicvideos", "music", "live"]
    for m in medias:
        if m == "movies":
            lib = plugin.get_setting(SETTING_MOVIES_LIBRARY_FOLDER, unicode)
            prite = RPC.videolibrary.get_movies(properties=[
                "title", "year", "playcount", "fanart", "originaltitle",
                "imdbnumber", "thumbnail", "file"
            ])
            if "movies" in prite: ite = prite["movies"]
            else: ite = []
        elif m == "tvshows":
            lib = plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode)
            prite = RPC.videolibrary.get_tvshows(properties=[
                "title", "year", "playcount", "fanart", "originaltitle",
                "imdbnumber", "thumbnail", "file"
            ])
            if "tvshows" in prite: ite = prite["tvshows"]
            else: ite = []
#        elif m == "musicvideos":
#            lib = plugin.get_setting(SETTING_TV_LIBRARY_FOLDER, unicode)
#            ite = RPC.videolibrary.get_tvshows(properties=["title","year","playcount","fanart","originaltitle","imdbnumber","thumbnail","file"])["tvshows"]
        else:
            continue
        liq = xbmcvfs.listdir(lib)[0]
        for i in ite:
            try:
                f = xbmcvfs.File(
                    os.path.join(lib, i["imdbnumber"], "player.info"))
                i["player"] = f.read()
                f.close()
            except:
                i["player"] = "na"
        f = xbmcvfs.File("{0}library.nfo".format(lib), 'w')
        f.write(str(ite))
        f.close()
        if len(ite) > 0:
            players = dict(zip(ite[0],
                               zip(*[d.values() for d in ite])))["player"]
        else:
            players = "()"
        f = xbmcvfs.File("{0}players.nfo".format(lib), 'w')
        f.write(str(players))
        f.close()
Пример #30
0
def search():
    plugin.set_content('TVShows')
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    # keyboard.setHiddenInput(hidden)
    xbmc.sleep(1000)
    keyboard.doModal()
    if not keyboard.isConfirmed():
        return

    keyword = keyboard.getText()

    page = 1
    #p_url = 'http://so.le.com/s?hl=1&dt=2&ph=420001&from=pcjs&ps=30&wd='
    p_url = 'http://suggest.letv.cn/suggestion?jf=3&q='
    link = get_html(p_url + quote_plus(keyword))
    items = []

    lists = loads(link)
    # fetch and build the video series episode list
    content = BeautifulSoup(link, 'html.parser')

    for item in lists['data_list']:
        try:
            aid = item['aid']
        except:
            continue

        title = item['name'].encode('utf-8')
        cate = item.get('sub_category_name', '')
        if cate:
            cate = '({})'.format(cate.encode('utf-8'))
        eps = item.get('episodes', 0)
        img = item.get('post_st', '')
        #if eps == '' or int(eps) < 2:
        #    items.append({
        #        'label': title + cate,
        #        'path': url_for('playvideo', vid=aid),
        #        'thumbnail': img,
        #        'is_playable': True,
        #        'info': {'title': title}
        #    })
        #else:
        items.append({
            'label': title + cate,
            'path': url_for('episodelist', aid=aid),
            'thumbnail': img,
            'info': {
                'title': title
            }
        })

    return items
Пример #31
0
    def pair_host(self, dialog):
        """
        :type dialog: DialogProgress
        """
        self.logger.info('[MoonlightHelper] - Attempting to pair host: ' + self.plugin.get_setting('host', unicode))
        pairing_proc = subprocess.Popen(
                ['stdbuf', '-oL', self.config_helper.get_binary(), 'pair', self.plugin.get_setting('host', unicode)],
                stdout=subprocess.PIPE)

        lines_iterator = iter(pairing_proc.stdout.readline, b"")

        pairing_thread = threading.Thread(target=loop_lines, args=(dialog, lines_iterator))
        pairing_thread.start()

        success = False

        while True:
            xbmc.sleep(1000)
            if not pairing_thread.isAlive():
                success = True
                break
            if dialog.iscanceled():
                pairing_proc.kill()
                dialog.close()
                success = False
                break

        if success:
            dialog.update(0, 'Checking if pairing has been successful.')
            xbmc.sleep(1000)
            pairing_check = subprocess.Popen([self.config_helper.get_binary(), 'list', self.config_helper.get_host()],
                                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            last = ''

            while True:
                line = pairing_check.stdout.readline()
                err = pairing_check.stderr.readline()
                if not re.match(self.regex_moonlight, line) and not re.match(self.regex_connect, line):
                    if line != '':
                        last = line
                if err != '':
                    last = err
                if not line and not err:
                    break

            dialog.close()
            if last.lower().strip() != 'You must pair with the PC first'.lower().strip() and not re.match(self.regex_connection_failed, last):
                return True
        else:

            return False
Пример #32
0
    def create_ctrl_map_new(self, dialog, map_file, device):
        # TODO: Implementation detail which should be hidden?
        input_queue = Queue.Queue()
        input_map = InputMap(map_file)
        input_device = None

        for handler in device.handlers:
            if handler[:-1] == 'js':
                input_device = os.path.join('/dev/input', handler)

        if not input_device:
            return False

        input_wrapper = InputWrapper(input_device, device.name, input_queue, input_map)
        input_wrapper.build_controller_map()

        print 'num buttons: %s' % input_wrapper.num_buttons
        print 'num_axes: %s' % input_wrapper.num_axes
        expected_input_number = input_wrapper.num_buttons + (input_wrapper.num_axes *2)

        js = StoppableJSHandler(input_wrapper, input_map)
        it = StoppableInputHandler(input_queue, input_map, dialog, expected_input_number)

        success = False

        while True:
            xbmc.sleep(1000)
            if not it.isAlive():
                js.stop()
                dialog.close()
                js.join(timeout=2)
                if input_map.status == InputMap.STATUS_DONE:
                    success = True
                if input_map.status == InputMap.STATUS_PENDING or input_map.status == InputMap.STATUS_ERROR:
                    success = False
                break
            if dialog.iscanceled():
                it.stop()
                js.stop()
                success = False
                it.join(timeout=2)
                js.join(timeout=2)
                dialog.close()
                break

        if os.path.isfile(map_file) and success:

            return True
        else:

            return False
Пример #33
0
def library_tv_remove_strm(show, folder, id, season, episode):
    enc_season = ('Season %s' % season).translate(None, '\/:*?"<>|').strip('.')
    enc_name = 'S%02dE%02d' % (season, episode)
    season_folder = os.path.join(folder, enc_season)
    stream_file = os.path.join(season_folder, enc_name + "%s" % plugin.get_setting(SETTING_LIBRARY_TAGS, unicode) + '.strm')
    if xbmcvfs.exists(stream_file):
        xbmcvfs.delete(stream_file)
        while not xbmc.abortRequested and xbmcvfs.exists(stream_file):
            xbmc.sleep(1000)
        a,b = xbmcvfs.listdir(season_folder)
        if not a and not b:
            xbmcvfs.rmdir(season_folder)
        return True
    return False
Пример #34
0
def man_control():
	xmod = xbmcaddon.Addon('plugin.video.interactivelighting')
	sport = xmod.getSetting('serial port')
	try:
		serport = serial.Serial(sport, '57600', timeout=2)
		while True:
			lvals = utils.getlightvals()
			plvals = utils.package_bytes(lvals, 32)
			print 'writing to channels'
			serport.write(bytearray(plvals))
			xbmc.sleep(100)
		serport.close()
	except Exception:
		print "serial port failed"
Пример #35
0
def man_control():
    xmod = xbmcaddon.Addon('plugin.video.interactivelighting')
    sport = xmod.getSetting('serial port')
    try:
        serport = serial.Serial(sport, '57600', timeout=2)
        while True:
            lvals = utils.getlightvals()
            plvals = utils.package_bytes(lvals, 32)
            print 'writing to channels'
            serport.write(bytearray(plvals))
            xbmc.sleep(100)
        serport.close()
    except Exception:
        print "serial port failed"
Пример #36
0
def keyboard(default='', heading='', hidden=False):

    if hidden:
        kb = _xbmc.Keyboard(default, heading, hidden)
    else:
        try:
            import ChineseKeyboard
            kb = ChineseKeyboard.Keyboard(default, heading)
        except:
            kb = xbmc.Keyboard(default, heading)

    xbmc.sleep(1000)
    kb.doModal()
    if (kb.isConfirmed()):
        return kb.getText()
Пример #37
0
def search():
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if not keyboard.isConfirmed():
        return
    keyword = keyboard.getText()
    key = quote_plus(keyword)

    searchapi = HOST + '/layout/smarttv/showsearch?'
    req = {'video_type': 1, 'keyword': keyword}
    req.update(BASEIDS)
    link = get_html(searchapi + urlencode(req))
    results = loads(link)['results']
    items = []
    for item in results:
        items.append({
            'label': item['showname'],
            'path': url_for('episodelist', tid=item['showid']),
            'thumbnail': item['show_vthumburl_hd']
        })

    searchapi = HOST + '/openapi-wireless/videos/search/{}?'
    req = {'pz': 500}
    req.update(BASEIDS)

    link = get_html(searchapi.format(key) + urlencode(req))

    # fetch and build the video series episode list
    finds = loads(link)
    for item in finds['results']:
        duration = 0
        for t in item['duration'].split(':'):
            duration = duration * 60 + int(t)

        items.append({
            'label': item['title'],
            'path': url_for('playvideo', videoid=item['videoid']),
            'thumbnail': item['img'],
            'is_playable': True,
            'info': {
                'title': item['title'],
                'plot': item['desc'],
                'duration': duration
            }
        })
    return items
Пример #38
0
def search():
    plugin.set_content('video')
    keyboard = xbmc.Keyboard('', '请输入搜索内容')

    xbmc.sleep(1500)
    keyboard.doModal()
    if not keyboard.isConfirmed():
        return []

    keyword = keyboard.getText()
    p_url = 'http://www.soku.com/nt/search/q_'
    url = p_url + quote_plus(keyword)
    page = get_html(url)
    tree = BeautifulSoup(page, 'html.parser')
    soup = tree.find_all('div', {'class': 's_base'})
    items = []
    for item in soup:
        title = item.a['_log_title']
        href = item.a['href']
        info = item.find('div', {'class': 'info-cont'})
        info = info.span['data-text'] if info else ''

        items.append({
            'label': title,
            'path': url_for('playvideo', url=href),
            'is_playable': True,
            'info': {
                'title': title,
                'plot': info
            },
        })
    soup = tree.find_all('ul', {'class': 'clearfix'})
    soups = soup[0].find_all('li')
    for item in soups:
        try:
            items.append({
                'label': item.a['_log_title'] + item.span.text,
                'path': url_for('playvideo', url=item.a['href']),
                'is_playable': True,
            })
        except:
            continue
    return items
Пример #39
0
def _play_video(urls_info, show_comments='1'):
    playlist = xbmc.PlayList(1)
    playlist.clear()
    list_item = xbmcgui.ListItem(u'播放')
    list_item.setInfo(type='video', infoLabels={"Title": u"播放"})
    _print_info(str(len(urls_info[0])) + ' parts found')
    stack_url = 'stack://' + ' , '.join(urls_info[0])
    playlist.add(stack_url, list_item)
    player = BiliPlayer()
    if show_comments == '1':
        _print_info('Play with subtitle')
        player.setSubtitle(get_tmp_dir() + '/' + urls_info[1])
    else:
        _print_info('Play without subtitle')
        player.showSubtitles(False)
        player.show_subtitle = False
    player.play(playlist)
    #while(not xbmc.abortRequested):
    xbmc.sleep(100)
Пример #40
0
def _play_video(urls_info, show_comments='1'):
    playlist = xbmc.PlayList(1)
    playlist.clear()
    list_item = xbmcgui.ListItem(u'播放')
    list_item.setInfo(type='video', infoLabels={"Title": u"播放"})
    _print_info(str(len(urls_info[0])) + ' parts found')
    stack_url = 'stack://' + ' , '.join(urls_info[0])
    playlist.add(stack_url, list_item)
    player = BiliPlayer()
    if show_comments == '1':
        _print_info('Play with subtitle')
        player.setSubtitle(get_tmp_dir() + '/' + urls_info[1])
    else:
        _print_info('Play without subtitle')
        player.showSubtitles(False)
        player.show_subtitle = False
    player.play(playlist)
    #while(not xbmc.abortRequested):
    xbmc.sleep(100)
Пример #41
0
def playmovie(cid, vid, name):
    if vid != '0':
        urls = video_from_vid(vid)
    else:
        urls = bilivideo_from_vid(cid)

    stack_url = 'stack://' + ' , '.join(urls)
    danmu = plugin.addon.getSetting('danmu')

    playlist = xbmc.PlayList(1)
    playlist.clear()
    list_item = xbmcgui.ListItem(name)
    if danmu == 'true':
        bilibili.parse_subtitle(cid)
        player.setSubtitle(bilibili._get_tmp_dir() + '/tmp.ass')
        playlist.add(stack_url, list_item)
        player.play(playlist)
        #while(not xbmc.abortRequested):
        xbmc.sleep(500)
    else:
        plugin.set_resolved_url(stack_url)
Пример #42
0
def _play_video(urls_info, show_comments='1'):
    playlist = xbmc.PlayList(1)
    playlist.clear()
    list_item = xbmcgui.ListItem(u'播放')
    list_item.setInfo(type='video', infoLabels={"Title": u"播放"})
    stack_url = 'stack://' + ' , '.join(urls_info[0])
    playlist.add(stack_url, list_item)
    #i = 1
    #for url in urls_info[0]:
        #list_item = xbmcgui.ListItem(u'播放')
        #list_item.setInfo(type='video', infoLabels={"Title": "第"+str(i)+"/"+str(len(urls_info[0]))+" 节"})
        #i += 1
        #playlist.add(url, listitem=list_item)
    player = BiliPlayer()
    if show_comments == '1':
        player.setSubtitle(tempfile.gettempdir() + '/' + urls_info[1])
    player.play(playlist)
    #if show_comments == '1':
        #xbmc.Player().setSubtitles(tempfile.gettempdir() + '/' + urls_info[1])
    while(not xbmc.abortRequested):
        xbmc.sleep(100)
Пример #43
0
def search():
    keyboard = xbmc.Keyboard('', '请输入搜索内容')
    xbmc.sleep(1500)
    keyboard.doModal()
    if not keyboard.isConfirmed():
        return
    keyword = keyboard.getText()
    key = quote_plus(keyword)
    searchapi = 'http://tv.api.3g.youku.com/openapi-wireless/videos/search/{}?pid=0ce22bfd5ef5d2c5&pz=500'

    link = get_html(searchapi.format(key))

    if link is None:
        xbmcgui.Dialog().ok(__addonname__,
                            ' 抱歉,没有找到[COLOR FFFF0000] ' + keyword +
                      ' [/COLOR]的相关视频')
        return []

    # fetch and build the video series episode list
    finds = loads(link)
    items = []
    for item in finds['results']:
        img = item['img']
        videoid = item['videoid']
        title = item['title']
        info = item['desc']
        duration = 0
        for t in item['duration'].split(':'):
            duration = duration*60 + int(t)

        items.append({
            'label': item['title'],
            'path': url_for('playvid', vid=videoid),
            'thumbnail': item['img'],
            'is_playable': True,
            'info': {'title': item['title'], 'plot': item['desc'],
                     'duration': duration}
        })
    return items
 def action_prerun(self, link):
     #    xbmc.executebuiltin('ActivateWindow(10025,addons://user/xbmc.addon.video/plugin.video.zen/,return)')
     if link.startswith("plugin://"):
         id = link.split("/")
         xbmc.executebuiltin('RunAddon(%s)' % id[2])
         while xbmc.getInfoLabel(
                 'Container.PluginName') != id[2] or xbmc.getCondVisibility(
                     'Window.IsActive(busydialog)'):
             xbmc.sleep(250)
         xbmc.sleep(250)
         self.play(link)
     while xbmc.getInfoLabel(
             'Container.PluginName') == id[2] and xbmc.getInfoLabel(
                 'Container.FolderPath') != "plugin://%s/" % id[2] and id[
                     2] in xbmc.getInfoLabel('Container.FolderPath'):
         xbmc.sleep(250)
         if xbmc.getInfoLabel(
                 'Container.FolderPath') == "plugin://%s/" % id[2] or id[
                     2] not in xbmc.getInfoLabel('Container.FolderPath'):
             break
     xbmc.executebuiltin('Container.Update("%s", replace)' %
                         self.returnlink)
Пример #45
0
def sleep(ms):
    from xbmcswift2 import xbmc
    if CLI_MODE:
        time.sleep(ms / 1000.0)
    else:
        xbmc.sleep(ms)
Пример #46
0
def play_basesloaded():
    delay_sec = 20
    refresh_sec = 10
    games_queue = MlbGamesQueue(delay_sec, refresh_sec, plugin)

    # Need a way of checking if there are any current games, not just
    # games that are currently *on*
    # Maybe display to user: "******"
    games = games_queue.get()
    if games is None:
        plugin.notify("No games on")
        return

    monitor = xbmc.Monitor()
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    player = mlb_player.MlbPlayer(mlb_playlist=playlist)

    curr_game = None
    streams_not_found = set([])
    while not monitor.abortRequested():
        # TODO encapsulate all this logic in an object
        if not games:
            # TODO better UX for this situation
            xbmc.log("No game found")
            xbmc.sleep(5000)
            continue

        # Update state of curr_game
        if curr_game is not None:
            new_curr_game = [game for game in games if game['state'].away_team == curr_game['state'].away_team
                                                   and game['state'].home_team == curr_game['state'].home_team]
            if not new_curr_game:
                curr_game = None
            else:
                curr_game = new_curr_game[0]

        # Iterate through best games in order, choosing first one a stream exists for
        for game in games:
            if curr_game == game:
                xbmc.log("Not switching because current game is still best game")
                break

            try:
                # Only switch games if:
                #  curr_game is None (either no curr_game or it's in commercial break)
                #  The change in leverage is > 1.5 and there's a new batter in curr_game
                #  game has a better leverage than curr_game and curr_game is below average leverage (1.0) and there's a new batter in curr_game
                curr_game_none = curr_game is None
                new_batter = curr_game and curr_game['state'].new_batter
                large_leverage_diff = curr_game and (game['leverage_index'] - curr_game['leverage_index'] > 1.5)
                game_better = curr_game and game['leverage_index'] > curr_game['leverage_index']
                curr_game_below_avg = curr_game and curr_game['leverage_index'] < 1.0
                if curr_game_none or (new_batter and (large_leverage_diff or (curr_game_below_avg and game_better))):
                    if (game['state'].home_team, game['state'].away_team) in streams_not_found:
                        xbmc.log("Already know stream doesn't exist for game {0}".format(game))
                        continue

                    stream = mlbtv_stream_api.get_stream(game['state'].home_team, game['state'].away_team)

                    xbmc.log("Switching from {0} to {1}".format(curr_game, game))
                    curr_game = game
                    xbmc.log("stream: " + stream)
                    player.play_video(stream)

                if curr_game == game:
                    xbmc.log("Current game is in commercial break or is over")
                if curr_game != game and (game['leverage_index'] - curr_game['leverage_index']) <= 1.5:
                    xbmc.log("{0} is better game, but not enough better to switch from {1}".format(game, curr_game))
                elif curr_game != game and (game['leverage_index'] - curr_game['leverage_index']) > 1.5:
                    xbmc.log("{0} is a better game, but {1} still has a batter at the plate".format(game, curr_game))

                break
            except mlb_exceptions.StreamNotFoundException:
                streams_not_found.add((game['state'].home_team, game['state'].away_team),)
                xbmc.log("Stream not found for {0}. Setting cache to {1}".format(game, streams_not_found))
                continue

        if monitor.waitForAbort(refresh_sec) or not player.isPlayingVideo():
            break

        # Update games
        games = games_queue.get()
Пример #47
0
 def wait_library_scan():
     while XBMCMixin.is_scanning_library() and not xbmc.abortRequested:
         xbmc.sleep(100)
Пример #48
0
def go_idle(duration):
    while not xbmc.abortRequested and duration > 0:
        if player.isPlayingVideo():
            player.currentTime = player.getTime()
        xbmc.sleep(1000)
        duration -= 1
Пример #49
0
 def __init__(self, heading):
     AbstractProgress.__init__(self)
     self.dialog = xbmcgui.DialogProgress()
     self.opened = False
     self.heading = heading
     xbmc.sleep(500)
Пример #50
0
def sleep(ms):
    if CLI_MODE:
        time.sleep(ms/1000.0)
    else:
        xbmc.sleep(ms)
Пример #51
0
 def __init__(self, heading):
     AbstractProgress.__init__(self)
     self.dialog = xbmcgui.DialogProgress()
     self.opened = False
     self.heading = heading
     xbmc.sleep(500)
Пример #52
0
def sleep(ms):
    from xbmcswift2 import xbmc
    if CLI_MODE:
        time.sleep(ms / 1000.0)
    else:
        xbmc.sleep(ms)