Exemple #1
0
    def reimport_torrents(self):
        """Import all torrent files in the collected torrent dir, all the files already in the database will be ignored.
        """
        self.status_update_func("Opening TorrentDBHandler...")
        # TODO(emilon): That's a freakishly ugly hack.
        torrent_db_handler = TorrentDBHandler(self.session)
        torrent_db_handler.category = Category.getInstance(self.session)

        # TODO(emilon): It would be nice to drop the corrupted torrent data from the store as a bonus.
        self.status_update_func("Registering recovered torrents...")
        try:
            for infoshash_str, torrent_data in self.torrent_store.itervalues():
                self.status_update_func("> %s" % infoshash_str)
                torrentdef = TorrentDef.load_from_memory(torrent_data)
                if torrentdef.is_finalized():
                    infohash = torrentdef.get_infohash()
                    if not torrent_db_handler.hasTorrent(infohash):
                        self.status_update_func(
                            u"Registering recovered torrent: %s" %
                            hexlify(infohash))
                        torrent_db_handler._addTorrentToDB(
                            torrentdef, extra_info={"filename": infoshash_str})
        finally:
            torrent_db_handler.close()
            Category.delInstance()
            self.db.commit_now()
            return self.torrent_store.flush()
Exemple #2
0
    def toggleFamilyFilter(self, newState = None, setCheck = False): 
        if newState == None:
            newState = not self.getFamilyFilter()

        Category.getInstance().set_family_filter(newState)
        for l in self.lists:
            if getattr(l, 'GotFilter', False):
                l.GotFilter(None)
                
        if setCheck:
            self.frame.SRstatusbar.ff_checkbox.SetValue(newState)
Exemple #3
0
 def set_family_filter(self, enable):
     """
     Set the state of the family filter.
     :param enable: Boolean with the new state.
     :return: Boolean indicating success.
     """
     try:
         Category.getInstance().set_family_filter(enable)
         return True
     except:
         return False
Exemple #4
0
 def set_family_filter(self, enable):
     """
     Set the state of the family filter.
     :param enable: Boolean with the new state.
     :return: Boolean indicating success.
     """
     try:
         Category.getInstance().set_family_filter(enable)
         return True
     except:
         return False
    def toggleFamilyFilter(self, newState = None, setCheck = False):
        if newState == None:
            newState = not self.getFamilyFilter()

        Category.getInstance().set_family_filter(newState)
        for l in self.lists:
            if getattr(l, 'GotFilter', False):
                l.GotFilter(None)

        if setCheck:
            self.frame.SRstatusbar.ff_checkbox.SetValue(newState)
    def __init__(self, guiUtility):
        if TorrentSearchGridManager.__single:
            raise RuntimeError, "TorrentSearchGridManager is singleton"
        TorrentSearchGridManager.__single = self

        self.guiUtility = guiUtility

        # Contains all matches for keywords in DB, not filtered by category
        self.hits = []
        # Remote results for current keywords
        self.remoteHits = {}
        self.dod = None
        # Jelle's word filter
        self.searchmgr = None
        self.torrent_db = None
        # For asking for a refresh when remote results came in
        self.gridmgr = None

        self.standardOverview = None
        self.searchkeywords = {'filesMode': [], 'libraryMode': []}
        self.oldsearchkeywords = {
            'filesMode': [],
            'libraryMode': []
        }  # previous query

        self.category = Category.getInstance()
Exemple #7
0
        def db_callback():
            familyfilter_sql = Category.getInstance().get_family_filter_sql(self.torrentdb._getCategoryID)
            if familyfilter_sql:
                familyfilter_sql = familyfilter_sql[4:]

            topTen = self.torrentdb._db.getAll("CollectedTorrent", ("infohash", "name", "(num_seeders+num_leechers) as popularity"), where = familyfilter_sql , order_by = "(num_seeders+num_leechers) DESC", limit= 10)
            self._RefreshList(topTen)
Exemple #8
0
 def toggleFamilyFilter(self, state = None):
      catobj = Category.getInstance()
      ff_enabled = not catobj.family_filter_enabled()
      #print 'Setting family filter to: %s' % ff_enabled
      if state is not None:
          ff_enabled = state
      catobj.set_family_filter(ff_enabled)
Exemple #9
0
def testFilter(catfilename, torrentpath):
    readCategorisationFile(catfilename)
    # print 'Install_dir is %s' % execpath
    c = Category.getInstance(execpath, None)
    total = p**n = fn = fp = 0
    for tfilename, isporn in tdict.items():
        torrent = getMetainfo(os.path.join(torrentpath, tfilename))
        name = torrent['info']['name']
        cat = c.calculateCategory(torrent, name)
        fporn = (cat == ['xxx'])
        total += 1
        p**n += int(isporn)
        if isporn == fporn:
            if DEBUG:
                print (isporn, fporn), 'good', name

        elif isporn and not fporn:
            fn += 1
            print 'FALSE NEGATIVE'
            showTorrent(os.path.join(torrentpath, tfilename))
        elif not isporn and fporn:
            fp += 1
            print 'FALSE POSITIVE'
            showTorrent(os.path.join(torrentpath, tfilename))

    print """
    Total torrents:   %(total)d
    XXX torrents:     %(p**n)d
    Correct filtered: %(good)d
    False negatives:  %(fn)d
    False positives:  %(fp)d
    """ % {'total': total, 'p**n': p**n, 'fn': fn,'fp':fp,'good':total-fn-fp}
    def __init__(self,guiUtility):
        if TorrentManager.__single:
            raise RuntimeError, "TorrentSearchGridManager is singleton"
        TorrentManager.__single = self
        self.guiUtility = guiUtility
        
        # Contains all matches for keywords in DB, not filtered by category
        self.hits = []
        
        # Remote results for current keywords
        self.remoteHits = {}
        
        #current progress of download states
        self.cache_progress = {}
        
        # For asking for a refresh when remote results came in
        self.gridmgr = None
        self.guiserver = GUITaskQueue.getInstance()
        
        # Gui callbacks
        self.gui_callback = []

        self.searchkeywords = {'filesMode':[], 'libraryMode':[]}
        self.rerankingStrategy = {'filesMode':DefaultTorrentReranker(), 'libraryMode':DefaultTorrentReranker()}
        self.oldsearchkeywords = {'filesMode':[], 'libraryMode':[]} # previous query
        
        self.filteredResults = 0
        self.category = Category.getInstance()
        
        # 09/10/09 boudewijn: CallLater does not accept zero as a
        # delay. the value needs to be a positive integer.
        self.user_download_choice = UserDownloadChoice.get_singleton()
Exemple #11
0
 def toggleFamilyFilter(self, state=None):
     catobj = Category.getInstance()
     ff_enabled = not catobj.family_filter_enabled()
     #print 'Setting family filter to: %s' % ff_enabled
     if state is not None:
         ff_enabled = state
     catobj.set_family_filter(ff_enabled)
    def __init__(self):
        self.session = FakeSession()
        self.crawler = Crawler.get_instance(self.session)

        self.my_db          = MyDBHandler.getInstance()
        self.peer_db        = PeerDBHandler.getInstance()
        self.torrent_db     = TorrentDBHandler.getInstance()
        self.torrent_db.register(Category.getInstance(),'.')
        self.mypref_db      = MyPreferenceDBHandler.getInstance()
        self.pref_db        = PreferenceDBHandler.getInstance()
        self.superpeer_db   = SuperPeerDBHandler.getInstance()
        self.friend_db      = FriendDBHandler.getInstance()
        self.bartercast_db  = BarterCastDBHandler.getInstance()
        self.bartercast_db.registerSession(self.session)
        self.secure_overlay = FakeSecureOverlay()
#        torrent_collecting_dir = os.path.abspath(config['torrent_collecting_dir'])
        self.listen_port = 1234

        self.channelcast_db = ChannelCastDBHandler.getInstance()
        self.channelcast_db.registerSession(self.session)

        self.votecast_db = VoteCastDBHandler.getInstance()
        self.votecast_db.registerSession(self.session)
        self.simi_db        = SimilarityDBHandler.getInstance()
        self.pops_db = PopularityDBHandler.getInstance()
Exemple #13
0
    def _connect(self):
        """
        Load database handles and Dispersy.
        :return: Nothing.
        """
        if not self._connected:
            self._connected = True
            self._remote_lock = threading.Lock()

            self._misc_db = self._session.open_dbhandler(NTFY_MISC)
            self._torrent_db = self._session.open_dbhandler(NTFY_TORRENTS)
            self._metadata_db = self._session.open_dbhandler(NTFY_METADATA)
            self._channelcast_db = self._session.open_dbhandler(NTFY_CHANNELCAST)
            self._votecast_db = self._session.open_dbhandler(NTFY_VOTECAST)

            self._category = Category.getInstance()
            self._category_names = {}
            self._xxx_category = -1
            for key, id in self._misc_db._category_name2id_dict.iteritems():
                self._category_names[id] = key

                if key.lower() == "xxx":
                    self._xxx_category = id

            self._dispersy = self._session.lm.dispersy
        else:
            raise RuntimeError('TorrentManager already connected')
Exemple #14
0
    def __init__(self):
        self.session = FakeSession()
        self.crawler = Crawler.get_instance(self.session)

        self.my_db = MyDBHandler.getInstance()
        self.peer_db = PeerDBHandler.getInstance()
        self.torrent_db = TorrentDBHandler.getInstance()
        self.torrent_db.register(Category.getInstance(), '.')
        self.mypref_db = MyPreferenceDBHandler.getInstance()
        self.pref_db = PreferenceDBHandler.getInstance()
        self.superpeer_db = SuperPeerDBHandler.getInstance()
        self.friend_db = FriendDBHandler.getInstance()
        self.bartercast_db = BarterCastDBHandler.getInstance()
        self.bartercast_db.registerSession(self.session)
        self.secure_overlay = FakeSecureOverlay()
        #        torrent_collecting_dir = os.path.abspath(config['torrent_collecting_dir'])
        self.listen_port = 1234

        self.channelcast_db = ChannelCastDBHandler.getInstance()
        self.channelcast_db.registerSession(self.session)

        self.votecast_db = VoteCastDBHandler.getInstance()
        self.votecast_db.registerSession(self.session)
        self.simi_db = SimilarityDBHandler.getInstance()
        self.pops_db = PopularityDBHandler.getInstance()
Exemple #15
0
 def get_family_filter(self):
     """
     Get the current state of the family filter.
     :return: Boolean indicating state.
     """
     catobj = Category.getInstance()
     return catobj.family_filter_enabled()
Exemple #16
0
 def __init__(self,guiUtility):
     if TorrentManager.__single:
         raise RuntimeError, "TorrentSearchGridManager is singleton"
     TorrentManager.__single = self
     self.guiUtility = guiUtility
     
     # Contains all matches for keywords in DB, not filtered by category
     self.hits = []
     
     # Remote results for current keywords
     self.remoteHits = {}
     
     # For asking for a refresh when remote results came in
     self.gridmgr = None
     self.guiserver = GUITaskQueue.getInstance()
     
     self.searchkeywords = []
     self.rerankingStrategy = DefaultTorrentReranker()
     self.oldsearchkeywords = []
     
     self.filteredResults = 0
     
     self.bundler = Bundler()
     self.bundle_mode = None
     self.category = Category.getInstance()
Exemple #17
0
    def _connect(self):
        """
        Load database handles and Dispersy.
        :return: Nothing.
        """
        if not self._connected:
            self._connected = True
            self._remote_lock = threading.Lock()

            self._misc_db = self._session.open_dbhandler(NTFY_MISC)
            self._torrent_db = self._session.open_dbhandler(NTFY_TORRENTS)
            self._metadata_db = self._session.open_dbhandler(NTFY_METADATA)
            self._channelcast_db = self._session.open_dbhandler(
                NTFY_CHANNELCAST)
            self._votecast_db = self._session.open_dbhandler(NTFY_VOTECAST)

            self._category = Category.getInstance()
            self._category_names = {}
            self._xxx_category = -1
            for key, id in self._misc_db._category_name2id_dict.iteritems():
                self._category_names[id] = key

                if key.lower() == "xxx":
                    self._xxx_category = id

            self._dispersy = self._session.lm.dispersy
        else:
            raise RuntimeError('TorrentManager already connected')
