示例#1
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)
 def magnetToTorrent(self, magnet):
     self.magnetLink = magnet
     self.initSession()
     torrentInfo = self.getMagnetInfo()
     if torrentInfo:
         try:
             torrentFile = self.lt.create_torrent(torrentInfo)
             baseName = os.path.basename(self.storageDirectory + os.sep +
                                         torrentInfo.files()[0].path)
             if not xbmcvfs.exists(self.torrentFilesPath):
                 xbmcvfs.mkdirs(self.torrentFilesPath)
             self.torrentFile = self.torrentFilesPath + self.md5(
                 baseName) + '.torrent'
             torentFileHandler = xbmcvfs.File(self.torrentFile, "w+b")
             torentFileHandler.write(self.lt.bencode(
                 torrentFile.generate()))
             torentFileHandler.close()
             e = self.lt.bdecode(
                 xbmcvfs.File(self.torrentFile, 'rb').read())
             self.torrentFileInfo = self.lt.torrent_info(e)
         except:
             xbmc.executebuiltin("Notification(%s, %s, 7500)" % (
                 Localization.localize('Error'),
                 Localization.localize(
                     'Can\'t download torrent, probably no seeds available.'
                 )))
             self.torrentFileInfo = torrentInfo
         finally:
             self.session.remove_torrent(self.torrentHandle)
             self.torrentHandle = None
示例#3
0
    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
