コード例 #1
0
def _properties(meta):
    log("(tmdb-properties) %s" % meta, LOGLEVEL.INFO)
    fanart = meta.get("fanart", '')
    if _Data.imageUrl and fanart:
        fanart = "%s/w500%s" % (_Data.imageUrl, fanart)

    return {"fanart_image": fanart}
コード例 #2
0
def _stream_info(meta):
    log("(tmdb-stream-info) %s" %meta, LOGLEVEL.INFO)
    return {
        "video": {
            "duration": int((meta.get("runtime") or 0)*60)
        }
    }
コード例 #3
0
ファイル: base3.py プロジェクト: markop159/KODI-Popcorn-Time
    def addItem(self, item, path, isFolder=True):
        if not isFolder:
            item["context_menu"] = []
            log("(base3-context-menu) %s" %item, LOGLEVEL.INFO)

            if "info" in item and "trailer" in item["info"] and item["info"]["trailer"]:
                item["context_menu"] = item["context_menu"]+[('%s' %(__addon__.getLocalizedString(30038)), 'PlayMedia(%s)' %(item["info"]["trailer"]))]

            if "info" in item and "mediatype" in item["info"] and item["info"]["mediatype"] == 'movie':
                isfav = False
                favs = favourites._get_favs('movies')
                for fav in favs:
                    if fav['id'] == item["info"]["code"]:
                        isfav = True
                if isfav == True:
                    item["context_menu"] = item["context_menu"]+[('%s' %__addon__.getLocalizedString(30042), 'RunPlugin(plugin://plugin.video.kodipopcorntime?cmd=remove_fav&action=movies&id=%s)' % (item["info"]["code"]))]
                    item["context_menu"] = item["context_menu"]+[('%s' %__addon__.getLocalizedString(30044), 'RunPlugin(plugin://plugin.video.kodipopcorntime?cmd=remove_fav&action=movies&id=all)')]
                else:
                    item["context_menu"] = item["context_menu"]+[('%s' %__addon__.getLocalizedString(30041), 'RunPlugin(plugin://plugin.video.kodipopcorntime?cmd=add_fav&action=movies&id=%s)' % (item["info"]["code"]))]

            for _q in QUALITIES:
                if "&%s=" %_q in path or "?%s=" %_q in path:
                    log("(base3-context) %s" %_q, LOGLEVEL.INFO)
                    item["context_menu"] = item["context_menu"]+[('%s %s' %(__addon__.getLocalizedString(30009), _q), 'RunPlugin(%s&quality=%s)' %(path, _q))]
            item["context_menu"] = item["context_menu"]+[self.getOpenSettings()]
            item["replace_context_menu"] = True
        super(_Base3, self).addItem(item, path, isFolder)
コード例 #4
0
 def __init__(self, mediaSettings, magnet):
     log('(Torrent) Initialize torrent engine', LOGLEVEL.INFO)
     self._mediaSettings = mediaSettings
     self._magnet = magnet
     self._url = None
     self._shutdown = False
     self._process = None
     self._logpipe = None
     self._file_id = None
     self._json = request.Json()
     # "IOError: [Errno 9] Bad file descriptor" FIX!!!
     self._last_status = {
         "name": "",
         "state": self.NO_CONNECTION,
         "state_str": "no_connection",
         "error": "",
         "progress": 0,
         "download_rate": 0,
         "upload_rate": 0,
         "total_download": 0,
         "total_upload": 0,
         "num_peers": 0,
         "num_seeds": 0,
         "total_seeds": -1,
         "total_peers": -1
     }
     self._last_files = []
コード例 #5
0
ファイル: addon.py プロジェクト: markop159/KODI-Popcorn-Time
        def _fanart(cls):
            today = date.today()

            # Check special dates
            for special_date in SPECIAL_DATES:
                start_date = date(today.year, special_date['start']['month'], special_date['start']['day'])
                end_date = date(today.year, special_date['end']['month'], special_date['end']['day'])

                if start_date <= today <= end_date:
                    log(
                        '(settings-date) {0} {1}'.format(special_date['name'], today),
                        LOGLEVEL.INFO,
                    )
                    cls.fanart = os.path.join(
                        __addon__.getAddonInfo('path'),
                        'resources',
                        'media',
                        'background',
                        special_date['image'],
                    )
                    break
            # No special date
            else:
                log('(settings-date) no condition met {0}'.format(today), LOGLEVEL.INFO)
                cls.fanart = __addon__.getAddonInfo('fanart')
コード例 #6
0
 def _isDownloadDone(self):
     if self._TEngine.status()['state'] in [self._TEngine.FINISHED, self._TEngine.SEEDING]:
         log('(Loader) Media is downloaded')
         #if self.callbackfn:
          #   self.callbackfn(Loader.PRELOADING, 100)
         return not self.stop.is_set()
     return False