Exemple #18
0
    def __init__(self, parent):
        self.nbdb = NetworkBuzzDBHandler.getInstance()
        self.xxx_filter = Category.getInstance().xxx_filter

        HomePanel.__init__(self, parent, "Click below to explore what's hot", LIST_GREY)

        self.tags = []
        self.buzz_cache = [[],[],[]]
        self.last_shown_buzz = None

        row1_font = self.GetFont()
        row1_font.SetPointSize(row1_font.GetPointSize() + 10)
        row1_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row2_font = self.GetFont()
        row2_font.SetPointSize(row2_font.GetPointSize() + 4)
        row2_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row3_font = self.GetFont()
        row3_font.SetWeight(wx.FONTWEIGHT_BOLD)
        self.TERM_FONTS = [row1_font, row2_font, row3_font]

        self.header.Bind(wx.EVT_ENTER_WINDOW, lambda event: self.OnLeaveWindow())
        self.footer.Bind(wx.EVT_ENTER_WINDOW, lambda event: self.OnLeaveWindow())
        self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.panel.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        self.vSizer.Add(self.getStaticText('...collecting buzz information...'), 0, wx.ALIGN_CENTER)

        self.refresh = 5
        self.GetBuzzFromDB(doRefresh=True)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnRefreshTimer, self.timer)
        self.timer.Start(1000, False)
Exemple #19
0
 def get_family_filter(self):
     """
     Get the current state of the family filter.
     :return: Boolean indicating state.
     """
     catobj = Category.getInstance()
     return catobj.family_filter_enabled()
def testFilter(catfilename, torrentpath):    
    readCategorisationFile(catfilename)
    #print 'Install_dir is %s' % execpath
    c = Category.getInstance(execpath, None)
    total = p**n = fn = fp = 0
    for tfilename,isporn in tdict.items():
        torrent = getMetainfo(os.path.join(torrentpath,tfilename))
        name = torrent['info']['name']
        cat = c.calculateCategory(torrent, name)
        fporn = (cat == ['xxx'])
        total+= 1
        p**n += int(isporn)
        if isporn == fporn:
            if DEBUG:
                print (isporn, fporn), 'good', name
            
        elif isporn and not fporn:
            fn+=1
            print 'FALSE NEGATIVE'
            showTorrent(os.path.join(torrentpath,tfilename))
        elif not isporn and fporn:
            fp +=1
            print 'FALSE POSITIVE'
            showTorrent(os.path.join(torrentpath,tfilename))
            
    print """
    Total torrents:   %(total)d
    XXX torrents:     %(p**n)d
    Correct filtered: %(good)d
    False negatives:  %(fn)d
    False positives:  %(fp)d
    """ % {'total':total, 'p**n':p**n, 'fn':fn,'fp':fp,'good':total-fn-fp}
Exemple #21
0
 def refresh(self):
     nametuples = [('all', 'All')]
     nametuples += Category.getInstance().getCategoryNames()
     nametuples.append(('other', 'Other'))
     self.filterData = [['category', nametuples]]
     #self._PostInit()
     self.addComponents()
     self.Show()
     self.filterChanged(self.filterState)
def init():
    init_bak_tribler_sdb()

    db = SQLiteCacheDB.getInstance()
    db.initDB(TRIBLER_DB_PATH, busytimeout=BUSYTIMEOUT)

    print >>sys.stderr,"OPENING DB",TRIBLER_DB_PATH

    #db.execute_write('drop index Torrent_relevance_idx')
    TorrentDBHandler.getInstance().register(Category.getInstance('..'),'.')
Exemple #23
0
 def __init__(self):
     nametuples = [('all', 'All')]
     nametuples += Category.getInstance().getCategoryNames()
     nametuples.append(('other', 'Other'))
     #nametuples.append(('search', 'Search Results'))
     
     filterData = [['category', nametuples]]
                  
     standardFilter.__init__(self, filterData = filterData)
     self.mode = 'filesMode'
Exemple #24
0
def init():
    init_bak_tribler_sdb()

    db = SQLiteCacheDB.getInstance()
    db.initDB(TRIBLER_DB_PATH, busytimeout=BUSYTIMEOUT)

    print >> sys.stderr, "OPENING DB", TRIBLER_DB_PATH

    #db.execute_write('drop index Torrent_relevance_idx')
    TorrentDBHandler.getInstance().register(Category.getInstance('..'), '.')
Exemple #25
0
    def toggleFamilyFilter(self, newState=None, setCheck=False):
        if newState is None:
            newState = not self.getFamilyFilter()

        Category.getInstance().set_family_filter(newState)
        for l in self.lists:
            if getattr(l, 'GotFilter', False):
                l.GotFilter(None)

        if setCheck:
            self.frame.SRstatusbar.ff_checkbox.SetValue(newState)

        self.frame.home.aw_panel.refreshNow()

        if newState:
            self.utility.write_config('family_filter', 1)
        else:
            self.utility.write_config('family_filter', 0)
        self.utility.flush_config()
Exemple #26
0
    def toggleFamilyFilter(self, newState=None, setCheck=False):
        if newState is None:
            newState = not self.getFamilyFilter()

        Category.getInstance().set_family_filter(newState)
        for l in self.lists:
            if getattr(l, 'GotFilter', False):
                l.GotFilter(None)

        if setCheck:
            self.frame.SRstatusbar.ff_checkbox.SetValue(newState)

        self.frame.home.aw_panel.refreshNow()

        if newState:
            self.utility.write_config('family_filter', 1)
        else:
            self.utility.write_config('family_filter', 0)
        self.utility.flush_config()
    def setUp(self):
        super(TestTorrentDBHandler, self).setUp()

        from Tribler.Core.APIImplementation.LaunchManyCore import TriblerLaunchMany
        from Tribler.Core.Modules.tracker_manager import TrackerManager
        self.session.lm = TriblerLaunchMany()
        self.session.lm.tracker_manager = TrackerManager(self.session)
        self.session.lm.tracker_manager.initialize()
        self.tdb = TorrentDBHandler(self.session)
        self.tdb.torrent_dir = TESTS_DATA_DIR
        self.tdb.category = Category.getInstance(self.session)
        self.tdb.mypref_db = MyPreferenceDBHandler(self.session)
Exemple #28
0
    def setUp(self):
        super(TestTorrentDBHandler, self).setUp()

        from Tribler.Core.APIImplementation.LaunchManyCore import TriblerLaunchMany
        from Tribler.Core.Modules.tracker_manager import TrackerManager
        self.session.lm = TriblerLaunchMany()
        self.session.lm.tracker_manager = TrackerManager(self.session)
        self.session.lm.tracker_manager.initialize()
        self.tdb = TorrentDBHandler(self.session)
        self.tdb.torrent_dir = TESTS_DATA_DIR
        self.tdb.category = Category.getInstance(self.session)
        self.tdb.mypref_db = MyPreferenceDBHandler(self.session)
Exemple #29
0
        def db_callback():
            familyfilter_sql = Category.getInstance().get_family_filter_sql()
            if familyfilter_sql:
                familyfilter_sql = familyfilter_sql[4:]

            topTen = self.torrentdb._db.getAll(
                "CollectedTorrent",
                ("infohash", "name",
                 "(num_seeders+num_leechers) as popularity"),
                where=familyfilter_sql,
                order_by="(num_seeders+num_leechers) DESC",
                limit=10)
            self._RefreshList(topTen)
Exemple #30
0
    def reimport_torrents(self):
        """Import all torrent files in the collected torrent dir, all the files already in the database will be ignored.
        """
        self.status_update_func("Opening TorrentDBHandler...")
        # TODO(emilon): That's a freakishly ugly hack.
        torrent_db_handler = TorrentDBHandler(self.session)
        torrent_db_handler.category = Category.getInstance(self.session)

        # TODO(emilon): It would be nice to drop the corrupted torrent data from the store as a bonus.
        self.status_update_func("Registering recovered torrents...")
        try:
            for infoshash_str, torrent_data in self.torrent_store.itervalues():
                self.status_update_func("> %s" % infoshash_str)
                torrentdef = TorrentDef.load_from_memory(torrent_data)
                if torrentdef.is_finalized():
                    infohash = torrentdef.get_infohash()
                    if not torrent_db_handler.hasTorrent(infohash):
                        self.status_update_func(u"Registering recovered torrent: %s" % hexlify(infohash))
                        torrent_db_handler._addTorrentToDB(torrentdef, extra_info={"filename": infoshash_str})
        finally:
            torrent_db_handler.close()
            Category.delInstance()
            self.db.commit_now()
            return self.torrent_store.flush()
    def _connect(self):
        """
        Load database handles and Dispersy.
        :return: Nothing.
        """
        if not self._connected:
            self._connected = True
            self._remote_lock = threading.Lock()

            self._torrent_db = self._session.open_dbhandler(NTFY_TORRENTS)
            self._channelcast_db = self._session.open_dbhandler(NTFY_CHANNELCAST)
            self._votecast_db = self._session.open_dbhandler(NTFY_VOTECAST)

            self._category = Category.getInstance()

            self._dispersy = self._session.lm.dispersy
        else:
            raise RuntimeError("TorrentManager already connected")
Exemple #32
0
 def isRelevantItem(self, subject, objectID):
     db_handler = self.session.open_dbhandler(subject)
     if subject == NTFY_PEERS:
         peer = db_handler.getPeer(objectID)
         ok = peer and (peer['buddycast_times']>0 or peer['friend'])
         #if not ok:
         #    print >> sys.stderr, 'Gridmanager: Peer is not relevant: %s' % peer
         return ok
     elif subject in (NTFY_TORRENTS):
         id_name = 'infohash'
         torrent = db_handler.getTorrent(objectID)
         ok = torrent is not None and torrent['status'] == 'good' and Category.getInstance().hasActiveCategory(torrent)
         #if not ok:
         #    print >> sys.stderr, 'Gridmanager: Torrent is not relevant: %s' % torrent
         return ok
     elif subject == NTFY_MYPREFERENCES:
         return True
     
     raise Exception('not yet implemented')
Exemple #33
0
    def _connect(self):
        """
        Load database handles and Dispersy.
        :return: Nothing.
        """
        if not self._connected:
            self._connected = True
            self._remote_lock = threading.Lock()

            self._torrent_db = self._session.open_dbhandler(NTFY_TORRENTS)
            self._channelcast_db = self._session.open_dbhandler(
                NTFY_CHANNELCAST)
            self._votecast_db = self._session.open_dbhandler(NTFY_VOTECAST)

            self._category = Category.getInstance()

            self._dispersy = self._session.lm.dispersy
        else:
            raise RuntimeError('TorrentManager already connected')
Exemple #34
0
    def __init__(self, parent):
        #Niels 04-06-2012: termextraction needs a session variable, create instance from mainthread
        TermExtraction.getInstance()
        self.nbdb = None
        self.xxx_filter = Category.getInstance().xxx_filter

        HomePanel.__init__(self, parent, "Click below to explore what's hot",
                           LIST_GREY)

        self.tags = []
        self.buzz_cache = [[], [], []]
        self.last_shown_buzz = None

        row1_font = self.GetFont()
        row1_font.SetPointSize(row1_font.GetPointSize() + 10)
        row1_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row2_font = self.GetFont()
        row2_font.SetPointSize(row2_font.GetPointSize() + 4)
        row2_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row3_font = self.GetFont()
        row3_font.SetWeight(wx.FONTWEIGHT_BOLD)
        self.TERM_FONTS = [row1_font, row2_font, row3_font]

        self.header.Bind(wx.EVT_ENTER_WINDOW,
                         lambda event: self.OnLeaveWindow())
        self.footer.Bind(wx.EVT_ENTER_WINDOW,
                         lambda event: self.OnLeaveWindow())
        self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.panel.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        self.vSizer.Add(
            self.getStaticText('...collecting buzz information...'), 0,
            wx.ALIGN_CENTER)

        self.refresh = 5
        self.GetBuzzFromDB(doRefresh=True, samplesize=10)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnRefreshTimer, self.timer)
        self.timer.Start(1000, False)