示例#4
0
 def getMagnetInfo(self):
     magnetSettings = {
         'url': self.magnetLink,
         'save_path': self.storageDirectory,
         'storage_mode': self.lt.storage_mode_t(0),
         'paused': True,
         #'auto_managed': True,
         #'duplicate_is_error': True
     }
     progressBar = xbmcgui.DialogProgress()
     progressBar.create(Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting'))
     #try:
     self.torrentHandle = self.session.add_torrent(magnetSettings)
     #except:
     #    self.torrentHandle = self.lt.add_magnet_uri(self.session, self.magnetLink, magnetSettings)
     iterator = 0
     while iterator < 100:
         xbmc.sleep(500)
         progressBar.update(iterator, Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting')+'.' * (iterator % 4), ' ')
         iterator += 1
         if progressBar.iscanceled():
             progressBar.update(0)
             progressBar.close()
             return
         if self.torrentHandle.status().has_metadata:
             iterator = 100
     progressBar.update(0)
     progressBar.close()
     if self.torrentHandle.status().has_metadata:
         try:
             info = self.torrentHandle.torrent_file()
         except:
             info = self.torrentHandle.get_torrent_info()
         return info
示例#5
0
def pipeline(path, start, end):
    moni = Monitor.Monitor(path)
    moni.creat_json_file()
    anchor = start
    while anchor < end:
        # print(anchor, end)
        if anchor == 0:
            GeoOPt.geo_opt(path, moni)
        elif anchor == 1:
            if start == 1:
                HF1.hf1_start(path, moni)
            else:
                HF1.hf1(path, moni)
        elif anchor == 2:
            Localization.localization(path, moni)
        elif anchor == 3:
            HF2.hf2(path, moni)
        elif anchor == 4:
            LMP2.lmp2(path, moni)
            if if_skip_rpa() == 1:
                anchor += 1
        elif anchor == 5:
            RPA.rpa(path, moni)
        elif anchor == 6:
            Cluster.cluster(path)
        elif anchor == 7:
            Correction.correction(path, moni)
        elif anchor == 8:
            Results.results(path)
        anchor += 1
    end_programm(path)
    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
示例#7
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
 def getMagnetInfo(self):
     magnetSettings = {
         'save_path': self.storageDirectory,
         'storage_mode': self.lt.storage_mode_t(2),
         'paused': True,
         'auto_managed': True,
         'duplicate_is_error': True
     }
     progressBar = xbmcgui.DialogProgress()
     progressBar.create(Localization.localize('Please Wait'),
                        Localization.localize('Magnet-link is converting.'))
     self.torrentHandle = self.lt.add_magnet_uri(self.session,
                                                 self.magnetLink,
                                                 magnetSettings)
     iterator = 0
     while not self.torrentHandle.has_metadata():
         time.sleep(0.1)
         progressBar.update(iterator)
         iterator += 1
         if iterator == 100:
             iterator = 0
         if progressBar.iscanceled():
             progressBar.update(0)
             progressBar.close()
             return
     progressBar.update(0)
     progressBar.close()
     return self.torrentHandle.get_torrent_info()
 def openSection(self, params = {}):
     get = params.get
     url = urllib.unquote_plus(get("url"))
     try: external=urllib.unquote_plus(get("external"))
     except: external=None
     filesList = []
     if None == get('isApi'):
         progressBar = xbmcgui.DialogProgress()
         progressBar.create(Localization.localize('Please Wait'), Localization.localize('Materials are loading now.'))
         iterator = 0
     searchersList = []
     dirList = os.listdir(self.ROOT + os.sep + 'resources' + os.sep + 'searchers')
     if not external or external=='torrenterall':
         for searcherFile in dirList:
             if re.match('^(\w+)\.py$', searcherFile):
                 searchersList.append(searcherFile)
     else: searchersList.append(external+'.py')
     for searcherFile in searchersList:
         searcher = re.search('^(\w+)\.py$', searcherFile).group(1)
         if searcher:
             if None == get('isApi'):
                 progressBar.update(int(iterator), searcher)
                 iterator += 100 / len(searchersList)
             filesList += self.searchWithSearcher(url, searcher)
         if None == get('isApi') and progressBar.iscanceled():
             progressBar.update(0)
             progressBar.close()
             return
     if None == get('isApi'):
         progressBar.update(0)
         progressBar.close()
     filesList = sorted(filesList, key=lambda x: x[0], reverse=True)
     self.showFilesList(filesList, params)
    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(
                Localization.localize('Torrenter v2'),
                Localization.localize(
                    'Your storage path is not writable or not local! Please change it in settings!'
                ), Localization.localize(self.storageDirectory))

            sys.exit(1)

        try:
            from python_libtorrent import get_libtorrent
            libtorrent = get_libtorrent()
            log('Imported libtorrent v%s from python_libtorrent' %
                (libtorrent.version))
            module = True
        except Exception, e:
            module = False
            log('Error importing python_libtorrent Exception: %s' % (str(e)))
            import libtorrent
    def registerUser(self, params = {}):
        if self.__settings__.getSetting("auth"):
            xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Already logged in')))
            return

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=False)
        keyboardUser = xbmc.Keyboard("", Localization.localize("Input Email (for password recovery):"))
        keyboardUser.doModal()
        email = keyboardUser.getText()
        if not email:
            return

        keyboardPass = xbmc.Keyboard("", Localization.localize("Input Password (6+ symbols):"))
        keyboardPass.setHiddenInput(True)
        keyboardPass.doModal()
        password = keyboardPass.getText()
        keyboardPass.setHiddenInput(False)
        if not password:
            return
        try:
            cookieJar = cookielib.CookieJar()
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
            value = json.loads(opener.open(self.URL + "/register?email=%s&password=%s" % (email, password)).read().encode('utf-8'))
            if 'logged' == value:
                xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Login successfull')))
                for cookie in cookieJar:
                    if cookie.name == 'PHPSESSID':
                        self.__settings__.setSetting("auth", 'PHPSESSID=' + cookie.value)
            else:
                xbmc.executebuiltin("Notification(%s, %s [%s], 2500)" % (Localization.localize('Auth'), Localization.localize('Login failed'), value))
                self.loginUser()
        except urllib2.HTTPError, e:
            print self.__plugin__ + " registerUser() exception: " + str(e)
 def getMagnetInfo(self):
     magnetSettings = {
         'save_path': self.storageDirectory,
         'storage_mode': self.lt.storage_mode_t(2),
         'paused': True,
         'auto_managed': True,
         'duplicate_is_error': True
     }
     progressBar = xbmcgui.DialogProgress()
     progressBar.create(Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting.'))
     self.torrentHandle = self.lt.add_magnet_uri(self.session, self.magnetLink, magnetSettings)
     iterator = 0
     while not self.torrentHandle.has_metadata():
         time.sleep(0.1)
         progressBar.update(iterator)
         iterator += 1
         if iterator == 100:
             iterator = 0
         if progressBar.iscanceled():
             progressBar.update(0)
             progressBar.close()
             return
     progressBar.update(0)
     progressBar.close()
     return self.torrentHandle.get_torrent_info()
示例#13
0
 def _get_status_lines(self, s):
     return [
         self.display_name.decode('utf-8'),
         "%.2f%% %s" % (s.progress * 100, Localization.localize(STATE_STRS[s.state]).decode('utf-8')),
         "D:%.2f%s U:%.2f%s S:%d P:%d" % (s.download_rate / 1000, Localization.localize('kb/s').decode('utf-8'),
                                          s.upload_rate / 1000, Localization.localize('kb/s').decode('utf-8'),
                                          s.num_seeds, s.num_peers)
     ]
示例#14
0
 def buffer(self):
     iterator = 0
     progressBar = xbmcgui.DialogProgress()
     progressBar.create(
         Localization.localize("Please Wait") + str(" [%s]" % str(self.torrent.lt.version)),
         Localization.localize("Seeds searching."),
     )
     if self.subs_dl:
         subs = self.torrent.getSubsIds(os.path.basename(self.torrent.getFilePath(self.contentId)))
         if len(subs) > 0:
             for ind, title in subs:
                 self.torrent.continueSession(ind)
     num_pieces = int(self.torrent.torrentFileInfo.num_pieces())
     while iterator < 100:
         xbmc.sleep(1000)
         self.torrent.debug()
         downloadedSize = self.torrent.torrentHandle.file_progress()[self.contentId]
         status = self.torrent.torrentHandle.status()
         iterator = int(status.progress * 100)
         if status.state == 0 or (status.progress == 0 and status.num_pieces > 0):
             iterator = int(status.num_pieces * 100 / num_pieces)
             if iterator > 99:
                 iterator = 99
             progressBar.update(iterator, Localization.localize("Checking preloaded files..."), " ", " ")
         elif status.state == 3:
             dialogText = (
                 Localization.localize("Preloaded: ")
                 + str(downloadedSize / 1024 / 1024)
                 + " MB / "
                 + str(self.fullSize / 1024 / 1024)
                 + " MB"
             )
             peersText = " [%s: %s; %s: %s]" % (
                 Localization.localize("Seeds"),
                 str(self.torrent.getSeeds()),
                 Localization.localize("Peers"),
                 str(self.torrent.getPeers()),
             )
             speedsText = "%s: %s Mbit/s; %s: %s Mbit/s" % (
                 Localization.localize("Downloading"),
                 str(self.torrent.getDownloadRate() * 8 / 1000000),
                 Localization.localize("Uploading"),
                 str(self.torrent.getUploadRate() * 8 / 1000000),
             )
             progressBar.update(
                 iterator, Localization.localize("Seeds searching.") + peersText, dialogText, speedsText
             )
         else:
             progressBar.update(iterator, Localization.localize("UNKNOWN STATUS"), " ", " ")
         if progressBar.iscanceled():
             progressBar.update(0)
             progressBar.close()
             self.torrent.threadComplete = True
             self.torrent.checkThread()
             return
     progressBar.update(0)
     progressBar.close()
     return True
 def logoutUser(self, params = {}):
     if not self.__settings__.getSetting("auth"):
         xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('User not logged in')))
         return
     self.__settings__.setSetting("auth", '')
     cookieJar = cookielib.CookieJar()
     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
     opener.open(self.URL + "/logout").read()
     xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('User successfully logged out')))
     xbmc.executebuiltin("Container.Refresh()")
 def addBookmark(self, params = {}):
     get = params.get
     if 0 < len(self.__settings__.getSetting("auth")):
         response = json.loads(self.fetchData(self.URL + '/bookmarks/add?link=%s&name=%s&seeds=%s&image=%s' % (get("url"), get('name'), get('seeds'), get('image'))).encode('utf-8'))
         if not self.checkForAuth(response):
             return
         if 'added' == response:
             xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Item successfully added to Bookmarks')))
         else:
             xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Bookmark not added')))
