Пример #1
0
    def playTorrentFile(self, mediaSettings, magnet, item, subtitleURL=None):
        with TorrentEngine(mediaSettings, magnet) as _TorrentEngine:
            # Loading
            log('(Torrent Player) Loading', LOGLEVEL.INFO)
            with closing(SafeDialogProgress()) as dialog:
                dialog.create(item['info']['title'])
                dialog.update(0, __addon__.getLocalizedString(30031), ' ', ' ')

                # Update progress dialog
                dialog.set_mentions((101+bool(subtitleURL)))

                def on_update(state, progressValue):
                    if state == Loader.PRELOADING:
                        dialog.update(progressValue, *self._get_status_lines(_TorrentEngine.status()))
                    elif state == Loader.CHECKING_DATA:
                        dialog.update(progressValue, __addon__.getLocalizedString(30037), ' ', ' ')
                    elif state == Loader.WAITING_FOR_PLAY_FILE:
                        dialog.update(progressValue, __addon__.getLocalizedString(30016), ' ', ' ')
                    elif state == Loader.DOWNLOADING_SUBTITLE:
                        dialog.update(progressValue, __addon__.getLocalizedString(30019), ' ', ' ')
                    elif state == Loader.FINISHED:
                        dialog.update(progressValue, __addon__.getLocalizedString(30020), ' ', ' ')

                with Loader(mediaSettings, _TorrentEngine, item, subtitleURL, on_update) as _loader:
                    while not _loader.is_done(0.100):
                        if xbmc.abortRequested or dialog.iscanceled():
                            raise Abort()

            # Starts the playback
            log('(Torrent Player) Start the playback', LOGLEVEL.INFO)
            self.play(Loader.url, xbmcItem(**item))

            # Waiting for playback to start
            log('(Torrent Player) Waiting for playback to start')
            for _ in xrange(300):
                if self.isPlaying():
                    break
                time.sleep(0.100)
            else:
                raise Error('Playback is terminated due to timeout', 30318)

            if Loader.subtitle:
                log('(Torrent Player) Add subtitle to the playback')
                self.setSubtitles(Loader.subtitle)

            with OverlayText() as self._overlay:
                while not xbmc.abortRequested and self.isPlaying():
                    if self._overlay.isShowing():
                        self._overlay.setText("\n".join(self._get_status_lines(_TorrentEngine.status())))
                        time.sleep(0.100)
                        continue
                    time.sleep(0.250)
                log('(Torrent Player) The playback has stop')
Пример #2
0
 def getSearchString(self):
     log("(Main) Getting search string")
     string = xbmc.getInfoLabel("ListItem.Property(searchString)")
     if not string:
         log("(Main) Showing keyboard")
         keyboard = xbmc.Keyboard('', __addon__.getLocalizedString(30001), False)
         keyboard.doModal()
         if not keyboard.isConfirmed() or not keyboard.getText():
             raise Abort()
         string = keyboard.getText()
     log("(Main) Returning search string '%s'" %string)
     return string
    def get_shows(cls, dom, **kwargs):
        if kwargs['search'] == 'true':
            search_string = xbmc.getInfoLabel("ListItem.Property(searchString)")
            if not search_string:
                keyboard = xbmc.Keyboard('', __addon__.getLocalizedString(30001), False)
                keyboard.doModal()
                if not keyboard.isConfirmed() or not keyboard.getText():
                    raise Abort()
                search_string = keyboard.getText()
                search_string = search_string.replace(' ', '+')
            search = '{domain}/{search_path}/1?keywords={keywords}'.format(
                domain=dom[0],
                search_path=cls.search_path,
                keywords=search_string,
            )
        else:
            search = '{domain}/{search_path}/{page}?genre={genre}&sort={sort}'.format(
                domain=dom[0],
                search_path=cls.search_path,
                page=kwargs['page'],
                genre=kwargs['genre'],
                sort=kwargs['act'],
            )

        req = urllib2.Request(
            search,
            headers={
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.66 Safari/537.36",
                "Accept-Encoding": "none",
            },
        )
        response = urllib2.urlopen(req)
        results = json.loads(response.read())

        items = [
            {
                "label": result['title'],  # "label" is required
                "icon": result.get('images').get('poster'),
                "thumbnail": result.get('images').get('poster'),
                "info": cls.get_meta_info(result, 0),
                "properties": {
                    "fanart_image": result.get('images').get('fanart'),
                },
                "params": {
                    "endpoint": "folders",  # "endpoint" is required
                    'action': "{category}-seasons".format(category=cls.category),  # Required when calling browse or folders (Action is used to separate the content)
                    cls.id_field: result[cls.id_field],
                    'poster': result.get('images').get('poster'),
                    'fanart': result.get('images').get('fanart'),
                    'tvshow': result['title']
                },
                "context_menu": [
                    (
                        '%s' % __addon__.getLocalizedString(30039),
                        'RunPlugin(plugin://plugin.video.kodipopcorntime?cmd=add_fav&action={action}&id={id})'.format(
                            action=cls.action,
                            id=result[cls.id_field],
                        ),
                    )
                ],
                "replace_context_menu": True
            }
            for result in results
        ]

        # Next Page
        items.append({
            "label": 'Show more',  # "label" is required
            "icon": os.path.join(settings.addon.resources_path, 'media', 'movies', 'more.png'),
            "thumbnail": os.path.join(settings.addon.resources_path, 'media', 'movies', 'more_thumbnail.png'),
            "params": {
                "endpoint": "folders",  # "endpoint" is required
                'action': "{category}-list".format(category=cls.category),  # Required when calling browse or folders (Action is used to separate the content)
                'act': kwargs['act'],
                'genre': kwargs['genre'],
                'search': kwargs['search'],
                'page': int(kwargs['page']) + 1,
            },
        })

        return items