コード例 #7
0
ファイル: torrent.py プロジェクト: vascool/KODI-Popcorn-Time
 def __init__(self, mediaSettings, magnet):
     log("(Torrent) Initialize torrent engine", LOGLEVEL.INFO)
     self._mediaSettings = mediaSettings
     self._magnet = magnet
     self._bind = None
     self._shutdown = False
     self._process = None
     self._logpipe = None
     self._file_id = None
     self._json = request.Json()
     # "IOError: [Errno 9] Bad file descriptor" FIX!!!
     self._last_status = {
         "name": "",
         "state": self.NO_CONNECTION,
         "state_str": "no_connection",
         "error": "",
         "progress": 0,
         "download_rate": 0,
         "upload_rate": 0,
         "total_download": 0,
         "total_upload": 0,
         "num_peers": 0,
         "num_seeds": 0,
         "total_seeds": -1,
         "total_peers": -1,
     }
     self._last_files = []
コード例 #8
0
def _properties(meta):
    log("(tmdb-properties) %s" %meta, LOGLEVEL.INFO)
    fanart = meta.get("fanart", '')
    if _Data.imageUrl and fanart:
        fanart = "%s/w500%s" %(_Data.imageUrl, fanart)

    return {"fanart_image": fanart}
コード例 #9
0
ファイル: base3.py プロジェクト: wetraining/KODI-Popcorn-Time
    def addNextButton(self, **kwargs):
        log("(%s) Adding item 'Show more'" % self.interfaceName)

        item = {
            "label":
            __addon__.getLocalizedString(30000),
            "icon":
            os.path.join(_settings.resources_path, 'media',
                         self.mediaSettings.mediaType, 'more.png'),
            "thumbnail":
            os.path.join(_settings.resources_path, 'media',
                         self.mediaSettings.mediaType, 'more_thumbnail.png'),
            "replace_context_menu":
            True,
            "context_menu": [self.getOpenSettings()],
            "properties": {
                "fanart_image": _settings.fanart
            }
        }
        item.setdefault('properties').update(
            dict((key, str(value)) for key, value in kwargs.items() if value))
        xbmcplugin.addDirectoryItem(
            _settings.handle,
            "%s?%s" % (_settings.base_url, _settings.cur_uri),
            xbmcItem(**item), True)
コード例 #10
0
ファイル: main.py プロジェクト: chakhdin/KODI-Popcorn-Time
    def player(self, subtitle=None, quality=None, **params):
        log("(Main) Creating player options")
        if settings.addon.handle > -1:
            xbmcplugin.endOfDirectory(settings.addon.handle, True, False, False)

        item = self.getSelectedItem()

        free_space = self._calculate_free_space()
        if not quality:
            waring = []
            for _q in self.mediaSettings.qualities:
                if params.get(_q):
                    if params['%ssize' %_q] > free_space:
                        if _q == '3D' and self.mediaSettings.play3d == 1 and not Dialog().yesno(line2=30011, lineStr1=' ', headingStr=item['info']['title']):
                            continue
                        quality = _q
                        break
                    waring = waring+[_q]

            if waring:
                if not quality:
                    raise Notify('There is not enough free space in %s' %self.mediaSettings.download_path, 30323, level=NOTIFYLEVEL.ERROR)

                if len(waring) > 1:
                    notify(message=__addon__.getLocalizedString(30325) %(", ".join(waring), waring.pop()), level=NOTIFYLEVEL.WARNING)
                else:
                    notify(message=__addon__.getLocalizedString(30326) %waring[0], level=NOTIFYLEVEL.WARNING)
                log('(Main) There must be a minimum of %s to play. %s available in %s' %(shortenBytes(params['%ssize' %quality]), shortenBytes(free_space), self.mediaSettings.download_path), LOGLEVEL.NOTICE)

        elif not params.get(quality):
                raise Error('%s quality was not found' %quality, 30023)
        elif params['%ssize' %quality] < free_space:
                raise Notify('There is not enough free space in %s' %self.mediaSettings.download_path, 30323, level=NOTIFYLEVEL.ERROR)

        TorrentPlayer().playTorrentFile(self.mediaSettings, build_magnetFromMeta(params[quality], "quality %s" %quality), item, subtitle)
コード例 #11
0
        def _fanart(cls):
            today = date.today()

            # Check special dates
            for special_date in SPECIAL_DATES:
                start_date = date(today.year, special_date['start']['month'],
                                  special_date['start']['day'])
                end_date = date(today.year, special_date['end']['month'],
                                special_date['end']['day'])

                if start_date <= today <= end_date:
                    log(
                        '(settings-date) {0} {1}'.format(
                            special_date['name'], today),
                        LOGLEVEL.INFO,
                    )
                    cls.fanart = os.path.join(
                        __addon__.getAddonInfo('path'),
                        'resources',
                        'media',
                        'background',
                        special_date['image'],
                    )
                    break
            # No special date
            else:
                log('(settings-date) no condition met {0}'.format(today),
                    LOGLEVEL.INFO)
                cls.fanart = __addon__.getAddonInfo('fanart')