示例#17
0
 def first_time(self):
     scrapers = {'tvdb': 'TheTVDB.com', 'tmdb': 'TheMovieDB.org', 'kinopoisk': 'KinoPoisk.ru'}
     ok = xbmcgui.Dialog().yesno(Localization.localize('Content Lists'),
                                 Localization.localize('Do you want to preload full metadata?') + ' (%s)' % (
                                     scrapers[os.path.basename(self.filename).split('.')[0]]),
                                 Localization.localize('It is highly recommended!'))
     if ok:
         return self.download()
     else:
         return False
示例#18
0
 def checkForAuth(self, response):
     if response == 'auth problems':
         xbmc.executebuiltin(
             "Notification(%s, %s, 2500)" %
             (Localization.localize('Auth'),
              Localization.localize('Auth expired, please relogin')))
         time.sleep(2.5)
         self.logoutUser()
         return False
     return True
示例#19
0
class Libtorrent:
    magnetLink = None
    startPart = 0
    endPart = 0
    partOffset = 0
    torrentHandle = None
    session = None
    downloadThread = None
    threadComplete = False
    lt = None
    save_resume_data = None

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

            sys.exit(1)

        try:
            from python_libtorrent import get_libtorrent
            libtorrent = get_libtorrent()
            log('Imported libtorrent v%s from python_libtorrent/%s' %
                (libtorrent.version, self.platform['system']))
            module = True
        except Exception, e:
            module = False
            log('Error importing python_libtorrent.%s. Exception: %s' %
                (self.platform['system'], str(e)))
            import libtorrent

        try:
            if not module:
                log('Imported libtorrent v' + libtorrent.version +
                    ' from system')
            self.lt = libtorrent
            del libtorrent

        except Exception, e:
            log('Error importing from system. Exception: ' + str(e))
            xbmcgui.Dialog().ok(
                Localization.localize('Python-Libtorrent Not Found'),
                Localization.localize(self.platform["message"][0]),
                Localization.localize(self.platform["message"][1]))
            return
 def removeBookmark(self, params = {}):
     get = params.get
     if 0 < len(self.__settings__.getSetting("auth")):
         response = json.loads(self.fetchData(self.URL + '/bookmarks/remove?id=%s' % (get("id"))).encode('utf-8'))
         if not self.checkForAuth(response):
             return
         if 'removed' == response:
             xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Item successfully removed from Bookmarks')))
             xbmc.executebuiltin("Container.Refresh()")
         else:
             xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Bookmark not removed')))
示例#21
0
 def __init__(self, *kargs):
     noFocus = sys.modules["__main__"].__root__ + '/icons/bookmarks.png'
     focus = sys.modules["__main__"].__root__ + '/icons/add_bookmark.png'
     self.addControl(
         xbmcgui.ControlLabel(
             0,
             self.height / 4,
             self.width,
             100,
             Localization.localize('Please, rate watched video:'),
             alignment=6))
     self.bad = xbmcgui.ControlButton(self.buttonWidth / 2,
                                      self.height / 2,
                                      self.buttonWidth,
                                      self.buttonHeight,
                                      Localization.localize('Bad'),
                                      alignment=6,
                                      textColor='0xFFCC3333',
                                      focusedColor='0xFFFF0000',
                                      focusTexture=focus,
                                      noFocusTexture=noFocus,
                                      shadowColor='0xFF000000')
     self.normal = xbmcgui.ControlButton(self.width / 2 -
                                         self.buttonWidth / 2,
                                         self.height / 2,
                                         self.buttonWidth,
                                         self.buttonHeight,
                                         Localization.localize('So-So'),
                                         alignment=6,
                                         textColor='0xFFCCCC33',
                                         focusedColor='0xFFFFFF00',
                                         focusTexture=focus,
                                         noFocusTexture=noFocus,
                                         shadowColor='0xFF000000')
     self.good = xbmcgui.ControlButton(self.width -
                                       self.buttonWidth * 3 / 2,
                                       self.height / 2,
                                       self.buttonWidth,
                                       self.buttonHeight,
                                       Localization.localize('Good'),
                                       alignment=6,
                                       textColor='0xFF33CC33',
                                       focusedColor='0xFF00FF00',
                                       focusTexture=focus,
                                       noFocusTexture=noFocus,
                                       shadowColor='0xFF000000')
     self.addControl(self.bad)
     self.addControl(self.normal)
     self.addControl(self.good)
     self.bad.setNavigation(self.bad, self.bad, self.bad, self.normal)
     self.normal.setNavigation(self.normal, self.normal, self.bad,
                               self.good)
     self.good.setNavigation(self.good, self.good, self.normal, self.good)
     self.setFocus(self.normal)
示例#22
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,
                )
示例#23
0
 def getRatings(self, params={}):
     filesList = []
     response = json.loads(
         self.fetchData(self.URL + '/rated').encode('utf-8'))
     for record in response:
         filesList.append(
             (0, 0, '%s [%s: %s/ %s: %s]' %
              (str(record['name'].encode('utf-8', 'replace')),
               Localization.localize('Views'), str(record['cnt']),
               Localization.localize('Rating'), str(record['rating'])),
              record['link'], ''))
     self.showFilesList(filesList)
示例#24
0
 def clearStorage(self, params={}):
     if xbmcvfs.exists(self.userStorageDirectory):
         import shutil
         temp = self.userStorageDirectory.rstrip('Torrenter').rstrip('/\\')
         shutil.move(os.path.join(self.userStorageDirectory, 'torrents'),
                     os.path.join(temp, 'torrents'))
         shutil.rmtree(self.userStorageDirectory, ignore_errors=True)
         shutil.move(os.path.join(temp, 'torrents'),
                     os.path.join(self.userStorageDirectory, 'torrents'))
     xbmc.executebuiltin("Notification(%s, %s, 2500)" %
                         (Localization.localize('Storage'),
                          Localization.localize('Storage was cleared')))
示例#25
0
 def getContentList(self):
     filelist = []
     try:
         for contentId, contentFile in enumerate(self.torrentFileInfo.files()):
             stringdata = {"title": contentFile.path, "size": contentFile.size, "ind": int(contentId),
                           'offset': contentFile.offset}
             filelist.append(stringdata)
         return filelist
     except:
         xbmcgui.Dialog().ok(Localization.localize('Python-Libtorrent Not Found'),
                             Localization.localize(self.platform["message"][0]),
                             Localization.localize(self.platform["message"][1]))
         return
