def __init__(self, torrent_id, infohash, swift_hash, swift_torrent_hash,
                 name, torrent_file_name, length, category_id, status_id,
                 num_seeders, num_leechers, channel):
        self._torrent_id = torrent_id
        self.infohash = infohash
        self.swift_hash = swift_hash
        self.swift_torrent_hash = swift_torrent_hash
        self.torrent_file_name = torrent_file_name
        self.name = name
        self.length = length or 0
        self.category_id = category_id
        self.status_id = status_id

        self.num_seeders = num_seeders or 0
        self.num_leechers = num_leechers or 0

        self._channel = channel

        self.channeltorrents_id = None
        self.torrent_db = None
        self.channelcast_db = None

        self.relevance_score = None
        self.query_candidates = None
        self._progress = None
        self.dslist = None
        self.magnetstatus = None

        self.udc = UserDownloadChoice.get_singleton()
Example #2
0
    def __init__(self, torrent_id, infohash, swift_hash, swift_torrent_hash, name, torrent_file_name, length, category_id, status_id, num_seeders, num_leechers, channel):
        self._torrent_id = torrent_id
        self.infohash = infohash
        self.swift_hash = swift_hash
        self.swift_torrent_hash = swift_torrent_hash
        self.torrent_file_name = torrent_file_name
        self.name = name
        self.length = length or 0
        self.category_id = category_id
        self.status_id = status_id

        self.num_seeders = num_seeders or 0
        self.num_leechers = num_leechers or 0

        self._channel = channel

        self.channeltorrents_id = None
        self.torrent_db = None
        self.channelcast_db = None

        self.relevance_score = None
        self.query_candidates = None
        self._progress = None
        self.dslist = None
        self.magnetstatus = None

        self.udc = UserDownloadChoice.get_singleton()
Example #3
0
    def loadSessionCheckpoint(self):
        # Niels: first remove all "swift" torrent collect checkpoints
        dir = self.utility.session.get_downloads_pstate_dir()
        coldir = os.path.basename(os.path.abspath(self.utility.session.get_torrent_collecting_dir()))

        filelist = os.listdir(dir)
        filelist = [os.path.join(dir, filename) for filename in filelist if filename.endswith('.pickle')]

        for file in filelist:
            try:
                pstate = self.utility.session.lm.load_download_pstate(file)
                dlconfig = pstate['dlconfig']

                if dlconfig.get('saveas', ''):
                    destdir = os.path.basename(dlconfig['saveas'])
                    if destdir == coldir:
                        os.remove(file)
            except:
                pass

        from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
        user_download_choice = UserDownloadChoice.get_singleton()
        initialdlstatus_dict = {}
        for id, state in user_download_choice.get_download_states().iteritems():
            if state == 'stop':
                initialdlstatus_dict[id] = DLSTATUS_STOPPED

        self.utility.session.load_checkpoint(initialdlstatus_dict=initialdlstatus_dict)
Example #4
0
    def GetContextMenu(self):
        menu = DoubleLineListItem.GetContextMenu(self)
        
        menu_items = [('Add to my channel', self.OnAddToMyChannel)] if 'seeding' in self.original_data.state else []
        menu_items += [None, ('Explore files', self.OnExplore)]
        menu_items += [('Change download location..', self.OnMove)] if self.original_data.infohash else []
        menu_items += [('Force recheck', self.OnRecheck)] if 'metadata' not in self.original_data.state and 'checking' not in self.original_data.state else []
        
        for item in menu_items:
            if not item:
                menu.AppendSeparator()
            else:
                label, handler = item
                itemid = wx.NewId()
                menu.Append(itemid, label)
                menu.Bind(wx.EVT_MENU, handler, id=itemid)

        if 'completed' in self.original_data.state or 'seeding' in self.original_data.state:
            torrent = self.original_data
            tdef = torrent.ds.get_download().get_def() if torrent.ds else None
            if tdef and tdef.get_def_type() == 'torrent':
                is_forced = UserDownloadChoice.get_singleton().get_download_state(tdef.get_id()) == 'restartseed'
                itemid = wx.NewId()
                menu.AppendCheckItem(itemid, 'Force seed')
                menu.Check(itemid, is_forced)
                menu.Bind(wx.EVT_MENU, lambda evt, force_seed = not is_forced: self.OnSeed(evt, force_seed), id=itemid)
        
        return menu
    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()
