def stream(self, args, client_class):
        self.c = client_class(args.directory, args=args, lt=self.lt)
        try:
            while True:
                try:
                    s = socket.socket()
                    res = s.connect_ex(('127.0.0.1', self.free_port))
                    if res:
                        break
                finally:
                    s.close()
                self.free_port += 1

            self.server = StreamServer(('127.0.0.1', self.free_port), BTFileHandler, allow_range=True,
                                  status_fn=self.c.get_normalized_status)
            log('Started http server on port %d' % self.free_port)
            self.server.run()

            log('Starting btclient - libtorrent version %s' % self.lt.version)
            self.c.start_url(args.url)
            self.setup_torrent()

            if self.buffer():
                f = self.c._file
                self.server.set_file(f)
                self.setup_play()

                while True:
                    if self.setup_play():
                        log('************************************* GOING LOOP')
                        #self.torrent.continueSession(self.contentId)
                        self.loop()
                    else:
                        break
                    log('************************************* GO NEXT?')
                    if self.next_dl and self.next_dling and isinstance(self.next_contentId, int) and self.iterator == 100:
                        self.contentId = self.next_contentId
                        continue
                    log('************************************* NO! break')
                    break

            if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory:
                xbmc.sleep(1000)
                clearStorage(self.userStorageDirectory)
            else:
                if self.seeding_status:
                    showMessage(self.localize('Information'),
                                self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
                else:
                    if self.seeding: self.db_delete()
                    showMessage(self.localize('Information'),
                                self.localize('Torrent downloading is stopped.'), forced=True)

            log('Play ended')
            if self.server:
                self.server.stop()
        except Exception:
            traceback.print_exc()
        finally:
            self.on_exit()
Esempio n. 2
0
 def setup_subs(self, label, path):
     iterator = 0
     subs = self.torrent.getSubsIds(label)
     # print str(subs)
     if len(subs) > 0:
         showMessage(Localization.localize('Information'),
                     Localization.localize('Downloading and copy subtitles. Please wait.'), forced=True)
         for ind, title in subs:
             self.torrent.continueSession(ind)
         while iterator < 100:
             xbmc.sleep(1000)
             self.torrent.debug()
             status = self.torrent.torrentHandle.status()
             iterator = int(status.progress * 100)
         # xbmc.sleep(2000)
         for ind, title in subs:
             folder = title.split(os.sep)[0]
             temp = os.path.basename(title)
             addition = os.path.dirname(title).lstrip(folder + os.sep).replace(os.sep, '.').replace(' ', '_').strip()
             ext = temp.split('.')[-1]
             temp = temp[:len(temp) - len(ext) - 1] + '.' + addition + '.' + ext
             newFileName = os.path.join(os.path.dirname(path), temp)
             # print str((os.path.join(os.path.dirname(os.path.dirname(path)),title),newFileName))
             if not xbmcvfs.exists(newFileName):
                 xbmcvfs.copy(os.path.join(os.path.dirname(os.path.dirname(path)), title), newFileName)
Esempio n. 3
0
 def loop(self):
     with closing(
             OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay:
         with nested(self.attach(overlay.show, self.on_playback_paused),
                     self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)):
             while not xbmc.abortRequested and self.isPlaying() and not self.torrent.threadComplete:
                 self.torrent.checkThread()
                 self.torrent.debug()
                 status = self.torrent.torrentHandle.status()
                 overlay.text = "\n".join(self._get_status_lines(status))
                 # downloadedSize = torrent.torrentHandle.file_progress()[contentId]
                 self.iterator = int(status.progress * 100)
                 xbmc.sleep(1000)
                 if self.iterator == 100 and self.next_dl:
                     next_contentId_index = self.ids_video.index(str(self.contentId)) + 1
                     if len(self.ids_video) > next_contentId_index:
                         self.next_contentId = int(self.ids_video[next_contentId_index])
                     else:
                         self.next_contentId = False
                         # print str(self.next_contentId)+'xxxxxx23'
                 if not self.seeding_run and self.iterator == 100 and self.seeding:
                     self.seeding_run = True
                     self.seed(self.contentId)
                     self.seeding_status = True
                     # xbmc.sleep(7000)
                 if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(self.next_contentId,
                                                                                                 int) and self.next_contentId != False:
                     showMessage(Localization.localize('Torrent Downloading'),
                                 Localization.localize('Starting download next episode!'), forced=True)
                     self.torrent.stopSession()
                     # xbmc.sleep(1000)
                     path = self.torrent.getFilePath(self.next_contentId)
                     self.basename = self.display_name = os.path.basename(path)
                     self.torrent.continueSession(self.next_contentId)
                     self.next_dling = True
Esempio n. 4
0
 def loop(self):
     debug_counter = 0
     pause = True
     self.torrent.torrentHandle.force_dht_announce()
     with closing(
             OverlayText(w=OVERLAY_WIDTH,
                         h=OVERLAY_HEIGHT,
                         alignment=XBFONT_CENTER_X
                         | XBFONT_CENTER_Y)) as overlay:
         with nested(
                 self.attach(overlay.show, self.on_playback_paused),
                 self.attach(overlay.hide, self.on_playback_resumed,
                             self.on_playback_stopped)):
             while not xbmc.abortRequested and self.isPlaying(
             ) and not self.torrent.threadComplete:
                 self.torrent.checkThread()
                 self.watchedTime = xbmc.Player().getTime()
                 self.totalTime = xbmc.Player().getTotalTime()
                 if self.iterator == 100 and debug_counter < 100:
                     debug_counter += 1
                 else:
                     self.torrent.debug()
                     debug_counter = 0
                 status = self.torrent.torrentHandle.status()
                 overlay.text = "\n".join(self._get_status_lines(status))
                 # downloadedSize = torrent.torrentHandle.file_progress()[contentId]
                 self.iterator = int(status.progress * 100)
                 if pause and self.__settings__.getSetting(
                         "pause_onplay") == 'true':
                     pause = False
                     xbmc.Player().pause()
                 xbmc.sleep(1000)
                 if self.iterator == 100 and self.next_dl:
                     next_contentId_index = self.ids_video.index(
                         str(self.contentId)) + 1
                     if len(self.ids_video) > next_contentId_index:
                         self.next_contentId = int(
                             self.ids_video[next_contentId_index])
                     else:
                         self.next_contentId = False
                         debug('[loop] next_contentId: ' +
                               str(self.next_contentId))
                 if not self.seeding_run and self.iterator == 100 and self.seeding:
                     self.seeding_run = True
                     self.seed(self.contentId)
                     self.seeding_status = True
                     # xbmc.sleep(7000)
                 if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(
                         self.next_contentId,
                         int) and self.next_contentId != False:
                     showMessage(
                         self.localize('Torrent Downloading'),
                         self.localize('Starting download next episode!'))
                     self.torrent.stopSession()
                     # xbmc.sleep(1000)
                     path = self.torrent.getFilePath(self.next_contentId)
                     self.basename = self.display_name = os.path.basename(
                         path)
                     self.torrent.continueSession(self.next_contentId)
                     self.next_dling = True
Esempio n. 5
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[TorrentPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
            log('[TorrentPlayer] Seek='+str(self.seek))   
        self.torrent = Downloader.Torrent(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory).player
        try:
            if self.get("url2"):
                self.ids_video = urllib.unquote_plus(self.get("url2")).split(',')
            else:
                self.ids_video = self.get_ids()
        except:
            pass
        self.init()
        self.setup_torrent()
        if self.buffer():
            while True:
                if self.setup_play():
                    debug('************************************* GOING LOOP')
                    self.torrent.startSession()
                    self.torrent.continueSession(self.contentId)
                    self.loop()
                    WatchedHistoryDB().add(self.basename, foldername(self.torrent.getContentList()[self.contentId]['title']), self.watchedTime, self.totalTime, self.contentId, self.fullSize / 1024 / 1024)
                else:
                    break
                debug('************************************* GO NEXT?')
                if self.next_dl and self.next_dling and isinstance(self.next_contentId, int) and self.iterator == 100:
                    if not self.next_play:
                        xbmc.sleep(3000)
                        if not xbmcgui.Dialog().yesno(
                                self.localize('python-libtorrent'),
                                self.localize('Would you like to play next episode?'),
                                self.display_name):
                            break
                    self.contentId = self.next_contentId
                    continue
                debug('************************************* NO! break')
                break

        self.torrent.stopSession()
        self.torrent.threadComplete = True
        self.torrent.checkThread()
        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            if self.seeding_status:
                showMessage(self.localize('Information'),
                            self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
            else:
                if self.seeding: self.db_delete()
                showMessage(self.localize('Information'),
                            self.localize('Torrent downloading is stopped.'), forced=True)
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        print '!!!!!!!!!!!!!!!!!! BORN ' + self.__class__.__name__
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[TorrentPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        self.torrent = Downloader.Torrent(self.userStorageDirectory,
                                          self.torrentUrl,
                                          self.torrentFilesDirectory).player
        try:
            if self.get("url2"):
                self.ids_video = urllib.unquote_plus(
                    self.get("url2")).split(',')
            else:
                self.ids_video = self.get_ids()
        except:
            pass
        self.init()
        self.setup_torrent()
        if self.buffer():
            while True:
                if self.setup_play():
                    debug('************************************* GOING LOOP')
                    self.torrent.startSession()
                    self.torrent.continueSession(self.contentId)
                    self.loop()
                else:
                    break
                debug('************************************* GO NEXT?')
                if self.next_dl and self.next_dling and isinstance(
                        self.next_contentId, int) and self.iterator == 100:
                    self.contentId = self.next_contentId
                    continue
                debug('************************************* NO! break')
                break

        self.torrent.stopSession()
        self.torrent.threadComplete = True
        self.torrent.checkThread()
        if '1' != self.__settings__.getSetting(
                "keep_files"
        ) and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            if self.seeding_status:
                showMessage(
                    self.localize('Information'),
                    self.localize(
                        'Torrent is seeding. To stop it use Download Status.'),
                    forced=True)
            else:
                if self.seeding: self.db_delete()
                showMessage(self.localize('Information'),
                            self.localize('Torrent downloading is stopped.'),
                            forced=True)
Esempio n. 7
0
    def loop(self):
        debug_counter = 0
        pause = True
        with closing(
                OverlayText(w=OVERLAY_WIDTH,
                            h=OVERLAY_HEIGHT,
                            alignment=XBFONT_CENTER_X
                            | XBFONT_CENTER_Y)) as overlay:
            with nested(
                    self.attach(overlay.show, self.on_playback_paused),
                    self.attach(overlay.hide, self.on_playback_resumed,
                                self.on_playback_stopped)):
                while not xbmc.abortRequested and self.isPlaying():
                    #self.print_fulldebug()
                    status = self.engine.status()
                    if not self.next_dling:
                        file_status = self.engine.file_status(self.contentId)
                    else:
                        file_status = self.engine.file_status(
                            self.next_contentId)
                    self.watchedTime = xbmc.Player().getTime()
                    self.totalTime = xbmc.Player().getTotalTime()
                    if self.iterator == 100 and debug_counter < 100:
                        debug_counter += 1
                    else:
                        self.print_debug(status)
                        debug_counter = 0

                    overlay.text = "\n".join(
                        self._get_status_lines(status, file_status))

                    self.iterator = int(file_status.progress * 100)

                    if pause and self.__settings__.getSetting(
                            "pause_onplay") == 'true':
                        pause = False
                        xbmc.Player().pause()
                    xbmc.sleep(1000)

                    if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(
                            self.next_contentId,
                            int) and self.next_contentId != False:
                        self.engine.activate_file(self.next_contentId)
                        showMessage(
                            self.localize('Torrent Downloading'),
                            self.localize('Starting download next episode!'),
                            forced=True)
                        log('[loop]: next_contentId ' +
                            str(self.next_contentId) +
                            str(isinstance(self.next_contentId, int)))
                        file_status = self.engine.file_status(
                            self.next_contentId)
                        self.basename = self.display_name = os.path.basename(
                            file_status.name)

                        self.next_dling = True
Esempio n. 8
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[AnteoPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
        #self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory)
        self.init()
        self.setup_engine()
        with closing(self.engine):
            self.engine.start(self.contentId)
            self.setup_nextep()
            while True:
                if self.buffer():
                    log('[AnteoPlayer]: ************************************* GOING LOOP'
                        )
                    if self.setup_play():
                        self.setup_subs()
                        self.loop()
                        WatchedHistoryDB().add(self.basename, self.watchedTime,
                                               self.totalTime, self.contentId,
                                               self.fullSize)
                    else:
                        log('[AnteoPlayer]: ************************************* break'
                            )
                        break
                    log('[AnteoPlayer]: ************************************* GO NEXT?'
                        )
                    if self.next_dl and isinstance(
                            self.next_contentId, int) and self.iterator == 100:
                        self.contentId = self.next_contentId
                        continue
                    log('[AnteoPlayer]: ************************************* NO! break'
                        )
                break

            xbmc.Player().stop()

        if '1' != self.__settings__.getSetting(
                "keep_files"
        ) and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            #if self.seeding_status:
            #showMessage(self.localize('Information'),
            #            self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
            #else:
            #if self.seeding: self.db_delete()
            showMessage(self.localize('Information'),
                        self.localize('Torrent downloading is stopped.'),
                        forced=True)
Esempio n. 9
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[TorrentPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        self.torrent = Downloader.Torrent(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory).player
        try:
            if self.get("url2"):
                self.ids_video = urllib.unquote_plus(self.get("url2")).split(",")
            else:
                self.ids_video = self.get_ids()
        except:
            pass
        self.init()
        self.setup_torrent()
        if self.buffer():
            while True:
                if self.setup_play():
                    debug("************************************* GOING LOOP")
                    self.torrent.startSession()
                    self.torrent.continueSession(self.contentId)
                    self.loop()
                    WatchedHistoryDB().add(
                        self.basename, self.watchedTime, self.totalTime, self.contentId, self.fullSize / 1024 / 1024
                    )
                else:
                    break
                debug("************************************* GO NEXT?")
                if self.next_dl and self.next_dling and isinstance(self.next_contentId, int) and self.iterator == 100:
                    self.contentId = self.next_contentId
                    continue
                debug("************************************* NO! break")
                break

        self.torrent.stopSession()
        self.torrent.threadComplete = True
        self.torrent.checkThread()
        if "1" != self.__settings__.getSetting("keep_files") and "Saved Files" not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            if self.seeding_status:
                showMessage(
                    self.localize("Information"),
                    self.localize("Torrent is seeding. To stop it use Download Status."),
                    forced=True,
                )
            else:
                if self.seeding:
                    self.db_delete()
                showMessage(self.localize("Information"), self.localize("Torrent downloading is stopped."), forced=True)
Esempio n. 10
0
    def loop(self):
        #debug_counter=0
        with closing(
                OverlayText(w=OVERLAY_WIDTH,
                            h=OVERLAY_HEIGHT,
                            alignment=XBFONT_CENTER_X
                            | XBFONT_CENTER_Y)) as overlay:
            with nested(
                    self.attach(overlay.show, self.on_playback_paused),
                    self.attach(overlay.hide, self.on_playback_resumed,
                                self.on_playback_stopped)):
                while True:
                    if xbmc.abortRequested or not self.isPlaying():
                        break

                    #if self.iterator == 100 and debug_counter < 100:
                    #    debug_counter += 1
                    #else:
                    #    self.torrent.debug()
                    #    debug_counter=0
                    status = self.c.status
                    overlay.text = "\n".join(self._get_status_lines(status))
                    self.iterator = int(status.progress * 100)
                    xbmc.sleep(1000)
                    if self.iterator == 100 and self.next_dl:
                        next_contentId_index = self.ids_video.index(
                            str(self.contentId)) + 1
                        if len(self.ids_video) > next_contentId_index:
                            self.next_contentId = int(
                                self.ids_video[next_contentId_index])
                        else:
                            self.next_contentId = False
                            log('[loop] next_contentId: ' +
                                str(self.next_contentId))
                    if not self.seeding_run and self.iterator == 100 and self.seeding:
                        self.seeding_run = True
                        self.seed(self.contentId)
                        self.seeding_status = True
                        # xbmc.sleep(7000)
                    if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(
                            self.next_contentId,
                            int) and self.next_contentId != False:
                        showMessage(
                            self.localize('Torrent Downloading'),
                            self.localize('Starting download next episode!'),
                            forced=True)
                        self.torrent.stopSession()
                        # xbmc.sleep(1000)
                        path = self.torrent.getFilePath(self.next_contentId)
                        self.basename = self.display_name = os.path.basename(
                            path)
                        self.torrent.continueSession(self.next_contentId)
                        self.next_dling = True
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[AnteoPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
        #self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory)
        self.init()
        self.setup_engine()
        with closing(self.engine):
            self.engine.start(self.contentId)
            self.setup_nextep()
            while True:
                if self.buffer():
                    log('[AnteoPlayer]: ************************************* GOING LOOP')
                    if self.setup_play():
                        self.setup_subs()
                        self.loop()
                        WatchedHistoryDB().add(self.basename, self.watchedTime, self.totalTime, self.contentId, self.fullSize)
                    else:
                        log('[AnteoPlayer]: ************************************* break')
                        break
                    log('[AnteoPlayer]: ************************************* GO NEXT?')
                    if self.next_dl and self.next_contentId != False and isinstance(self.next_contentId, int) and self.iterator == 100:
                        if not self.next_play:
                            xbmc.sleep(3000)
                            if not xbmcgui.Dialog().yesno(
                                self.localize('Torrent2HTTP'),
                                self.localize('Would you like to play next episode?')):
                                break
                        self.contentId = self.next_contentId
                        continue

                    log('[AnteoPlayer]: ************************************* NO! break')
                break

        xbmc.Player().stop()

        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            #if self.seeding_status:
            #showMessage(self.localize('Information'),
            #            self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
            #else:
            #if self.seeding: self.db_delete()
            showMessage(self.localize('Information'),
                        self.localize('Torrent downloading is stopped.'), forced=True)
Esempio n. 12
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        print ("[TorrentPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        self.torrent = Downloader.Torrent(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory).player
        try:
            if self.get("url2"):
                self.ids_video = urllib.unquote_plus(self.get("url2")).split(",")
            else:
                self.ids_video = self.get_ids()
        except:
            pass
        self.init()
        self.setup_torrent()
        if self.buffer():
            while True:
                if self.setup_play():
                    # print '************************************* GOING LOOP'
                    self.torrent.continueSession(self.contentId)
                    self.loop()
                else:
                    break
                # print '************************************* GO NEXT?'
                if self.next_dl and self.next_dling and isinstance(self.next_contentId, int) and self.iterator == 100:
                    self.contentId = self.next_contentId
                    continue
                # print '************************************* NO! break'
                break

        self.torrent.stopSession()
        self.torrent.threadComplete = True
        self.torrent.checkThread()
        if "false" == self.__settings__.getSetting("keep_files"):
            clearStorage(self.userStorageDirectory)
        else:
            if self.seeding_status:
                showMessage(
                    Localization.localize("Information"),
                    Localization.localize("Torrent is seeding. To stop it use Download Status."),
                    forced=True,
                )
            else:
                if self.seeding:
                    self.db_delete()
                showMessage(
                    Localization.localize("Information"),
                    Localization.localize("Torrent downloading is stopped."),
                    forced=True,
                )
Esempio n. 13
0
 def makeRequest(self, url, data={}, headers={}):
     self.load_cookie()
     opener = None
     if self.proxy == 1:
         try:
             from resources.proxy import antizapret
             opener = urllib2.build_opener(
                 antizapret.AntizapretProxyHandler(),
                 urllib2.HTTPCookieProcessor(self.cookieJar))
             config = antizapret.config()
             self.debug('[antizapret]: ' + str(config["domains"]))
             self.debug('[antizapret]: ' + str(config["server"]))
         except:
             showMessage('AntiZapret', Localization.localize('Error'))
             self.debug('[antizapret]: OFF!')
     #elif self.proxy == 2:
     #    from resources.proxy import immunicity
     #    opener = urllib2.build_opener(immunicity.ImmunicityProxyHandler(), urllib2.HTTPCookieProcessor(self.cookieJar))
     #    config = immunicity.config()
     #    self.debug('[immunicity]: '+str(config["domains"]))
     #    self.debug('[immunicity]: '+str(config["server"]))
     if not opener:
         opener = urllib2.build_opener(
             urllib2.HTTPCookieProcessor(self.cookieJar))
     opener.addheaders = headers
     if 0 < len(data):
         encodedData = urllib.urlencode(data)
     else:
         encodedData = None
     try:
         response = opener.open(url, encodedData)
     except urllib2.HTTPError as e:
         if e.code == 404:
             self.log('[makeRequest]: Not Found! HTTP Error, e.code=' +
                      str(e.code))
             return
         elif e.code in [503]:
             self.log('[makeRequest]: Denied, HTTP Error, e.code=' +
                      str(e.code))
             return
         else:
             self.log('[makeRequest]: HTTP Error, e.code=' + str(e.code))
             return
     #self.cookieJar.extract_cookies(response, urllib2)
     if response.info().get('Content-Encoding') == 'gzip':
         buf = StringIO(response.read())
         f = gzip.GzipFile(fileobj=buf)
         response = f.read()
     else:
         response = response.read()
     return response
Esempio n. 14
0
    def setup_engine(self):
        #uri=None, binaries_path=None, platform=None, download_path=".",
        #bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None,
        #enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False,
        #log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False,
        #keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False,
        #listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file=None,
        #user_agent=None, startup_timeout=5, state_file=None, enable_utp=True, enable_tcp=True,
        #debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50,
        #peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3,
        #dht_routers=None, trackers=None)

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

        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.userStorageDirectory:
            keep_complete = False
            keep_incomplete = False
            keep_files = False
            resume_file = None
        else:
            keep_complete = True
            keep_incomplete = True
            keep_files = True
            resume_file=os.path.join(self.userStorageDirectory, 'torrents', os.path.basename(self.torrentUrl)+'.resume_data')

        dht_routers = ["router.bittorrent.com:6881","router.utorrent.com:6881"]
        user_agent = 'uTorrent/2200(24683)'
        self.pre_buffer_bytes = int(self.__settings__.getSetting("pre_buffer_bytes"))*1024*1024
        if self.__settings__.getSetting('debug') == 'true':
            showMessage('[%sPlayer v%s] ' % (author, __version__), self.localize('Please Wait'))

        self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory,
                             connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_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,
                             keep_files=keep_files, user_agent=user_agent, resume_file=resume_file)
Esempio n. 15
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        print '!!!!!!!!!!!!!!!!!! BORN '+self.__class__.__name__
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[TorrentPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        self.torrent = Downloader.Torrent(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory).player
        try:
            if self.get("url2"):
                self.ids_video = urllib.unquote_plus(self.get("url2")).split(',')
            else:
                self.ids_video = self.get_ids()
        except:
            pass
        self.init()
        self.setup_torrent()
        if self.buffer():
            while True:
                if self.setup_play():
                    debug('************************************* GOING LOOP')
                    self.torrent.startSession()
                    self.torrent.continueSession(self.contentId)
                    self.loop()
                else:
                    break
                debug('************************************* GO NEXT?')
                if self.next_dl and self.next_dling and isinstance(self.next_contentId, int) and self.iterator == 100:
                    self.contentId = self.next_contentId
                    continue
                debug('************************************* NO! break')
                break

        self.torrent.stopSession()
        self.torrent.threadComplete = True
        self.torrent.checkThread()
        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            if self.seeding_status:
                showMessage(self.localize('Information'),
                            self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
            else:
                if self.seeding: self.db_delete()
                showMessage(self.localize('Information'),
                            self.localize('Torrent downloading is stopped.'), forced=True)
Esempio n. 16
0
 def loop(self):
     debug_counter=0
     pause = True
     self.torrent.torrentHandle.force_dht_announce()
     with closing(
             OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay:
         with nested(self.attach(overlay.show, self.on_playback_paused),
                     self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)):
             while not xbmc.abortRequested and self.isPlaying() and not self.torrent.threadComplete:
                 self.torrent.checkThread()
                 self.watchedTime = xbmc.Player().getTime()
                 self.totalTime = xbmc.Player().getTotalTime()
                 if self.iterator == 100 and debug_counter < 100:
                     debug_counter += 1
                 else:
                     self.torrent.debug()
                     debug_counter=0
                 status = self.torrent.torrentHandle.status()
                 overlay.text = "\n".join(self._get_status_lines(status))
                 # downloadedSize = torrent.torrentHandle.file_progress()[contentId]
                 self.iterator = int(status.progress * 100)
                 if pause and self.__settings__.getSetting("pause_onplay") == 'true':
                     pause = False
                     xbmc.Player().pause()
                 xbmc.sleep(1000)
                 if self.iterator == 100 and self.next_dl:
                     next_contentId_index = self.ids_video.index(str(self.contentId)) + 1
                     if len(self.ids_video) > next_contentId_index:
                         self.next_contentId = int(self.ids_video[next_contentId_index])
                     else:
                         self.next_contentId = False
                         debug('[loop] next_contentId: '+str(self.next_contentId))
                 if not self.seeding_run and self.iterator == 100 and self.seeding:
                     self.seeding_run = True
                     self.seed(self.contentId)
                     self.seeding_status = True
                     # xbmc.sleep(7000)
                 if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(self.next_contentId,
                                                                                                 int) and self.next_contentId != False:
                     showMessage(self.localize('Torrent Downloading'),
                                 self.localize('Starting download next episode!'), forced=True)
                     self.torrent.stopSession()
                     # xbmc.sleep(1000)
                     path = self.torrent.getFilePath(self.next_contentId)
                     self.basename = self.display_name = os.path.basename(path)
                     self.torrent.continueSession(self.next_contentId)
                     self.next_dling = True
Esempio n. 17
0
    def makeRequest(self, url, data={}, headers={}):
        self.load_cookie()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar))
        if proxy == 1:
            try:
                from resources.proxy import antizapret
                opener.add_handler(antizapret.AntizapretProxyHandler())
                config = antizapret.config()
                self.debug('[antizapret]: '+str(config["domains"]))
                self.debug('[antizapret]: '+str(config["server"]))
            except:
                showMessage('AntiZapret', Localization.localize('Error'))
                self.debug('[antizapret]: OFF!')
        # python ssl Context support - PEP 0466
        if 'https:' in url:
            ssl_context = ssl.create_default_context()
            ssl_context.check_hostname = False
            ssl_context.verify_mode = ssl.CERT_NONE
            log('urllib2.HTTPSHandler(context=ssl_context)')
            opener.add_handler(urllib2.HTTPSHandler(context=ssl_context))

        opener.addheaders = headers
        if 0 < len(data):
            encodedData = urllib.urlencode(data)
        else:
            encodedData = None
        try:
            response = opener.open(url, encodedData)
        except urllib2.HTTPError as e:
            if e.code == 404:
                self.log('[makeRequest]: Not Found! HTTP Error, e.code=' + str(e.code))
                return
            elif e.code in [503]:
                self.log('[makeRequest]: Denied, HTTP Error, e.code=' + str(e.code))
                return
            else:
                self.log('[makeRequest]: HTTP Error, e.code=' + str(e.code))
                return
        #self.cookieJar.extract_cookies(response, urllib2)
        #self.log(response.info().get('Set-Cookie'))
        if response.info().get('Content-Encoding') == 'gzip':
            buf = StringIO(response.read())
            decomp = zlib.decompressobj(16 + zlib.MAX_WBITS)
            text = decomp.decompress(buf.getvalue())
        else:
            text = response.read()
        return text
Esempio n. 18
0
 def makeRequest(self, url, data={}, headers={}):
     self.load_cookie()
     opener = None
     if self.proxy == 1:
         try:
             from resources.proxy import antizapret
             opener = urllib2.build_opener(antizapret.AntizapretProxyHandler(), urllib2.HTTPCookieProcessor(self.cookieJar))
             config = antizapret.config()
             self.debug('[antizapret]: '+str(config["domains"]))
             self.debug('[antizapret]: '+str(config["server"]))
         except:
             showMessage('AntiZapret', Localization.localize('Error'))
             self.debug('[antizapret]: OFF!')
     #elif self.proxy == 2:
     #    from resources.proxy import immunicity
     #    opener = urllib2.build_opener(immunicity.ImmunicityProxyHandler(), urllib2.HTTPCookieProcessor(self.cookieJar))
     #    config = immunicity.config()
     #    self.debug('[immunicity]: '+str(config["domains"]))
     #    self.debug('[immunicity]: '+str(config["server"]))
     if not opener:
         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar))
     opener.addheaders = headers
     if 0 < len(data):
         encodedData = urllib.urlencode(data)
     else:
         encodedData = None
     try:
         response = opener.open(url, encodedData)
     except urllib2.HTTPError as e:
         if e.code == 404:
             self.log('[makeRequest]: Not Found! HTTP Error, e.code=' + str(e.code))
             return
         elif e.code in [503]:
             self.log('[makeRequest]: Denied, HTTP Error, e.code=' + str(e.code))
             return
         else:
             self.log('[makeRequest]: HTTP Error, e.code=' + str(e.code))
             return
     #self.cookieJar.extract_cookies(response, urllib2)
     if response.info().get('Content-Encoding') == 'gzip':
         buf = StringIO(response.read())
         f = gzip.GzipFile(fileobj=buf)
         response = f.read()
     else:
         response = response.read()
     return response
Esempio n. 19
0
    def loop(self):
        debug_counter = 0
        pause = True
        with closing(
                OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay:
            with nested(self.attach(overlay.show, self.on_playback_paused),
                        self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)):
                while not xbmc.abortRequested and self.isPlaying():
                    self.print_fulldebug()
                    status = self.engine.status()
                    if not self.next_dling:
                        file_status = self.engine.file_status(self.contentId)
                    else:
                        file_status = self.engine.file_status(self.next_contentId)
                    self.watchedTime = xbmc.Player().getTime()
                    self.totalTime = xbmc.Player().getTotalTime()
                    if self.iterator == 100 and debug_counter < 100:
                        debug_counter += 1
                    else:
                        self.print_debug(status)
                        debug_counter=0

                    overlay.text = "\n".join(self._get_status_lines(status, file_status))

                    self.iterator = int(file_status.progress * 100)

                    if pause and self.__settings__.getSetting("pause_onplay") == 'true':
                        pause = False
                        xbmc.Player().pause()
                    xbmc.sleep(1000)

                    if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(self.next_contentId,
                                                                                                    int) and self.next_contentId != False:
                        self.engine.activate_file(self.next_contentId)
                        showMessage(self.localize('Torrent Downloading'),
                                    self.localize('Starting download next episode!'), forced=True)
                        log('[loop]: next_contentId '+str(self.next_contentId)+str(isinstance(self.next_contentId, int)))
                        file_status = self.engine.file_status(self.next_contentId)
                        self.basename = self.display_name = os.path.basename(file_status.name)

                        self.next_dling = True
    def loop(self):
        #debug_counter=0
        with closing(
           OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay:
           with nested(self.attach(overlay.show, self.on_playback_paused),
                            self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)):
                while True:
                    if xbmc.abortRequested or not self.isPlaying():
                        break

                    #if self.iterator == 100 and debug_counter < 100:
                    #    debug_counter += 1
                    #else:
                    #    self.torrent.debug()
                    #    debug_counter=0
                    status = self.c.status
                    overlay.text = "\n".join(self._get_status_lines(status))
                    self.iterator = int(status.progress * 100)
                    xbmc.sleep(1000)
                    if self.iterator == 100 and self.next_dl:
                        next_contentId_index = self.ids_video.index(str(self.contentId)) + 1
                        if len(self.ids_video) > next_contentId_index:
                            self.next_contentId = int(self.ids_video[next_contentId_index])
                        else:
                            self.next_contentId = False
                            log('[loop] next_contentId: '+str(self.next_contentId))
                    if not self.seeding_run and self.iterator == 100 and self.seeding:
                        self.seeding_run = True
                        self.seed(self.contentId)
                        self.seeding_status = True
                        # xbmc.sleep(7000)
                    if self.iterator == 100 and self.next_dl and not self.next_dling and isinstance(self.next_contentId,
                                                                                                    int) and self.next_contentId != False:
                        showMessage(self.localize('Torrent Downloading'),
                                    self.localize('Starting download next episode!'), forced=True)
                        self.torrent.stopSession()
                        # xbmc.sleep(1000)
                        path = self.torrent.getFilePath(self.next_contentId)
                        self.basename = self.display_name = os.path.basename(path)
                        self.torrent.continueSession(self.next_contentId)
                        self.next_dling = True
Esempio n. 21
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("["+author+"Player] Initalized v"+__version__)
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
        self.init()
        self.setup_engine()
        showMessage('[%sPlayer v%s] ' % (author, __version__), self.localize('Please Wait'))
        try:
            self.engine.start()
            self.setup_nextep()
            self.engine.activate_file(self.contentId)
            if self.buffer():
                while True:
                    log('['+author+'Player]: ************************************* GOING LOOP')
                    if self.setup_play():
                        self.setup_subs()
                        self.loop()
                        WatchedHistoryDB().add(self.basename, foldername(self.getContentList()[self.contentId]['title']), self.watchedTime, self.totalTime, self.contentId, self.fullSize)
                    else:
                        log('['+author+'Player]: ************************************* break')
                        break
                    log('['+author+'Player]: ************************************* GO NEXT?')
                    if self.next_dl and self.next_contentId != False and isinstance(self.next_contentId, int) and self.iterator == 100:
                        if not self.next_play:
                            xbmc.sleep(3000)
                            if not xbmcgui.Dialog().yesno(
                                self.localize('[%sPlayer v%s] ' % (author, __version__)),
                                self.localize('Would you like to play next episode?')):
                                break
                        self.contentId = self.next_contentId
                        self.engine.activate_file(self.contentId)
                        showMessage('[%sPlayer v%s] ' % (author, __version__), self.localize('Please Wait'))
                        continue
                    log('['+author+'Player]: ************************************* NO! break')
                    break
        except:
            import traceback
            log(traceback.format_exc())
        finally:
            self.engine.close()

        xbmc.Player().stop()

        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            #if self.seeding_status:
            #showMessage(self.localize('Information'),
            #            self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
            #else:
            #if self.seeding: self.db_delete()
            showMessage(self.localize('Information'),
                        self.localize('Torrent downloading is stopped.'), forced=True)
Esempio n. 22
0
 def setup_subs(self, label, path):
     iterator = 0
     subs = self.torrent.getSubsIds(label)
     debug('[setup_subs] subs: ' + str(subs))
     if len(subs) > 0:
         self.torrent.startSession()
         showMessage(
             self.localize('Information'),
             self.localize('Downloading and copy subtitles. Please wait.'))
         for ind, title in subs:
             self.torrent.continueSession(ind)
         while iterator < 100:
             xbmc.sleep(1000)
             self.torrent.debug()
             status = self.torrent.torrentHandle.status()
             iterator = int(status.progress * 100)
         # xbmc.sleep(2000)
         for ind, title in subs:
             folder = title.split(os.sep)[0]
             temp = os.path.basename(title)
             addition = os.path.dirname(title).lstrip(folder +
                                                      os.sep).replace(
                                                          os.sep,
                                                          '.').replace(
                                                              ' ',
                                                              '_').strip()
             ext = temp.split('.')[-1]
             temp = temp[:len(temp) - len(ext) -
                         1] + '.' + addition + '.' + ext
             newFileName = os.path.join(
                 ensure_str(os.path.dirname(decode_str(path))),
                 ensure_str(temp))
             debug('[setup_subs]: {} {}'.format(newFileName, title))
             if not xbmcvfs.exists(newFileName):
                 fileName = os.path.join(
                     ensure_str(
                         os.path.dirname(os.path.dirname(
                             decode_str(path)))), ensure_str(title))
                 xbmcvfs.copy(fileName, newFileName)
Esempio n. 23
0
    def setup_engine(self):
        #uri=None, binaries_path=None, platform=None, download_path=".",
        #bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None,
        #enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False,
        #log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False,
        #keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False,
        #listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file=None,
        #user_agent=None, startup_timeout=5, state_file=None, enable_utp=True, enable_tcp=True,
        #debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50,
        #peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3,
        #dht_routers=None, trackers=None)

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

        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.userStorageDirectory:
            keep_complete = False
            keep_incomplete = False
            keep_files = False
            resume_file = None
        else:
            keep_complete = True
            keep_incomplete = True
            keep_files = True
            resume_file = os.path.join(
                self.userStorageDirectory, 'torrents',
                os.path.basename(self.torrentUrl) + '.resume_data')

        dht_routers = [
            "router.bittorrent.com:6881", "router.utorrent.com:6881"
        ]
        user_agent = ''
        self.pre_buffer_bytes = int(
            self.__settings__.getSetting("pre_buffer_bytes")) * 1024 * 1024
        if self.__settings__.getSetting('debug') == 'true':
            showMessage('[%sPlayer v%s] ' % (author, __version__),
                        self.localize('Please Wait'))

        self.engine = Engine(uri=file_url(self.torrentUrl),
                             download_path=self.userStorageDirectory,
                             connections_limit=connections_limit,
                             download_kbps=download_limit,
                             upload_kbps=upload_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,
                             keep_files=keep_files,
                             user_agent=user_agent,
                             resume_file=resume_file)
Esempio n. 24
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        if not is_writable(self.userStorageDirectory):
            xbmcgui.Dialog().ok(
                Localization.localize('Torrenter v2'),
                Localization.localize(
                    'Your storage path is not writable or not local! Please change it in settings!'
                ), self.storageDirectory)

            sys.exit(1)
        xbmc.Player.__init__(self)
        log("[" + author + "Player] Initalized v" + __version__)
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
        self.init()
        self.setup_engine()
        self.on_playback_resumed.append(self.engine.resume)
        self.on_playback_paused.append(self.engine.pause)
        showMessage('[%sPlayer v%s] ' % (author, __version__),
                    self.localize('Please Wait'))
        try:
            self.engine.start()
            self.setup_nextep()
            self.engine.activate_file(self.contentId)
            if self.buffer():
                while True:
                    log('[' + author +
                        'Player]: ************************************* GOING LOOP'
                        )
                    if self.setup_play():
                        WatchedHistoryDB().add(
                            self.basename, self.torrentUrl,
                            foldername(self.getContentList()[self.contentId]
                                       ['title']), self.watchedTime,
                            self.totalTime, self.contentId, self.fullSize)
                        self.setup_subs()
                        self.loop()
                        WatchedHistoryDB().add(
                            self.basename, self.torrentUrl,
                            foldername(self.getContentList()[self.contentId]
                                       ['title']), self.watchedTime,
                            self.totalTime, self.contentId, self.fullSize)
                    else:
                        log('[' + author +
                            'Player]: ************************************* break'
                            )
                        break
                    log('[' + author +
                        'Player]: ************************************* GO NEXT?'
                        )
                    if self.next_dl and self.next_contentId != False and isinstance(
                            self.next_contentId, int) and self.iterator == 100:
                        if not self.next_play:
                            xbmc.sleep(3000)
                            if not xbmcgui.Dialog().yesno(
                                    self.localize('[%sPlayer v%s] ' %
                                                  (author, __version__)),
                                    self.localize(
                                        'Would you like to play next episode?')
                            ):
                                break
                        self.contentId = self.next_contentId
                        self.engine.activate_file(self.contentId)
                        showMessage('[%sPlayer v%s] ' % (author, __version__),
                                    self.localize('Please Wait'))
                        continue
                    log('[' + author +
                        'Player]: ************************************* NO! break'
                        )
                    break
        except:
            import traceback
            log(traceback.format_exc())
        finally:
            self.engine.close()

        xbmc.Player().stop()

        if '1' != self.__settings__.getSetting(
                "keep_files"
        ) and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            #if self.seeding_status:
            #showMessage(self.localize('Information'),
            #            self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True)
            #else:
            #if self.seeding: self.db_delete()
            showMessage(self.localize('Information'),
                        self.localize('Torrent downloading is stopped.'))

        loadsw_onstop()  # Reload Search Window
Esempio n. 25
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        xbmc.Player.__init__(self)
        log("[TorrentPlayer] Initalized")
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
            log('[TorrentPlayer] Seek=' + str(self.seek))
        self.torrent = Downloader.Torrent(self.userStorageDirectory,
                                          self.torrentUrl,
                                          self.torrentFilesDirectory).player
        try:
            if self.get("url2"):
                self.ids_video = urllib.unquote_plus(
                    self.get("url2")).split(',')
            else:
                self.ids_video = self.get_ids()
        except:
            pass
        self.init()
        self.setup_torrent()
        if self.buffer():
            while True:
                if self.setup_play():
                    debug('************************************* GOING LOOP')
                    self.torrent.startSession()
                    self.torrent.continueSession(self.contentId)
                    WatchedHistoryDB().add(
                        self.basename, self.torrentUrl,
                        foldername(self.torrent.getContentList()[
                            self.contentId]['title']), self.watchedTime,
                        self.totalTime, self.contentId,
                        self.fullSize / 1024 / 1024)
                    self.loop()
                    WatchedHistoryDB().add(
                        self.basename, self.torrentUrl,
                        foldername(self.torrent.getContentList()[
                            self.contentId]['title']), self.watchedTime,
                        self.totalTime, self.contentId,
                        self.fullSize / 1024 / 1024)
                else:
                    break
                debug('************************************* GO NEXT?')
                if self.next_dl and self.next_dling and isinstance(
                        self.next_contentId, int) and self.iterator == 100:
                    if not self.next_play:
                        xbmc.sleep(3000)
                        if not xbmcgui.Dialog().yesno(
                                self.localize('python-libtorrent'),
                                self.localize(
                                    'Would you like to play next episode?'),
                                self.display_name):
                            break
                    self.contentId = self.next_contentId
                    continue
                debug('************************************* NO! break')
                break

        self.torrent.stopSession()
        self.torrent.threadComplete = True
        self.torrent.checkThread()
        if '1' != self.__settings__.getSetting(
                "keep_files"
        ) and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)
        else:
            if self.seeding_status:
                showMessage(
                    self.localize('Information'),
                    self.localize(
                        'Torrent is seeding. To stop it use Download Status.'))
            else:
                if self.seeding: self.db_delete()
                showMessage(self.localize('Information'),
                            self.localize('Torrent downloading is stopped.'))

        loadsw_onstop()  # Reload Search Window
Esempio n. 26
0
    def stream(self, args, client_class):
        self.c = client_class(args.directory, args=args, lt=self.lt)
        try:
            while True:
                try:
                    s = socket.socket()
                    res = s.connect_ex(('127.0.0.1', self.free_port))
                    if res:
                        break
                finally:
                    s.close()
                self.free_port += 1

            self.server = StreamServer(('127.0.0.1', self.free_port),
                                       BTFileHandler,
                                       allow_range=True,
                                       status_fn=self.c.get_normalized_status)
            log('Started http server on port %d' % self.free_port)
            self.server.run()

            log('Starting btclient - libtorrent version %s' % self.lt.version)
            self.c.start_url(args.url)
            self.setup_torrent()

            if self.buffer():
                f = self.c._file
                self.server.set_file(f)
                self.setup_play()

                while True:
                    if self.setup_play():
                        log('************************************* GOING LOOP')
                        #self.torrent.continueSession(self.contentId)
                        self.loop()
                    else:
                        break
                    log('************************************* GO NEXT?')
                    if self.next_dl and self.next_dling and isinstance(
                            self.next_contentId, int) and self.iterator == 100:
                        self.contentId = self.next_contentId
                        continue
                    log('************************************* NO! break')
                    break

            if '1' != self.__settings__.getSetting(
                    "keep_files"
            ) and 'Saved Files' not in self.userStorageDirectory:
                xbmc.sleep(1000)
                clearStorage(self.userStorageDirectory)
            else:
                if self.seeding_status:
                    showMessage(
                        self.localize('Information'),
                        self.localize(
                            'Torrent is seeding. To stop it use Download Status.'
                        ),
                        forced=True)
                else:
                    if self.seeding: self.db_delete()
                    showMessage(
                        self.localize('Information'),
                        self.localize('Torrent downloading is stopped.'),
                        forced=True)

            log('Play ended')
            if self.server:
                self.server.stop()
        except Exception:
            traceback.print_exc()
        finally:
            self.on_exit()
Esempio n. 27
0
    def __init__(self, userStorageDirectory, torrentUrl, params={}):
        self.userStorageDirectory = userStorageDirectory
        self.torrentUrl = torrentUrl
        if not is_writable(self.userStorageDirectory):
            xbmcgui.Dialog().ok(Localization.localize('Torrenter v2'),
                    Localization.localize('Your storage path is not writable or not local! Please change it in settings!'),
                    self.storageDirectory)

            sys.exit(1)
        xbmc.Player.__init__(self)
        log("["+author+"Player] Initalized v"+__version__)
        self.params = params
        self.get = self.params.get
        self.contentId = int(self.get("url"))
        if self.get("seek"):
            self.seek = int(self.get("seek"))
        #self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory)
        self.init()
        self.setup_engine()
        with closing(self.engine):
            self.engine.start(self.contentId)
            self.setup_nextep()
            while True:
                if self.buffer():
                    log('[AnteoPlayer]: ************************************* GOING LOOP')
                    if self.setup_play():
                        WatchedHistoryDB().add(self.basename, self.torrentUrl,
                                               foldername(self.getContentList()[self.contentId]['title']),
                                               self.watchedTime, self.totalTime, self.contentId, self.fullSize)
                        self.setup_subs()
                        self.loop()
                        WatchedHistoryDB().add(self.basename, self.torrentUrl, foldername(self.getContentList()[self.contentId]['title']), self.watchedTime, self.totalTime, self.contentId, self.fullSize)
                    else:
                        log('[AnteoPlayer]: ************************************* break')
                        break
                    log('[AnteoPlayer]: ************************************* GO NEXT?')
                    if self.next_dl and self.next_contentId != False and isinstance(self.next_contentId, int) and self.iterator == 100:
                        if not self.next_play:
                            xbmc.sleep(3000)
                            if not xbmcgui.Dialog().yesno(
                                self.localize('[%sPlayer v%s] ' % (author, __version__)),
                                self.localize('Would you like to play next episode?')):
                                break
                        self.contentId = self.next_contentId
                        continue

                    log('[AnteoPlayer]: ************************************* NO! break')
                    showMessage(self.localize('Information'),
                                self.localize('Stopping the torrent2http process...'))
                break

        xbmc.Player().stop()

        if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory:
            xbmc.sleep(1000)
            clearStorage(self.userStorageDirectory)

        showMessage(self.localize('Information'),
                    self.localize('torrent2http process stopped.'))

        loadsw_onstop()  # Reload Search Window