コード例 #12
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
 def _isDownloadDone(self):
     if self._TEngine.status()['state'] in [self._TEngine.FINISHED, self._TEngine.SEEDING]:
         log('(Loader) Media is downloaded')
         if self.callbackfn:
             self.callbackfn(Loader.PRELOADING, 100)
         return not self.stop.is_set()
     return False
コード例 #13
0
def ensure_android_binary_location(binary_path, android_binary_path):
    log("Trying to copy torrent2http to ext4, since the sdcard is noexec", LOGLEVEL.INFO)
    if not os.path.exists(os.path.dirname(android_binary_path)):
        os.makedirs(os.path.dirname(android_binary_path))
    if not os.path.exists(android_binary_path) or int(os.path.getmtime(android_binary_path)) < int(os.path.getmtime(binary_path)):
        shutil.copy2(binary_path, android_binary_path)
    return android_binary_path
コード例 #14
0
def build_pre(data):
    log("(tmdb-build_pre) %s" % data, LOGLEVEL.INFO)
    if data:
        _Data.imageUrl = data[0].get("images", {}).get("base_url")
        if _Data.imageUrl:
            Cache("movies.metadata.imdb.conf",
                  ttl=24 * 3600)['imageUrl'] = _Data.imageUrl
コード例 #15
0
def _info(meta, title=''):
    log("(tmdb-info) %s; %s" % (meta, title), LOGLEVEL.INFO)
    try:
        if meta['data']:
            log(
                "(tmdb-info-except) %s" %
                meta['data'][0]['attributes']['canonicalTitle'], LOGLEVEL.INFO)
            if not meta['data'][0]['attributes']['canonicalTitle'] == 'None':
                title = meta['data'][0]['attributes']['canonicalTitle']
            item = {
                "title":
                title,
                "year":
                int(meta['data'][0]['attributes']['airdate'].split("-").pop(
                    0)),
                "originaltitle":
                title,
                "plot":
                meta['data'][0]['attributes']['synopsis'],
                "plotoutline":
                meta['data'][0]['attributes']['synopsis'],
                "code":
                meta['data'][0]['id'],
            }
    except:
        overview = meta.get('overview', '')
        vote_average = meta.get('vote_average')
        item = {
            "title":
            title,
            "year":
            int(meta.get("release_date", '0').split("-").pop(0)),
            "originaltitle":
            meta.get("original_title", ''),
            "genre":
            u" / ".join(g["name"] for g in meta.get("genres", [])),
            "plot":
            overview,
            "plotoutline":
            overview,
            "tagline":
            meta.get("tagline", ''),
            "rating":
            float(vote_average or 0.0),
            "duration":
            int(meta.get("runtime") or 0),
            "code":
            meta.get("imdb_id"),
            "studio":
            u" / ".join(
                [s['name'] for s in meta.get("production_companies", [])]),
            "votes":
            vote_average and float(meta.get("vote_count")) or 0.0
        }
        credits = meta.get("credits")
        if credits:
            item.update(_credits(credits))

    return item
コード例 #16
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
 def _getPlayFile(self):
     log('(Loader) Waiting on play file')
     if self.callbackfn:
         self.callbackfn(self.WAITING_FOR_PLAY_FILE, 0)
     while not self.stop.is_set():
             if self._TEngine.playFile(1):
                 return not self.stop.is_set()
     return False
コード例 #17
0
 def _getPlayFile(self):
     log('(Loader) Waiting on play file')
     if self.callbackfn:
         self.callbackfn(self.WAITING_FOR_PLAY_FILE, 0)
     while not self.stop.is_set():
             if self._TEngine.playFile(1):
                 return not self.stop.is_set()
     return False
コード例 #18
0
ファイル: media.py プロジェクト: chakhdin/KODI-Popcorn-Time
 def _run(self):
     log("(Media) Getting list", LOGLEVEL.INFO)
     _res = self._handle_param(**self._provider_fn(*self._args, **self._kwargs))
     if not self.stop.is_set():
         self._data = self._provider_build_fn(
             _res, *self._args, **self._kwargs
         )  # 1. Get request parameter. 2. Perform request. 3. Build item.
         self.close()
コード例 #19
0
ファイル: main.py プロジェクト: chakhdin/KODI-Popcorn-Time
 def index(self, **params):
     if settings.tvshows.provider:
         log("(Main) Creating index view")
         self.addItem('movies', **settings.movies.provider.folders(None)[0])
         self.addItem('tvshows', **settings.tvshows.provider.folders(None)[0])
         self.finish()
     else:
         self('movies', **settings.movies.provider.folders(None)[0]["params"])