示例#26
0
 def logoutUser(self, params={}):
     if not self.__settings__.getSetting("auth"):
         xbmc.executebuiltin("Notification(%s, %s, 2500)" %
                             (Localization.localize('Auth'),
                              Localization.localize('User not logged in')))
         return
     self.__settings__.setSetting("auth", '')
     cookieJar = cookielib.CookieJar()
     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
     opener.open(self.URL + "/logout").read()
     xbmc.executebuiltin(
         "Notification(%s, %s, 2500)" %
         (Localization.localize('Auth'),
          Localization.localize('User successfully logged out')))
     xbmc.executebuiltin("Container.Refresh()")
示例#27
0
 def make(self):
     self.clear_right_text()
     message = Localization.translate_text('Press any key')
     self.print_message(message)
     key_code = terminal.read()
     key = Config.convert_code_to_key(key_code)
     message = Config.set_comand(self.name, key)
     translated_message = Localization.translate_text(message)
     self.right_text = self.get_right_text()
     self.print_message(translated_message)
     if translated_message in [
             Localization.translate_text('This key is already busy'),
             Localization.translate_text('Can not set this key')
     ]:
         terminal.read()
示例#28
0
 def localization_command(message):
     """
         Send the PC location
     """
     bot.send_chat_action(message.chat.id, "find_location")
     try:
         lat, lng = Localization.get_location_by_wifi()
         bot.send_message(message.chat.id, "By WiFi:")
         bot.send_location(message.chat.id, lat, lng)
     except Localization.FailedLocalization:
         try:
             lat, lng = Localization.get_location_by_ip()
             bot.send_message(message.chat.id, "By IP:")
             bot.send_location(message.chat.id, lat, lng)
         except Localization.FailedLocalization:
             bot.reply_to(message, "Could not get the location.")
示例#29
0
 def search(self, keyword):
     filesList = []
     url = "http://playble.ru/data/1.php?q=%s&section=video" % (
         urllib.quote_plus(keyword))
     response = self.makeRequest(url)
     try:
         jdata = json.loads(response)
     except:
         return
     if None != response and 0 < len(jdata['results']):
         for data in jdata['results']:
             seeds = int(data['seeds'])
             title = data['title'].encode('utf-8', 'ignore')
             torrentTitle = "%s [%s: %s]" % (
                 title, Localization.localize('Seeds'), seeds)
             image = sys.modules["__main__"].__root__ + self.searchIcon
             link = data['magnet']
             filesList.append((
                 int(int(self.sourceWeight) * int(seeds)),
                 int(seeds),
                 self.unescape(self.stripHtml(torrentTitle)),
                 self.__class__.__name__ + '::' + link,
                 image,
             ))
     return filesList
示例#30
0
 def showFilesList(self, filesList, params={}): #myshows
     get = params.get
     try: external=urllib.unquote_plus(get("external"))
     except: external=None
     if external:
         try:
             s=json.loads(json.loads(urllib.unquote_plus(get("sdata"))))
             if len(filesList)<1:
                 xbmc.executebuiltin('XBMC.ActivateWindow(%s)' % 'Videos,plugin://plugin.video.myshows/?mode=20&showId=%s' % (self.jstr(s['showId'])))
                 return
             myshows_setting=xbmcaddon.Addon(id='plugin.video.myshows')
             myshows_lang=myshows_setting.getLocalizedString
             for (order, seeds, title, link, image) in filesList:
                 #print '{"filename":"%s", "stype":%s, "showId":%s, "seasonId":%s, "id":%s, "episodeId":%s}' % (link, self.jstr(s['stype']), self.jstr(s['showId']), self.jstr(s['seasonId']), self.jstr(s['id']), self.jstr(s['episodeId']))
                 contextMenu = [
                     (myshows_lang(30409),
                      'XBMC.RunPlugin(%s)' % ('plugin://plugin.video.myshows/?mode=3010&sort=activate&stringdata='+urllib.quote_plus('{"filename":"%s", "stype":%s, "showId":%s, "seasonId":%s, "id":%s, "episodeId":%s}' % (link, self.jstr(s['stype']), self.jstr(s['showId']), self.jstr(s['seasonId']), self.jstr(s['id']), self.jstr(s['episodeId']))))),
                     (myshows_lang(30400) ,
                      'XBMC.ActivateWindow(%s)' % 'Videos,plugin://plugin.video.myshows/?mode=20&showId=%s' % (self.jstr(s['showId'])))
                 ]
                 self.drawItem(title, 'openTorrent', link, image, contextMenu=contextMenu)
         except:
             xbmc.executebuiltin('XBMC.ActivateWindow(%s)' % 'Videos,plugin://plugin.video.myshows/?mode=20&showId=%s' % (self.jstr(s['showId'])))
             return
     else:
         for (order, seeds, title, link, image) in filesList:
             contextMenu = [
                 (Localization.localize('Add To Bookmarks'),
                  'XBMC.RunPlugin(%s)' % ('%s?action=%s&url=%s&name=%s&seeds=%s&image=%s') % (sys.argv[0], 'addBookmark', urllib.quote_plus(link), urllib.quote_plus(title), seeds, urllib.quote_plus(image)))
             ]
             self.drawItem(title, 'openTorrent', link, image, contextMenu=contextMenu)
     self.lockView('wide')
     xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
示例#31
0
 def search(self, keyword):
     filesList = []
     data = {
         'action': 'search',
         'word': keyword,
     }
     response = self.makeRequest('http://kino-zal.tv/search', data)
     if None != response and 0 < len(response) and re.search(
             "seed\.gif", response):
         for (link, title, title2, title3, seeds) in re.compile(
                 "<a href=\"(.+?)\".+?><b.+?>(.+?)</b>.+?<td class=\"centro td90 sizer\".+?>(.+?)</td>.+?<td nowrap class=\"centro sizer td95\">(.+?)</td>.+?<span class=\"seedor\".+?>(.+?)</span>",
                 re.DOTALL | re.MULTILINE).findall(response):
             title = ('%s %s %s' % (title, title2, title3)).replace(
                 '<br>', '')
             #if len(title)>100:
             #    title=title[:100]+'<br>'+title[100:]
             torrentTitle = "%s [%s: %s]" % (
                 title, Localization.localize('Seeds'), seeds)
             image = sys.modules["__main__"].__root__ + self.searchIcon
             filesList.append((
                 int(int(self.sourceWeight) * int(seeds)),
                 int(seeds),
                 self.unescape(self.stripHtml(torrentTitle)),
                 self.__class__.__name__ + '::' + link,
                 image,
             ))
     return filesList