Exemple #35
0
    def initStandardOverview(self, standardOverview):
        "Called by standardOverview when ready with init"
        self.standardOverview = standardOverview
        self.standardFilesOverview()
        wx.CallAfter(self.refreshOnResize)

        # Preselect mainButtonFiles
        filesButton = xrc.XRCCTRL(self.frame, 'mainButtonFiles')
        filesButton.setSelected(True)
        self.selectedMainButton = filesButton
        
        # Init family filter

        self.familyButtonOn = xrc.XRCCTRL(self.frame, 'familyFilterOn')
        self.familyButtonOff = xrc.XRCCTRL(self.frame, 'familyFilterOff')
        catobj = Category.getInstance()
        if catobj.family_filter_enabled():
            self.familyButtonOn.setToggled(True)
        else:    
            self.familyButtonOff.setToggled(True)
Exemple #36
0
    def isRelevantItem(self, subject, objectID):
        db_handler = self.session.open_dbhandler(subject)
        if subject == NTFY_PEERS:
            peer = db_handler.getPeer(objectID)
            ok = peer and (peer['buddycast_times'] > 0 or peer['friend'])
            #if not ok:
            #    print >> sys.stderr, 'Gridmanager: Peer is not relevant: %s' % peer
            return ok
        elif subject in (NTFY_TORRENTS):
            id_name = 'infohash'
            torrent = db_handler.getTorrent(objectID)
            ok = torrent is not None and torrent[
                'status'] == 'good' and Category.getInstance(
                ).hasActiveCategory(torrent)
            #if not ok:
            #    print >> sys.stderr, 'Gridmanager: Torrent is not relevant: %s' % torrent
            return ok
        elif subject == NTFY_MYPREFERENCES:
            return True

        raise Exception('not yet implemented')
def testFilter(catfilename, torrentpath):
    readCategorisationFile(catfilename)
    # print 'Install_dir is %s' % execpath
    c = Category.getInstance(execpath, None)
    total = p**n = fn = fp = 0
    for tfilename, isporn in tdict.items():
        torrent = getMetainfo(os.path.join(torrentpath, tfilename))
        name = torrent["info"]["name"]
        cat = c.calculateCategory(torrent, name)
        fporn = cat == ["xxx"]
        total += 1
        p**n += int(isporn)
        if isporn == fporn:
            if DEBUG:
                print (isporn, fporn), "good", name

        elif isporn and not fporn:
            fn += 1
            print "FALSE NEGATIVE"
            showTorrent(os.path.join(torrentpath, tfilename))
        elif not isporn and fporn:
            fp += 1
            print "FALSE POSITIVE"
            showTorrent(os.path.join(torrentpath, tfilename))

    print """
    Total torrents:   %(total)d
    XXX torrents:     %(p**n)d
    Correct filtered: %(good)d
    False negatives:  %(fn)d
    False positives:  %(fp)d
    """ % {
        "total": total,
        "p**n": p**n,
        "fn": fn,
        "fp": fp,
        "good": total - fn - fp,
    }
Exemple #38
0
    def OnPopupFileType(self, event):
        menu = wx.Menu()
        itemid = wx.NewId()
        menu.AppendRadioItem(itemid, "All")
        menu.Bind(wx.EVT_MENU, lambda x: self.CategoryFilter(''), id=itemid)
        menu.Check(itemid, not self.parent_list.categoryfilter)
        for _, filetype in Category.getInstance().getCategoryNames():
            if filetype != 'XXX':
                itemid = wx.NewId()
                menu.AppendRadioItem(itemid, filetype)
                menu.Bind(wx.EVT_MENU, lambda x, filetype=filetype: self.CategoryFilter(filetype), id=itemid)
                menu.Check(
                    itemid,
                    bool(
                        self.parent_list.categoryfilter) and (
                            filetype.lower(
                            ) in self.parent_list.categoryfilter))

        ctrl = self.filetype_icon
        pos = wx.Point(ctrl.GetPosition().x, self.GetPosition().y + self.filter_panel.GetSize().y)
        self.PopupMenu(menu, pos)
        menu.Destroy()
        self.Layout()
Exemple #39
0
 def __init__(self,guiUtility):
     if ChannelSearchGridManager.__single:
         raise RuntimeError, "ChannelSearchGridManager is singleton"
     ChannelSearchGridManager.__single = self
     self.guiUtility = guiUtility
     self.guiserver = GUITaskQueue.getInstance()
     
     # Contains all matches for keywords in DB, not filtered by category
     self.hits = {}
     
     self.searchmgr = None
     self.channelcast_db = None
     self.pref_db = None # Nic: for rerankers
     self.mypref_db = None
     self.search_db = None
     
     # For asking for a refresh when remote results came in
     self.gridmgr = None
     
     self.searchkeywords = []
     self.oldsearchkeywords = []
     
     self.category = Category.getInstance()
Exemple #40
0
    def _gotRemoteHits(self, permid, kws, answers):
        try:
            if DEBUG:
                print >>sys.stderr,"TorrentSearchGridManager: gotRemoteHist: got",len(answers),"unfiltered results for",kws, bin2str(permid), time()
            
            # Always store the results, only display when in filesMode
            # We got some replies. First check if they are for the current query
            if self.searchkeywords == kws:
                numResults = 0
                catobj = Category.getInstance()
                for key,value in answers.iteritems():
                    
                    if self.torrent_db.hasTorrent(key):
                        if DEBUG:
                            print >>sys.stderr,"TorrentSearchGridManager: gotRemoteHist: Ignoring hit for",`value['content_name']`,"already got it"
                        continue # do not show results we have ourselves
                    
                    # First, check if it matches the word boundaries, that belongs to previous version
                    
                    # Convert answer fields as per 
                    # Session.query_connected_peers() spec. to NEWDB format
                    newval = {}
                    newval['name'] = value['content_name']                    
                    newval['infohash'] = key
                    newval['torrent_file_name'] = ''
                    newval['length'] = value['length']
                    newval['creation_date'] = time()  # None  gives '?' in GUI
                    newval['relevance'] = 0
                    newval['source'] = 'RQ'
                    newval['category'] = value['category'][0] 
                    # We trust the peer
                    newval['status'] = 'good'
                    newval['num_seeders'] = value['seeder'] or 0
                    newval['num_leechers'] = value['leecher'] or 0

                    # OLPROTO_VER_NINETH includes a torrent_size. Set to
                    # -1 when not available.
                    if 'torrent_size' in value:
                        newval['torrent_size'] = value['torrent_size']
                    else:
                        newval['torrent_size'] = -1
                        
                    # OLPROTO_VER_ELEVENTH includes channel_permid, channel_name fields.
                    if 'channel_permid' not in value:
                        # just to check if it is not OLPROTO_VER_ELEVENTH version
                        # if so, check word boundaries in the swarm name
                        ls = split_into_keywords(value['content_name'])

                        if DEBUG:
                            print >>sys.stderr,"TorrentSearchGridManager: ls is",`ls`
                            print >>sys.stderr,"TorrentSearchGridManager: kws is",`kws`
                        
                        flag = False
                        for kw in kws:
                            if kw not in ls:
                                flag=True
                                break
                        if flag:
                            continue
                        
                    if 'channel_permid' in value:
                        newval['channel_permid']=value['channel_permid']
                    else:
                        newval['channel_permid']=""
                        
                    if 'channel_name' in value:
                        newval['channel_name'] = value['channel_name']
                    else:
                        newval['channel_name']=""
                        
                    if 'channel_permid' in value:
                        newval['neg_votes'] = self.votecastdb.getNegVotes(value['channel_permid'])
                        newval['subscriptions'] = self.votecastdb.getNumSubscriptions(value['channel_permid'])
                        if newval['subscriptions']-newval['neg_votes']<VOTE_LIMIT:
                            # now, this is SPAM
                            continue
                    else:
                        newval['subscriptions']=0
                        newval['neg_votes'] = 0
                            

                    # Extra field: Set from which peer this info originates
                    newval['query_permids'] = [permid]
                        
                    # Filter out results from unwanted categories
                    flag = False
                    for cat in value['category']:
                        rank = catobj.getCategoryRank(cat)
                        if rank == -1:
                            if DEBUG:
                                print >>sys.stderr,"TorrentSearchGridManager: gotRemoteHits: Got",`newval['name']`,"from banned category",cat,", discarded it."
                            flag = True
                            self.filteredResults += 1
                            break
                    if flag:
                        continue

                    if newval['infohash'] in self.remoteHits:
                        if DEBUG:
                            print >>sys.stderr,"TorrentSearchGridManager: gotRemoteHist: merging hit",`newval['name']`

                        # merge this result with previous results
                        oldval = self.remoteHits[newval['infohash']]
                        for query_permid in newval['query_permids']:
                            if not query_permid in oldval['query_permids']:
                                oldval['query_permids'].append(query_permid)
                        
                        # if a hit belongs to a more popular channel, then replace the previous
                        if newval['channel_permid'] !="" and newval['channel_name'] != "" and newval['subscriptions']-newval['neg_votes'] > oldval['subscriptions']-oldval['neg_votes']:
                            oldval['subscriptions'] = newval['subscriptions']
                            oldval['neg_votes'] = newval['neg_votes']
                            oldval['channel_permid'] = newval['channel_permid']
                            oldval['channel_name'] = newval['channel_name']
                    else:
                        if DEBUG:
                            print >>sys.stderr,"TorrentSearchGridManager: gotRemoteHist: appending hit",`newval['name']`

                        self.remoteHits[newval['infohash']] = newval
                        numResults +=1
                        # if numResults % 5 == 0:
                        # self.refreshGrid()
             
                if numResults > 0:
                    self.refreshGrid()
                    if DEBUG:
                        print >>sys.stderr,'TorrentSearchGridManager: gotRemoteHits: Refresh grid after new remote torrent hits came in'
                return True
            elif DEBUG:
                print >>sys.stderr,"TorrentSearchGridManager: gotRemoteHits: got hits for",kws,"but current search is for",self.searchkeywords
            return False
        except:
            print_exc()
            return False
Exemple #41
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)
        self.SetForegroundColour(parent.GetForegroundColour())
                
        #Niels 04-06-2012: termextraction needs a session variable, create instance from mainthread
        TermExtraction.getInstance()

        self.nbdb       = None
        self.xxx_filter = Category.getInstance().xxx_filter
        self.guiutility = GUIUtility.getInstance()
        self.utility    = self.guiutility.utility

        vSizer = wx.BoxSizer(wx.VERTICAL)
        vSizer.Add(DetailHeader(self, "Click below to explore what's hot"), 0, wx.EXPAND)
        vSizer.AddSpacer((-1,10))

        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour(DEFAULT_BACKGROUND)
        self.vSizer = wx.BoxSizer(wx.VERTICAL)
        self.panel.SetSizer(self.vSizer)
        vSizer.Add(self.panel, 1, wx.EXPAND|wx.BOTTOM, 5)

        self.footer = wx.StaticText(self)
        vSizer.Add(self.footer, 0, wx.ALIGN_RIGHT|wx.RIGHT|wx.BOTTOM, 1)

        self.tags = []
        self.buzz_cache = [[],[],[]]
        self.last_shown_buzz = None

        row1_font = self.GetFont()
        row1_font.SetPointSize(row1_font.GetPointSize() + 10)
        row1_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row2_font = self.GetFont()
        row2_font.SetPointSize(row2_font.GetPointSize() + 4)
        row2_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row3_font = self.GetFont()
        row3_font.SetWeight(wx.FONTWEIGHT_BOLD)
        self.TERM_FONTS = [row1_font, row2_font, row3_font]

        self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.panel.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        text = wx.StaticText(self.panel, -1, '...collecting buzz information...')
        _set_font(text, fontcolour = BuzzPanel.INACTIVE_COLOR)
        self.vSizer.AddStretchSpacer()
        self.vSizer.Add(text, 0, wx.ALIGN_CENTER)
        self.vSizer.AddStretchSpacer()

        self.refresh = 5
        self.GetBuzzFromDB(doRefresh=True,samplesize=10)
        self.guiutility.addList(self)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnRefreshTimer, self.timer)
        self.timer.Start(1000, False)

        self.SetSizer(vSizer)
        self.Layout()