コード例 #20
0
 def show(self, **params):
     log("(Index) Creating view")
     for mediaType in settings.MEDIATYPES:
         item = getattr(settings, ".provider" % mediaType).folders(None)[0]
         self.addItem(
             item, self.createUrl(mediaType=mediaType,
                                  **item.pop('params')))
     self.finish()
コード例 #21
0
 def _read(self, response):
     log("(Download) Store data on location %s" % self.downloadPath,
         LOGLEVEL.NONE)
     with open(self.downloadPath, "wb") as f:
         f.write(response.read())
     log("(Download) Successful stored data at %s" % self.url,
         LOGLEVEL.NONE)
     return self.downloadPath
コード例 #22
0
ファイル: base2.py プロジェクト: 1boko1/KODI-Popcorn-Time
    def addItem(self, item, path, isFolder=True):
        log("(%s) Adding item '%s'" %(self.interfaceName, item["label"]))

        # Ensure fanart
        if not item.setdefault("properties", {}).get("fanart_image"):
            item["properties"]["fanart_image"] = _settings.fanart

        xbmcplugin.addDirectoryItem(_settings.handle, path, xbmcItem(**item), isFolder)
コード例 #23
0
 def finish(self,
            contentType='files',
            updateListing=False,
            cacheToDisc=True):
     log("(%s) Finish" % self.interfaceName, LOGLEVEL.INFO)
     xbmcplugin.setContent(_settings.handle, contentType)
     xbmcplugin.endOfDirectory(_settings.handle, True, updateListing,
                               cacheToDisc)
コード例 #24
0
 def _run(self):
     log("(Media) Getting list", LOGLEVEL.INFO)
     _res = self._handle_param(
         **self._provider_fn(*self._args, **self._kwargs))
     if not self.stop.is_set():
         self._data = self._provider_build_fn(
             _res, *self._args, **self._kwargs
         )  # 1. Get request parameter. 2. Perform request. 3. Build item.
         self.close()
コード例 #25
0
    def addItem(self, item, path, isFolder=True):
        log("(%s) Adding item '%s'" % (self.interfaceName, item["label"]))

        # Ensure fanart
        if not item.setdefault("properties", {}).get("fanart_image"):
            item["properties"]["fanart_image"] = _settings.fanart

        xbmcplugin.addDirectoryItem(_settings.handle, path, xbmcItem(**item),
                                    isFolder)
コード例 #26
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
 def _checkData(self):
     log('(Loader) Checking data')
     while not self.stop.is_set():
         if self.callbackfn:
             self.callbackfn(self.CHECKING_DATA, 0)
         if self._TEngine.status()['state'] in [self._TEngine.FINISHED, self._TEngine.SEEDING, self._TEngine.DOWNLOADING]:
             return not self.stop.is_set()
         time.sleep(0.100)
     else:
         return False
コード例 #27
0
 def _qualities(cls):
     __qualities = []
     if cls.play3d > 0:
         __qualities = [QUALITIES[0]]
     if __addon__.getSetting("%s_quality" %cls.mediaType) == '0':
         cls.qualities = __qualities+QUALITIES[-2:]
         log("(settings-base2-1) %s" %cls.qualities, LOGLEVEL.INFO)
     else:
         cls.qualities = __qualities+QUALITIES[1:]
         log("(settings-base2-2) %s" %cls.qualities, LOGLEVEL.INFO)
コード例 #28
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
    def __init__(self):
        log('(Overlay) Initialize overlay text', LOGLEVEL.INFO)
        x, y, w, h = self._calculate_the_size()

        self._shown       = False
        self._window     = xbmcgui.Window(12005)
        self._label      = xbmcgui.ControlLabel(x, y, w, h, '', alignment=0x00000002 | 0x00000004)
        self._background = xbmcgui.ControlImage(x, y, w, h, os.path.join(_settings.resources_path, "media", "black.png"))

        self._background.setColorDiffuse("0xD0000000")
コード例 #29
0
def _add_to_favs(mediatype, data):
    favourites = get_favourites_from_file()
    log("(Favourites) _add_to_favs %s" % favourites)

    add_favourite_by_type(new_fav_id=data, fav_type=mediatype, favourites=favourites)

    log("(Favourites2) _add_to_favs %s" % favourites)
    set_favourites_to_file(favourites)

    xbmc.executebuiltin('Notification(%s, %s favourite has been added, 5000)' % (__addonname__, mediatype))
コード例 #30
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
 def files(self, timeout=10):
     if not self._shutdown:
         try:
             if not self.isAlive():
                 raise TorrentError("torrent2http are not running")
             self._last_files = self._json.request(self._url, "/ls", timeout=timeout)['files'] or self._last_files
         except (JSONDecodeError, socket.timeout, IOError) as e:
             log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
             sys.exc_clear()
     return self._last_files