示例#32
0
 def first_time(self):
     scrapers = {
         'tvdb': 'TheTVDB.com',
         'tmdb': 'TheMovieDB.org',
         'kinopoisk': 'KinoPoisk.ru'
     }
     ok = xbmcgui.Dialog().yesno(
         Localization.localize('Content Lists'),
         Localization.localize('Do you want to preload full metadata?') +
         ' (%s)' %
         (scrapers[os.path.basename(self.filename).split('.')[0]]),
         Localization.localize('It is highly recommended!'))
     if ok:
         return self.download()
     else:
         return False
 def sectionMenu(self):
     self.drawItem(Localization.localize('< Search >'), 'search', image=self.ROOT + '/icons/search.png')
     '''self.drawItem(Localization.localize('< Popular >'), 'getPopular', image=self.ROOT + '/icons/video.png')
     self.drawItem(Localization.localize('< Ratings >'), 'getRatings', image=self.ROOT + '/icons/video.png')        
     self.drawItem(Localization.localize('< Recent Materials >'), 'recentMaterilas', image=self.ROOT + '/icons/video.png')
     if self.__settings__.getSetting("auth"):
         self.drawItem(Localization.localize('< Bookmarks >'), 'getBookmarks', image=self.ROOT + '/icons/bookmarks.png')
         self.drawItem(Localization.localize('< History >'), 'getHistory', image=self.ROOT + '/icons/history.png')
         self.drawItem(Localization.localize('< Logout >'), 'logoutUser', image=self.ROOT + '/icons/logout.png')
     else:
         self.drawItem(Localization.localize('< Login >'), 'loginUser', image=self.ROOT + '/icons/login.png')
         self.drawItem(Localization.localize('< Register >'), 'registerUser', image=self.ROOT + '/icons/register.png')'''
     if 'true' == self.__settings__.getSetting("keep_files"):
         self.drawItem(Localization.localize('< Clear Storage >'), 'clearStorage', isFolder = True)
     self.lockView('list')
     xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
 def checkForAuth(self, response):
     if response == 'auth problems':
         xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Auth expired, please relogin')))
         time.sleep(2.5)
         self.logoutUser()
         return False
     return True
示例#35
0
def main():
    algo = input('Algorithm? 1 - Random direction, 2 - RSS gradient\n')
    max_it = input('Max iterations?\n')
    nb_samples = input('Nb of RSS samples for averaging?\n')
    mode = input('Mode? 1 - Thread, 2 - Procedural\n')
    write = input('Output file? 1/0 (y/n)\n')

    sim = input('Simulation? 1/0 (y/n)\n')
    roomba_sim = None
    if sim:
        roomba_sim = Roomba_sim.Roomba_sim()
        roomba_sim.daemon = True  # Thread is killed when main thread killed
        roomba_sim.start()  # Start thread

    explore = Exploration.Exploration(roomba_sim)
    explore.daemon = True  # Thread is killed when main thread killed
    explore.start(
    )  # Start thread (Needed for procedural too, it activate the control of the robot)
    rssi_obj = RSSI_Measure.RSSI_Measure()
    localize = Localization.Localization(explore, rssi_obj, algo, max_it,
                                         nb_samples, mode, write)
    localize.daemon = True  # Thread is killed when main thread killed
    localize.start()  # Start thread
    print 'Algorithm Start'

    localize.join()
    explore.stop()
    explore.join()
示例#36
0
    def __init__(self, click_count, board_size):
        self.click_count = click_count
        self.board_size = board_size
        self.user_name = ""
        self.board_name = f"{self.board_size}x{self.board_size}"
        self._scale_factor = Settings.get_scale_factor()

        self.scores = Scores(self.board_name)
        self.show_input = self.scores.is_score_rated(self.click_count)

        menu_button = Button(Localization.get_text('menu'))
        menu_button.click_method = lambda: MainMenuScreen()

        buttons = [menu_button]

        super().__init__(buttons, Localization.get_text('congratulations'))
示例#37
0
    def __init__(self, board_name):
        self.pipes = list()
        self.success = False
        self.board = None
        self._scale_factor = Settings.get_scale_factor()
        self.scale = int(100 * self._scale_factor)
        self.click_count = 0
        self.text = CenteredText('', 40 * self._scale_factor, (255, 153, 153))

        pipes_file_path = f"Boards/{board_name}.txt"

        pipes_importer = PipesImporter('GamePipe.GamePipe')
        self.pipes = pipes_importer.get_pipes_from_file(pipes_file_path)
        self.size = int(math.sqrt(len(self.pipes)))
        self.board = Board(self.size, self.size, self.pipes)

        for pipe in self.pipes:
            pipe.image = pygame.transform.scale(pipe.image,
                                                (self.scale, self.scale))

        back_button = Button(Localization.get_text('back'))
        back_button.click_method = lambda: GameTypePickerScreen(
            'choose_size', lambda x: GameScreen(x))
        buttons = [back_button]
        super().__init__(buttons, None)
示例#38
0
 def localize(self, string):
     if string:
         try:
             return Localization.localize(string)
         except:
             return string
     else:
         return 'Empty string'
 def clearStorage(self, params = {}):
     if xbmcvfs.exists(self.userStorageDirectory):
         import shutil
         temp=self.userStorageDirectory.rstrip('Torrenter').rstrip('/\\')
         shutil.move(os.path.join(self.userStorageDirectory, 'torrents'), os.path.join(temp, 'torrents'))
         shutil.rmtree(self.userStorageDirectory, ignore_errors=True)
         shutil.move(os.path.join(temp, 'torrents'), os.path.join(self.userStorageDirectory, 'torrents'))
     xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Storage'), Localization.localize('Storage was cleared')))
示例#40
0
 def localize(self, string):
     if string:
         try:
             return Localization.localize(string)
         except:
             return string
     else:
         return 'Empty string'