Exemple #42
0
    def register(self, session, sesslock, autoload_discovery=True):
        if not self.registered:
            self.registered = True

            self.session = session
            self.sesslock = sesslock

            if self.session.get_torrent_store():
                from Tribler.Core.leveldbstore import LevelDbStore
                self.torrent_store = LevelDbStore(
                    self.session.get_torrent_store_dir())

            if self.session.get_enable_metadata():
                from Tribler.Core.leveldbstore import LevelDbStore
                self.metadata_store = LevelDbStore(
                    self.session.get_metadata_store_dir())

            # torrent collecting: RemoteTorrentHandler
            if self.session.get_torrent_collecting():
                from Tribler.Core.RemoteTorrentHandler import RemoteTorrentHandler
                self.rtorrent_handler = RemoteTorrentHandler(self.session)

            # TODO(emilon): move this to a megacache component or smth
            if self.session.get_megacache():
                from Tribler.Core.CacheDB.SqliteCacheDBHandler import (
                    PeerDBHandler, TorrentDBHandler, MyPreferenceDBHandler,
                    VoteCastDBHandler, ChannelCastDBHandler)
                from Tribler.Category.Category import Category

                self._logger.debug('tlm: Reading Session state from %s',
                                   self.session.get_state_dir())

                self.cat = Category.getInstance(self.session)

                # create DBHandlers
                self.peer_db = PeerDBHandler(self.session)
                self.torrent_db = TorrentDBHandler(self.session)
                self.mypref_db = MyPreferenceDBHandler(self.session)
                self.votecast_db = VoteCastDBHandler(self.session)
                self.channelcast_db = ChannelCastDBHandler(self.session)

                # initializes DBHandlers
                self.peer_db.initialize()
                self.torrent_db.initialize()
                self.mypref_db.initialize()
                self.votecast_db.initialize()
                self.channelcast_db.initialize()

                from Tribler.Core.Modules.tracker_manager import TrackerManager
                self.tracker_manager = TrackerManager(self.session)
                self.tracker_manager.initialize()

            if self.session.get_videoplayer():
                self.videoplayer = VideoPlayer(self.session)

            # Dispersy
            self.session.dispersy_member = None
            self.tftp_handler = None
            if self.session.get_dispersy():
                from Tribler.dispersy.dispersy import Dispersy
                from Tribler.dispersy.endpoint import StandaloneEndpoint

                # set communication endpoint
                endpoint = StandaloneEndpoint(self.session.get_dispersy_port(),
                                              ip=self.session.get_ip())

                working_directory = unicode(self.session.get_state_dir())
                self.dispersy = Dispersy(endpoint, working_directory)

                # register TFTP service
                from Tribler.Core.TFTP.handler import TftpHandler
                self.tftp_handler = TftpHandler(self.session,
                                                endpoint,
                                                "fffffffd".decode('hex'),
                                                block_size=1024)
                self.tftp_handler.initialize()

            if self.session.get_enable_torrent_search(
            ) or self.session.get_enable_channel_search():
                self.search_manager = SearchManager(self.session)
                self.search_manager.initialize()

            if self.session.get_enable_channel_search():
                from Tribler.Core.Modules.channel_manager import ChannelManager
                self.channel_manager = ChannelManager(self.session)
                self.channel_manager.initialize()

        if not self.initComplete:
            self.init(autoload_discovery)
Exemple #43
0
    def __init__(self,
                 params,
                 installdir,
                 autoload_discovery=True,
                 use_torrent_search=True,
                 use_channel_search=True):
        assert not isInIOThread(
        ), "isInIOThread() seems to not be working correctly"
        self._logger = logging.getLogger(self.__class__.__name__)

        self.params = params
        self.installdir = installdir

        self.state_dir = None
        self.error = None
        self.last_update = 0
        self.ready = False
        self.done = False
        self.frame = None
        self.upgrader = None

        self.said_start_playback = False
        self.decodeprogress = 0

        self.old_reputation = 0

        # DISPERSY will be set when available
        self.dispersy = None
        # BARTER_COMMUNITY will be set when both Dispersy and the EffortCommunity are available
        self.barter_community = None
        self.tunnel_community = None

        self.torrentfeed = None
        self.webUI = None
        self.utility = None

        # Stage 1 start
        session = self.InitStage1(installdir,
                                  autoload_discovery=autoload_discovery,
                                  use_torrent_search=use_torrent_search,
                                  use_channel_search=use_channel_search)

        self.splash = None
        try:
            bm = self.gui_image_manager.getImage(u'splash.png')
            self.splash = GaugeSplash(bm, "Loading...", 13)
            self.splash.Show()

            self._logger.info('Client Starting Up.')
            self._logger.info("Tribler is using %s as working directory",
                              self.installdir)

            # Stage 2: show the splash window and start the session

            self.splash.tick('Starting API')
            s = self.startAPI(session, self.splash.tick)

            self.utility = Utility(self.installdir, s.get_state_dir())

            if self.utility.read_config(u'saveas', u'downloadconfig'):
                DefaultDownloadStartupConfig.getInstance().set_dest_dir(
                    self.utility.read_config(u'saveas', u'downloadconfig'))

            self.utility.set_app(self)
            self.utility.set_session(s)
            self.guiUtility = GUIUtility.getInstance(self.utility, self.params,
                                                     self)
            GUIDBProducer.getInstance()

            self._logger.info('Tribler Version: %s Build: %s', version_id,
                              commit_id)

            version_info = self.utility.read_config('version_info')
            if version_info.get('version_id', None) != version_id:
                # First run of a different version
                version_info['first_run'] = int(time())
                version_info['version_id'] = version_id
                self.utility.write_config('version_info', version_info)

            self.splash.tick(
                'Starting session and upgrading database (it may take a while)'
            )
            s.start()
            self.dispersy = s.lm.dispersy

            self.splash.tick('Loading userdownloadchoice')
            from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
            UserDownloadChoice.get_singleton().set_utility(self.utility)

            self.splash.tick('Initializing Family Filter')
            cat = Category.getInstance(session)

            state = self.utility.read_config('family_filter')
            if state in (1, 0):
                cat.set_family_filter(state == 1)
            else:
                self.utility.write_config('family_filter', 1)
                self.utility.flush_config()

                cat.set_family_filter(True)

            # Create global speed limits
            self.splash.tick('Setting up speed limits')

            # Counter to suppress some event from occurring
            self.ratestatecallbackcount = 0

            maxup = self.utility.read_config('maxuploadrate')
            maxdown = self.utility.read_config('maxdownloadrate')
            # set speed limits using LibtorrentMgr
            s.set_max_upload_speed(maxup)
            s.set_max_download_speed(maxdown)

            # Only allow updates to come in after we defined ratelimiter
            self.prevActiveDownloads = []
            s.set_download_states_callback(self.sesscb_states_callback)

            # Schedule task for checkpointing Session, to avoid hash checks after
            # crashes.
            startWorker(consumer=None,
                        workerFn=self.guiservthread_checkpoint_timer,
                        delay=SESSION_CHECKPOINT_INTERVAL)

            if not ALLOW_MULTIPLE:
                # Put it here so an error is shown in the startup-error popup
                # Start server for instance2instance communication
                Instance2InstanceServer(
                    self.utility.read_config('i2ilistenport'),
                    self.i2ithread_readlinecallback)

            self.splash.tick('GUIUtility register')
            self.guiUtility.register()

            self.frame = MainFrame(
                self, None, PLAYBACKMODE_INTERNAL
                in return_feasible_playback_modes(), self.splash.tick)
            self.frame.SetIcon(
                wx.Icon(
                    os.path.join(self.installdir, 'Tribler', 'Main', 'vwxGUI',
                                 'images', 'tribler.ico'), wx.BITMAP_TYPE_ICO))

            # Arno, 2011-06-15: VLC 1.1.10 pops up separate win, don't have two.
            self.frame.videoframe = None
            if PLAYBACKMODE_INTERNAL in return_feasible_playback_modes():
                vlcwrap = s.lm.videoplayer.get_vlcwrap()
                wx.CallLater(3000, vlcwrap._init_vlc)
                self.frame.videoframe = VideoDummyFrame(
                    self.frame.videoparentpanel, self.utility, vlcwrap)

            if sys.platform == 'win32':
                wx.CallAfter(self.frame.top_bg.Refresh)
                wx.CallAfter(self.frame.top_bg.Layout)
            else:
                self.frame.top_bg.Layout()

            # Arno, 2007-05-03: wxWidgets 2.8.3.0 and earlier have the MIME-type for .bmp
            # files set to 'image/x-bmp' whereas 'image/bmp' is the official one.
            try:
                bmphand = None
                hands = wx.Image.GetHandlers()
                for hand in hands:
                    # print "Handler",hand.GetExtension(),hand.GetType(),hand.GetMimeType()
                    if hand.GetMimeType() == 'image/x-bmp':
                        bmphand = hand
                        break
                # wx.Image.AddHandler()
                if bmphand is not None:
                    bmphand.SetMimeType('image/bmp')
            except:
                # wx < 2.7 don't like wx.Image.GetHandlers()
                print_exc()

            self.splash.Destroy()
            self.frame.Show(True)
            session.lm.threadpool.call_in_thread(
                0, self.guiservthread_free_space_check)

            self.torrentfeed = RssParser.getInstance()

            self.webUI = None
            if self.utility.read_config('use_webui'):
                try:
                    from Tribler.Main.webUI.webUI import WebUI
                    self.webUI = WebUI.getInstance(
                        self.guiUtility.library_manager,
                        self.guiUtility.torrentsearch_manager,
                        self.utility.read_config('webui_port'))
                    self.webUI.start()
                except Exception:
                    print_exc()

            self.emercoin_mgr = None
            try:
                from Tribler.Main.Emercoin.EmercoinMgr import EmercoinMgr
                self.emercoin_mgr = EmercoinMgr(self.utility)
            except Exception:
                print_exc()

            wx.CallAfter(self.PostInit2)

            # 08/02/10 Boudewijn: Working from home though console
            # doesn't allow me to press close.  The statement below
            # gracefully closes Tribler after 120 seconds.
            # wx.CallLater(120*1000, wx.GetApp().Exit)

            self.ready = True

        except Exception as e:
            if self.splash:
                self.splash.Destroy()

            self.onError(e)