Example #6
0
    def restart_other_downloads(self, download_state_list):
        if len(download_state_list) == 0:
            return
        
        def get_vod_download_status(default):
            for download_state in download_state_list:
                if self.vod_download == download_state.get_download():
                    return download_state.get_status()
            return default

        if self.resume_by_system:
            # resume when there is no VOD download
            if self.vod_download is None:
                self.resume_by_system += 1
                if DEBUG: print >> sys.stderr, "VideoPlayer: restart_other_downloads: Resume because vod_download is None", "(%d)" % self.resume_by_system

            # resume when the VOD download is not part of download_state_list
            elif not self.vod_download in [download_state.get_download() for download_state in download_state_list]:
                self.resume_by_system += 1
                if DEBUG:
                    print >> sys.stderr, "VideoPlayer: restart_other_downloads: Resume because", `self.vod_download.get_def().get_name()`, "not in list", "(%d)" % self.resume_by_system
                    print >> sys.stderr, "VideoPlayer: list:", `[download_state.get_download().get_def().get_name() for download_state in download_state_list]`

            # resume when the VOD download has finished downloading
            elif not get_vod_download_status(DLSTATUS_ALLOCATING_DISKSPACE) in (DLSTATUS_ALLOCATING_DISKSPACE, DLSTATUS_WAITING4HASHCHECK, DLSTATUS_HASHCHECKING, DLSTATUS_DOWNLOADING):
                self.resume_by_system += 1
                if DEBUG:
                    print >> sys.stderr, "VideoPlayer: restart_other_downloads: Resume because vod_download_status is inactive", "(%d)" % self.resume_by_system
                    print >> sys.stderr, "VideoPlayer: status:", dlstatus_strings[get_vod_download_status(DLSTATUS_ALLOCATING_DISKSPACE)]

            # otherwise we do not resume
            else:
                self.resume_by_system = 1

            # because of threading issues it is possible that we have
            # false positives. therefore we will only resume torrents
            # after we checked 2 times (once every second)
            if self.resume_by_system > 2:
                self.resume_by_system = 0

                # sometimes the self.vod_download stays set to a
                # download class that is no longer downloading
                self.set_vod_download(None)

                for download_state in download_state_list:
                    download = download_state.get_download()
                    content_def = download.get_def()
                    infohash = content_def.get_id()
                    
                    from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
                    self.user_download_choice = UserDownloadChoice.get_singleton()
                    user_state = self.user_download_choice.get_download_state(infohash)

                    # resume a download unless the user explisitly
                    # stopped the download
                    if not user_state == "stop":
                        if DEBUG: print >> sys.stderr, "VideoPlayer: restart_other_downloads: Restarting", `download.get_def().get_name()`
                        download.set_mode(DLMODE_NORMAL)
                        download.restart()
Example #7
0
 def do_gui(delayedResult):
     choices, dstates, infohashes = delayedResult.get()
     user_download_choice = UserDownloadChoice.get_singleton()
     
     if len(choices) > 0:
         message = 'Please select all torrents which should be '
         if start:
             message += 'started.'
         else:
             message += 'stopped.'
         message += "\nUse ctrl+a to select all/deselect all."
         
         def bindAll(control):
             control.Bind(wx.EVT_KEY_DOWN, lambda event: self._SelectAll(dlg, event, len(choices)))
             func = getattr(control, 'GetChildren', False)
             if func:
                 for child in func():
                     bindAll(child)
         
         dlg = wx.MultiChoiceDialog(self, message, 'Select torrents', choices)
         dlg.allselected = False
         bindAll(dlg)
         
         if dlg.ShowModal() == wx.ID_OK:
             selections = dlg.GetSelections()
             for selection in selections:
                 if start:
                     if dstates[selection]:
                         if isinstance(dstates[selection], MergedDs):
                             for ds in dstates[selection].dslist:
                                 ds.get_download().restart()
                         else:
                             dstates[selection].get_download().restart()
                         
                         
                     user_download_choice.set_download_state(infohashes[selection], "restart")
                     
                 else:
                     if dstates[selection]:
                         if isinstance(dstates[selection], MergedDs):
                             for ds in dstates[selection].dslist:
                                 ds.get_download().stop()
                         else:
                             dstates[selection].get_download().stop()
                     
                     user_download_choice.set_download_state(infohashes[selection], "stop")
                     
             user_download_choice.flush()
     else:
         message = "No torrents in library which could be "
         if start:
             message += "started."
         else:
             message += "stopped."
         dlg = wx.MessageDialog(self, message, 'No torrents found.', wx.OK | wx.ICON_INFORMATION)
         dlg.ShowModal()
     dlg.Destroy()