コード例 #31
0
    def __init__(self):
        log('(Overlay) Initialize overlay text', LOGLEVEL.INFO)
        x, y, w, h = self._calculate_the_size()

        self._shown       = False
        self._window     = xbmcgui.Window(12005)
        self._label      = xbmcgui.ControlLabel(x, y, w, h, '', alignment=0x00000002 | 0x00000004)
        self._background = xbmcgui.ControlImage(x, y, w, h, os.path.join(_settings.resources_path, "media", "black.png"))

        self._background.setColorDiffuse("0xD0000000")
コード例 #32
0
 def files(self, timeout=10):
     if not self._shutdown:
         try:
             if not self.isAlive():
                 raise TorrentError("torrent2http are not running")
             self._last_files = self._json.request(self._url, "/ls", timeout=timeout)['files'] or self._last_files
         except (JSONDecodeError, socket.timeout, IOError) as e:
             log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
             sys.exc_clear()
     return self._last_files
コード例 #33
0
 def _checkData(self):
     log('(Loader) Checking data')
     while not self.stop.is_set():
         if self.callbackfn:
             self.callbackfn(self.CHECKING_DATA, 0)
         if self._TEngine.status()['state'] in [self._TEngine.FINISHED, self._TEngine.SEEDING, self._TEngine.DOWNLOADING]:
             return not self.stop.is_set()
         time.sleep(0.100)
     else:
         return False
コード例 #34
0
ファイル: base2.py プロジェクト: vascool/KODI-Popcorn-Time
 def _preferred_subtitles(cls):
     subtitles = []
     if cls.subtitles_provider:
         for i in xrange(3):
             _n = int(__addon__.getSetting('%s_subtitle_language%d' %(cls.mediaType, i)))
             log(str(_n))
             if not _n > 0:
                 break
             subtitles = subtitles+[SUBTITLE_ISO[_n-1]]
     cls.preferred_subtitles = subtitles
コード例 #35
0
def _remove_from_favs(mediatype, data):
    favourites = get_favourites_from_file()
    log("(Favourites) _remove_from_favs %s" % favourites)

    remove_favourite_by_type(fav_id=data, fav_type=mediatype, favourites=favourites)

    log("(Favourites2) _remove_from_favs %s" % favourites)
    set_favourites_to_file(favourites)

    xbmc.executebuiltin('Notification(%s, %s favourite has been removed, 5000)' % (__addonname__, mediatype))
    xbmc.executebuiltin('Container.Refresh')
コード例 #36
0
ファイル: main.py プロジェクト: chakhdin/KODI-Popcorn-Time
    def __call__(self, mediaType=None, endpoint=None, **params):
        self.mediaSettings = None
        if mediaType:
            self.mediaSettings = getattr(settings, mediaType)

        if not endpoint:
            endpoint = 'index'
        log("(Main) Calling %s. Params: %s" %(endpoint, str(params)))
        if not hasattr(self, endpoint):
            raise Error("'PopcornTime' class has no method '%s'" %endpoint)
        getattr(self, endpoint)(**params)
コード例 #37
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
 def status(self, timeout=10):
     if not self._shutdown:
         try:
             if not self.isAlive():
                 raise TorrentError("torrent2http are not running")
             self._last_status = self._json.request(self._url, "/status", timeout=timeout) or self._last_status
             if self._last_status.get('error'):
                 raise TorrentError("torrent2http error: %s" %self._last_status['error'])
         except (JSONDecodeError, socket.timeout, IOError) as e:
             log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
             sys.exc_clear()
     return self._last_status
コード例 #38
0
ファイル: torrent.py プロジェクト: freak4pc/KODI-Popcorn-Time
    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')
コード例 #39
0
 def _run(self):
     log("(Media) Running preloader", LOGLEVEL.INFO)
     if self._mediaSettings.metadata_provider:
         _res = self._handle_params(self._mediaSettings.metadata_provider.pre())
         if not self.stop.is_set():
             self._mediaSettings.metadata_provider.build_pre(_res)
     if self._mediaSettings.subtitles_provider and not self.stop.is_set():
         _res = self._handle_params(self._mediaSettings.subtitles_provider.pre())
         if not self.stop.is_set():
             self._mediaSettings.subtitles_provider.build_pre(_res)
     log("(Media) Preloader done")
     self.close()
コード例 #40
0
ファイル: base.py プロジェクト: 1boko1/KODI-Popcorn-Time
    def __getattr__(cls, name):
        # Do we have a setting method
        if not hasattr(cls, '_%s' %name):
            raise AttributeError("type object '%s' has no attribute '%s'" %(cls.__name__.lower(), name))

        # Create setting
        getattr(cls, '_%s' %name)()

        # Return setting
        value = getattr(cls, name)
        log("(Settings) %s.%s is '%s'" %(cls.__name__.lower(), name, str(value)))
        return value