Exemple #44
0
    def register(self, session, sesslock):
        if not self.registered:
            self.registered = True

            self.session = session
            self.sesslock = sesslock

            self.downloads = {}
            config = session.sessconfig  # Should be safe at startup

            self.upnp_ports = []

            # Orig
            self.sessdoneflag = Event()

            self.rawserver = RawServer(
                self.sessdoneflag,
                config['timeout_check_interval'],
                config['timeout'],
                ipv6_enable=config['ipv6_enabled'],
                failfunc=self.rawserver_fatalerrorfunc,
                errorfunc=self.rawserver_nonfatalerrorfunc)
            self.rawserver.add_task(self.rawserver_keepalive, 1)
            self.listen_port = config['minport']
            self.shutdownstarttime = None

            self.multihandler = MultiHandler(self.rawserver, self.sessdoneflag)

            # SWIFTPROC
            swift_exists = config['swiftproc'] and (
                os.path.exists(config['swiftpath'])
                or os.path.exists(config['swiftpath'] + '.exe'))
            if swift_exists:
                from Tribler.Core.Swift.SwiftProcessMgr import SwiftProcessMgr

                self.spm = SwiftProcessMgr(
                    config['swiftpath'], config['swiftcmdlistenport'],
                    config['swiftdlsperproc'],
                    self.session.get_swift_tunnel_listen_port(), self.sesslock)
                try:
                    self.swift_process = self.spm.get_or_create_sp(
                        self.session.get_swift_working_dir(),
                        self.session.get_torrent_collecting_dir(),
                        self.session.get_swift_tunnel_listen_port(),
                        self.session.get_swift_tunnel_httpgw_listen_port(),
                        self.session.get_swift_tunnel_cmdgw_listen_port())
                    self.upnp_ports.append(
                        (self.session.get_swift_tunnel_listen_port(), 'UDP'))

                except OSError:
                    # could not find/run swift
                    print >> sys.stderr, "lmc: could not start a swift process"

            else:
                self.spm = None
                self.swift_process = None

            # Dispersy
            self.session.dispersy_member = None
            if config['dispersy']:
                from Tribler.dispersy.callback import Callback
                from Tribler.dispersy.dispersy import Dispersy
                from Tribler.dispersy.endpoint import RawserverEndpoint, TunnelEndpoint
                from Tribler.dispersy.community import HardKilledCommunity

                # set communication endpoint
                if config['dispersy-tunnel-over-swift'] and self.swift_process:
                    endpoint = TunnelEndpoint(self.swift_process)
                else:
                    endpoint = RawserverEndpoint(self.rawserver,
                                                 config['dispersy_port'])

                callback = Callback("Dispersy")  # WARNING NAME SIGNIFICANT
                working_directory = unicode(config['state_dir'])

                self.dispersy = Dispersy(callback, endpoint, working_directory)

                # TODO: see if we can postpone dispersy.start to improve GUI responsiveness.
                # However, for now we must start self.dispersy.callback before running
                # try_register(nocachedb, self.database_thread)!

                self.dispersy.start()

                print >> sys.stderr, "lmc: Dispersy is listening on port", self.dispersy.wan_address[
                    1], "using", endpoint
                self.upnp_ports.append((self.dispersy.wan_address[1], 'UDP'))

                self.dispersy.callback.call(self.dispersy.define_auto_load,
                                            args=(HardKilledCommunity, ),
                                            kargs={'load': True})

                # notify dispersy finished loading
                self.session.uch.notify(NTFY_DISPERSY, NTFY_STARTED, None)

                from Tribler.Core.permid import read_keypair
                from Tribler.dispersy.crypto import ec_to_public_bin, ec_to_private_bin
                keypair = read_keypair(
                    self.session.get_permid_keypair_filename())
                self.session.dispersy_member = callback.call(
                    self.dispersy.get_member,
                    (ec_to_public_bin(keypair), ec_to_private_bin(keypair)))

                self.database_thread = callback
            else:

                class FakeCallback():
                    def __init__(self):
                        from Tribler.Utilities.TimedTaskQueue import TimedTaskQueue
                        self.queue = TimedTaskQueue("FakeCallback")

                    def register(self,
                                 call,
                                 args=(),
                                 kargs=None,
                                 delay=0.0,
                                 priority=0,
                                 id_=u"",
                                 callback=None,
                                 callback_args=(),
                                 callback_kargs=None,
                                 include_id=False):
                        def do_task():
                            if kargs:
                                call(*args, **kargs)
                            else:
                                call(*args)

                            if callback:
                                if callback_kargs:
                                    callback(*callback_args, **callback_kargs)
                                else:
                                    callback(*callback_args)

                        self.queue.add_task(do_task, t=delay)

                    def shutdown(self, immediately=False):
                        self.queue.shutdown(immediately)

                self.database_thread = FakeCallback()

            if config['megacache']:
                import Tribler.Core.CacheDB.cachedb as cachedb
                from Tribler.Core.CacheDB.SqliteCacheDBHandler import PeerDBHandler, TorrentDBHandler, MyPreferenceDBHandler, VoteCastDBHandler, ChannelCastDBHandler, NetworkBuzzDBHandler, UserEventLogDBHandler
                from Tribler.Category.Category import Category
                from Tribler.Core.Tag.Extraction import TermExtraction
                from Tribler.Core.CacheDB.sqlitecachedb import try_register

                if DEBUG:
                    print >> sys.stderr, 'tlm: Reading Session state from', config[
                        'state_dir']

                nocachedb = cachedb.init(config, self.rawserver_fatalerrorfunc)
                try_register(nocachedb, self.database_thread)

                self.cat = Category.getInstance(config['install_dir'])
                self.term = TermExtraction.getInstance(config['install_dir'])

                self.peer_db = PeerDBHandler.getInstance()
                self.peer_db.registerConnectionUpdater(self.session)

                self.torrent_db = TorrentDBHandler.getInstance()
                self.torrent_db.register(
                    os.path.abspath(config['torrent_collecting_dir']))
                self.mypref_db = MyPreferenceDBHandler.getInstance()
                self.votecast_db = VoteCastDBHandler.getInstance()
                self.votecast_db.registerSession(self.session)
                self.channelcast_db = ChannelCastDBHandler.getInstance()
                self.channelcast_db.registerSession(self.session)
                self.nb_db = NetworkBuzzDBHandler.getInstance()
                self.ue_db = UserEventLogDBHandler.getInstance()

                if self.dispersy:
                    self.dispersy.database.attach_commit_callback(
                        self.channelcast_db._db.commitNow)
            else:
                config['torrent_checking'] = 0

            self.rtorrent_handler = None
            if config['torrent_collecting']:
                from Tribler.Core.RemoteTorrentHandler import RemoteTorrentHandler
                self.rtorrent_handler = RemoteTorrentHandler()
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)
        self.SetForegroundColour(parent.GetForegroundColour())

        #Niels 04-06-2012: termextraction needs a session variable, create instance from mainthread
        TermExtraction.getInstance()

        self.nbdb = None
        self.xxx_filter = Category.getInstance().xxx_filter
        self.guiutility = GUIUtility.getInstance()
        self.utility = self.guiutility.utility

        vSizer = wx.BoxSizer(wx.VERTICAL)
        vSizer.Add(DetailHeader(self, "Click below to explore what's hot"), 0,
                   wx.EXPAND)
        vSizer.AddSpacer((-1, 10))

        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour(DEFAULT_BACKGROUND)
        self.vSizer = wx.BoxSizer(wx.VERTICAL)
        self.panel.SetSizer(self.vSizer)
        vSizer.Add(self.panel, 1, wx.EXPAND | wx.BOTTOM, 5)

        self.footer = wx.StaticText(self)
        vSizer.Add(self.footer, 0, wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, 1)

        self.tags = []
        self.buzz_cache = [[], [], []]
        self.last_shown_buzz = None

        row1_font = self.GetFont()
        row1_font.SetPointSize(row1_font.GetPointSize() + 10)
        row1_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row2_font = self.GetFont()
        row2_font.SetPointSize(row2_font.GetPointSize() + 4)
        row2_font.SetWeight(wx.FONTWEIGHT_BOLD)

        row3_font = self.GetFont()
        row3_font.SetWeight(wx.FONTWEIGHT_BOLD)
        self.TERM_FONTS = [row1_font, row2_font, row3_font]

        self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.panel.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        text = wx.StaticText(self.panel, -1,
                             '...collecting buzz information...')
        _set_font(text, fontcolour=BuzzPanel.INACTIVE_COLOR)
        self.vSizer.AddStretchSpacer()
        self.vSizer.Add(text, 0, wx.ALIGN_CENTER)
        self.vSizer.AddStretchSpacer()

        self.refresh = 5
        self.GetBuzzFromDB(doRefresh=True, samplesize=10)
        self.guiutility.addList(self)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnRefreshTimer, self.timer)
        self.timer.Start(1000, False)

        self.SetSizer(vSizer)
        self.Layout()
    def gotRemoteHits(self, permid, kws, answers, mode):
        """ Called by GUIUtil when hits come in. """
        print >> sys.stderr, "rmote each time, so we can call sort here, hehe"
        try:
            if DEBUG:
                print >> sys.stderr, "TorrentSearchGridManager: gotRemoteHist: got", len(
                    answers)

            # Always store the results, only display when in filesMode
            # We got some replies. First check if they are for the current query
            if self.searchkeywords['filesMode'] == kws:
                numResults = 0
                catobj = Category.getInstance()
                for key, value in answers.iteritems():

                    if self.torrent_db.hasTorrent(key):
                        continue  # do not show results we have ourselves

                    # Convert answer fields as per
                    # Session.query_connected_peers() spec. to NEWDB format
                    newval = {}
                    newval['name'] = value['content_name']
                    newval['infohash'] = key
                    newval['torrent_file_name'] = ''
                    newval['length'] = value['length']
                    newval['creation_date'] = time()  # None  gives '?' in GUI
                    newval['relevance'] = 0
                    newval['source'] = 'RQ'
                    newval['category'] = value['category'][0]
                    # We trust the peer
                    newval['status'] = 'good'
                    newval['num_seeders'] = value['seeder']
                    newval['num_leechers'] = value['leecher']

                    # Extra fiedl: Set from which peer this info originates
                    newval['query_permid'] = permid
                    if DEBUG:
                        print >> sys.stderr, "TorrentSearchGridManager: gotRemoteHist: appending hit", ` newval[
                            'name'] `
                        #value['name'] = 'REMOTE '+value['name']

                    # Filter out results from unwanted categories
                    flag = False
                    for cat in value['category']:
                        rank = catobj.getCategoryRank(cat)
                        if rank == -1:
                            if DEBUG:
                                print >> sys.stderr, "TorrentSearchGridManager: gotRemoteHits: Got", ` newval[
                                    'name'] `, "from banned category", cat, ", discarded it."
                            flag = True
                            break
                    if flag:
                        continue

                    # TODO: select best result?
                    if not (newval['infohash'] in self.remoteHits):
                        self.remoteHits[newval['infohash']] = newval

                if mode == 'filesMode' and self.standardOverview.getSearchBusy(
                ):
                    self.refreshGrid()
                #    if self.notifyView(value, 'add'):
                #        numResults +=1
                #self.standardOverview.setSearchFeedback('remote', False, numResults, self.searchkeywords[mode])

                return True
            elif DEBUG:
                print >> sys.stderr, "TorrentSearchGridManager: gotRemoteHist: got hits for", kws, "but current search is for", self.searchkeywords[
                    mode]
            return False
        except:
            print_exc()
            return False
