Ejemplo n.º 1
0
def get_files(t_url):
    engine = Engine(uri=t_url,download_path=temp_dir,bind_host='127.0.0.1',bind_port=5001)
    file_id = None
    files=[]
    try:
        with closing(engine):
            engine.start(0)
            files = engine.list(media_types=[MediaType.VIDEO])
            n=files[0].name
    except Error as err:
        print "Error"
        print err
    return files
Ejemplo n.º 2
0
def list(uri):
    # Create instance of Engine
    engine = Engine(uri)
    files = []
    # Ensure we'll close engine on exception
    with closing(engine):
        # Start engine
        engine.start()
        # Wait until files received
        while not files and not xbmc.abortRequested:
            # Will list only video files in torrent
            files = engine.list(media_types=[MediaType.VIDEO])
            # Check if there is loading torrent error and raise exception
            engine.check_torrent_error()
            xbmc.sleep(200)
    return files
class AnteoLoader:
    magnetLink = None
    engine = None
    torrentFile = None
    __plugin__ = sys.modules["__main__"].__plugin__
    __settings__ = sys.modules["__main__"].__settings__

    def __init__(self, storageDirectory='', torrentFile='', torrentFilesDirectory='torrents'):
        self.storageDirectory = storageDirectory
        self.torrentFilesPath = os.path.join(self.storageDirectory, torrentFilesDirectory) + os.sep
        if not is_writable(self.storageDirectory):
            xbmcgui.Dialog().ok(self.localize('Torrenter v2'),
                    self.localize('Your storage path is not writable or not local! Please change it in settings!'),
                    self.localize(self.storageDirectory))

            sys.exit(1)

        #pre settings
        if re.match("^magnet\:.+$", torrentFile):
            self.magnetLink = torrentFile
        else:
            self.torrentFile = torrentFile

    def __exit__(self):
        log('on __exit__')
        if self.engine:
            self.engine.close()
            log('__exit__ worked!')

    def setup_engine(self):
        encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED

        if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]:
            connections_limit = int(self.__settings__.getSetting("connections_limit"))
        else:
            connections_limit = None

        use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False

        listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting(
            "listen_port") != "" else 6881

        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.storageDirectory:
            keep_complete = False
            keep_incomplete = False
        else:
            keep_complete = True
            keep_incomplete = True

        dht_routers = ["router.bittorrent.com:6881", "router.utorrent.com:6881"]
        user_agent = 'uTorrent/2200(24683)'
        self.engine = Engine(uri=file_url(self.torrentFile), download_path=self.storageDirectory,
                             connections_limit=connections_limit,
                             encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete,
                             dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port,
                             user_agent=user_agent)

    def localize(self, string):
        try:
            return Localization.localize(string)
        except:
            return string

    def getContentList(self):
        self.setup_engine()
        files = []
        filelist = []
        with closing(self.engine):
            self.engine.start()
            #media_types=[MediaType.VIDEO, MediaType.AUDIO, MediaType.SUBTITLES, MediaType.UNKNOWN]

            iterator = 0
            text = Localization.localize('Magnet-link is converting') if self.magnetLink\
                else Localization.localize('Opening torrent file')
            while not files and not xbmc.abortRequested and iterator < 100:
                files = self.engine.list()
                self.engine.check_torrent_error()
                if iterator==4:
                    progressBar = xbmcgui.DialogProgress()
                    progressBar.create(Localization.localize('Please Wait'),
                               Localization.localize('Magnet-link is converting'))
                elif iterator>4:
                    progressBar.update(iterator, Localization.localize('Please Wait'),text+'.' * (iterator % 4), ' ')
                    if progressBar.iscanceled():
                        progressBar.update(0)
                        progressBar.close()
                        return []
                xbmc.sleep(500)
                iterator += 1

            for fs in files:
                stringdata = {"title": fs.name, "size": fs.size, "ind": fs.index,
                              'offset': fs.offset}
                filelist.append(stringdata)
        return filelist

    def saveTorrent(self, torrentUrl):
        if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
            if re.match("^magnet\:.+$", torrentUrl):
                self.magnetLink = torrentUrl
                self.magnetToTorrent(torrentUrl)
                self.magnetLink = None
                return self.torrentFile
            else:
                if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
                torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
                try:
                    if not re.match("^http\:.+$", torrentUrl):
                        content = xbmcvfs.File(torrentUrl, "rb").read()
                    else:
                        request = urllib2.Request(torrentUrl)
                        request.add_header('Referer', torrentUrl)
                        request.add_header('Accept-encoding', 'gzip')
                        result = urllib2.urlopen(request)
                        if result.info().get('Content-Encoding') == 'gzip':
                            buf = StringIO(result.read())
                            f = gzip.GzipFile(fileobj=buf)
                            content = f.read()
                        else:
                            content = result.read()

                    localFile = xbmcvfs.File(torrentFile, "w+b")
                    localFile.write(content)
                    localFile.close()
                except Exception, e:
                    print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(
                        e)
                    return
        else:
class Torrent2HTTPPlayer(TorrentPlayer):
    def debug(self, msg):
        try:
            import log
            log.debug('[Torrent2HTTPPlayer] %s' % msg)
        except:
            pass

    def debug_assignment(self, value, varname):
        try:
            self.debug('%s: %s' % (varname, str(value)))
        except:
            pass
        return value

    def __init__(self, settings):
        self.engine = None
        self.file_id = None
        self.settings = settings
        self.download_path = None

        self.pre_buffer_bytes = self.debug_assignment(
            int(getSetting('pre_buffer_bytes')) * 1024 * 1024,
            'pre_buffer_bytes')

        self.debug('__init__')

        TorrentPlayer.__init__(self)

    def close(self):
        if self.engine != None:
            self.engine.close()
            self.engine = None

        self.debug('close')

    def __exit__(self):
        self.debug('__exit__')
        self.close()

    def _AddTorrent(self, path):

        if filesystem.exists(path):
            if path.startswith(r'\\') or '://' in path:
                tempPath = xbmc.translatePath('special://temp').decode('utf-8')
                destPath = filesystem.join(tempPath, 't2h.torrent')
                filesystem.copyfile(path, destPath)
                path = destPath

            uri = path2url(path)
        else:
            uri = path

        self.debug('AddTorrent: ' + uri)

        add_trackers = []
        if getSetting('add_tracker'):
            add_trackers.append(getSetting('add_tracker'))

        download_path = self.settings.storage_path
        if download_path == '':
            download_path = xbmc.translatePath('special://temp')

        self.debug('download_path: %s' % download_path)
        self.download_path = download_path

        encryption = self.debug_assignment(
            Encryption.ENABLED if getSetting('encryption') == 'true' else
            Encryption.DISABLED, 'encryption')
        upload_limit = self.debug_assignment(
            int(getSetting("upload_limit")) *
            1024 if getSetting("upload_limit") != "" else 0, "upload_limit")
        download_limit = self.debug_assignment(
            int(getSetting("download_limit")) *
            1024 if getSetting("download_limit") != "" else 0,
            "download_limit")

        if getSetting("connections_limit") not in ["", 0, "0"]:
            connections_limit = self.debug_assignment(
                int(getSetting("connections_limit")), "connections_limit")
        else:
            connections_limit = None

        use_random_port = self.debug_assignment(
            True if getSetting('use_random_port') == 'true' else False,
            'use_random_port')
        listen_port = self.debug_assignment(
            int(getSetting("listen_port"))
            if getSetting("listen_port") != "" else 62881, "listen_port")
        if listen_port == 6881:
            use_random_port = True

        keep_files = getSetting('action_files').decode('utf-8') != u'удалить'

        args = {
            'uri': uri,
            'download_path': download_path,
            'user_agent': user_agent,
            'encryption': encryption,
            'upload_kbps': upload_limit,
            'download_kbps': download_limit,
            'connections_limit': connections_limit,
            'keep_incomplete': False,
            'keep_complete': keep_files,
            'keep_files': keep_files,
            'dht_routers': dht_routers,
            'use_random_port': use_random_port,
            'listen_port': listen_port,
            'log_files_progress': True,
            'trackers': add_trackers,
            'startup_timeout': 1000
        }

        try:
            if keep_files:
                args['resume_file'] = filesystem.join(
                    self.settings.torrents_path(), self.info_hash + '.resume')
        except BaseException as e:
            log.print_tb(e)
            if keep_files:
                args['resume_file'] = filesystem.join(
                    download_path, self.info_hash + '.resume')

        if args.get('resume_file'):
            self.debug('resume file is: ' + args['resume_file'])

        self.engine = Engine(**args)

    def CheckTorrentAdded(self):
        if self.engine:
            status = self.engine.status()
            self.engine.check_torrent_error(status)

            self.debug('CheckTorrentAdded')

            if status.state == State.CHECKING_FILES:
                self.debug('State.CHECKING_FILES')
                return False
        else:
            return TorrentPlayer.CheckTorrentAdded(self)

        return True

    def _GetLastTorrentData(self):
        while True:
            time.sleep(0.2)

            # Get torrent files list, filtered by video file type only
            files = self.engine.list()  #(media_types=[MediaType.VIDEO])
            # If torrent metadata is not loaded yet then continue
            if files is None:
                self.debug('files is None')
                continue

            self.debug('files len: ' + str(len(files)))

            # Torrent has no video files
            if not files or len(files) > 0:
                break

        info_hash = ''
        playable_items = []
        for item in files:
            if TorrentPlayer.is_playable(item.name):
                playable_items.append({
                    'index': item.index,
                    'name': item.name,
                    'size': long(item.size)
                })

        return {'info_hash': info_hash, 'files': playable_items}

    def StartBufferFile(self, fileIndex):
        self._AddTorrent(self.path)

        self.download_path = None

        self.engine.start(fileIndex)
        self.file_id = fileIndex

        self.debug('StartBufferFile: %d' % fileIndex)

    def CheckBufferComplete(self):
        if not self.download_path is None:
            return True

        status = self.engine.status()
        self.debug('CheckBufferComplete: ' + str(status.state_str))
        if status.state == State.DOWNLOADING:
            # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC
            f_status = self.engine.file_status(self.file_id)
            self.debug('f_status.download %d' % f_status.download)
            if f_status.download >= self.pre_buffer_bytes:
                return True

        return status.state in [State.FINISHED, State.SEEDING]

    def GetBufferingProgress(self):
        f_status = self.engine.file_status(self.file_id)

        try:
            progress = int(
                round(float(f_status.download) / self.pre_buffer_bytes, 2) *
                100)
            self.debug('GetBufferingProgress: %d' % progress)
            if progress > 99:
                progress = 99
        except:
            progress = 0

        return progress

    def updateCheckingProgress(self, progressBar):
        status = self.engine.status()
        percents = int(status.progress * 100)
        if percents > 99:
            percents = 99
        progressBar.update(percents, u'Media Aggregator: проверка файлов...',
                           ' ', ' ')

    def updateDialogInfo(self, progress, progressBar):
        f_status = self.engine.file_status(self.file_id)
        status = self.engine.status()

        if f_status is None or status is None:
            return

        dialogText = u'Загружено: ' + "%d MB / %d MB" % \
                   (int(f_status.download / 1024 / 1024), int(f_status.size / 1024 / 1024))
        peersText = u' [%s: %s; %s: %s]' % (u'Сидов', status.num_seeds,
                                            u'Пиров', status.num_peers)
        speedsText = u'%s: %d Mbit/s; %s: %d Mbit/s' % (
            u'Загрузка', int(status.download_rate / 1024 * 8), u'Отдача',
            int(status.upload_rate / 1024 * 8))
        progressBar.update(progress, dialogText + '          ' + peersText,
                           speedsText)

    def GetTorrentInfo(self):
        f_status = self.engine.file_status(self.file_id)
        status = self.engine.status()

        if f_status is None or status is None:
            return None

        try:
            return {
                'downloaded': int(f_status.download / 1024 / 1024),
                'size': int(f_status.size / 1024 / 1024),
                'dl_speed': int(status.download_rate),
                'ul_speed': int(status.upload_rate),
                'num_seeds': status.num_seeds,
                'num_peers': status.num_peers
            }
        except:
            pass

        return None

    def GetStreamURL(self, playable_item):
        if self.download_path is None:
            f_status = self.engine.file_status(self.file_id)
            self.debug('GetStreamURL: %s' % f_status.url)
            return f_status.url
        else:
            self.debug('GetStreamURL: %s' % self.download_path)
            return self.download_path