Пример #4
0
    def search(self, **params):
        log("(Main) Creating search view", LOGLEVEL.INFO)
        searchString = self.getSearchString()

        curPageNum = self.getCurPageNum()
        with closing(Cache("%s.search.query" %self.mediaSettings.mediaType, ttl=24 * 3600, last_changed=self.mediaSettings.lastchanged)) as cache:
            # Reset cache when we have different search string
            if cache and not searchString == cache['searchString']:
                log("(Main) Resetting view cache")
                cache.trunctate()

            # Reset page number if the user have cleaned the cache
            # or we have a different search string
            if not cache:
                curPageNum = 1

            if not cache or curPageNum > cache['curNumOfPages']:
                log("(Main) Reading item cache")
                items = {}
                pages = 0

                with closing(SafeDialogProgress()) as dialog:
                    dialog.create(__addon__.getLocalizedString(30028))
                    dialog.update(0, __addon__.getLocalizedString(30007), ' ', ' ')

                    _time = time.time()
                    # Getting item list
                    log("(Main) Getting item list")
                    with closing(media.List(self.mediaSettings, 'search', *(searchString, curPageNum,), **params)) as medialist:
                        while not medialist.is_done(0.100):
                            if xbmc.abortRequested or dialog.iscanceled():
                                raise Abort()
                        res = medialist.get_data()
                        if not res:
                            raise Notify("No search result", 30327, NOTIFYLEVEL.INFO)
                        items = res['items']
                        pages = res['pages']

                    # Update progress dialog
                    dialog.set_mentions(len(items)+2)
                    dialog.update(1, __addon__.getLocalizedString(30018), ' ', ' ')

                    def on_data(progressValue, oldItem, newItem):
                            label = ["%s %s" %(__addon__.getLocalizedString(30034), oldItem["label"])]
                            if newItem.get("label") and not oldItem["label"] == newItem["label"]:
                                label = label+["%s %s" %(__addon__.getLocalizedString(30035), newItem["label"])]
                            if newItem.get("stream_info", {}).get("subtitle", {}).get("language"):
                                label = label+["%s %s" %(__addon__.getLocalizedString(30012), isoToLang(newItem["stream_info"]["subtitle"]["language"]))]
                            while len(label) < 3:
                                label = label+[' ']
                            dialog.update(progressValue, *label)

                    # Getting media cache
                    log("(Main) Getting media info")
                    with closing(media.MediaCache(self.mediaSettings, on_data)) as mediadata:
                        [mediadata.submit(item) for item in items]
                        mediadata.start()
                        while not mediadata.is_done(0.100):
                            if xbmc.abortRequested or dialog.iscanceled():
                                raise Abort()
                        items = mediadata.get_data()
                        if not items:
                            raise Error("Did not receive any data", 30304)
                    log("(Main) Reading time: %s" %(time.time()-_time))

                    # Done
                    dialog.update(1, __addon__.getLocalizedString(30017), ' ', ' ')

                log("(Main) Updating view cache")
                cache.extendKey("items", items)
                cache.update({"curNumOfPages": curPageNum, "totalPages": pages, "searchString": searchString})
            pageCache = cache.copy()

        log("(Main) Adding items")
        self.addItems(self.mediaSettings.mediaType, pageCache["items"], 'player', False)

        # NOTE:
        # Add show more, but we stop at page 20... yes 20 pages sounds all right...
        # ... each page cache file can be between 2 and 3 mByt with 20 pages and will have an average of 1 mByt...
        # This can become substantial problem with movies and tv-shows pages
        if pageCache['curNumOfPages'] < pageCache['totalPages'] and pageCache['curNumOfPages'] < 21:
            self.addNextButton(**{'pageNum': pageCache['curNumOfPages']+1, 'searchString': searchString})

        update_listing = False
        if curPageNum > 1:
            update_listing = True

        self.finish(self.mediaSettings.mediaType, update_listing)