Exemple #47
0
    def __init__(self, abc, parent, internalvideo, progress):
        self.abc = abc
        self._logger = logging.getLogger(self.__class__.__name__)

        self._logger.info('GUI started')

        # Do all init here
        self.ready = False
        self.guiUtility = GUIUtility.getInstance()
        self.guiUtility.frame = self
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None
        self.videoframe = None
        self.category = Category.getInstance()
        self.shutdown_and_upgrade_notes = None

        title = "Tribler %s" % version_id

        # Get window size and (sash) position from config file
        size, position, sashpos = self.getWindowSettings()
        style = wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN

        wx.Frame.__init__(self, parent, wx.ID_ANY, title, position, size, style)
        if sys.platform == 'linux2':
            font = self.GetFont()
            if font.GetPointSize() > 9:
                font.SetPointSize(9)
                self.SetFont(font)

        self.Freeze()
        self.SetDoubleBuffered(True)
        self.SetBackgroundColour(DEFAULT_BACKGROUND)

        themeColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        r, g, b = themeColour.Get(False)
        if r > 190 or g > 190 or b > 190:  # Grey == 190,190,190
            self.SetForegroundColour(wx.BLACK)

        if internalvideo:
            self.videoparentpanel = wx.Panel(self)
            self.videoparentpanel.Hide()
        else:
            self.videoparentpanel = None

        # Create all components
        progress('Creating panels')

        self.actlist = ActivitiesList(self)
        self.top_bg = TopSearchPanel(self)
        self.home = Home(self)

        self.splitter = wx.SplitterWindow(self, style=wx.SP_NOBORDER)
        self.splitter.SetMinimumPaneSize(1)
        self.splitter.SetForegroundColour(self.GetForegroundColour())
        self.splitter_top_window = wx.Panel(self.splitter, style=wx.NO_BORDER)
        self.splitter_top_window.SetForegroundColour(self.GetForegroundColour())
        self.splitter_top = wx.BoxSizer(wx.HORIZONTAL)
        self.splitter_top_window.SetSizer(self.splitter_top)
        self.splitter_bottom_window = wx.Panel(self.splitter)
        self.splitter_bottom_window.SetMinSize((-1, 25))
        self.splitter_bottom_window.SetForegroundColour(self.GetForegroundColour())
        self.splitter_bottom_window.OnChange = lambda: self.splitter_bottom.Layout()
        self.splitter_bottom_window.parent_list = self.splitter_bottom_window

        self.networkgraph = NetworkGraphPanel(self)
        self.networkgraph.Show(False)
        self.searchlist = SearchList(self.splitter_top_window)
        self.searchlist.Show(False)
        self.librarylist = LibraryList(self.splitter_top_window)
        self.librarylist.Show(False)
        self.channellist = ChannelList(self.splitter_top_window)
        self.channellist.Show(False)
        self.selectedchannellist = SelectedChannelList(self.splitter_top_window)
        self.selectedchannellist.Show(False)
        self.playlist = Playlist(self.splitter_top_window)
        self.playlist.Show(False)

        # Populate the bottom window
        self.splitter_bottom = wx.BoxSizer(wx.HORIZONTAL)
        self.torrentdetailspanel = TorrentDetails(self.splitter_bottom_window)
        self.torrentdetailspanel.Show(False)
        self.librarydetailspanel = LibraryDetails(self.splitter_bottom_window)
        self.librarydetailspanel.Show(False)
        self.channeldetailspanel = ChannelDetails(self.splitter_bottom_window)
        self.channeldetailspanel.Show(False)
        self.playlistdetailspanel = PlaylistDetails(self.splitter_bottom_window)
        self.playlistdetailspanel.Show(False)
        self.searchinfopanel = SearchInfoPanel(self.splitter_bottom_window)
        self.searchinfopanel.Show(False)
        self.channelinfopanel = ChannelInfoPanel(self.splitter_bottom_window)
        self.channelinfopanel.Show(False)
        self.libraryinfopanel = LibraryInfoPanel(self.splitter_bottom_window)
        self.libraryinfopanel.Show(False)
        self.playlistinfopanel = PlaylistInfoPanel(self.splitter_bottom_window)
        self.playlistinfopanel.Show(False)
        self.selectedchannelinfopanel = SelectedchannelInfoPanel(self.splitter_bottom_window)
        self.selectedchannelinfopanel.Show(False)
        self.splitter_bottom.Add(self.torrentdetailspanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.librarydetailspanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.channeldetailspanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.playlistdetailspanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.searchinfopanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.channelinfopanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.libraryinfopanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.playlistinfopanel, 1, wx.EXPAND)
        self.splitter_bottom.Add(self.selectedchannelinfopanel, 1, wx.EXPAND)
        self.splitter_bottom_window.SetSizer(self.splitter_bottom)

        self.splitter.SetSashGravity(0.8)
        self.splitter.SplitHorizontally(self.splitter_top_window, self.splitter_bottom_window, sashpos)
        self.splitter.Show(False)

        # Reset the sash position after the splitter has been made visible
        def OnShowSplitter(event):
            wx.CallAfter(self.splitter.SetSashPosition, sashpos)
            self.splitter.Unbind(wx.EVT_SHOW)
            event.Skip()
        self.splitter.Bind(wx.EVT_SHOW, OnShowSplitter)

        self.stats = Stats(self)
        self.stats.Show(False)
        self.managechannel = ManageChannel(self)
        self.managechannel.Show(False)

        progress('Positioning')

        # position all elements
        vSizer = wx.BoxSizer(wx.VERTICAL)

        vSizer.Add(self.top_bg, 0, wx.EXPAND)

        hSizer = wx.BoxSizer(wx.HORIZONTAL)
        vSizer.Add(hSizer, 1, wx.EXPAND)

        hSizer.Add(self.actlist, 0, wx.EXPAND)
        separator = wx.Panel(self, size=(1, -1))
        separator.SetBackgroundColour(SEPARATOR_GREY)
        hSizer.Add(separator, 0, wx.EXPAND)
        hSizer.Add(self.home, 1, wx.EXPAND)
        hSizer.Add(self.stats, 1, wx.EXPAND)
        hSizer.Add(self.networkgraph, 1, wx.EXPAND)
        hSizer.Add(self.splitter, 1, wx.EXPAND)

        hSizer.Add(self.managechannel, 1, wx.EXPAND)

        if self.videoparentpanel:
            hSizer.Add(self.videoparentpanel, 1, wx.EXPAND)

        self.SetSizer(vSizer)

        # set sizes
        self.top_bg.SetMinSize((-1, 45))
        self.actlist.SetMinSize((200, -1))

        self.SRstatusbar = SRstatusbar(self)
        self.SetStatusBar(self.SRstatusbar)

        def preload_data():
            self.guiUtility.showChannelCategory('All', False)
            self.guiUtility.showLibrary(False)
        startWorker(None, preload_data, delay=1.5, workerType="ThreadPool")

        if sys.platform != 'darwin':
            dragdroplist = FileDropTarget(self)
            self.SetDropTarget(dragdroplist)
        try:
            self.SetIcon(
                wx.Icon(os.path.join(self.utility.getPath(), 'Tribler', 'Main', 'vwxGUI', 'images', 'tribler.ico'), wx.BITMAP_TYPE_ICO))
        except:
            pass

        self.tbicon = None
        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()

        # Don't update GUI as often when iconized
        self.GUIupdate = True
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility

        progress('Binding events')
        # Menu Events
        #
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # leaving here for the time being:
        # wxMSW apparently sends the event to the App object rather than
        # the top-level Frame, but there seemed to be some possibility of
        # change
        self.Bind(wx.EVT_QUERY_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)

        findId = wx.NewId()
        quitId = wx.NewId()
        nextId = wx.NewId()
        prevId = wx.NewId()
        dispId = wx.NewId()
        anonId = wx.NewId()
        DISPERSY_DEBUG_FRAME_ID = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnFind, id=findId)
        self.Bind(wx.EVT_MENU, lambda event: self.Close(), id=quitId)
        self.Bind(wx.EVT_MENU, self.OnNext, id=nextId)
        self.Bind(wx.EVT_MENU, self.OnPrev, id=prevId)
        self.Bind(wx.EVT_MENU, lambda evt: self.guiUtility.ShowPage('stats'), id=dispId)
        self.Bind(wx.EVT_MENU, lambda evt: self.guiUtility.ShowPage('networkgraph'), id=anonId)
        self.Bind(wx.EVT_MENU, self.OnOpenDebugFrame, id=DISPERSY_DEBUG_FRAME_ID)

        accelerators = [(wx.ACCEL_CTRL, ord('f'), findId)]
        accelerators.append((wx.ACCEL_CTRL, ord('d'), dispId))
        accelerators.append((wx.ACCEL_CTRL, ord('n'), anonId))
        accelerators.append((wx.ACCEL_CTRL, wx.WXK_TAB, nextId))
        accelerators.append((wx.ACCEL_CTRL | wx.ACCEL_SHIFT, wx.WXK_TAB, prevId))
        accelerators.append((wx.ACCEL_CTRL | wx.ACCEL_ALT, ord('d'), DISPERSY_DEBUG_FRAME_ID))

        if sys.platform == 'linux2':
            accelerators.append((wx.ACCEL_CTRL, ord('q'), quitId))
            accelerators.append((wx.ACCEL_CTRL, ord('/'), findId))
        self.SetAcceleratorTable(wx.AcceleratorTable(accelerators))

        # Init video player
        progress('GUI complete')

        self.Thaw()
        self.ready = True

        def post():
            self.startCMDLineTorrent()

        # If the user passed a torrentfile on the cmdline, load it.
        wx.CallAfter(post)
Exemple #48
0
    def __init__(self, params, installdir, autoload_discovery=True,
                 use_torrent_search=True, use_channel_search=True):
        assert not isInIOThread(), "isInIOThread() seems to not be working correctly"
        self._logger = logging.getLogger(self.__class__.__name__)

        self.params = params
        self.installdir = installdir

        self.state_dir = None
        self.error = None
        self.last_update = 0
        self.ready = False
        self.done = False
        self.frame = None
        self.upgrader = None

        self.said_start_playback = False
        self.decodeprogress = 0

        self.old_reputation = 0

        # DISPERSY will be set when available
        self.dispersy = None
        # BARTER_COMMUNITY will be set when both Dispersy and the EffortCommunity are available
        self.barter_community = None
        self.tunnel_community = None

        self.torrentfeed = None
        self.webUI = None
        self.utility = None

        # Stage 1 start
        session = self.InitStage1(installdir, autoload_discovery=autoload_discovery,
                                  use_torrent_search=use_torrent_search, use_channel_search=use_channel_search)

        self.splash = None
        try:
            bm = self.gui_image_manager.getImage(u'splash.png')
            self.splash = GaugeSplash(bm, "Loading...", 13)
            self.splash.Show()

            self._logger.info('Client Starting Up.')
            self._logger.info("Tribler is using %s as working directory", self.installdir)

            # Stage 2: show the splash window and start the session

            self.splash.tick('Starting API')
            s = self.startAPI(session, self.splash.tick)

            self.utility = Utility(self.installdir, s.get_state_dir())

            if self.utility.read_config(u'saveas', u'downloadconfig'):
                DefaultDownloadStartupConfig.getInstance().set_dest_dir(self.utility.read_config(u'saveas', u'downloadconfig'))

            self.utility.set_app(self)
            self.utility.set_session(s)
            self.guiUtility = GUIUtility.getInstance(self.utility, self.params, self)
            GUIDBProducer.getInstance()

            self._logger.info('Tribler Version: %s Build: %s', version_id, commit_id)

            version_info = self.utility.read_config('version_info')
            if version_info.get('version_id', None) != version_id:
                # First run of a different version
                version_info['first_run'] = int(time())
                version_info['version_id'] = version_id
                self.utility.write_config('version_info', version_info)

            self.splash.tick('Starting session and upgrading database (it may take a while)')
            s.start()
            self.dispersy = s.lm.dispersy

            self.splash.tick('Loading userdownloadchoice')
            from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
            UserDownloadChoice.get_singleton().set_utility(self.utility)

            self.splash.tick('Initializing Family Filter')
            cat = Category.getInstance(session)

            state = self.utility.read_config('family_filter')
            if state in (1, 0):
                cat.set_family_filter(state == 1)
            else:
                self.utility.write_config('family_filter', 1)
                self.utility.flush_config()

                cat.set_family_filter(True)

            # Create global speed limits
            self.splash.tick('Setting up speed limits')

            # Counter to suppress some event from occurring
            self.ratestatecallbackcount = 0

            maxup = self.utility.read_config('maxuploadrate')
            maxdown = self.utility.read_config('maxdownloadrate')
            # set speed limits using LibtorrentMgr
            s.set_max_upload_speed(maxup)
            s.set_max_download_speed(maxdown)

            # Only allow updates to come in after we defined ratelimiter
            self.prevActiveDownloads = []
            s.set_download_states_callback(self.sesscb_states_callback)

            # Schedule task for checkpointing Session, to avoid hash checks after
            # crashes.
            startWorker(consumer=None, workerFn=self.guiservthread_checkpoint_timer, delay=SESSION_CHECKPOINT_INTERVAL)

            if not ALLOW_MULTIPLE:
                # Put it here so an error is shown in the startup-error popup
                # Start server for instance2instance communication
                Instance2InstanceServer(self.utility.read_config('i2ilistenport'), self.i2ithread_readlinecallback)

            self.splash.tick('GUIUtility register')
            self.guiUtility.register()

            self.frame = MainFrame(self,
                                   None,
                                   PLAYBACKMODE_INTERNAL in return_feasible_playback_modes(),
                                   self.splash.tick)
            self.frame.SetIcon(wx.Icon(os.path.join(self.installdir, 'Tribler',
                                                    'Main', 'vwxGUI', 'images',
                                                    'tribler.ico'),
                                       wx.BITMAP_TYPE_ICO))

            # Arno, 2011-06-15: VLC 1.1.10 pops up separate win, don't have two.
            self.frame.videoframe = None
            if PLAYBACKMODE_INTERNAL in return_feasible_playback_modes():
                vlcwrap = s.lm.videoplayer.get_vlcwrap()
                wx.CallLater(3000, vlcwrap._init_vlc)
                self.frame.videoframe = VideoDummyFrame(self.frame.videoparentpanel, self.utility, vlcwrap)

            if sys.platform == 'win32':
                wx.CallAfter(self.frame.top_bg.Refresh)
                wx.CallAfter(self.frame.top_bg.Layout)
            else:
                self.frame.top_bg.Layout()

            # Arno, 2007-05-03: wxWidgets 2.8.3.0 and earlier have the MIME-type for .bmp
            # files set to 'image/x-bmp' whereas 'image/bmp' is the official one.
            try:
                bmphand = None
                hands = wx.Image.GetHandlers()
                for hand in hands:
                    # print "Handler",hand.GetExtension(),hand.GetType(),hand.GetMimeType()
                    if hand.GetMimeType() == 'image/x-bmp':
                        bmphand = hand
                        break
                # wx.Image.AddHandler()
                if bmphand is not None:
                    bmphand.SetMimeType('image/bmp')
            except:
                # wx < 2.7 don't like wx.Image.GetHandlers()
                print_exc()

            self.splash.Destroy()
            self.frame.Show(True)
            session.lm.threadpool.call_in_thread(0, self.guiservthread_free_space_check)

            self.torrentfeed = RssParser.getInstance()

            self.webUI = None
            if self.utility.read_config('use_webui'):
                try:
                    from Tribler.Main.webUI.webUI import WebUI
                    self.webUI = WebUI.getInstance(self.guiUtility.library_manager,
                                                   self.guiUtility.torrentsearch_manager,
                                                   self.utility.read_config('webui_port'))
                    self.webUI.start()
                except Exception:
                    print_exc()

            self.emercoin_mgr = None
            try:
                from Tribler.Main.Emercoin.EmercoinMgr import EmercoinMgr
                self.emercoin_mgr = EmercoinMgr(self.utility)
            except Exception:
                print_exc()

            wx.CallAfter(self.PostInit2)

            # 08/02/10 Boudewijn: Working from home though console
            # doesn't allow me to press close.  The statement below
            # gracefully closes Tribler after 120 seconds.
            # wx.CallLater(120*1000, wx.GetApp().Exit)

            self.ready = True

        except Exception as e:
            if self.splash:
                self.splash.Destroy()

            self.onError(e)