Ejemplo n.º 5
0
def sub_play(params):
    if params['r'][:4] == 'http':
        purl = urllib.unquote_plus(params['r'])
        item = xbmcgui.ListItem(path=purl)
        xbmcplugin.setResolvedUrl(handle, True, item)
        return

    if params['r'][:4] == 'myvi':
        url = urllib.unquote_plus(params['r']).replace('myvi', 'http')
        data = get_myvi_data(url)

        item = xbmcgui.ListItem(path=data['url'])
        xbmcplugin.setResolvedUrl(handle, True, item)
        return

    file_id = int(params.get('i', 0))
    uri = sections['get_torrent'] + '/' + params['r'] + '/' + params['t']

    torrent = get_html(uri)

    temp_name = os.path.join(xt('special://masterprofile'), 'shiza.torrent')

    temp_file = open(
        temp_name.decode('utf-8') if sys.platform == 'win32' else temp_name,
        "wb")
    temp_file.write(torrent)
    temp_file.close()

    uri = 'file://' + temp_name.replace('\\', '//')

    if addon.getSetting('Engine') == '1':
        sub_play_yatp(uri, file_id)
        return

    if addon.getSetting('Engine') == '2':
        sub_play_tam(temp_name, file_id)
        return

    if addon.getSetting('Engine') == '3':
        sub_play_elem(temp_name, file_id)
        return

    #, cwd=os.path.dirname(binary_path)) in torrent2html engine.py

    from torrent2http import State, Engine, MediaType
    progressBar = xbmcgui.DialogProgress()
    from contextlib import closing
    DDir = xt('special://masterprofile')

    progressBar.create('Torrent2Http', 'Запуск')
    # XBMC addon handle
    # handle = ...
    # Playable list item
    # listitem = ...
    # We can know file_id of needed video file on this step, if no, we'll try to detect one.
    # file_id = None
    # Flag will set to True when engine is ready to resolve URL to XBMC
    ready = False
    # Set pre-buffer size to 24Mb. This is a size of file that need to be downloaded before we resolve URL to XMBC
    pre_buffer_bytes = 24 * 1024 * 1024

    engine = Engine(uri, download_path=DDir)
    with closing(engine):
        # Start engine and instruct torrent2http to begin download first file,
        # so it can start searching and connecting to peers
        engine.start(file_id)
        progressBar.update(0, 'Torrent2Http', 'Загрузка торрента', "")
        while not xbmc.abortRequested and not ready:
            xbmc.sleep(500)

            if progressBar.iscanceled():
                ready = False
                break

            status = engine.status()
            # Check if there is loading torrent error and raise exception
            engine.check_torrent_error(status)
            # Trying to detect file_id
            if file_id is None:
                # Get torrent files list, filtered by video file type only
                files = engine.list(media_types=[MediaType.VIDEO])
                # If torrent metadata is not loaded yet then continue
                if files is None:
                    continue
                # Torrent has no video files
                if not files:
                    progressBar.close()
                    break
                # Select first matching file
                file_id = files[0].index
                file_status = files[0]
            else:
                # If we've got file_id already, get file status
                file_status = engine.file_status(file_id)
                # If torrent metadata is not loaded yet then continue
                if not file_status:
                    continue
            if status.state == State.DOWNLOADING:
                # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC
                if file_status.download >= pre_buffer_bytes:
                    ready = True
                    break
                #print file_status
                #downloadedSize = status.total_download / 1024 / 1024
                getDownloadRate = status.download_rate / 1024 * 8
                #getUploadRate = status.upload_rate / 1024 * 8
                getSeeds = status.num_seeds

                progressBar.update(
                    100 * file_status.download / pre_buffer_bytes,
                    'Предварительная буферизация: ' +
                    str(file_status.download / 1024 / 1024) + " MB",
                    "Сиды: " + str(getSeeds),
                    "Скорость: " + str(getDownloadRate)[:4] + ' Mbit/s')

            elif status.state in [State.FINISHED, State.SEEDING]:
                #progressBar.update(0, 'T2Http', 'We have already downloaded file', "")
                # We have already downloaded file
                ready = True
                break

            # Here you can update pre-buffer progress dialog, for example.
            # Note that State.CHECKING also need waiting until fully finished, so it better to use resume_file option
            # for engine to avoid CHECKING state if possible.
            # ...
        progressBar.update(0)
        progressBar.close()
        if ready:
            # Resolve URL to XBMC
            item = xbmcgui.ListItem(path=file_status.url)
            xbmcplugin.setResolvedUrl(handle, True, item)
            xbmc.sleep(3000)
            # Wait until playing finished or abort requested
            while not xbmc.abortRequested and xbmc.Player().isPlaying():
                xbmc.sleep(500)