示例#41
0
 def get_hint(self, text):
     hint = Localization.translate_text(text)
     length = len(hint)
     count_of_left_spases = (screen_width - length) // 2
     left_spases = ' ' * count_of_left_spases
     count_of_rightn_spases = screen_width - length - count_of_left_spases
     right_spases = ' ' * count_of_rightn_spases
     centrifyed_hint = left_spases + hint + right_spases
     return centrifyed_hint
示例#42
0
    def __init__(self, board_name):
        self.board_name = board_name
        scores = Scores(board_name)
        self.scores = scores._get_scores_for_board()
        self._scale_factor = Settings.get_scale_factor()
        self._font_size = int(20 * self._scale_factor)
        self._user_name_x_shift = int(200 * self._scale_factor)
        self._score_x_shift = int(350 * self._scale_factor)

        clear_scores_button = Button(Localization.get_text('clear_scores'))
        clear_scores_button.click_method = lambda: (scores.clear_scores(), ScoresScreen(self.board_name))[1]

        back_button = Button(Localization.get_text('back'))
        back_button.click_method = lambda: GameTypePickerScreen('best_scores', lambda x: ScoresScreen(x))

        buttons = (clear_scores_button, back_button)

        super().__init__(buttons, f"{Localization.get_text('best_scores')} {self.board_name}")
示例#43
0
    def __init__(self):
        language_button = Button(
            f"{Localization.get_text('language')}: {Settings.get_language()}")
        language_button.click_method = lambda: (Settings.set_to_next_language(
        ), SettingsScreen())[1]

        sounds_button = Button(
            f"{Localization.get_text('sounds')}: {Localization.get_text(Settings.get_sound_enable())}"
        )
        sounds_button.click_method = lambda: (Settings.toggle_sound_enable(),
                                              SettingsScreen())[1]

        back_button = Button(Localization.get_text('back'))
        back_button.click_method = lambda: MainMenuScreen()

        buttons = (language_button, sounds_button, back_button)

        super().__init__(buttons, Localization.get_text('settings'))
示例#44
0
 def clearStorage(self, params = {}):
     try:
         xbmcaddon.Addon(id='plugin.video.myshows')
         fuckyou=True
     except: fuckyou=False
     if not fuckyou:
         if xbmcvfs.exists(self.userStorageDirectory):
             import shutil
             shutil.rmtree(self.userStorageDirectory, ignore_errors=True)
         xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Storage'), Localization.localize('Storage was cleared')))
示例#45
0
    def __init__(self):
        new_game_button = Button(Localization.get_text('new_game'))
        new_game_button.click_method = lambda: GameTypePickerScreen(
            'choose_size', lambda x: GameScreen(x))

        scores_button = Button(Localization.get_text('best_scores'))
        scores_button.click_method = lambda: GameTypePickerScreen(
            'best_scores', lambda x: ScoresScreen(x))

        settings_button = Button(Localization.get_text('settings'))
        settings_button.click_method = lambda: SettingsScreen()

        exit_button = Button(Localization.get_text('exit'))
        exit_button.click_method = lambda: None

        buttons = (new_game_button, scores_button, settings_button,
                   exit_button)

        super().__init__(buttons, "Plumber", 110)
    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(Localization.localize('Torrenter v2'),
                    Localization.localize('Your storage path is not writable or not local! Please change it in settings!'),
                    Localization.localize(self.storageDirectory))

            sys.exit(1)

        try:
            from python_libtorrent import get_libtorrent
            libtorrent=get_libtorrent()
            log('Imported libtorrent v%s from python_libtorrent' %(libtorrent.version))
            module=True
        except Exception, e:
            module=False
            log('Error importing python_libtorrent Exception: %s' %( str(e)))
            import libtorrent
示例#47
0
 def removeBookmark(self, params={}):
     get = params.get
     if 0 < len(self.__settings__.getSetting("auth")):
         response = json.loads(
             self.fetchData(self.URL + '/bookmarks/remove?id=%s' %
                            (get("id"))).encode('utf-8'))
         if not self.checkForAuth(response):
             return
         if 'removed' == response:
             xbmc.executebuiltin(
                 "Notification(%s, %s, 2500)" %
                 (Localization.localize('Bookmark'),
                  Localization.localize(
                      'Item successfully removed from Bookmarks')))
             xbmc.executebuiltin("Container.Refresh()")
         else:
             xbmc.executebuiltin(
                 "Notification(%s, %s, 2500)" %
                 (Localization.localize('Bookmark'),
                  Localization.localize('Bookmark not removed')))
示例#48
0
 def get_left_text(self):
     text = self.name
     translated_text = Localization.translate_text(text)
     # добавляем справа пробелы для подсветки, 5, врде, нормально
     count_of_left_spases = 5
     left_spases = ' ' * count_of_left_spases
     count_of_right_spases = screen_width // 2 - len(
         translated_text) - count_of_left_spases
     right_spases = ' ' * count_of_right_spases
     extended_text = left_spases + translated_text + right_spases
     return extended_text
 def magnetToTorrent(self, magnet):
     self.magnetLink = magnet
     self.initSession()
     torrentInfo = self.getMagnetInfo()
     try:
         torrentFile = self.lt.create_torrent(torrentInfo)
         baseName = os.path.basename(self.storageDirectory + os.sep +
                                     torrentInfo.files()[0].path).decode(
                                         'utf-8').encode('ascii', 'ignore')
         self.torrentFile = self.storageDirectory + os.sep + self.torrentFilesDirectory + os.sep + baseName + '.torrent'
         torentFileHandler = open(self.torrentFile, "wb")
         torentFileHandler.write(self.lt.bencode(torrentFile.generate()))
         torentFileHandler.close()
         self.torrentFileInfo = self.lt.torrent_info(self.torrentFile)
     except:
         xbmc.executebuiltin("Notification(%s, %s, 7500)" % (
             Localization.localize('Error'),
             Localization.localize(
                 'Your library out of date and can\'t save magnet-links.')))
         self.torrentFileInfo = torrentInfo
示例#50
0
 def __init__(self, name, buttons):
     # Заголовок меню
     translated_name = Localization.translate_text(name)
     normilized_name = '| ' + translated_name + ' |'
     self.name = normilized_name
     # Кнопки меню
     self.buttons = buttons
     # Начальная позиция
     self.state = 0
     # Количество кнопок
     self.length = len(buttons)