Example #8
0
    def loadSessionCheckpoint(self):
        pstate_dir = self.utility.session.get_downloads_pstate_dir()

        filelist = os.listdir(pstate_dir)
        if any([filename.endswith('.pickle') for filename in filelist]):
            convertDownloadCheckpoints(pstate_dir)

        from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
        user_download_choice = UserDownloadChoice.get_singleton()
        initialdlstatus_dict = {}
        for infohash, state in user_download_choice.get_download_states().iteritems():
            if state == 'stop':
                initialdlstatus_dict[infohash] = DLSTATUS_STOPPED

        self.utility.session.load_checkpoint(initialdlstatus_dict=initialdlstatus_dict)
Example #9
0
 def do_gui(delayedResult):
     choices, dstates, infohashes = delayedResult.get()
     user_download_choice = UserDownloadChoice.get_singleton()
     
     if len(choices) > 0:
         message = 'Please select all torrents which should be '
         if start:
             message += 'started.'
         else:
             message += 'stopped.'
         message += "\nUse ctrl+a to select all/deselect all."
         
         def bindAll(control):
             control.Bind(wx.EVT_KEY_DOWN, lambda event: self._SelectAll(dlg, event, len(choices)))
             func = getattr(control, 'GetChildren', False)
             if func:
                 for child in func():
                     bindAll(child)
         
         dlg = wx.MultiChoiceDialog(self, message, 'Select torrents', choices)
         dlg.allselected = False
         bindAll(dlg)
         
         if dlg.ShowModal() == wx.ID_OK:
             selections = dlg.GetSelections()
             for selection in selections:
                 if start:
                     if dstates[selection]:
                         dstates[selection].get_download().restart()
                     user_download_choice.set_download_state(infohashes[selection], "restart")
                     
                 else:
                     if dstates[selection]:
                         dstates[selection].get_download().stop()
                     
                     user_download_choice.set_download_state(infohashes[selection], "stop")
                     
             user_download_choice.flush()
     else:
         message = "No torrents in library which could be "
         if start:
             message += "started."
         else:
             message += "stopped."
         dlg = wx.MessageDialog(self, message, 'No torrents found.', wx.OK | wx.ICON_INFORMATION)
         dlg.ShowModal()
     dlg.Destroy()
Example #10
0
    def loadSessionCheckpoint(self):
        pstate_dir = self.utility.session.get_downloads_pstate_dir()

        filelist = os.listdir(pstate_dir)
        if any([filename.endswith('.pickle') for filename in filelist]):
            convertDownloadCheckpoints(pstate_dir)

        from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
        user_download_choice = UserDownloadChoice.get_singleton()
        initialdlstatus_dict = {}
        for infohash, state in user_download_choice.get_download_states(
        ).iteritems():
            if state == 'stop':
                initialdlstatus_dict[infohash] = DLSTATUS_STOPPED

        self.utility.session.load_checkpoint(
            initialdlstatus_dict=initialdlstatus_dict)
Example #11
0
 def __init__(self,guiUtility):
     if LibraryManager.__single:
         raise RuntimeError, "LibraryManager is singleton"
     LibraryManager.__single = self
     self.guiUtility = guiUtility
     
     # Contains all matches for keywords in DB, not filtered by category
     self.hits = []
     
     #current progress of download states
     self.cache_progress = {}
     
     self.rerankingStrategy = DefaultTorrentReranker()
     
     # For asking for a refresh when remote results came in
     self.gridmgr = None
     self.guiserver = GUITaskQueue.getInstance()
     
     # Gui callbacks
     self.gui_callback = []
     
     self.user_download_choice = UserDownloadChoice.get_singleton()