Ejemplo n.º 6
0
def play(uri, handle, file_id=0, DDir=""):
    if DDir == "":
        DDir = os.path.join(xbmc.translatePath("special://home/"), "userdata")
    progressBar.create('Torrent2Http', 'Запуск')
    # XBMC addon handle
    # handle = ...
    # Playable list item
    # listitem = ...
    # We can know file_id of needed video file on this step, if no, we'll try to detect one.
    # file_id = None
    # Flag will set to True when engine is ready to resolve URL to XBMC
    ready = False
    # Set pre-buffer size to 15Mb. This is a size of file that need to be downloaded before we resolve URL to XMBC
    pre_buffer_bytes = 15 * 1024 * 1024
    engine = Engine(uri, download_path=DDir)
    with closing(engine):
        # Start engine and instruct torrent2http to begin download first file,
        # so it can start searching and connecting to peers
        engine.start(file_id)
        progressBar.update(0, 'Torrent2Http', 'Загрузка торрента', "")
        while not xbmc.abortRequested and not ready:
            xbmc.sleep(500)
            status = engine.status()
            # Check if there is loading torrent error and raise exception
            engine.check_torrent_error(status)
            # Trying to detect file_id
            if file_id is None:
                # Get torrent files list, filtered by video file type only
                files = engine.list(media_types=[MediaType.VIDEO])
                # If torrent metadata is not loaded yet then continue
                if files is None:
                    continue
                # Torrent has no video files
                if not files:
                    break
                    progressBar.close()
                # Select first matching file
                file_id = files[0].index
                file_status = files[0]
            else:
                # If we've got file_id already, get file status
                file_status = engine.file_status(file_id)
                # If torrent metadata is not loaded yet then continue
                if not file_status:
                    continue
            if status.state == State.DOWNLOADING:
                # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC
                if file_status.download >= pre_buffer_bytes:
                    ready = True
                    break
                print file_status
                progressBar.update(
                    100 * file_status.download / pre_buffer_bytes,
                    'Torrent2Http',
                    xt('Предварительная буферизация: ' +
                       str(file_status.download / 1024 / 1024) + " MB"), "")

            elif status.state in [State.FINISHED, State.SEEDING]:
                #progressBar.update(0, 'T2Http', 'We have already downloaded file', "")
                # We have already downloaded file
                ready = True
                break

            if progressBar.iscanceled():
                progressBar.update(0)
                progressBar.close()
                break
            # Here you can update pre-buffer progress dialog, for example.
            # Note that State.CHECKING also need waiting until fully finished, so it better to use resume_file option
            # for engine to avoid CHECKING state if possible.
            # ...
        progressBar.update(0)
        progressBar.close()
        if ready:
            # Resolve URL to XBMC
            #listitem = xbmcgui.ListItem(path=file_status.url)
            #xbmcplugin.SetResolvedUrl(handle, True, listitem)
            xbmc.Player().play(file_status.url)
            # Wait until playing finished or abort requested
            while not xbmc.abortRequested and xbmc.Player().isPlaying():
                xbmc.sleep(500)