コード例 #41
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')
コード例 #42
0
ファイル: media.py プロジェクト: freak4pc/KODI-Popcorn-Time
 def _run(self):
     log("(Media) Running preloader", LOGLEVEL.INFO)
     if self._mediaSettings.metadata_provider:
         _res = self._handle_params(self._mediaSettings.metadata_provider.pre())
         if not self.stop.is_set():
             self._mediaSettings.metadata_provider.build_pre(_res)
     if self._mediaSettings.subtitles_provider and not self.stop.is_set():
         _res = self._handle_params(self._mediaSettings.subtitles_provider.pre())
         if not self.stop.is_set():
             self._mediaSettings.subtitles_provider.build_pre(_res)
     log("(Media) Preloader done")
     self.close()
コード例 #43
0
 def status(self, timeout=10):
     if not self._shutdown:
         try:
             if not self.isAlive():
                 raise TorrentError("torrent2http are not running")
             self._last_status = self._json.request(self._url, "/status", timeout=timeout) or self._last_status
             if self._last_status.get('error'):
                 raise TorrentError("torrent2http error: %s" %self._last_status['error'])
         except (JSONDecodeError, socket.timeout, IOError) as e:
             log('(Torrent) %s: %s' %(e.__class__.__name__, str(e)), LOGLEVEL.NOTICE)
             sys.exc_clear()
     return self._last_status
コード例 #44
0
    def __getattr__(cls, name):
        # Do we have a setting method
        if not hasattr(cls, '_%s' % name):
            raise AttributeError("type object '%s' has no attribute '%s'" %
                                 (cls.__name__, name))

        # Create setting
        getattr(cls, '_%s' % name)()

        # Return setting
        value = getattr(cls, name)
        log("(Settings) %s.%s is '%s'" % (cls.__name__, name, str(value)))
        return value
コード例 #45
0
ファイル: main.py プロジェクト: chakhdin/KODI-Popcorn-Time
    def addNextButton(self, **kwargs):
        log("(Main) Adding item 'Show more'")

        item = {
            "label": __addon__.getLocalizedString(30000),
            "icon": os.path.join(settings.addon.resources_path, 'media', self.mediaSettings.mediaType, 'more.png'),
            "thumbnail": os.path.join(settings.addon.resources_path, 'media', self.mediaSettings.mediaType, 'more_thumbnail.png'),
            "properties": {
                "fanart_image": settings.addon.fanart
            }
        }
        item.setdefault('properties',  {}).update(dict((key, str(value)) for key, value in kwargs.items() if value))
        xbmcplugin.addDirectoryItem(settings.addon.handle, "%s?%s" %(settings.addon.base_url, settings.addon.cur_uri), ListItem.from_dict(**item).as_xbmc_listitem(), True)
コード例 #46
0
def item(id, label, year, lang):
    log("(tmdb-item) %s; %s; %s; %s" % (id, label, year, lang), LOGLEVEL.INFO)
    _Data.limit()
    time.sleep(50.0 / 1000.0)
    if label.startswith('Episode'):
        try:
            url = '%s/3/find/%s?api_key=%s&external_source=tvdb_id' % (
                _base_url, id, _api_key)
            req = urllib2.Request(
                url,
                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)
            result = json.loads(response.read())
            metadat = result['tv_episode_results']
            return {
                'domain':
                _base_url,
                'path':
                "/3/tv/%s/season/%s/episode/%s" %
                (metadat[0]['show_id'], metadat[0]['season_number'],
                 metadat[0]['episode_number']),
                'params': {
                    "api_key": _api_key,
                    "append_to_response": "credits",
                    "language": lang,
                    "include_image_language": "en,null"
                }
            }
        except:
            episode = int(label[-1:]) - 1
            id = id.split('-')[0]
            path = '/anime/%s/episodes?page limit=1&page offset=%s&sort=number' % (
                id, episode)
            path = path.replace(' ', '%5B')
            return {'domain': _anime_base_url, 'path': path, 'params': {}}
    else:
        return {
            'domain': _base_url,
            'path': "/3/movie/%s" % id,
            'params': {
                "api_key": _api_key,
                "append_to_response": "credits",
                "language": lang,
                "include_image_language": "en,null"
            }
        }
コード例 #47
0
    def __init__(self, mediaSettings, TorrentEngine, item, subtitleURL=None, callback=None):
        log('(Loader) Initialize loader')
        self._item          = item
        self.callbackfn     = callback
        # Torrent
        self._mediaSettings = mediaSettings
        self._TEngine       = TorrentEngine
        # Subtitle
        self._subtitleURL   = subtitleURL
        self._request       = request.Download()
        self._path          = os.path.join(_settings.cache_path, 'temp.zip')
        self._tmppath       = None

        super(Loader, self).__init__(target=self._run)