示例#51
0
 def sectionMenu(self):
     self.drawItem(Localization.localize('< Search >'),
                   'search',
                   image=self.ROOT + '/icons/search.png')
     '''self.drawItem(Localization.localize('< Popular >'), 'getPopular', image=self.ROOT + '/icons/video.png')
     self.drawItem(Localization.localize('< Ratings >'), 'getRatings', image=self.ROOT + '/icons/video.png')        
     self.drawItem(Localization.localize('< Recent Materials >'), 'recentMaterilas', image=self.ROOT + '/icons/video.png')
     if self.__settings__.getSetting("auth"):
         self.drawItem(Localization.localize('< Bookmarks >'), 'getBookmarks', image=self.ROOT + '/icons/bookmarks.png')
         self.drawItem(Localization.localize('< History >'), 'getHistory', image=self.ROOT + '/icons/history.png')
         self.drawItem(Localization.localize('< Logout >'), 'logoutUser', image=self.ROOT + '/icons/logout.png')
     else:
         self.drawItem(Localization.localize('< Login >'), 'loginUser', image=self.ROOT + '/icons/login.png')
         self.drawItem(Localization.localize('< Register >'), 'registerUser', image=self.ROOT + '/icons/register.png')'''
     if 'true' == self.__settings__.getSetting("keep_files"):
         self.drawItem(Localization.localize('< Clear Storage >'),
                       'clearStorage',
                       isFolder=True)
     self.lockView('list')
     xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
 def getBookmarks(self, params = {}):
     response = json.loads(self.fetchData(self.URL + '/bookmarks').encode('utf-8'))
     if not self.checkForAuth(response):
         return
     for record in response:
         contextMenu = [(
             Localization.localize('Remove From Bookmarks'),
             'XBMC.RunPlugin(%s)' % ('%s?action=%s&id=%s') % (sys.argv[0], 'removeBookmark', record['id'])
         )]
         self.drawItem(str(record['name'].encode('utf-8', 'replace')), 'openTorrent', record['link'], record['image'], contextMenu=contextMenu)
     self.lockView('wide')
     xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
 def askCaptcha(self, url):
     urllib.URLopener().retrieve(url, tempfile.gettempdir() + "/captcha.png")
     window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
     image = xbmcgui.ControlImage(460, 20, 360, 160, tempfile.gettempdir() + "/captcha.png")
     window.addControl(image)
     keyboardCaptcha = xbmc.Keyboard("", Localization.localize("Input symbols from CAPTCHA image:"))
     keyboardCaptcha.doModal()
     captchaText = keyboardCaptcha.getText()
     window.removeControl(image)
     if not captchaText:
         return False
     else:
         return captchaText
示例#54
0
 def __init__(self, *kargs):
     noFocus  = sys.modules[ "__main__"].__root__ + '/icons/bookmarks.png'
     focus  = sys.modules[ "__main__"].__root__ + '/icons/add_bookmark.png'
     self.addControl(xbmcgui.ControlLabel(0, self.height/4, self.width, 100, Localization.localize('Please, rate watched video:'), alignment=6))
     self.bad = xbmcgui.ControlButton(self.buttonWidth/2, self.height/2, self.buttonWidth, self.buttonHeight, Localization.localize('Bad'), alignment=6, textColor='0xFFCC3333', focusedColor='0xFFFF0000', focusTexture=focus, noFocusTexture=noFocus, shadowColor='0xFF000000')
     self.normal = xbmcgui.ControlButton(self.width/2-self.buttonWidth/2, self.height/2, self.buttonWidth, self.buttonHeight, Localization.localize('So-So'), alignment=6, textColor='0xFFCCCC33', focusedColor='0xFFFFFF00', focusTexture=focus, noFocusTexture=noFocus, shadowColor='0xFF000000')
     self.good = xbmcgui.ControlButton(self.width-self.buttonWidth*3/2, self.height/2, self.buttonWidth, self.buttonHeight, Localization.localize('Good'), alignment=6, textColor='0xFF33CC33', focusedColor='0xFF00FF00', focusTexture=focus, noFocusTexture=noFocus, shadowColor='0xFF000000')
     self.addControl(self.bad)
     self.addControl(self.normal)
     self.addControl(self.good)
     self.bad.setNavigation(self.bad, self.bad, self.bad, self.normal)
     self.normal.setNavigation(self.normal, self.normal, self.bad, self.good)
     self.good.setNavigation(self.good, self.good, self.normal, self.good)
     self.setFocus(self.normal)
 def magnetToTorrent(self, magnet):
     self.magnetLink = magnet
     self.initSession()
     torrentInfo = self.getMagnetInfo()
     try:
         torrentFile = self.lt.create_torrent(torrentInfo)
         baseName = os.path.basename(self.storageDirectory + os.sep + torrentInfo.files()[0].path).decode('utf-8').encode('ascii', 'ignore')
         self.torrentFile = self.storageDirectory + os.sep + self.torrentFilesDirectory + os.sep + baseName + '.torrent'
         torentFileHandler = open(self.torrentFile, "wb")
         torentFileHandler.write(self.lt.bencode(torrentFile.generate()))
         torentFileHandler.close()
         self.torrentFileInfo = self.lt.torrent_info(self.torrentFile)
     except:
         xbmc.executebuiltin("Notification(%s, %s, 7500)" % (Localization.localize('Error'), Localization.localize('Your library out of date and can\'t save magnet-links.')))
         self.torrentFileInfo = torrentInfo