Ejemplo n.º 7
0
class AnteoLoader:
    magnetLink = None
    engine = None
    torrentFile = None
    __plugin__ = sys.modules["__main__"].__plugin__
    __settings__ = sys.modules["__main__"].__settings__

    def __init__(self,
                 storageDirectory='',
                 torrentFile='',
                 torrentFilesDirectory='torrents'):
        self.storageDirectory = storageDirectory
        self.torrentFilesPath = os.path.join(self.storageDirectory,
                                             torrentFilesDirectory) + os.sep
        if not is_writable(self.storageDirectory):
            xbmcgui.Dialog().ok(
                self.localize('Torrenter v2'),
                self.localize(
                    'Your storage path is not writable or not local! Please change it in settings!'
                ), self.localize(self.storageDirectory))

            sys.exit(1)

        #pre settings
        if re.match("^magnet\:.+$", torrentFile):
            self.magnetLink = torrentFile
        else:
            self.torrentFile = torrentFile

    def __exit__(self):
        log('on __exit__')
        if self.engine:
            self.engine.close()
            log('__exit__ worked!')

    def setup_engine(self):
        encryption = Encryption.ENABLED if self.__settings__.getSetting(
            'encryption') == 'true' else Encryption.DISABLED

        if self.__settings__.getSetting("connections_limit") not in [
                "", 0, "0"
        ]:
            connections_limit = int(
                self.__settings__.getSetting("connections_limit"))
        else:
            connections_limit = None

        use_random_port = True if self.__settings__.getSetting(
            'use_random_port') == 'true' else False

        listen_port = int(
            self.__settings__.getSetting("listen_port")
        ) if self.__settings__.getSetting("listen_port") != "" else 6881

        if '1' != self.__settings__.getSetting(
                "keep_files") and 'Saved Files' not in self.storageDirectory:
            keep_complete = False
            keep_incomplete = False
        else:
            keep_complete = True
            keep_incomplete = True

        dht_routers = [
            "router.bittorrent.com:6881", "router.utorrent.com:6881"
        ]
        user_agent = 'uTorrent/2200(24683)'
        self.engine = Engine(uri=file_url(self.torrentFile),
                             download_path=self.storageDirectory,
                             connections_limit=connections_limit,
                             encryption=encryption,
                             keep_complete=keep_complete,
                             keep_incomplete=keep_incomplete,
                             dht_routers=dht_routers,
                             use_random_port=use_random_port,
                             listen_port=listen_port,
                             user_agent=user_agent)

    def localize(self, string):
        try:
            return Localization.localize(string)
        except:
            return string

    def getContentList(self):
        self.setup_engine()
        files = []
        filelist = []
        with closing(self.engine):
            self.engine.start()
            #media_types=[MediaType.VIDEO, MediaType.AUDIO, MediaType.SUBTITLES, MediaType.UNKNOWN]

            iterator = 0
            text = Localization.localize('Magnet-link is converting') if self.magnetLink\
                else Localization.localize('Opening torrent file')
            while not files and not xbmc.abortRequested and iterator < 100:
                files = self.engine.list()
                self.engine.check_torrent_error()
                if iterator == 4:
                    progressBar = xbmcgui.DialogProgress()
                    progressBar.create(
                        Localization.localize('Please Wait'),
                        Localization.localize('Magnet-link is converting'))
                elif iterator > 4:
                    progressBar.update(iterator,
                                       Localization.localize('Please Wait'),
                                       text + '.' * (iterator % 4), ' ')
                    if progressBar.iscanceled():
                        progressBar.update(0)
                        progressBar.close()
                        return []
                xbmc.sleep(500)
                iterator += 1

            for fs in files:
                stringdata = {
                    "title": fs.name,
                    "size": fs.size,
                    "ind": fs.index,
                    'offset': fs.offset
                }
                filelist.append(stringdata)
        return filelist

    def saveTorrent(self, torrentUrl):
        if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
            if re.match("^magnet\:.+$", torrentUrl):
                self.magnetLink = torrentUrl
                self.magnetToTorrent(torrentUrl)
                self.magnetLink = None
                return self.torrentFile
            else:
                if not xbmcvfs.exists(self.torrentFilesPath):
                    xbmcvfs.mkdirs(self.torrentFilesPath)
                torrentFile = os.path.join(self.torrentFilesPath,
                                           self.md5(torrentUrl) + '.torrent')
                try:
                    if not re.match("^http\:.+$", torrentUrl):
                        content = xbmcvfs.File(torrentUrl, "rb").read()
                    else:
                        request = urllib2.Request(torrentUrl)
                        request.add_header('Referer', torrentUrl)
                        request.add_header('Accept-encoding', 'gzip')
                        result = urllib2.urlopen(request)
                        if result.info().get('Content-Encoding') == 'gzip':
                            buf = StringIO(result.read())
                            f = gzip.GzipFile(fileobj=buf)
                            content = f.read()
                        else:
                            content = result.read()

                    localFile = xbmcvfs.File(torrentFile, "w+b")
                    localFile.write(content)
                    localFile.close()
                except Exception, e:
                    print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(
                        e)
                    return
        else:
Ejemplo n.º 8
0
class AnteoLoader:
    magnetLink = None
    engine = None
    torrentFile = None
    __plugin__ = sys.modules["__main__"].__plugin__
    __settings__ = sys.modules["__main__"].__settings__

    def __init__(self, storageDirectory='', torrentFile='', torrentFilesDirectory='torrents'):
        self.storageDirectory = storageDirectory
        self.torrentFilesPath = os.path.join(self.storageDirectory, torrentFilesDirectory) + os.sep
        if not is_writable(self.storageDirectory):
            xbmcgui.Dialog().ok(self.localize('Torrenter v2'),
                    self.localize('Your storage path is not writable or not local! Please change it in settings!'),
                    self.localize(self.storageDirectory))

            sys.exit(1)

        #pre settings
        if re.match("^magnet\:.+$", torrentFile):
            self.magnetLink = torrentFile
        else:
            self.torrentFile = torrentFile

    def setup_engine(self):
        encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED

        if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]:
            connections_limit = int(self.__settings__.getSetting("connections_limit"))
        else:
            connections_limit = None

        use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False

        listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting(
            "listen_port") != "" else 6881

        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.storageDirectory:
            keep_complete = False
            keep_incomplete = False
        else:
            keep_complete = True
            keep_incomplete = True

        dht_routers = ["router.bittorrent.com:6881", "router.utorrent.com:6881"]
        user_agent = ''
        self.engine = Engine(uri=file_url(localize_path(self.torrentFile)), download_path=self.storageDirectory,
                             connections_limit=connections_limit,
                             encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete,
                             dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port,
                             user_agent=user_agent)

    def localize(self, string):
        try:
            return Localization.localize(string)
        except:
            return string

    def getContentList(self):
        try:
            from SkorbaLoader import SkorbaLoader
            torrent = SkorbaLoader(self.storageDirectory, self.torrentFile)
            return torrent.getContentList()
        except:
            import traceback
            log(traceback.format_exc())
            return self.getContentList_engine()

    def getContentList_engine(self):
        self.setup_engine()
        files = []
        filelist = []
        with closing(self.engine):
            self.engine.start()
            #media_types=[MediaType.VIDEO, MediaType.AUDIO, MediaType.SUBTITLES, MediaType.UNKNOWN]

            iterator = 0
            text = Localization.localize('Magnet-link is converting') if self.magnetLink\
                else Localization.localize('Opening torrent file')
            while not files and not xbmc.abortRequested and iterator < 100:
                files = self.engine.list()
                self.engine.check_torrent_error()
                if iterator==4:
                    progressBar = xbmcgui.DialogProgress()
                    progressBar.create(Localization.localize('Please Wait'),
                               Localization.localize('Magnet-link is converting'))
                elif iterator>4:
                    progressBar.update(iterator, Localization.localize('Please Wait'),text+'.' * (iterator % 4), ' ')
                    if progressBar.iscanceled():
                        progressBar.update(0)
                        progressBar.close()
                        return []
                xbmc.sleep(500)
                iterator += 1

            for fs in files:
                stringdata = {"title": ensure_str(fs.name), "size": fs.size, "ind": fs.index,
                              'offset': fs.offset}
                filelist.append(stringdata)
        return filelist

    def saveTorrent(self, torrentUrl):
        #if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl):
        if re.match("^magnet\:.+$", torrentUrl):
            self.magnetLink = torrentUrl
            self.magnetToTorrent(torrentUrl)
            self.magnetLink = None
            return self.torrentFile
        else:
            if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
            torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
            try:
                if not re.match("^[htps]+?://.+$|^://.+$", torrentUrl):
                    log('xbmcvfs.File for %s' % torrentUrl)
                    content = xbmcvfs.File(torrentUrl, "rb").read()
                else:
                    log('request for %s' % torrentUrl)
                    content = self.makeRequest(torrentUrl)

                localFile = xbmcvfs.File(torrentFile, "w+b")
                localFile.write(content)
                localFile.close()
            except Exception, e:
                log('Unable to rename torrent file from %s to %s in AnteoLoader::saveTorrent. Exception: %s' %
                        (torrentUrl, torrentFile, str(e)))
                return
        if xbmcvfs.exists(torrentFile) and not os.path.exists(torrentFile):
            if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath)
            torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')
            xbmcvfs.copy(torrentUrl, torrentFile)
        if os.path.exists(torrentFile):
            self.torrentFile = torrentFile
            return self.torrentFile