コード例 #48
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
    def __init__(self, mediaSettings, TorrentEngine, item, subtitleURL=None, callback=None):
        log('(Loader) Initialize loader')
        self._item          = item
        self.callbackfn     = callback
        # Torrent
        self._mediaSettings = mediaSettings
        self._TEngine       = TorrentEngine
        # Subtitle
        self._subtitleURL   = subtitleURL
        self._request       = request.Download()
        self._path          = os.path.join(_settings.cache_path, 'temp.zip')
        self._tmppath       = None

        super(Loader, self).__init__(target=self._run)
コード例 #49
0
ファイル: base3.py プロジェクト: 1boko1/KODI-Popcorn-Time
    def addNextButton(self, **kwargs):
        log("(%s) Adding item 'Show more'" %self.interfaceName)

        item = {
            "label": __addon__.getLocalizedString(30000),
            "icon": os.path.join(_settings.resources_path, 'media', self.mediaSettings.mediaType, 'more.png'),
            "thumbnail": os.path.join(_settings.resources_path, 'media', self.mediaSettings.mediaType, 'more_thumbnail.png'),
            "replace_context_menu": True,
            "context_menu": [self.getOpenSettings()],
            "properties": {
                "fanart_image": _settings.fanart
            }
        }
        item.setdefault('properties').update(dict((key, str(value)) for key, value in kwargs.items() if value))
        xbmcplugin.addDirectoryItem(_settings.handle, "%s?%s" %(_settings.base_url, _settings.cur_uri), xbmcItem(**item), True)
コード例 #50
0
ファイル: utils.py プロジェクト: markop159/KODI-Popcorn-Time
def notify(messageID=0, message=None, level=NOTIFYLEVEL.INFO):
    if level == NOTIFYLEVEL.WARNING:
        image = settings.addon.warning_image
    elif level == NOTIFYLEVEL.ERROR:
        image = settings.addon.error_image
    else:
        image = settings.addon.info_image

    if not message:
        message = __addon__.getLocalizedString(messageID)

    try:
        xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' % (settings.addon.name, message, len(message)*210, image))
    except Exception as e:
        log('(Utils) Notification failed: %s' % (str(e)), LOGLEVEL.ERROR)
コード例 #51
0
ファイル: torrent.py プロジェクト: chaen/KODI-Popcorn-Time
 def playFile(self, timeout=10):
     files = self.files(timeout)
     if not files:
         return {}
     if self._file_id is None:
         size = 0
         for i, f in enumerate(files):
             mimeType = mimetypes.guess_type(f['name'])
             log('(Torrent) File name: %s, MIME info: %s' %(f['name'], str(mimeType)))
             if mimeType[0] and mimeType[0][:5] == 'video' and f['size'] > size:
                 self._file_id = i
     try:
         return files[self._file_id]
     except (KeyError, TypeError):
         raise TorrentError("Can not find a file to play")
コード例 #52
0
ファイル: media.py プロジェクト: markop159/KODI-Popcorn-Time
    def _getMeta(self, item, args, id):
            metadata = Cache("%s.mediainfo.metadata" %self._mediaSettings.mediaType, ttl=_ttl, readOnly=True, last_changed=self._mediaSettings.metadata_lastchanged).get(id)
            if not metadata:
                try:
                    log("(Media) Getting metadata")
                    _res = self._handle_param(**self._mediaSettings.metadata_provider.item(*args+[_settings.language]))
                    if not self.stop.is_set():
                        metadata = cleanDictList(self._mediaSettings.metadata_provider.build_item(_res, *args+[_settings.language])) # 1. Get request parameter. 2. Perform request(s). 3. Build info.
                except:
                    log_error()
                    sys.exc_clear()
                finally:
                    if self._callbackfn:
                        log("(Media) Callback with '%s'" %item['label'])
                        self._callbackfn(self._progressValue, item, metadata or {})

                if not self._mediaSettings.metadata_provider.FALLBACKLANG == _settings.language:
                    fallbackMeta = None
                    try:
                        log("(Media) Getting fallback metadata")
                        _res = self._handle_param(**self._mediaSettings.metadata_provider.item(*args+[_settings.language]))
                        if not self.stop.is_set():
                            fallbackMeta = self._mediaSettings.metadata_provider.build_item(_res, *args+[_settings.language]) # 1. Get request parameter. 2. Perform request(s). 3. Build info.
                    except:
                        log_error()
                        sys.exc_clear()
                    else:
                        if metadata and fallbackMeta:
                            fallbackMeta.update(metadata)
                        if fallbackMeta:
                            metadata = cleanDictList(fallbackMeta)
                    finally:
                        if self._callbackfn:
                            log("(Media) Callback with '%s'" %item['label'])
                            self._callbackfn(self._progressValue, item, metadata or {})

                if metadata:
                    Cache("%s.mediainfo.metadata" %self._mediaSettings.mediaType, ttl=_ttl, last_changed=self._mediaSettings.metadata_lastchanged)[id] = metadata
            else:
                if self._callbackfn:
                    log("(Media) Callback with '%s'" %item['label'])
                    self._callbackfn(self._progressValue*(1+(not self._mediaSettings.metadata_provider.FALLBACKLANG == _settings.language)), item, metadata)

            if metadata:
                item.setdefault('info',        {}).update(dict((key, value) for key, value in metadata.pop('info',        {}).items() if value))
                item.setdefault('properties',  {}).update(dict((key, value) for key, value in metadata.pop('properties',  {}).items() if value))
                item.setdefault('stream_info', {}).setdefault('video', {}).update(dict((key, value) for key, value in metadata.pop('stream_info', {}).pop('video', {}).items() if value))
                item.update(dict((key, value) for key, value in metadata.items() if value))