Exemple #49
0
    def buttonClicked(self, event):
        "One of the buttons in the GUI has been clicked"

        event.Skip(True) #should let other handlers use this event!!!!!!!
            
        name = ""
        obj = event.GetEventObject()
        try:
            name = obj.GetName()
        except:
            print >>sys.stderr,'GUIUtil: Error: Could not get name of buttonObject: %s' % obj
        
        if DEBUG:
            print >>sys.stderr,'GUIUtil: Button clicked %s' % name
        
        if name.startswith('mainButton'):
            self.mainButtonClicked(name, obj)
        elif name.lower().find('detailstab') > -1:
            self.detailsTabClicked(name)
        elif name == 'refresh':
            self.refreshTracker()
        elif name == "addAsFriend" or name == 'deleteFriend':
            self.standardDetails.addAsFriend()
        elif name == 'download':
            self.standardDetails.download()
        elif name == 'addFriend':
            #print >>sys.stderr,"GUIUtil: buttonClicked: parent is",obj.GetParent().GetName()
            dialog = MakeFriendsDialog(obj,self.utility)
            ret = dialog.ShowModal()
            dialog.Destroy()
        elif name == 'inviteFriends':
            self.emailFriend(event)
       
            #else:
            #    print >>sys.stderr,"GUIUtil: buttonClicked: dlbooster: Torrent is None"
            
        elif (name == 'edit' or name == "top10Sharers" or name.startswith('bgPanel')) and obj.GetParent().GetName() == "profileOverview":
            self.standardOverview.currentPanel.sendClick(event)
            self.detailsTabClicked(name) #a panel was clicked in the profile overview and this is the most elegant so far method of informing the others
        elif name == "takeMeThere0" : #a button to go to preferences was clicked
            panel_name = self.standardDetails.currentPanel.GetName()
            if panel_name == "profileDetails_Files":
                #self.utility.actions[ACTION_PREFERENCES].action()
                self.utility.actions[ACTION_PREFERENCES].action(openname=self.utility.lang.get('triblersetting'))
                self.selectData(self.standardDetails.getData())
            if panel_name == "profileDetails_Download":
                #self.utility.actions[ACTION_PREFERENCES].action(openname=self.utility.lang.get('triblersetting'))
                self.utility.actions[ACTION_PREFERENCES].action(openname=self.utility.lang.get('videosetting'))
                self.selectData(self.standardDetails.getData())
            elif panel_name == "profileDetails_Presence":
                self.emailFriend(event)
                #self.mainButtonClicked( 'mainButtonPersons', self.frame.mainButtonPersons)
            #generate event to change page -> this should be done as a parameter to action because is modal
            #event = wx.TreeEvent(wx.EVT_TREE_ITEM_ACTIVATED)
            #wx.PostEvent()
        elif name == "takeMeThere1": #switch to another view
            panel_name = self.standardDetails.currentPanel.GetName()
            if panel_name == "profileDetails_Download":
                self.emailFriend(event)
                #self.mainButtonClicked( 'mainButtonPersons', self.frame.mainButtonPersons)
            if panel_name == "profileDetails_Presence": 
                URL = 'http://www.tribler.org/'
                webbrowser.open(URL)  
            else:
                print >>sys.stderr,'GUIUtil: A button was clicked, but no action is defined for: %s' % name
                
        elif name == "takeMeThere2": #switch to another view
            panel_name = self.standardDetails.currentPanel.GetName()
            if panel_name == "profileDetails_Download":
                URL = 'http://www.tribler.org/'
                webbrowser.open(URL)                
        elif name == "search": # search files/persons button
            if DEBUG:
                print >>sys.stderr,'GUIUtil: search button clicked'
            self.dosearch()
        elif name == 'subscribe':
            self.subscribe()
        elif name == 'firewallStatus':
            self.firewallStatusClick()
        elif name == 'options':            
            self.standardDetails.rightMouseButton(event)
        elif name == 'viewModus':            
            self.onChangeViewModus()
        elif name == 'searchClear':
            # this has to be a callafter to avoid segmentation fault
            # otherwise the panel with the event generating button is destroyed
            # in the execution of the event.
            self.standardOverview.clearSearch()
                        
            wx.CallAfter(self.standardOverview.toggleSearchDetailsPanel, False)
        elif name == 'familyFilterOn' or name == 'familyFilterOff':
            if ((self.familyButtonOn.isToggled() and name == 'familyFilterOff') or
                (self.familyButtonOff.isToggled() and name == 'familyFilterOn')):

                catobj = Category.getInstance()
                ff_enabled = not catobj.family_filter_enabled()
                print 'Setting family filter to: %s' % ff_enabled
                catobj.set_family_filter(ff_enabled)
                self.familyButtonOn.setToggled()
                self.familyButtonOff.setToggled()
#                obj.setToggled(ff_enabled)
                for filtername in ['filesFilter', 'libraryFilter']:
                    filterCombo = xrc.XRCCTRL(self.frame, filtername)
                    if filterCombo:
                        filterCombo.refresh()
        elif DEBUG:
            print 'GUIUtil: A button was clicked, but no action is defined for: %s' % name
Exemple #50
0
    def _PostInit(self):
        # Do all init here
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None
        self.category = Category.getInstance()
        self.shutdown_and_upgrade_notes = None

        self.guiserver = GUITaskQueue.getInstance()
        title = self.utility.lang.get('title') + \
                " " + \
                self.utility.lang.get('version')

        # Get window size and position from config file
        size, position = self.getWindowSettings()
        style = wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN

        self.SetSize(size)
        self.SetPosition(position)
        self.SetTitle(title)
        tt = self.GetToolTip()
        if tt is not None:
            tt.SetTip('')

        self.SRstatusbar = SRstatusbar(self)
        self.SetStatusBar(self.SRstatusbar)

        if sys.platform != 'darwin':
            dragdroplist = FileDropTarget(self)
            self.SetDropTarget(dragdroplist)

        self.tbicon = None

        try:
            self.SetIcon(self.utility.icon)
        except:
            pass

        # Don't update GUI as often when iconized
        self.GUIupdate = True
        self.oldframe = None
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility

        # Menu Events
        ############################

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # leaving here for the time being:
        # wxMSW apparently sends the event to the App object rather than
        # the top-level Frame, but there seemed to be some possibility of
        # change
        self.Bind(wx.EVT_QUERY_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_END_SESSION, self.OnCloseWindow)


        findId = wx.NewId()
        quitId = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnFind, id = findId)
        self.Bind(wx.EVT_MENU, lambda event: self.Close(), id = quitId)

        accelerators = [(wx.ACCEL_CTRL, ord('f'), findId)]
        if sys.platform == 'linux2':
            accelerators.append((wx.ACCEL_CTRL, ord('q'), quitId))
            accelerators.append((wx.ACCEL_CTRL, ord('/'), findId))
        self.SetAcceleratorTable(wx.AcceleratorTable(accelerators))

        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)

        # Init video player
        sys.stdout.write('GUI Complete.\n')

        self.Show(True)
        self.ready = True

        # Just for debugging: add test permids and display top 5 peers from which the most is downloaded in bartercastdb
#        bartercastdb = self.utility.session.open_dbhandler(NTFY_BARTERCAST)
#        mypermid = bartercastdb.my_permid
#
#        if DEBUG:
#
#            top = bartercastdb.getTopNPeers(5)['top']
#
#            print 'My Permid: ', show_permid(mypermid)
#
#            print 'Top 5 BarterCast peers:'
#            print '======================='
#
#            i = 1
#            for (permid, up, down) in top:
#                print '%2d: %15s  -  %10d up  %10d down' % (i, bartercastdb.getName(permid), up, down)
#                i += 1

        self.checkVersion()

        # If the user passed a torrentfile on the cmdline, load it.
        wx.CallAfter(self.startCMDLineTorrent)

        # ProxyService 90s Test_
        from Tribler.Core.Session import Session
        session = Session.get_instance()
        session.uch.notify(NTFY_GUI_STARTED, NTFY_INSERT, None, None)