Example #12
0
 def __init__(self, download_state):
     self.download_state = download_state
     self.policy = None
     self.udc = UserDownloadChoice.get_singleton()
Example #13
0
 def OnMultiple(self, start):
     user_download_choice = UserDownloadChoice.get_singleton()
     
     choices = []
     dstates = []
     infohashes = []
     
     self.guiUtility.frame.librarylist.GetManager().refresh()
     items = self.guiUtility.frame.librarylist.GetItems()
     
     def sort_by_name(a, b):
         return cmp(a.original_data['name'], b.original_data['name'])
     
     downloads = items.values()
     downloads.sort(cmp = sort_by_name)
     
     for item in downloads:
         started = False
         ds = item.original_data.get('ds', None)
         if ds and ds.get_status() in [DLSTATUS_SEEDING, DLSTATUS_DOWNLOADING]:
             started = True
             
         if start != started:
             choices.append(item.original_data['name'])
             dstates.append(ds)
             infohashes.append(item.original_data["infohash"])
      
     if len(choices) > 0:
         message = 'Please select all torrents which should be '
         if start:
             message += 'started.'
         else:
             message += 'stopped.'
         message += "\nUse ctrl+a to select all/deselect all."
         
         def bindAll(control):
             control.Bind(wx.EVT_KEY_DOWN, lambda event: self._SelectAll(dlg, event, len(choices)))
             func = getattr(control, 'GetChildren', False)
             if func:
                 for child in func():
                     bindAll(child)
         
         dlg = wx.MultiChoiceDialog(self, message, 'Select torrents', choices)
         dlg.allselected = False
         bindAll(dlg)
         
         if dlg.ShowModal() == wx.ID_OK:
             selections = dlg.GetSelections()
             for selection in selections:
                 if start:
                     if dstates[selection]:
                         dstates[selection].get_download().restart()
                     user_download_choice.set_download_state(infohashes[selection], "restart")
                     
                 else:
                     if dstates[selection]:
                         dstates[selection].get_download().stop()
                     
                     user_download_choice.set_download_state(infohashes[selection], "stop")
     else:
         message = "No torrents in library which could be "
         if start:
             message += "started."
         else:
             message += "stopped."
         dlg = wx.MessageDialog(self, message, 'No torrents found.', wx.OK | wx.ICON_INFORMATION)
         dlg.ShowModal()
     dlg.Destroy()