示例#56
0
 def askCaptcha(self, url):
     temp_dir = self.tempdir()
     if isinstance(temp_dir, list): temp_dir = temp_dir[0]
     urllib.URLopener().retrieve(url, temp_dir + '/captcha.png')
     window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
     if isinstance(temp_dir, list): temp_dir = temp_dir[0]
     image = xbmcgui.ControlImage(460, 20, 360, 160, temp_dir + '/captcha.png')
     window.addControl(image)
     keyboardCaptcha = xbmc.Keyboard('', '[%s] %s' % (self.__plugin__, Localization.localize('Input symbols from CAPTCHA image:')))
     keyboardCaptcha.doModal()
     captchaText = keyboardCaptcha.getText()
     window.removeControl(image)
     if not captchaText:
         return False
     else:
         return captchaText
 def search(self, keyword):
     cookie=None
     try:do_login=int(time.time())-int(sys.modules[ "__main__" ].__settings__.getSetting("rutracker-auth-time"))
     except: do_login=10001
     if do_login>1000: cookie = self.login()
     if cookie: sys.modules[ "__main__" ].__settings__.setSetting("rutracker-auth", cookie)
     filesList = []
     if not sys.modules[ "__main__" ].__settings__.getSetting("rutracker-auth"):
         cookie = self.login()
         if cookie:
             sys.modules[ "__main__" ].__settings__.setSetting("rutracker-auth", cookie)
         else:
             print 'Auth attempt was failed'
             return filesList
     response = self.makeRequest(
         'http://rutracker.org/forum/tracker.php?nm=' + urllib.quote_plus(keyword),
         headers=[('Cookie', sys.modules[ "__main__" ].__settings__.getSetting("rutracker-auth"))]
     )
     if re.search('ses_short', response):
         cookie = self.login()
         if cookie:
             sys.modules[ "__main__" ].__settings__.setSetting("rutracker-auth", cookie)
         else:
             print 'Auth attempt was failed'
             return filesList
         response = self.makeRequest(
             'http://rutracker.org/forum/tracker.php?nm=' + urllib.quote_plus(keyword), 
             headers=[('Cookie', sys.modules[ "__main__" ].__settings__.getSetting("rutracker-auth"))]
         )
     if None != response and 0 < len(response):
         response = response.decode('cp1251').encode('utf8')
         #print response
         forums = [7, 187, 2090, 2221, 2091, 2092, 2093, 934, 505, 212, 2459, 1235, 185, 22, 941, 1666, 124, 1543, 376, 709, 1577, 511, 656, 93, 905, 1576, 101, 100, 103, 572, 1670, 2198, 2199, 313, 2201, 312, 2339, 314, 352, 549, 1213, 2109, 514, 2097, 4, 930, 2365, 1900, 521, 2258, 208, 539, 209, 484, 822, 921, 922, 1247, 923, 924, 1991, 925, 1165, 1245, 928, 926, 1246, 1250, 927, 1248, 33, 281, 1386, 1387, 1388, 282, 599, 1105, 1389, 404, 1390, 1642, 1391, 893, 1478, 670, 2107, 294, 1453, 1475, 46, 2178, 671, 2177, 251, 97, 851, 821, 2076, 98, 56, 1469, 2123, 1280, 876, 752, 1114, 2380, 1467, 672, 249, 552, 500, 2112, 1327, 1468, 24, 1959, 115, 939, 1481, 113, 882, 1482, 393, 1569, 373, 1186, 137, 1321, 532, 979, 827, 1484, 1485, 114, 1332, 1495, 255, 256, 1986, 1551, 626, 262, 1326, 978, 1287, 1188, 1667, 1675, 257, 845, 875, 263, 2073, 550, 2124, 1470, 528, 486, 854, 2079, 260, 2111, 1608, 1952, 1613, 1614, 1623, 1615, 1630, 2514, 1616, 2014, 1617, 1987, 2171, 1620, 1621, 1998, 751, 1697, 2004, 2001, 2002, 283, 1997, 2003, 2009, 2010, 2006, 2007, 2005, 259, 2008, 126, 9, 104, 1535, 91, 1356, 856, 188, 1408, 310, 202, 935, 990, 80, 119, 1530, 175, 79, 172, 812, 207, 805, 123, 189, 271, 273, 743, 184, 842, 194, 1605, 85, 1144, 595, 1288, 1171, 1694, 1690, 820, 819, 625, 84, 242, 623, 1417, 1798, 106, 166, 236, 507, 504, 536, 173, 918, 920, 203, 1243, 1120, 140, 636, 606, 776, 235, 1499, 81, 266, 252, 1102, 1449, 196, 372, 110, 193, 1531, 237, 265, 181, 1214, 497, 121, 721, 1117, 1359, 387, 134, 195, 2366, 2390, 2391, 2392, 2407, 2393, 2370, 2394, 2408, 2395, 2396, 2397, 2398, 2399, 2400, 2401, 2402, 2403, 2404, 2405, 2406, 911, 1691, 704, 1493, 1500, 1574, 1940, 1539, 1939, 823, 1006, 972, 1299, 781, 717, 1300, 1803, 1298, 825, 1606, 1458, 1463, 1459, 1938, 1461, 718, 1498, 907, 877, 992, 607, 594, 775, 534, 1462, 904, 1460, 816, 815, 325, 1457, 1301, 1692, 1540, 694, 1949, 1678, 1541, 860, 1941, 1537, 2100, 2102, 2103, 1242, 2104, 610, 1542, 2335, 1544, 1545, 1546, 1549, 1597, 1552, 1550, 1568, 1553, 1554, 617, 1555, 2017, 1257, 1258, 2208, 677, 1255, 1479, 1261, 614, 1259, 2065, 1254, 1260, 2209, 2210, 1547, 1548, 2211, 615, 1581, 1590, 1587, 1594, 1591, 1588, 1596, 1585, 1586, 2078, 1929, 1593, 1592, 1595, 1556, 1560, 1561, 1653, 1570, 1654, 1655, 1656, 1930, 1931, 1932, 1562, 1563, 1626, 1564, 1565, 1559, 1566, 1573, 1567]
         for (forum, link, title, seeds) in re.compile('<a class="gen f" href="tracker\.php\?f=(\d+)">.+? class=".+?" href="\./viewtopic\.php\?t=(\d+)">(.+?)</a>.+?<td class=".+?"><b>(\d+)', re.DOTALL).findall(response):
             if int(forum) in forums:
                 torrentTitle = "%s [%s: %s]" % (title, Localization.localize('Seeds'), seeds)
                 image = sys.modules[ "__main__"].__root__ + self.searchIcon
                 link = 'http://dl.rutracker.org/forum/dl.php?t=' + link
                 #print forum, int(seeds), self.unescape(self.stripHtml(torrentTitle)), link, image
                 filesList.append((
                     int(int(self.sourceWeight) * int(seeds)),
                     int(seeds),
                     self.unescape(self.stripHtml(torrentTitle)),
                     self.__class__.__name__ + '::' + link,
                     image,
                 ))
     return filesList
示例#58
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
示例#59
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