Exemple #51
0
 def getFamilyFilter(self):
     catobj = Category.getInstance()
     return catobj.family_filter_enabled()
    def __init__(self, parent, channelonly, internalvideo, progress):
        # Do all init here
        self.guiUtility = GUIUtility.getInstance()
        self.guiUtility.frame = self
        self.utility = self.guiUtility.utility
        self.params = self.guiUtility.params
        self.utility.frame = self
        self.torrentfeed = None
        self.category = Category.getInstance()
        self.shutdown_and_upgrade_notes = None
        
        self.guiserver = GUITaskQueue.getInstance()
        
        title = self.utility.lang.get('title') + \
                " " + \
                self.utility.lang.get('version')
        
        # Get window size and position from config file
        size, position = self.getWindowSettings()
        style = wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.RESIZE_BORDER|wx.NO_FULL_REPAINT_ON_RESIZE|wx.CLIP_CHILDREN
            
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, position, size, style)
        if sys.platform == 'linux2':
            font = self.GetFont()
            if font.GetPointSize() > 9:
                font.SetPointSize(9)
                self.SetFont(font)
                
        self.Freeze()
        self.SetDoubleBuffered(True)
        self.SetBackgroundColour(DEFAULT_BACKGROUND)
        
        themeColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        r, g, b = themeColour.Get(False)
        if r > 190 or g > 190 or b > 190: #Grey == 190,190,190
            self.SetForegroundColour(wx.BLACK)
            
        #Create all components        
        progress('Creating panels')
        if not channelonly:
            self.top_bg = TopSearchPanel(self)
            
            self.home = Home(self)
        
            #build channelselector panel
            self.channelselector = wx.BoxSizer(wx.VERTICAL)
            self.channelcategories = ChannelCategoriesList(self)
            quicktip = HtmlWindow(self)
            quicktip.SetBorders(2)
            self.channelcategories.SetQuicktip(quicktip)

            self.channelselector.Add(self.channelcategories, 0, wx.EXPAND)
            self.channelselector.Add(quicktip, 1, wx.EXPAND)
            self.channelselector.AddStretchSpacer()
            self.channelselector.ShowItems(False)
        
            self.searchlist = SearchList(self)
            self.searchlist.Show(False)
            
            self.channellist = ChannelList(self)
            self.channellist.Show(False)
        else:
            self.top_bg = None
            
            self.guiUtility.guiPage = 'selectedchannel'
            self.home = None
            self.channelselector = None
            self.channelcategories = None
            self.searchlist = None
            self.channellist = None
        
        self.stats = Stats(self)
        self.stats.Show(False)
        self.selectedchannellist = SelectedChannelList(self)
        self.selectedchannellist.Show(bool(channelonly))
        self.playlist = Playlist(self)
        self.playlist.Show(False)
        
        self.managechannel = ManageChannel(self)
        self.managechannel.Show(False)
        self.librarylist = LibraryList(self)
        self.librarylist.Show(False)
        
        if internalvideo:
            self.videoparentpanel = wx.Panel(self)
            self.videoparentpanel.Hide()
        else:
            self.videoparentpanel = None
        
        progress('Positioning')
        
        if not channelonly:
            #position all elements            
            vSizer = wx.BoxSizer(wx.VERTICAL)
            
            vSizer.Add(self.top_bg, 0, wx.EXPAND)
            hSizer = wx.BoxSizer(wx.HORIZONTAL)
            vSizer.Add(hSizer, 1, wx.EXPAND|wx.ALL, 5)
            
            hSizer.Add(self.home, 1, wx.EXPAND|wx.ALL, 20)
            hSizer.Add(self.stats, 1, wx.EXPAND|wx.ALL, 20)
            hSizer.Add(self.channelselector, 0, wx.EXPAND|wx.RIGHT, 5)
            hSizer.Add(self.channellist, 1, wx.EXPAND)
            hSizer.Add(self.searchlist, 1, wx.EXPAND)
            
        else:
            vSizer = wx.BoxSizer(wx.VERTICAL) 
            hSizer = wx.BoxSizer(wx.HORIZONTAL)
            vSizer.Add(hSizer, 1, wx.EXPAND|wx.ALL, 5)
            
            self.top_bg = TopSearchPanelStub()
            
        hSizer.Add(self.selectedchannellist, 1, wx.EXPAND)
        hSizer.Add(self.playlist, 1, wx.EXPAND)
        hSizer.Add(self.managechannel, 1, wx.EXPAND)
        hSizer.Add(self.librarylist, 1, wx.EXPAND)
        
        if self.videoparentpanel:
            hSizer.Add(self.videoparentpanel, 0, wx.LEFT, 5)
        
        self.SetSizer(vSizer)
        
        #set sizes
        if not channelonly:
            self.top_bg.SetMinSize((-1,70))
            self.channelselector.SetMinSize((110,-1))
            quicktip.SetMinSize((-1,300))
        
        if self.videoparentpanel:
            self.videoparentpanel.SetSize((320,500))
        
        self.SRstatusbar = SRstatusbar(self)
        self.SetStatusBar(self.SRstatusbar)
        
        if not channelonly:
            self.channelcategories.Select(1, False)
        
        def preload_data():
            if not channelonly:
                self.guiUtility.showChannelCategory('Popular', False)
            self.guiUtility.showLibrary(False)
            
        wx.CallLater(1500, preload_data)
        if channelonly:
            self.guiUtility.showChannelFromDispCid(channelonly)
            if not self.guiUtility.useExternalVideo:
                self.guiUtility.ShowPlayer(True)

        if sys.platform != 'darwin':
            dragdroplist = FileDropTarget(self)
            self.SetDropTarget(dragdroplist)
        try:
            self.SetIcon(self.utility.icon)
        except:
            pass
        
        self.tbicon = None        
        try:
            self.tbicon = ABCTaskBarIcon(self)
        except:
            print_exc()

        # Don't update GUI as often when iconized
        self.GUIupdate = True
        self.window = self.GetChildren()[0]
        self.window.utility = self.utility

        progress('Binding events')        
        # Menu Events 
        ############################
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # leaving here for the time being:
        # wxMSW apparently sends the event to the App object rather than
        # the top-level Frame, but there seemed to be some possibility of
        # change
        self.Bind(wx.EVT_QUERY_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_END_SESSION, self.OnCloseWindow)
        self.Bind(wx.EVT_ICONIZE, self.onIconify)
        self.Bind(wx.EVT_SIZE, self.onSize)
        self.Bind(wx.EVT_MAXIMIZE, self.onSize)
        
        findId = wx.NewId()
        quitId = wx.NewId()
        nextId = wx.NewId()
        prevId = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnFind, id = findId)
        self.Bind(wx.EVT_MENU, lambda event: self.Close(), id = quitId)
        self.Bind(wx.EVT_MENU, self.OnNext, id = nextId)
        self.Bind(wx.EVT_MENU, self.OnPrev, id = prevId)
        
        accelerators = [(wx.ACCEL_CTRL, ord('f'), findId)]
        accelerators.append((wx.ACCEL_CTRL, wx.WXK_TAB, nextId))
        accelerators.append((wx.ACCEL_CTRL|wx.ACCEL_SHIFT, wx.WXK_TAB, prevId))
        if sys.platform == 'linux2':
            accelerators.append((wx.ACCEL_CTRL, ord('q'), quitId))
            accelerators.append((wx.ACCEL_CTRL, ord('/'), findId))
        self.SetAcceleratorTable(wx.AcceleratorTable(accelerators))

        # Init video player
        sys.stdout.write('GUI Complete.\n')
        self.Thaw()
        self.ready = True
        
        # Just for debugging: add test permids and display top 5 peers from which the most is downloaded in bartercastdb
#        bartercastdb = self.utility.session.open_dbhandler(NTFY_BARTERCAST)
#        mypermid = bartercastdb.my_permid
#        
#        if DEBUG:
#            
#            top = bartercastdb.getTopNPeers(5)['top']
#    
#            print 'My Permid: ', show_permid(mypermid)
#            
#            print 'Top 5 BarterCast peers:'
#            print '======================='
#    
#            i = 1
#            for (permid, up, down) in top:
#                print '%2d: %15s  -  %10d up  %10d down' % (i, bartercastdb.getName(permid), up, down)
#                i += 1
        
        
        def post():
            self.checkVersion()
            self.startCMDLineTorrent()

        # If the user passed a torrentfile on the cmdline, load it.
        wx.CallAfter(post)
Exemple #53
0
 def getFamilyFilter(self):
     catobj = Category.getInstance()
     return catobj.family_filter_enabled()  
Exemple #54
0
    def register(self, session, sesslock):
        if not self.registered:
            self.registered = True

            self.session = session
            self.sesslock = sesslock

            self.downloads = {}
            config = session.sessconfig  # Should be safe at startup

            self.upnp_ports = []

            # Orig
            self.sessdoneflag = Event()

            self.rawserver = RawServer(self.sessdoneflag,
                                       config['timeout_check_interval'],
                                       config['timeout'],
                                       ipv6_enable=config['ipv6_enabled'],
                                       failfunc=self.rawserver_fatalerrorfunc,
                                       errorfunc=self.rawserver_nonfatalerrorfunc)
            self.rawserver.add_task(self.rawserver_keepalive, 1)
            self.listen_port = config['minport']
            self.shutdownstarttime = None

            self.multihandler = MultiHandler(self.rawserver, self.sessdoneflag)

            # SWIFTPROC
            swift_exists = config['swiftproc'] and (os.path.exists(config['swiftpath']) or os.path.exists(config['swiftpath'] + '.exe'))
            if swift_exists:
                from Tribler.Core.Swift.SwiftProcessMgr import SwiftProcessMgr

                self.spm = SwiftProcessMgr(config['swiftpath'], config['swiftcmdlistenport'], config['swiftdlsperproc'], self.session.get_swift_tunnel_listen_port(), self.sesslock)
                try:
                    self.swift_process = self.spm.get_or_create_sp(self.session.get_swift_working_dir(), self.session.get_torrent_collecting_dir(), self.session.get_swift_tunnel_listen_port(), self.session.get_swift_tunnel_httpgw_listen_port(), self.session.get_swift_tunnel_cmdgw_listen_port())
                    self.upnp_ports.append((self.session.get_swift_tunnel_listen_port(), 'UDP'))

                except OSError:
                    # could not find/run swift
                    print >> sys.stderr, "lmc: could not start a swift process"

            else:
                self.spm = None
                self.swift_process = None

            # Dispersy
            self.session.dispersy_member = None
            if config['dispersy']:
                from Tribler.dispersy.callback import Callback
                from Tribler.dispersy.dispersy import Dispersy
                from Tribler.dispersy.endpoint import RawserverEndpoint, TunnelEndpoint
                from Tribler.dispersy.community import HardKilledCommunity

                # set communication endpoint
                if config['dispersy-tunnel-over-swift'] and self.swift_process:
                    endpoint = TunnelEndpoint(self.swift_process)
                else:
                    endpoint = RawserverEndpoint(self.rawserver, config['dispersy_port'])

                callback = Callback("Dispersy")  # WARNING NAME SIGNIFICANT
                working_directory = unicode(config['state_dir'])

                self.dispersy = Dispersy(callback, endpoint, working_directory)

                # TODO: see if we can postpone dispersy.start to improve GUI responsiveness.
                # However, for now we must start self.dispersy.callback before running
                # try_register(nocachedb, self.database_thread)!

                self.dispersy.start()

                print >> sys.stderr, "lmc: Dispersy is listening on port", self.dispersy.wan_address[1], "using", endpoint
                self.upnp_ports.append((self.dispersy.wan_address[1], 'UDP'))

                self.dispersy.callback.call(self.dispersy.define_auto_load, args=(HardKilledCommunity,), kargs={'load': True})

                # notify dispersy finished loading
                self.session.uch.notify(NTFY_DISPERSY, NTFY_STARTED, None)

                from Tribler.Core.permid import read_keypair
                from Tribler.dispersy.crypto import ec_to_public_bin, ec_to_private_bin
                keypair = read_keypair(self.session.get_permid_keypair_filename())
                self.session.dispersy_member = callback.call(self.dispersy.get_member, (ec_to_public_bin(keypair), ec_to_private_bin(keypair)))

                self.database_thread = callback
            else:
                class FakeCallback():
                    def __init__(self):
                        from Tribler.Utilities.TimedTaskQueue import TimedTaskQueue
                        self.queue = TimedTaskQueue("FakeCallback")

                    def register(self, call, args=(), kargs=None, delay=0.0, priority=0, id_=u"", callback=None, callback_args=(), callback_kargs=None, include_id=False):
                        def do_task():
                            if kargs:
                                call(*args, **kargs)
                            else:
                                call(*args)

                            if callback:
                                if callback_kargs:
                                    callback(*callback_args, **callback_kargs)
                                else:
                                    callback(*callback_args)
                        self.queue.add_task(do_task, t=delay)

                    def shutdown(self, immediately=False):
                        self.queue.shutdown(immediately)

                self.database_thread = FakeCallback()

            if config['megacache']:
                import Tribler.Core.CacheDB.cachedb as cachedb
                from Tribler.Core.CacheDB.SqliteCacheDBHandler import PeerDBHandler, TorrentDBHandler, MyPreferenceDBHandler, VoteCastDBHandler, ChannelCastDBHandler, NetworkBuzzDBHandler, UserEventLogDBHandler
                from Tribler.Category.Category import Category
                from Tribler.Core.Tag.Extraction import TermExtraction
                from Tribler.Core.CacheDB.sqlitecachedb import try_register

                if DEBUG:
                    print >> sys.stderr, 'tlm: Reading Session state from', config['state_dir']

                nocachedb = cachedb.init(config, self.rawserver_fatalerrorfunc)
                try_register(nocachedb, self.database_thread)

                self.cat = Category.getInstance(config['install_dir'])
                self.term = TermExtraction.getInstance(config['install_dir'])

                self.peer_db = PeerDBHandler.getInstance()
                self.peer_db.registerConnectionUpdater(self.session)

                self.torrent_db = TorrentDBHandler.getInstance()
                self.torrent_db.register(os.path.abspath(config['torrent_collecting_dir']))
                self.mypref_db = MyPreferenceDBHandler.getInstance()
                self.votecast_db = VoteCastDBHandler.getInstance()
                self.votecast_db.registerSession(self.session)
                self.channelcast_db = ChannelCastDBHandler.getInstance()
                self.channelcast_db.registerSession(self.session)
                self.nb_db = NetworkBuzzDBHandler.getInstance()
                self.ue_db = UserEventLogDBHandler.getInstance()

                if self.dispersy:
                    self.dispersy.database.attach_commit_callback(self.channelcast_db._db.commitNow)
            else:
                config['torrent_checking'] = 0

            self.rtorrent_handler = None
            if config['torrent_collecting']:
                from Tribler.Core.RemoteTorrentHandler import RemoteTorrentHandler
                self.rtorrent_handler = RemoteTorrentHandler()