コード例 #53
0
ファイル: torrent.py プロジェクト: vascool/KODI-Popcorn-Time
    def _preloading(self, duration=0):
        log("(Loader) Pre-Loading media", LOGLEVEL.INFO)
        if self.callbackfn:
            self.callbackfn(self.PRELOADING, 0)

        progress = 0
        while not self.stop.is_set():
            time.sleep(0.100)

            status = self._TEngine.status()
            if status["download_rate"] <= 0:
                continue

            filestatus = self._TEngine.playFile()

            bytSeconds = (
                status["download_rate"] * 0.8 * 1024
            )  # Download rate is reduced by 20 percent to make sure against fluctuations.
            needSizeInProcent = 0.015  # Fix cache size
            if duration > 0:
                # How long does it take to download the entire movie in seconds.
                seconds = filestatus["size"] / bytSeconds
                # Does it take longer time than to play the movie? Otherwise we only
                # need a buffer to protect against fluctuations (0.02)
                if seconds > duration:
                    # If a movie has a playback time of 2 hours and we take 3 hours to download the movie,
                    # we can only reach to download 2/3 of the movie. We therefore need to cache 1/3 of the movie before playback.
                    # (Or the user need a new connection)
                    needSizeInProcent = 1 - (duration / seconds)
                else:
                    needSizeInProcent = 1 - (duration / (duration + 60.0))  # 60 seconds cache

            needCacheSize = filestatus["size"] * needSizeInProcent
            progressValue = (100 / (((needCacheSize) / bytSeconds) * 1000)) * 100
            if self.callbackfn:
                self.callbackfn(self.PRELOADING, progressValue)

            progress = progress + progressValue
            if (
                progress >= 100 or (filestatus["download"] * 0.45) >= needCacheSize
            ):  # We are caching about 65% (filestatus['download']*0.45) more end need (needCacheSize).
                if self.callbackfn:
                    self.callbackfn(self.PRELOADING, (100 - progress) > 0 and (100 - progress) or 0)
                log("(Loader) Finished with pre-loading media")
                return not self.stop.is_set()

        return False
コード例 #54
0
ファイル: main.py プロジェクト: chakhdin/KODI-Popcorn-Time
    def addItem(self, mediaType, endpoint, params, isFolder=True, **item):
        log("(Main) Adding item '%s'" %item["label"])
        path = "%s?%s" %(settings.addon.base_url, urllib.urlencode(dict([('mediaType', mediaType), ('endpoint', endpoint)], **params)))

        if not isFolder:
            item["replace_context_menu"] = True
            item["context_menu"] = []
            for _q in settings.QUALITIES:
                if params.get(_q):
                    item["context_menu"] = item["context_menu"]+[('%s %s' %(__addon__.getLocalizedString(30009), _q), 'RunPlugin(%s&quality=%s)' %(path, _q))]
            item["context_menu"] = item["context_menu"]+[(__addon__.getLocalizedString(30010), 'RunPlugin(%s?cmd=True&endpoint=openSettings)' %settings.addon.base_url)]

        # Ensure fanart
        if not item.setdefault("properties", {}).get("fanart_image"):
            item["properties"]["fanart_image"] = settings.addon.fanart

        xbmcplugin.addDirectoryItem(settings.addon.handle, path, ListItem.from_dict(**item).as_xbmc_listitem(), isFolder)
コード例 #55
0
ファイル: media.py プロジェクト: freak4pc/KODI-Popcorn-Time
    def __init__(self, mediaSettings, callback=None, workers=2):
        log("(Media) Initialize media cache", LOGLEVEL.INFO)
        self._mediaSettings      = mediaSettings
        self._callbackfn         = callback
        self._workers            = workers or 2

        self._indexCount         = 0
        self._data               = []
        self._queue              = []
        self._queueStart         = False
        self._threads            = []
        self._preloader          = None
        self._progressValue      = 1

        if self._mediaSettings.metadata_provider or self._mediaSettings.subtitles_provider:
            self._preloader = _Preloader(self._mediaSettings)
            self._progressValue = self._progressValue/(bool(self._mediaSettings.metadata_provider)+(not self._mediaSettings.metadata_provider.FALLBACKLANG == _settings.language)+bool(self._mediaSettings.subtitles_provider)+0.0)