Example #14
0
    def __init__(self, params, single_instance_checker, installdir):
        self.params = params
        self.single_instance_checker = single_instance_checker
        self.installdir = self.configure_install_dir(installdir)

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

        self.guiserver = GUITaskQueue.getInstance()
        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.seedingmanager = None
        self.i2is = None
        self.torrentfeed = None
        self.webUI = None
        self.utility = None
        self.videoplayer = None

        try:
            bm = wx.Bitmap(os.path.join(self.installdir, 'Tribler', 'Main', 'vwxGUI', 'images', 'splash.png'), wx.BITMAP_TYPE_ANY)
            self.splash = GaugeSplash(bm)
            self.splash.setTicks(10)
            self.splash.Show()

            print >> sys.stderr, 'Client Starting Up.'
            print >> sys.stderr, "Tribler is using", self.installdir, "as working directory"

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

            print >> sys.stderr, "Tribler is expecting swift in", self.sconfig.get_swift_path()

            self.dispersy = s.lm.dispersy

            self.utility = Utility(self.installdir, s.get_state_dir())
            self.utility.app = self
            self.utility.session = s
            self.guiUtility = GUIUtility.getInstance(self.utility, self.params, self)
            GUIDBProducer.getInstance(self.dispersy.callback)

            print >> sys.stderr, 'Tribler Version:', self.utility.lang.get('version'), ' Build:', self.utility.lang.get('build')

            self.splash.tick('Loading userdownloadchoice')
            from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
            UserDownloadChoice.get_singleton().set_session_dir(s.get_state_dir())

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

            state = self.utility.config.Read('family_filter')
            if state in ('1', '0'):
                cat.set_family_filter(state == '1')
            else:
                self.utility.config.Write('family_filter', '1')
                self.utility.config.Flush()

                cat.set_family_filter(True)

            # Create global rate limiter
            self.splash.tick('Setting up ratelimiters')
            self.ratelimiter = UserDefinedMaxAlwaysOtherwiseDividedOverActiveSwarmsRateManager()

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

            # So we know if we asked for peer details last cycle
            self.lastwantpeers = []

            # boudewijn 01/04/2010: hack to fix the seedupload speed that
            # was never used and defaulted to 0 (unlimited upload)
            maxup = self.utility.config.Read('maxuploadrate', "int")
            if maxup == -1:  # no upload
                self.ratelimiter.set_global_max_speed(UPLOAD, 0.00001)
                self.ratelimiter.set_global_max_seedupload_speed(0.00001)
            else:
                self.ratelimiter.set_global_max_speed(UPLOAD, maxup)
                self.ratelimiter.set_global_max_seedupload_speed(maxup)

            maxdown = self.utility.config.Read('maxdownloadrate', "int")
            self.ratelimiter.set_global_max_speed(DOWNLOAD, maxdown)

            self.seedingmanager = GlobalSeedingManager(self.utility.config.Read)

            # 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.
            self.guiserver.add_task(self.guiservthread_checkpoint_timer, SESSION_CHECKPOINT_INTERVAL)

            self.utility.postAppInit(os.path.join(self.installdir, 'Tribler', 'Main', 'vwxGUI', 'images', 'tribler.ico'))

            # Put it here so an error is shown in the startup-error popup
            # Start server for instance2instance communication
            self.i2iconnhandler = InstanceConnectionHandler(self.i2ithread_readlinecallback)
            self.i2is = Instance2InstanceServer(I2I_LISTENPORT, self.i2iconnhandler)
            self.i2is.start()

            # Arno, 2010-01-15: VLC's reading behaviour of doing open-ended
            # Range: GETs causes performance problems in our code. Disable for now.
            # Arno, 2010-01-22: With the addition of a CachingStream the problem
            # is less severe (see VideoPlayer), so keep GET Range enabled.
            #
            # SimpleServer.RANGE_REQUESTS_ENABLED = False

            # Fire up the VideoPlayer, it abstracts away whether we're using
            # an internal or external video player.
            playbackmode = self.utility.config.Read('videoplaybackmode', "int")
            self.videoplayer = VideoPlayer.getInstance(httpport=VIDEOHTTP_LISTENPORT)
            self.videoplayer.register(self.utility, preferredplaybackmode=playbackmode)

            notification_init(self.utility)
            self.guiUtility.register()

            channel_only = os.path.exists(os.path.join(self.installdir, 'joinchannel'))
            if channel_only:
                f = open(os.path.join(self.installdir, 'joinchannel'), 'rb')
                channel_only = f.readline()
                f.close()

            self.frame = MainFrame(None, channel_only, PLAYBACKMODE_INTERNAL in return_feasible_playback_modes(self.utility.getPath()), self.splash.tick)

            # 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(self.utility.getPath()):
                vlcwrap = self.videoplayer.get_vlcwrap()

                self.frame.videoframe = VideoDummyFrame(self.frame.videoparentpanel, self.utility, vlcwrap)
                self.videoplayer.set_videoframe(self.frame.videoframe)

            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)

            self.torrentfeed = RssParser.getInstance()

            self.webUI = None
            if self.utility.config.Read('use_webui', "boolean"):
                try:
                    from Tribler.Main.webUI.webUI import WebUI
                    self.webUI = WebUI.getInstance(self.guiUtility.library_manager, self.guiUtility.torrentsearch_manager, self.utility.config.Read('webui_port', "int"))
                    self.webUI.start()
                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)

            status = get_status_holder("LivingLab")
            status.add_reporter(NullReporter("Periodically remove all events", 0))