Ejemplo n.º 9
0
        print "no url entered"

elif mode[0] == 'playtorrent':
    surl=args['slink'][0]
    sname=args['sname'][0]
    sid=int(args['sid'][0])
    ready = False
    pre_buffer_bytes = 15*1024*1024
    engine = Engine(uri=surl,download_path=temp_dir,bind_host='127.0.0.1',bind_port=5001)
     
    progress = xbmcgui.DialogProgress()
    progress.create('Downloading', 'Prebuffering...')
    
    try:
        with closing(engine):
            engine.start(sid)
            #xbmcgui.DialogProgress()
            while not xbmc.abortRequested and not ready and not progress.iscanceled():
                xbmc.sleep(500)
                status = engine.status()
                print "Status:",status
                engine.check_torrent_error(status)
                files = engine.list(media_types=[MediaType.VIDEO])
                file_status = engine.file_status(sid)
                if status.state == State.DOWNLOADING:
                    prcnt=100.0
                    prcnt=prcnt*file_status.download/pre_buffer_bytes
                    s1="Downloaded: "+str(file_status.download/1024/1024)+"MB of 15MB"
                    s2="D: "+str(int(status.download_rate))+"KB/s U: "+str(int(status.upload_rate))+"KB/s"
                    s3="Peers: "+str(status.num_peers)+" Seeds: "+str(status.num_seeds)
                    progress.update(int(prcnt),s1,s2,s3)