# status.add_reporter(LivingLabPeriodicReporter("Living lab CS reporter", 300, "Tribler client")) # Report every 5 minutes
# status.add_reporter(LivingLabPeriodicReporter("Living lab CS reporter", 30, "Tribler client")) # Report every 30 seconds - ONLY FOR TESTING

            # report client version
            status.create_and_add_event("client-startup-version", [self.utility.lang.get("version")])
            status.create_and_add_event("client-startup-build", [self.utility.lang.get("build")])
            status.create_and_add_event("client-startup-build-date", [self.utility.lang.get("build_date")])

            self.ready = True

        except Exception as e:
            self.onError(e)
            return False
Example #15
0
    def sesscb_states_callback(self, dslist):
        if not self.ready:
            return 5.0, []

        wantpeers = []
        self.ratestatecallbackcount += 1
        try:
            # Print stats on Console
            if self.ratestatecallbackcount % 5 == 0:
                for ds in dslist:
                    safename = repr(ds.get_download().get_def().get_name())
                    self._logger.debug(
                        "%s %s %.1f%% dl %.1f ul %.1f n %d",
                        safename,
                        dlstatus_strings[ds.get_status()],
                        100.0 * ds.get_progress(),
                        ds.get_current_speed(DOWNLOAD),
                        ds.get_current_speed(UPLOAD),
                        ds.get_num_peers())
                    if ds.get_status() == DLSTATUS_STOPPED_ON_ERROR:
                        self._logger.error("main: Error: %s", repr(ds.get_error()))
                        download = self.utility.session.lm.downloads.get(ds.get_infohash())
                        if download:
                            download.stop()

                        # show error dialog
                        dlg = wx.MessageDialog(self.frame,
                                               "Download stopped on error: %s" % repr(ds.get_error()),
                                               "Download Error",
                                               wx.OK | wx.ICON_ERROR)
                        dlg.ShowModal()
                        dlg.Destroy()

            # Pass DownloadStates to libaryView
            no_collected_list = [ds for ds in dslist]
            try:
                # Arno, 2012-07-17: Retrieving peerlist for the DownloadStates takes CPU
                # so only do it when needed for display.
                wantpeers.extend(self.guiUtility.library_manager.download_state_callback(no_collected_list))
            except:
                print_exc()

            # Check to see if a download has finished
            newActiveDownloads = []
            doCheckpoint = False
            seeding_download_list = []
            for ds in dslist:
                state = ds.get_status()
                download = ds.get_download()
                tdef = download.get_def()
                safename = tdef.get_name_as_unicode()

                if state == DLSTATUS_DOWNLOADING:
                    newActiveDownloads.append(safename)

                elif state == DLSTATUS_SEEDING:
                    seeding_download_list.append({u'infohash': tdef.get_infohash(),
                                                  u'download': download,
                                                  })

                    if safename in self.prevActiveDownloads:
                        infohash = tdef.get_infohash()

                        self.utility.session.notifier.notify(NTFY_TORRENTS, NTFY_FINISHED, infohash, safename)

                        doCheckpoint = True

                    elif download.get_hops() == 0 and download.get_safe_seeding():
                        self._logger.info("Re-add torrent with default nr of hops to prevent naked seeding")
                        self.utility.session.remove_download(download)

                        # copy the old download_config and change the hop count
                        dscfg = download.copy()
                        dscfg.set_hops(self.utility.read_config('default_number_hops'))

                        # TODO(emilon): That's a hack to work around the fact
                        # that removing a torrent is racy.
                        self.utility.session.lm.threadpool.call(0.5,
                                                                reactor.callInThread,
                                                                self.utility.session.start_download,
                                                                tdef, dscfg)

            self.prevActiveDownloads = newActiveDownloads
            if doCheckpoint:
                self.utility.session.checkpoint()

            if self.utility.read_config(u'seeding_mode') == 'never':
                for data in seeding_download_list:
                    data[u'download'].stop()
                    from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
                    UserDownloadChoice.get_singleton().set_download_state(data[u'infohash'], "stop")

            # Adjust speeds and call TunnelCommunity.monitor_downloads once every 4 seconds
            adjustspeeds = False
            if self.ratestatecallbackcount % 4 == 0:
                adjustspeeds = True

            if adjustspeeds and self.tunnel_community:
                self.tunnel_community.monitor_downloads(dslist)

        except:
            print_exc()

        return 1.0, wantpeers
Example #16
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)
Example #17
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)
Example #18
0
    def sesscb_states_callback(self, dslist):
        if not self.ready:
            return 5.0, []

        wantpeers = []
        self.ratestatecallbackcount += 1
        try:
            # Print stats on Console
            if self.ratestatecallbackcount % 5 == 0:
                for ds in dslist:
                    safename = repr(ds.get_download().get_def().get_name())
                    self._logger.debug("%s %s %.1f%% dl %.1f ul %.1f n %d",
                                       safename,
                                       dlstatus_strings[ds.get_status()],
                                       100.0 * ds.get_progress(),
                                       ds.get_current_speed(DOWNLOAD),
                                       ds.get_current_speed(UPLOAD),
                                       ds.get_num_peers())
                    if ds.get_status() == DLSTATUS_STOPPED_ON_ERROR:
                        self._logger.error("main: Error: %s",
                                           repr(ds.get_error()))
                        download = self.utility.session.lm.downloads.get(
                            ds.get_infohash())
                        if download:
                            download.stop()

                        # show error dialog
                        dlg = wx.MessageDialog(
                            self.frame, "Download stopped on error: %s" %
                            repr(ds.get_error()), "Download Error",
                            wx.OK | wx.ICON_ERROR)
                        dlg.ShowModal()
                        dlg.Destroy()

            # Pass DownloadStates to libaryView
            no_collected_list = [ds for ds in dslist]
            try:
                # Arno, 2012-07-17: Retrieving peerlist for the DownloadStates takes CPU
                # so only do it when needed for display.
                wantpeers.extend(
                    self.guiUtility.library_manager.download_state_callback(
                        no_collected_list))
            except:
                print_exc()

            # Check to see if a download has finished
            newActiveDownloads = []
            doCheckpoint = False
            seeding_download_list = []
            for ds in dslist:
                state = ds.get_status()
                download = ds.get_download()
                tdef = download.get_def()
                safename = tdef.get_name_as_unicode()

                if state == DLSTATUS_DOWNLOADING:
                    newActiveDownloads.append(safename)

                elif state == DLSTATUS_SEEDING:
                    seeding_download_list.append({
                        u'infohash':
                        tdef.get_infohash(),
                        u'download':
                        download,
                    })

                    if safename in self.prevActiveDownloads:
                        infohash = tdef.get_infohash()

                        self.utility.session.notifier.notify(
                            NTFY_TORRENTS, NTFY_FINISHED, infohash, safename)

                        doCheckpoint = True

                    elif download.get_hops(
                    ) == 0 and download.get_safe_seeding():
                        self._logger.info(
                            "Re-add torrent with default nr of hops to prevent naked seeding"
                        )
                        self.utility.session.remove_download(download)

                        # copy the old download_config and change the hop count
                        dscfg = download.copy()
                        dscfg.set_hops(
                            self.utility.read_config('default_number_hops'))

                        # TODO(emilon): That's a hack to work around the fact
                        # that removing a torrent is racy.
                        self.utility.session.lm.threadpool.call(
                            0.5, reactor.callInThread,
                            self.utility.session.start_download, tdef, dscfg)

            self.prevActiveDownloads = newActiveDownloads
            if doCheckpoint:
                self.utility.session.checkpoint()

            if self.utility.read_config(u'seeding_mode') == 'never':
                for data in seeding_download_list:
                    data[u'download'].stop()
                    from Tribler.Main.vwxGUI.UserDownloadChoice import UserDownloadChoice
                    UserDownloadChoice.get_singleton().set_download_state(
                        data[u'infohash'], "stop")

            # Adjust speeds and call TunnelCommunity.monitor_downloads once every 4 seconds
            adjustspeeds = False
            if self.ratestatecallbackcount % 4 == 0:
                adjustspeeds = True

            if adjustspeeds and self.tunnel_community:
                self.tunnel_community.monitor_downloads(dslist)

        except:
            print_exc()

        return 1.0, wantpeers