Example #1
0
    def startDownload(self,torrentfilename,destdir=None,tdef = None, cmdline = False):
        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            if destdir is not None:
                dscfg.set_dest_dir(destdir)
        
            videofiles = tdef.get_files(exts=videoextdefaults)
            
            if tdef.get_live() or (cmdline and len(videofiles) > 0):
                videoplayer = VideoPlayer.getInstance()
                return videoplayer.start_and_play(tdef,dscfg)
            else:
                return self.utility.session.start_download(tdef,dscfg)

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(None,
                                   self.utility.lang.get('duplicate_download_msg'),
                                   self.utility.lang.get('duplicate_download_title'),
                                   wx.OK|wx.ICON_INFORMATION)
            result = dlg.ShowModal()
            dlg.Destroy()

        except Exception,e:
            print_exc()
            self.onWarning(e)
Example #2
0
    def startDownload(self,
                      torrentfilename,
                      destdir=None,
                      tdef=None,
                      cmdline=False):
        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            if destdir is not None:
                dscfg.set_dest_dir(destdir)

            videofiles = tdef.get_files(exts=videoextdefaults)

            if tdef.get_live() or (cmdline and len(videofiles) > 0):
                videoplayer = VideoPlayer.getInstance()
                return videoplayer.start_and_play(tdef, dscfg)
            else:
                return self.utility.session.start_download(tdef, dscfg)

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(
                None, self.utility.lang.get('duplicate_download_msg'),
                self.utility.lang.get('duplicate_download_title'),
                wx.OK | wx.ICON_INFORMATION)
            result = dlg.ShowModal()
            dlg.Destroy()

        except Exception, e:
            print_exc()
            self.onWarning(e)
Example #3
0
 def do_downloadfrommagnet():
     self.guiUtility.showLibrary()
     destdir = DefaultDownloadStartupConfig.getInstance().get_dest_dir()
     self.frame.startDownloadFromMagnet(
         r'magnet:?xt=urn:btih:5ac55cf1b935291f6fc92ad7afd34597498ff2f7&dn=Pioneer+One+S01E01+Xvid-VODO&title=',
         destdir)
     self.Call(120, do_assert)
Example #4
0
    def guiservthread_free_space_check(self):
        if not (self and self.frame and self.frame.SRstatusbar):
            return

        free_space = get_free_space(
            DefaultDownloadStartupConfig.getInstance().get_dest_dir())
        self.frame.SRstatusbar.RefreshFreeSpace(free_space)

        storage_locations = defaultdict(list)
        for download in self.utility.session.get_downloads():
            if download.get_status() == DLSTATUS_DOWNLOADING:
                storage_locations[download.get_dest_dir()].append(download)

        show_message = False
        low_on_space = [
            path for path in storage_locations.keys() if 0 < get_free_space(
                path) < self.utility.read_config('free_space_threshold')
        ]
        for path in low_on_space:
            for download in storage_locations[path]:
                download.stop()
                show_message = True

        if show_message:
            wx.CallAfter(
                wx.MessageBox,
                "Tribler has detected low disk space. Related downloads have been stopped.",
                "Error")

        self.utility.session.lm.threadpool.call_in_thread(
            FREE_SPACE_CHECK_INTERVAL, self.guiservthread_free_space_check)
Example #5
0
 def OnBrowse(self, event):
     dlg = wx.FileDialog(None, "Please select the .torrent file(s).", wildcard = "torrent (*.torrent)|*.torrent", style = wx.FD_OPEN|wx.FD_MULTIPLE)
     
     path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
     dlg.SetPath(path)
     
     if dlg.ShowModal() == wx.ID_OK:
         filenames = dlg.GetPaths()
         dlg.Destroy()
         
         destdir = self.defaultDLConfig.get_dest_dir()
         if self.choose and self.choose.IsChecked():
             destdir = self._GetDestPath()
             if not destdir:
                 return
         
         if getattr(self.frame, 'startDownloads', False):
             self.frame.startDownloads(filenames, fixtorrent = True, destdir = destdir)
         else:
             for filename in filenames:
                 self.frame.startDownload(filename, fixtorrent = True, destdir = destdir)
             
         self.EndModal(wx.ID_OK)
     else:
         dlg.Destroy()
Example #6
0
    def guiservthread_free_space_check(self):
        if not (self and self.frame and self.frame.SRstatusbar):
            return

        free_space = get_free_space(DefaultDownloadStartupConfig.getInstance().get_dest_dir())
        self.frame.SRstatusbar.RefreshFreeSpace(free_space)

        storage_locations = defaultdict(list)
        for download in self.utility.session.get_downloads():
            if download.get_status() == DLSTATUS_DOWNLOADING:
                storage_locations[download.get_dest_dir()].append(download)

        show_message = False
        low_on_space = [
            path for path in storage_locations.keys(
            ) if 0 < get_free_space(
                path) < self.utility.read_config(
                'free_space_threshold')]
        for path in low_on_space:
            for download in storage_locations[path]:
                download.stop()
                show_message = True

        if show_message:
            wx.CallAfter(wx.MessageBox, "Tribler has detected low disk space. Related downloads have been stopped.",
                         "Error")

        self.utility.session.lm.threadpool.call_in_thread(FREE_SPACE_CHECK_INTERVAL, self.guiservthread_free_space_check)
Example #7
0
 def do_downloadfromurl():
     self.guiUtility.showLibrary()
     destdir = DefaultDownloadStartupConfig.getInstance().get_dest_dir()
     self.frame.startDownloadFromUrl(
         r'http://www.clearbits.net/get/1678-zenith-part-1.torrent',
         destdir)
     self.Call(30, do_assert)
Example #8
0
 def OnBrowse(self, event):
     dlg = wx.FileDialog(None, "Please select the .torrent file(s).", wildcard = "torrent (*.torrent)|*.torrent", style = wx.FD_OPEN|wx.FD_MULTIPLE)
     
     path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
     dlg.SetPath(path)
     
     if dlg.ShowModal() == wx.ID_OK:
         filenames = dlg.GetPaths()
         dlg.Destroy()
         
         destdir = self.defaultDLConfig.get_dest_dir()
         if self.choose and self.choose.IsChecked():
             destdir = self._GetDestPath()
             if not destdir:
                 return
         
         if getattr(self.frame, 'startDownloads', False):
             self.frame.startDownloads(filenames, fixtorrent = True, destdir = destdir)
         else:
             for filename in filenames:
                 self.frame.startDownload(filename, fixtorrent = True, destdir = destdir)
             
         self.EndModal(wx.ID_OK)
     else:
         dlg.Destroy()
    def _create_and_reseed(self, session):
        # 1. Create a 500K randomdata file
        storagepath = os.path.join(self.getDestDir(), "output_file")
        with open(storagepath, 'wb') as fout:
            fout.write(os.urandom(512000))

        # 2. Create the SwiftDef
        sdef = SwiftDef()
        sdef.set_tracker("127.0.0.1:%d" % session.get_swift_dht_listen_port())
        sdef.add_content(storagepath)
        sdef.finalize(session.get_swift_path(), destdir=self.getDestDir())

        # 3. Save swift files to metadata dir
        metadir = session.get_swift_meta_dir()
        metapath = os.path.join(metadir, "output_file")
        try:
            move(storagepath + '.mhash', metapath + '.mhash')
            move(storagepath + '.mbinmap', metapath + '.mbinmap')
        except:
            print_exc()

        # 4. Start seeding this file
        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        dscfg = defaultDLConfig.copy()
        dscfg.set_dest_dir(storagepath)
        d = session.start_download(sdef, dscfg)
        d.set_state_callback(self.seeder_state_callback)

        return sdef.get_id()
Example #10
0
    def _create_and_reseed(self, session):
        # 1. Create a 500K randomdata file
        storagepath = os.path.join(self.getDestDir(), "output_file")
        with open(storagepath, 'wb') as fout:
            fout.write(os.urandom(512000))

        # 2. Create the SwiftDef
        sdef = SwiftDef()
        sdef.set_tracker("127.0.0.1:%d" % session.get_swift_dht_listen_port())
        sdef.add_content(storagepath)
        sdef.finalize(session.get_swift_path(), destdir=self.getDestDir())

        # 3. Save swift files to metadata dir
        metadir = session.get_swift_meta_dir()
        metapath = os.path.join(metadir, "output_file")
        try:
            move(storagepath + '.mhash', metapath + '.mhash')
            move(storagepath + '.mbinmap', metapath + '.mbinmap')
        except:
            print_exc()

        # 4. Start seeding this file
        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        dscfg = defaultDLConfig.copy()
        dscfg.set_dest_dir(storagepath)
        d = session.start_download(sdef, dscfg)
        d.set_state_callback(self.seeder_state_callback)

        return sdef.get_id()
Example #11
0
 def do_download():
     self.screenshot('After doing vodo search + pioneer filter + selecting item')
     
     defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
     defaultDLConfig.set_show_saveas(False)
 
     self.frame.top_bg.OnDownload()
     self.CallConditional(120, lambda: self.frame.librarylist.GetNrResults() > 0, do_assert, 'no download in librarylist')
    def __init__(self, remote_th, session):
        Requester.__init__(self, remote_th.scheduletask, 0)

        self.remote_th = remote_th
        self.session = session

        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        self.dscfg = defaultDLConfig.copy()
        self.dscfg.set_dest_dir(session.get_torrent_collecting_dir())
 def do_vod():
     defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
     defaultDLConfig.set_show_saveas(False)            
     
     self.frame.params = [r'http://www.clearbits.net/get/8-blue---a-short-film.torrent', os.path.join('Content', 'blue-a-short-film-divx.avi')]
     self.frame.startCMDLineTorrent()
     self.guiUtility.ShowPlayer()
     
     self.Call(30, do_monitor)
Example #14
0
def convertDefaultDownloadConfig(oldfilename, newfilename):
    # Convert tribler <= 6.2 default download config file to tribler 6.3

    # We assume oldfilename exists
    with open(oldfilename, "rb") as f:
        dlconfig = pickle.load(f)

    # Upgrade to new config
    ddsconfig = DefaultDownloadStartupConfig()
    for key, value in dlconfig.iteritems():
        if key in ['saveas', 'max_upload_rate', 'max_download_rate', 'super_seeder', 'mode', 'selected_files',
                   'correctedfilename']:
            ddsconfig.dlconfig.set('downloadconfig', key, value)

    # Save the new file, remove the old one
    ddsconfig.save(newfilename)
    os.remove(oldfilename)
    return ddsconfig
        def do_start():
            self.guiUtility.showLibrary()

            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            defaultDLConfig.set_show_saveas(False)

            self.frame.params = [r'http://www.clearbits.net/get/1763-zenith-part-2.torrent']
            self.frame.startCMDLineTorrent()
            self.Call(60, do_stop)
    def __init__(self, remote_th, magnet_requester, session, prio):
        Requester.__init__(self, remote_th.scheduletask, prio)

        self.remote_th = remote_th
        self.magnet_requester = magnet_requester
        self.session = session

        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        self.dscfg = defaultDLConfig.copy()
        self.dscfg.set_dest_dir(session.get_torrent_collecting_dir())
Example #17
0
    def setupConfig(self):
        self.configfilepath = os.path.join(self.getConfigPath(), STATEDIR_GUICONFIG)
        self.config = CallbackConfigParser()

        # Load the config file.
        if os.path.exists(self.configfilepath):
            self.config.read_file(self.configfilepath, 'utf-8-sig')

        if not self.config.has_section('Tribler'):
            self.config.add_section('Tribler')

        # Tribler.conf also contains the default download config. So we need to merge it now.
        if not self.config.has_section('downloadconfig'):
            self.config.add_section('downloadconfig')
            for k, v in DefaultDownloadStartupConfig.getInstance().dlconfig._sections['downloadconfig'].iteritems():
                self.config.set('downloadconfig', k, v)

        # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig.
        DefaultDownloadStartupConfig.getInstance().dlconfig = self.config
Example #18
0
    def __init__(self, remote_th, session):
        Requester.__init__(self, remote_th.scheduletask, 0)

        self.remote_th = remote_th
        self.session = session

        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        self.dscfg = defaultDLConfig.copy()
        self.dscfg.set_dest_dir(session.get_torrent_collecting_dir())
        self.dscfg.set_swift_meta_dir(session.get_torrent_collecting_dir())
Example #19
0
        def do_start():
            self.guiUtility.showLibrary()

            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            defaultDLConfig.set_show_saveas(False)

            self.frame.params = [
                r'http://www.clearbits.net/get/1763-zenith-part-2.torrent'
            ]
            self.frame.startCMDLineTorrent()
            self.Call(60, do_stop)
        def do_download():
            self.screenshot(
                'After doing vodo search + pioneer filter + selecting item')

            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            defaultDLConfig.set_show_saveas(False)

            self.frame.top_bg.OnDownload()
            self.CallConditional(
                120, lambda: self.frame.librarylist.GetNrResults() > 0,
                do_assert, 'no download in librarylist')
Example #21
0
    def __init__(self, remote_th, magnet_requester, session, prio):
        Requester.__init__(self, remote_th.scheduletask, prio)

        self.remote_th = remote_th
        self.magnet_requester = magnet_requester
        self.session = session

        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        self.dscfg = defaultDLConfig.copy()
        self.dscfg.set_dest_dir(session.get_torrent_collecting_dir())
        self.dscfg.set_swift_meta_dir(session.get_torrent_collecting_dir())
Example #22
0
    def setupConfig(self):
        self.configfilepath = os.path.join(self.getConfigPath(),
                                           STATEDIR_GUICONFIG)
        self.config = CallbackConfigParser()

        # Load the config file.
        if os.path.exists(self.configfilepath):
            self.config.read_file(self.configfilepath, 'utf-8-sig')

        if not self.config.has_section('Tribler'):
            self.config.add_section('Tribler')

        # Tribler.conf also contains the default download config. So we need to merge it now.
        if not self.config.has_section('downloadconfig'):
            self.config.add_section('downloadconfig')
            for k, v in DefaultDownloadStartupConfig.getInstance(
            ).dlconfig._sections['downloadconfig'].iteritems():
                self.config.set('downloadconfig', k, v)

        # Make sure we use the same ConfigParser instance for both Utility and DefaultDownloadStartupConfig.
        DefaultDownloadStartupConfig.getInstance().dlconfig = self.config
Example #23
0
        def do_vod():
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            defaultDLConfig.set_show_saveas(False)

            self.frame.params = [
                r'http://www.clearbits.net/get/8-blue---a-short-film.torrent',
                os.path.join('Content', 'blue-a-short-film-divx.avi')
            ]
            self.frame.startCMDLineTorrent()
            self.guiUtility.ShowPlayer()

            self.Call(30, do_monitor)
Example #24
0
    def __init__(self):
        super(SettingsDialog, self).__init__(None, size=(600, 600),
                                             title="Settings", name="settingsDialog", style=wx.DEFAULT_DIALOG_STYLE)
        self.SetExtraStyle(self.GetExtraStyle() | wx.WS_EX_VALIDATE_RECURSIVELY)
        self._logger = logging.getLogger(self.__class__.__name__)

        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        # create the dialog and widgets
        self._tree_ctrl = wx.TreeCtrl(self,
                                      style=wx.TR_DEFAULT_STYLE | wx.SUNKEN_BORDER | wx.TR_HIDE_ROOT | wx.TR_SINGLE)
        self._tree_ctrl.SetMinSize(wx.Size(150, -1))
        tree_root = self._tree_ctrl.AddRoot('Root')
        self._tree_ctrl.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnSelectionChanging)

        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(self._tree_ctrl, 0, wx.EXPAND | wx.RIGHT, 10)

        self._general_panel, self._general_id = self.__create_s1(tree_root, hsizer)
        self._conn_panel, self._conn_id = self.__create_s2(tree_root, hsizer)
        self._bandwidth_panel, self._bandwidth_id = self.__create_s3(tree_root, hsizer)
        self._seeding_panel, self._seeding_id = self.__create_s4(tree_root, hsizer)
        self._experimental_panel, self._experimental_id = self.__create_s5(tree_root, hsizer)
        self._tunnel_panel, self._tunnel_id = self.__create_s6(tree_root, hsizer)

        self._general_panel.Show(True)
        self._conn_panel.Show(False)
        self._bandwidth_panel.Show(False)
        self._seeding_panel.Show(False)
        self._experimental_panel.Show(False)
        self._tunnel_panel.Show(False)

        self._save_btn = wx.Button(self, wx.ID_OK, label="Save")
        self._cancel_btn = wx.Button(self, wx.ID_CANCEL, label="Cancel")

        btn_sizer = wx.StdDialogButtonSizer()
        btn_sizer.AddButton(self._save_btn)
        btn_sizer.AddButton(self._cancel_btn)
        btn_sizer.Realize()

        self._save_btn.Bind(wx.EVT_BUTTON, self.saveAll)
        self._cancel_btn.Bind(wx.EVT_BUTTON, self.cancelAll)

        vsizer = wx.BoxSizer(wx.VERTICAL)
        vsizer.Add(hsizer, 1, wx.EXPAND | wx.ALL, 10)
        vsizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizer(vsizer)

        # select General page by default
        self._tree_ctrl.SelectItem(self._general_id)
Example #25
0
 def OnBrowse(self, event):
     dlg = wx.FileDialog(None, "Please select the .torrent file(s).", wildcard = "torrent (*.torrent)|*.torrent", style = wx.FD_OPEN|wx.FD_MULTIPLE)
     
     path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
     dlg.SetPath(path)
     
     if dlg.ShowModal() == wx.ID_OK:
         filenames = dlg.GetPaths()
         dlg.Destroy()
         
         self.__processPaths(filenames)
         self.EndModal(wx.ID_OK)
     else:
         dlg.Destroy()
Example #26
0
 def OnBrowseDir(self, event):
     dlg = wx.DirDialog(self, "Please select a directory contain the .torrent files", style = wx.wx.DD_DIR_MUST_EXIST)
     
     path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
     dlg.SetPath(path)
     
     if dlg.ShowModal() == wx.ID_OK and os.path.isdir(dlg.GetPath()):
         filenames = [os.path.join(dlg.GetPath(), file) for file in os.listdir(dlg.GetPath())]
         dlg.Destroy()
         
         self.__processPaths(filenames)
         self.EndModal(wx.ID_OK)
         
     dlg.Destroy()
Example #27
0
    def OnBrowseDir(self, event):
        dlg = wx.DirDialog(None, "Please select a directory contain the .torrent files", style=wx.wx.DD_DIR_MUST_EXIST)

        path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
        dlg.SetPath(path)

        if dlg.ShowModal() == wx.ID_OK and os.path.isdir(dlg.GetPath()):
            filenames = [os.path.join(dlg.GetPath(), file) for file in os.listdir(dlg.GetPath())]
            dlg.Destroy()

            self.__processPaths(filenames)
            self.EndModal(wx.ID_OK)

        dlg.Destroy()
Example #28
0
    def OnBrowse(self, event):
        dlg = wx.FileDialog(None, "Please select the .torrent file(s).",
                            wildcard="torrent (*.torrent)|*.torrent", style=wx.FD_OPEN | wx.FD_MULTIPLE)

        path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
        dlg.SetPath(path)

        if dlg.ShowModal() == wx.ID_OK:
            filenames = dlg.GetPaths()
            dlg.Destroy()

            self.__processPaths(filenames)
            self.EndModal(wx.ID_OK)
        else:
            dlg.Destroy()
Example #29
0
 def __init__(self, parent, frame):
     wx.Dialog.__init__(self, parent, -1, 'Add an external .torrent', size=(500,150))
     self.frame = frame
     self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
     
     vSizer = wx.BoxSizer(wx.VERTICAL)
     
     firstLine = wx.StaticText(self, -1, 'Please use one of the provided methods to import an external .torrent')
     vSizer.Add(firstLine, 0, wx.EXPAND|wx.BOTTOM, 3)
     vSizer.AddSpacer((-1, 25))
     
     header = wx.StaticText(self, -1, 'Browse for local .torrent file or files')
     font = header.GetFont()
     font.SetWeight(wx.FONTWEIGHT_BOLD)
     header.SetFont(font)
     vSizer.Add(header, 0, wx.EXPAND|wx.BOTTOM, 3)
     vSizer.Add(wx.StaticText(self, -1, 'Use this option if you have downloaded a .torrent manually'), 0, wx.BOTTOM, 3)
     
     browseButton = wx.Button(self, -1, 'Browse')
     browseButton.Bind(wx.EVT_BUTTON, self.OnBrowse)
     vSizer.Add(browseButton, 0, wx.ALIGN_RIGHT|wx.BOTTOM, 3)
     vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 10)
     
     header = wx.StaticText(self, -1, 'Url')
     font = header.GetFont()
     font.SetWeight(wx.FONTWEIGHT_BOLD)
     header.SetFont(font)
     vSizer.Add(header, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 3)
     vSizer.Add(wx.StaticText(self, -1, 'This could either be a direct http-link (starting with http://), or a magnet link'), 0, wx.BOTTOM, 3)
     
     hSizer = wx.BoxSizer(wx.HORIZONTAL)
     self.magnet = wx.TextCtrl(self, -1)
     hSizer.Add(self.magnet, 1, wx.ALIGN_CENTER_VERTICAL)
     linkButton = wx.Button(self, -1, "Add")
     linkButton.Bind(wx.EVT_BUTTON, self.OnAdd)
     hSizer.Add(linkButton, 0, wx.LEFT, 3)
     vSizer.Add(hSizer, 0 , wx.EXPAND|wx.BOTTOM, 3)
     
     self.choose = wx.CheckBox(self, -1, "Let me choose a downloadlocation for these torrents")
     self.choose.SetValue(self.defaultDLConfig.get_show_saveas())
     vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 10)
     vSizer.Add(self.choose, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 3)
     
     sizer = wx.BoxSizer()
     sizer.Add(vSizer, 1, wx.EXPAND|wx.ALL, 10)
     self.SetSizerAndFit(sizer)
Example #30
0
        def add_torrent_callback():
            try:
                bin_infohash = binascii.unhexlify(infohash)

                tdef = TorrentDefNoMetainfo(bin_infohash, name)
                _logger.info("[%s] Adding torrent by magnet link" % infohash)

                defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
                dscfg = defaultDLConfig.copy()

                dl = self._session.start_download(tdef, dscfg)
                dl.set_state_callback(self._update_dl_state, delay=1)

                self._session.checkpoint()

            except Exception, e:
                _logger.error("Error adding torrent (infohash=%s,name=%s) (%s)" % (infohash, name, e.args))
                return False
        def add_torrent_callback():
            try:
                bin_infohash = binascii.unhexlify(infohash)

                tdef = TorrentDefNoMetainfo(bin_infohash, name)
                _logger.info("[%s] Adding torrent by magnet link" % infohash)

                defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
                dscfg = defaultDLConfig.copy()

                dl = self._session.start_download(tdef, dscfg)
                dl.set_state_callback(self._update_dl_state, delay=1)

                self._session.checkpoint()

            except Exception, e:
                _logger.error("Error adding torrent (infohash=%s,name=%s) (%s)" % (infohash, name, e.args))
                return False
Example #32
0
    def OnBrowseDir(self, event):
        dlg = wx.DirDialog(self, "Please select a directory contain the .torrent files", style=wx.wx.DD_DIR_MUST_EXIST)

        path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
        dlg.SetPath(path)

        if dlg.ShowModal() == wx.ID_OK and os.path.isdir(dlg.GetPath()):
            filenames = []
            files = os.listdir(dlg.GetPath())

            for file in files:
                if file.endswith(".torrent"):
                    filenames.append(os.path.join(dlg.GetPath(), file))

            cancel = False
            if len(filenames) > 10:
                warning = wx.MessageDialog(
                    self,
                    "This will add %d .torrents, are you sure?" % len(filenames),
                    "Please confirm Add",
                    wx.OK | wx.CANCEL | wx.ICON_WARNING,
                )
                if warning.ShowModal() != wx.ID_OK:
                    cancel = True

                warning.Destroy()

            if not cancel:
                destdir = self.defaultDLConfig.get_dest_dir()
                if self.choose and self.choose.IsChecked():
                    destdir = self._GetDestPath()
                    if not destdir:
                        return

                if getattr(self.frame, "startDownloads", False):
                    self.frame.startDownloads(filenames, fixtorrent=True, destdir=destdir)
                else:
                    for filename in filenames:
                        self.frame.startDownload(filename, fixtorrent=True, destdir=destdir)

            dlg.Destroy()
            self.EndModal(wx.ID_OK)

        dlg.Destroy()
Example #33
0
    def doAction(self, args):
        action = args['action']

        if action == 'add-url':
            url = args['s']
            destdir = DefaultDownloadStartupConfig.getInstance().get_dest_dir()

            if url.startswith("http"):
                self.guiUtility.frame.startDownloadFromUrl(url, destdir)
            elif url.startswith("magnet:"):
                self.guiUtility.frame.startDownloadFromMagnet(url, destdir)

        elif action == 'getprops':
            return self.doProps(args)

        elif action == 'getfiles':
            return self.doFiles(args)

        elif action == 'getsettings':
            return self.doSettings(args)

        elif 'hash' in args:
            if isinstance(args.get('hash', ''), basestring):
                infohashes = [args.get('hash', '')]
            else:
                infohashes = args['hash']

            for h in infohashes:
                infohash = unhexlify(h)

                torrent = self.library_manager.getTorrentFromInfohash(infohash)
                if action in ['start', 'forcestart', 'unpause']:
                    self.library_manager.resumeTorrent(torrent)
                elif action in ['stop', 'pause']:
                    self.library_manager.stopTorrent(torrent.infohash)
                elif action == 'remove':
                    self.library_manager.deleteTorrent(torrent)
                elif action == 'removedata':
                    self.library_manager.deleteTorrent(torrent, removecontent=True)

        return {}
Example #34
0
 def playTorrent(self, torrent, selectedinfilename = None):
     ds = torrent.get('ds')
     
     videoplayer = self._get_videoplayer(ds)
     videoplayer.stop_playback()
     videoplayer.show_loading()
     
     if ds is None:
         #Making sure we actually have this .torrent
         callback = lambda infohash, metadata, filename: self.playTorrent(torrent)
         filename = self.torrentsearch_manager.getTorrent(torrent, callback)
         
         if isinstance(filename, basestring):
             #got actual filename, load torrentdef and create downloadconfig
             
             tdef = TorrentDef.load(filename)
             defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
             dscfg = defaultDLConfig.copy()
             videoplayer.start_and_play(tdef, dscfg, selectedinfilename)
     else:
         videoplayer.play(ds, selectedinfilename)
Example #35
0
 def OnBrowseDir(self, event):
     dlg = wx.DirDialog(self, "Please select a directory contain the .torrent files", style = wx.wx.DD_DIR_MUST_EXIST)
     
     path = DefaultDownloadStartupConfig.getInstance().get_dest_dir() + os.sep
     dlg.SetPath(path)
     
     if dlg.ShowModal() == wx.ID_OK and os.path.isdir(dlg.GetPath()):
         filenames = []
         files = os.listdir(dlg.GetPath())
         
         for file in files:
             if file.endswith('.torrent'):
                 filenames.append(os.path.join(dlg.GetPath(), file))
         
         cancel = False
         if len(filenames) > 10:
             warning = wx.MessageDialog(self, "This will add %d .torrents, are you sure?"%len(filenames), "Please confirm Add", wx.OK|wx.CANCEL|wx.ICON_WARNING)
             if warning.ShowModal() != wx.ID_OK:
                 cancel = True
                 
             warning.Destroy()
             
         if not cancel:
             destdir = self.defaultDLConfig.get_dest_dir()
             if self.choose and self.choose.IsChecked():
                 destdir = self._GetDestPath()
                 if not destdir:
                     return
                 
             if getattr(self.frame, 'startDownloads', False):
                 self.frame.startDownloads(filenames, fixtorrent = True, destdir = destdir)
             else:
                 for filename in filenames:
                     self.frame.startDownload(filename, fixtorrent = True, destdir = destdir)
         
         dlg.Destroy()
         self.EndModal(wx.ID_OK)
         
     dlg.Destroy()
    def onDone(self, event):
        self.flag.set()
        self.frame.Destroy()
        if self.startnow:
            # When seeding immediately, add torrents to queue
            for orig,torrentfilename in self.files:
                try:
                    absorig = os.path.abspath(orig)
                    if os.path.isfile(absorig):
                        # To seed a file, destdir must be one up.
                        destdir = os.path.dirname(absorig)
                    else:
                        destdir = absorig

                    tdef = TorrentDef.load(torrentfilename)
                    defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
                    dscfg = defaultDLConfig.copy()
                    dscfg.set_dest_dir(destdir)
                    self.utility.session.start_download(tdef,dscfg)

                except Exception,e:
                    print_exc()
                    self.onError(e)
 def do_downloadfromurl():
     self.guiUtility.showLibrary()
     destdir = DefaultDownloadStartupConfig.getInstance().get_dest_dir()
     self.frame.startDownloadFromUrl(r'http://www.clearbits.net/get/1678-zenith-part-1.torrent', destdir)
     self.Call(30, do_assert)
Example #38
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 #39
0
    def _PostInit(self):
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        dialog = xrc.XRCCTRL(self, "settingsDialog")
        for element in self.elementsName:
            xrcElement = xrc.XRCCTRL(dialog, element)
            if not xrcElement:
                print 'settingsOverviewPanel: Error: Could not identify xrc element:',element
            self.elements[element] = xrcElement
        
        #Building tree
        self.tree = xrc.XRCCTRL(self,"settings_tree")
        root = self.tree.AddRoot('Root')
        self.tree.SelectItem(self.tree.AppendItem(root,'General',data=wx.TreeItemData(xrc.XRCCTRL(self,"general_panel"))),True)
        self.tree.AppendItem(root,'Connection',data=wx.TreeItemData(xrc.XRCCTRL(self,"connection_panel")))
        self.tree.AppendItem(root,'Bandwidth',data=wx.TreeItemData(xrc.XRCCTRL(self,"bandwidth_panel")))
        self.tree.AppendItem(root,'Misc',data=wx.TreeItemData(xrc.XRCCTRL(self,"misc_panel")))
        self.tree.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnSelectionChanging)

        #Bind event listeners
        self.elements['diskLocationChoice'].Bind(wx.EVT_CHECKBOX, self.OnDownloadChoice)
        
        self.elements['zeroUp'].Bind(wx.EVT_BUTTON, lambda event: self.setUp(0, event))
        self.elements['fiftyUp'].Bind(wx.EVT_BUTTON, lambda event: self.setUp(50, event))
        self.elements['hundredUp'].Bind(wx.EVT_BUTTON, lambda event: self.setUp(100, event))
        self.elements['unlimitedUp'].Bind(wx.EVT_BUTTON, lambda event: self.setUp('unlimited', event))

        self.elements['seventyfiveDown'].Bind(wx.EVT_BUTTON, lambda event: self.setDown(75, event))
        self.elements['threehundredDown'].Bind(wx.EVT_BUTTON, lambda event: self.setDown(300, event))
        self.elements['sixhundreddDown'].Bind(wx.EVT_BUTTON, lambda event: self.setDown(600, event))
        self.elements['unlimitedDown'].Bind(wx.EVT_BUTTON, lambda event: self.setDown('unlimited', event))

        self.elements['uploadCtrl'].Bind(wx.EVT_KEY_DOWN, self.removeUnlimited)
        self.elements['downloadCtrl'].Bind(wx.EVT_KEY_DOWN, self.removeUnlimited)
        
        self.elements['edit'].Bind(wx.EVT_BUTTON, self.EditClicked)
        self.elements['browse'].Bind(wx.EVT_BUTTON, self.BrowseClicked)
        
        self.elements['batchstart'].Bind(wx.EVT_BUTTON, lambda event: self.OnMultiple(True))
        self.elements['batchstop'].Bind(wx.EVT_BUTTON, lambda event: self.OnMultiple(False))
        
        self.Bind(wx.EVT_BUTTON, self.saveAll, id = xrc.XRCID("wxID_OK"))
        self.Bind(wx.EVT_BUTTON, self.cancelAll, id = xrc.XRCID("wxID_CANCEL"))
        
        #Loading settings
        self.myname = self.utility.session.get_nickname()
        mime, data = self.utility.session.get_mugshot()
        if data is None:
            im = IconsManager.getInstance()
            self.mugshot = im.get_default('personsMode','DEFAULT_THUMB')
        else:
            self.mugshot = data2wxBitmap(mime, data)
        
        self.elements['myNameField'].SetValue(self.myname)
        self.elements['thumb'].setBitmap(self.mugshot)
        
        if self.guiUtility.frame.SRstatusbar.IsReachable():
            self.elements['firewallStatus'].setSelected(2)
            self.elements['firewallStatusText'].SetLabel('Port is working')
        
        if self.utility.config.Read('family_filter', "boolean"):
            self.elements['familyFilter'].SetSelection(0)
        else:
            self.elements['familyFilter'].SetSelection(1)

        self.currentPopup = self.utility.config.Read('popup_player', "boolean")
        if self.currentPopup:
            self.elements['externalplayer'].SetSelection(1)
        else:
            self.elements['externalplayer'].SetSelection(0)
        
        self.currentPortValue = str(self.guiUtility.get_port_number())
        self.elements['firewallValue'].SetValue(self.currentPortValue)
        
        maxdownloadrate = self.utility.config.Read('maxdownloadrate', 'int')
        if maxdownloadrate == 0:
            self.elements['downloadCtrl'].SetValue('unlimited')        
        else:
            self.elements['downloadCtrl'].SetValue(str(maxdownloadrate))
        
        maxuploadrate = self.utility.config.Read('maxuploadrate', 'int')
        if maxuploadrate == -1:
            self.elements['uploadCtrl'].SetValue('0')        
        elif maxuploadrate == 0:
            self.elements['uploadCtrl'].SetValue('unlimited')        
        else:
            self.elements['uploadCtrl'].SetValue(str(maxuploadrate))
        
        self.currentDestDir = self.defaultDLConfig.get_dest_dir()
        self.elements['diskLocationCtrl'].SetValue(self.currentDestDir)
        self.elements['diskLocationCtrl'].Enable(not self.defaultDLConfig.get_show_saveas())
        self.elements['diskLocationChoice'].SetValue(self.defaultDLConfig.get_show_saveas())
        
        self.elements['use_bundle_magic'].SetValue(self.utility.config.Read('use_bundle_magic', "boolean"))
        
        wx.CallAfter(self.Refresh)
Example #40
0
    def start_session(self):
        """
        This function loads any previous configuration files from the TRIBLER_STATE_DIR environment variable and then
        starts a Tribler session.
        :return: Nothing.
        """
        if self._running:
            return False

        _logger.info("Set tribler_state_dir to %s" %
                     os.environ['TRIBLER_STATE_DIR'])

        # Load configuration file (if exists)
        cfgfilename = Session.get_default_config_filename(
            os.environ['TRIBLER_STATE_DIR'])
        try:
            self._sconfig = SessionStartupConfig.load(cfgfilename)
            _logger.info("Loaded previous configuration file from %s" %
                         cfgfilename)
        except:
            self._sconfig = SessionStartupConfig()
            self._sconfig.set_state_dir(os.environ['TRIBLER_STATE_DIR'])
            _logger.info(
                "No previous configuration file found, creating one in %s" %
                os.environ['TRIBLER_STATE_DIR'])

        dlcfgfilename = get_default_dscfg_filename(
            self._sconfig.get_state_dir())
        _logger.debug("main: Download config %s", dlcfgfilename)
        try:
            defaultDLConfig = DefaultDownloadStartupConfig.load(dlcfgfilename)
        except:
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        if not defaultDLConfig.get_dest_dir():
            defaultDLConfig.set_dest_dir(os.environ['TRIBLER_DOWNLOAD_DIR'])
            self._sconfig.set_torrent_collecting_dir(
                os.path.join(os.environ['TRIBLER_DOWNLOAD_DIR'],
                             ".%s" % STATEDIR_TORRENTCOLL_DIR))
            self._sconfig.set_swift_meta_dir(
                os.path.join(os.environ['TRIBLER_DOWNLOAD_DIR'],
                             ".%s" % STATEDIR_SWIFTRESEED_DIR))

        if not os.path.isdir(defaultDLConfig.get_dest_dir()):
            try:
                _logger.info("Creating download directory: %s" %
                             defaultDLConfig.get_dest_dir())
                os.makedirs(defaultDLConfig.get_dest_dir())
            except:
                _logger.error("Couldn't create download directory! (%s)" %
                              defaultDLConfig.get_dest_dir())

        # Disable unneeded dependencies
        self._sconfig.set_torrent_checking(False)
        self._sconfig.set_multicast_local_peer_discovery(False)
        #self._sconfig.set_megacache(False)
        #self._sconfig.set_swift_proc(False)
        self._sconfig.set_mainline_dht(False)
        #self._sconfig.set_torrent_collecting(False)
        #self._sconfig.set_libtorrent(False)
        self._sconfig.set_dht_torrent_collecting(False)
        #self._sconfig.set_videoplayer(False)

        self._sconfig.set_dispersy_tunnel_over_swift(False)
        self._sconfig.set_torrent_collecting_max_torrents(5000)

        # Start session
        _logger.info("Starting tribler session")
        self._session = Session(self._sconfig)
        self._session.start()

        self._swift = self._session.get_swift_proc(
        ) and self._session.get_swift_process()
        self._dispersy = self._session.get_dispersy_instance()

        _logger.info("libTribler session started!")
        self.define_communities()
Example #41
0
    def resume_download(self,
                        filename,
                        initialdlstatus=None,
                        initialdlstatus_dict={},
                        commit=True,
                        setupDelay=0):
        tdef = sdef = dscfg = pstate = None

        try:
            pstate = self.load_download_pstate(filename)

            # SWIFTPROC
            if SwiftDef.is_swift_url(pstate['metainfo']):
                sdef = SwiftDef.load_from_url(pstate['metainfo'])
            elif 'infohash' in pstate['metainfo']:
                tdef = TorrentDefNoMetainfo(pstate['metainfo']['infohash'],
                                            pstate['metainfo']['name'])
            else:
                tdef = TorrentDef.load_from_dict(pstate['metainfo'])

            dlconfig = pstate['dlconfig']
            if isinstance(dlconfig['saveas'], tuple):
                dlconfig['saveas'] = dlconfig['saveas'][-1]

            if sdef and 'name' in dlconfig and isinstance(
                    dlconfig['name'], basestring):
                sdef.set_name(dlconfig['name'])
            if sdef and sdef.get_tracker().startswith("127.0.0.1:"):
                current_port = int(sdef.get_tracker().split(":")[1])
                if current_port != self.session.get_swift_dht_listen_port():
                    print >> sys.stderr, "Modified SwiftDef to new tracker port"
                    sdef.set_tracker("127.0.0.1:%d" %
                                     self.session.get_swift_dht_listen_port())

            dscfg = DownloadStartupConfig(dlconfig)

        except:
            print_exc()
            # pstate is invalid or non-existing
            _, file = os.path.split(filename)

            infohash = binascii.unhexlify(file[:-7])
            torrent = self.torrent_db.getTorrent(
                infohash,
                keys=['name', 'torrent_file_name', 'swift_torrent_hash'],
                include_mypref=False)
            torrentfile = None
            if torrent:
                torrent_dir = self.session.get_torrent_collecting_dir()

                if torrent['swift_torrent_hash']:
                    sdef = SwiftDef(torrent['swift_torrent_hash'])
                    save_name = sdef.get_roothash_as_hex()
                    torrentfile = os.path.join(torrent_dir, save_name)

                if torrentfile and os.path.isfile(torrentfile):
                    # normal torrentfile is not present, see if readable torrent is there
                    save_name = get_readable_torrent_name(
                        infohash, torrent['name'])
                    torrentfile = os.path.join(torrent_dir, save_name)

            if torrentfile and os.path.isfile(torrentfile):
                tdef = TorrentDef.load(torrentfile)

                defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
                dscfg = defaultDLConfig.copy()

                if self.mypref_db != None:
                    preferences = self.mypref_db.getMyPrefStatsInfohash(
                        infohash)
                    if preferences:
                        if os.path.isdir(
                                preferences[2]) or preferences[2] == '':
                            dscfg.set_dest_dir(preferences[2])

        if DEBUG:
            print >> sys.stderr, "tlm: load_checkpoint: pstate is", dlstatus_strings[
                pstate['dlstate']['status']], pstate['dlstate']['progress']
            if pstate['engineresumedata'] is None:
                print >> sys.stderr, "tlm: load_checkpoint: resumedata None"
            else:
                print >> sys.stderr, "tlm: load_checkpoint: resumedata len", len(
                    pstate['engineresumedata'])

        if (tdef or sdef) and dscfg:
            if dscfg.get_dest_dir() != '':  # removed torrent ignoring
                try:
                    if not self.download_exists((tdef or sdef).get_id()):
                        if tdef:
                            initialdlstatus = initialdlstatus_dict.get(
                                tdef.get_id(), initialdlstatus)
                            self.add(tdef,
                                     dscfg,
                                     pstate,
                                     initialdlstatus,
                                     commit=commit,
                                     setupDelay=setupDelay)
                        else:
                            initialdlstatus = initialdlstatus_dict.get(
                                sdef.get_id(), initialdlstatus)
                            self.swift_add(sdef, dscfg, pstate,
                                           initialdlstatus)
                    else:
                        print >> sys.stderr, "tlm: not resuming checkpoint because download has already been added"

                except Exception as e:
                    self.rawserver_nonfatalerrorfunc(e)
            else:
                print >> sys.stderr, "tlm: removing checkpoint", filename, "destdir is", dscfg.get_dest_dir(
                )
                os.remove(filename)
        else:
            print >> sys.stderr, "tlm: could not resume checkpoint", filename, tdef, dscfg
Example #42
0
 def __init__(self, parent, frame, libraryTorrents = None):
     wx.Dialog.__init__(self, parent, -1, 'Add an external .torrent', size=(500,200))
     
     self.frame = frame
     self.guiutility = GUIUtility.getInstance()
     self.toChannel = libraryTorrents != None
     self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
     
     vSizer = wx.BoxSizer(wx.VERTICAL)
     
     firstLine = wx.StaticText(self, -1, 'Please use one of the provided methods to import an external .torrent')
     vSizer.Add(firstLine, 0, wx.EXPAND|wx.BOTTOM, 3)
     vSizer.AddSpacer((-1, 25))
     
     header = wx.StaticText(self, -1, 'Browse for local .torrent file or files')
     _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
     vSizer.Add(header, 0, wx.EXPAND|wx.BOTTOM, 3)
     vSizer.Add(wx.StaticText(self, -1, 'Use this option if you have downloaded a .torrent manually'), 0, wx.BOTTOM, 3)
     
     browseButton = wx.Button(self, -1, 'Browse')
     browseButton.Bind(wx.EVT_BUTTON, self.OnBrowse)
     
     browseDirectory = wx.Button(self, -1, 'Browse for Directory')
     browseDirectory.Bind(wx.EVT_BUTTON, self.OnBrowseDir)
     
     hSizer = wx.BoxSizer(wx.HORIZONTAL)
     hSizer.Add(browseButton, 0, wx.RIGHT, 3)
     hSizer.Add(browseDirectory)
     vSizer.Add(hSizer, 0, wx.ALIGN_RIGHT|wx.BOTTOM, 3)
     vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.BOTTOM, 10)
     
     header = wx.StaticText(self, -1, 'Url')
     _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
     vSizer.Add(header, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 3)
     vSizer.Add(wx.StaticText(self, -1, 'This could either be a direct http-link (starting with http://), or a magnet link'), 0, wx.BOTTOM, 3)
     
     hSizer = wx.BoxSizer(wx.HORIZONTAL)
     self.magnet = wx.TextCtrl(self, -1)
     hSizer.Add(self.magnet, 1, wx.ALIGN_CENTER_VERTICAL)
     linkButton = wx.Button(self, -1, "Add")
     linkButton.Bind(wx.EVT_BUTTON, self.OnAdd)
     hSizer.Add(linkButton, 0, wx.LEFT, 3)
     vSizer.Add(hSizer, 0 , wx.EXPAND|wx.BOTTOM, 3)
     
     vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.BOTTOM, 10)
     if libraryTorrents != None:
         if len(libraryTorrents) > 0:
             header = wx.StaticText(self, -1, 'Choose one from you library')
             _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
             vSizer.Add(header, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 3)
             
             torrentNames = [torrent.name for torrent in libraryTorrents]
             
             hSizer = wx.BoxSizer(wx.HORIZONTAL)
             self.libraryChoice = wx.Choice(self, -1, choices=torrentNames)
             self.libraryChoice.torrents = libraryTorrents
             hSizer.Add(self.libraryChoice, 1, wx.ALIGN_CENTER_VERTICAL)
             
             linkButton = wx.Button(self, -1, "Add")
             linkButton.Bind(wx.EVT_BUTTON, self.OnLibrary)
             
             hSizer.Add(linkButton, 0, wx.LEFT, 3)
             vSizer.Add(hSizer, 0 , wx.EXPAND|wx.BOTTOM, 3)
         
         vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.BOTTOM, 10)
         header = wx.StaticText(self, -1, 'Create your own .torrents')
         _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
         vSizer.Add(header, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 3)
         vSizer.Add(wx.StaticText(self, -1, 'Using your own local files'), 0, wx.BOTTOM, 3)
         
         create = wx.Button(self, -1, 'Create')
         create.Bind(wx.EVT_BUTTON, self.OnCreate)
         vSizer.Add(create, 0, wx.ALIGN_RIGHT|wx.BOTTOM, 3)
         
         self.choose = None
         
     else:
         self.choose = wx.CheckBox(self, -1, "Let me choose a downloadlocation for these torrents")
         self.choose.SetValue(self.defaultDLConfig.get_show_saveas())
         vSizer.Add(self.choose, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 3)
     
     sizer = wx.BoxSizer()
     sizer.Add(vSizer, 1, wx.EXPAND|wx.ALL, 10)
     self.SetSizerAndFit(sizer)
    def __init__(self, parent, frame, libraryTorrents=None):
        wx.Dialog.__init__(self,
                           parent,
                           -1,
                           'Add an external .torrent',
                           size=(500, 200))

        self.frame = frame
        self.guiutility = GUIUtility.getInstance()
        self.toChannel = libraryTorrents != None
        self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        vSizer = wx.BoxSizer(wx.VERTICAL)

        firstLine = wx.StaticText(
            self, -1,
            'Please use one of the provided methods to import an external .torrent'
        )
        vSizer.Add(firstLine, 0, wx.EXPAND | wx.BOTTOM, 3)
        vSizer.AddSpacer((-1, 25))

        header = wx.StaticText(self, -1,
                               'Browse for local .torrent file or files')
        _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
        vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM, 3)
        vSizer.Add(
            wx.StaticText(
                self, -1,
                'Use this option if you have downloaded a .torrent manually'),
            0, wx.BOTTOM, 3)

        browseButton = wx.Button(self, -1, 'Browse')
        browseButton.Bind(wx.EVT_BUTTON, self.OnBrowse)

        browseDirectory = wx.Button(self, -1, 'Browse for Directory')
        browseDirectory.Bind(wx.EVT_BUTTON, self.OnBrowseDir)

        hSizer = wx.BoxSizer(wx.HORIZONTAL)
        hSizer.Add(browseButton, 0, wx.RIGHT, 3)
        hSizer.Add(browseDirectory)
        vSizer.Add(hSizer, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 3)
        vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.BOTTOM, 10)

        header = wx.StaticText(self, -1, 'Url')
        _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
        vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 3)
        vSizer.Add(
            wx.StaticText(
                self, -1,
                'This could either be a direct http-link (starting with http://), or a magnet link'
            ), 0, wx.BOTTOM, 3)

        hSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.magnet = wx.TextCtrl(self, -1)
        hSizer.Add(self.magnet, 1, wx.ALIGN_CENTER_VERTICAL)
        linkButton = wx.Button(self, -1, "Add")
        linkButton.Bind(wx.EVT_BUTTON, self.OnAdd)
        hSizer.Add(linkButton, 0, wx.LEFT, 3)
        vSizer.Add(hSizer, 0, wx.EXPAND | wx.BOTTOM, 3)

        vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.BOTTOM, 10)
        if libraryTorrents != None:
            if len(libraryTorrents) > 0:
                header = wx.StaticText(self, -1, 'Choose one from you library')
                _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
                vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 3)

                torrentNames = [torrent.name for torrent in libraryTorrents]

                hSizer = wx.BoxSizer(wx.HORIZONTAL)
                self.libraryChoice = wx.Choice(self, -1, choices=torrentNames)
                self.libraryChoice.torrents = libraryTorrents
                hSizer.Add(self.libraryChoice, 1, wx.ALIGN_CENTER_VERTICAL)

                linkButton = wx.Button(self, -1, "Add")
                linkButton.Bind(wx.EVT_BUTTON, self.OnLibrary)

                hSizer.Add(linkButton, 0, wx.LEFT, 3)
                vSizer.Add(hSizer, 0, wx.EXPAND | wx.BOTTOM, 3)

            vSizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.BOTTOM, 10)
            header = wx.StaticText(self, -1, 'Create your own .torrents')
            _set_font(header, fontweight=wx.FONTWEIGHT_BOLD)
            vSizer.Add(header, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 3)
            vSizer.Add(wx.StaticText(self, -1, 'Using your own local files'),
                       0, wx.BOTTOM, 3)

            create = wx.Button(self, -1, 'Create')
            create.Bind(wx.EVT_BUTTON, self.OnCreate)
            vSizer.Add(create, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 3)

            self.choose = None

        else:
            self.choose = wx.CheckBox(
                self, -1,
                "Let me choose a downloadlocation for these torrents")
            self.choose.SetValue(self.defaultDLConfig.get_show_saveas())
            vSizer.Add(self.choose, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 3)

        sizer = wx.BoxSizer()
        sizer.Add(vSizer, 1, wx.EXPAND | wx.ALL, 10)
        self.SetSizerAndFit(sizer)
Example #44
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)
 def do_downloadfrommagnet():
     self.guiUtility.showLibrary()
     destdir = DefaultDownloadStartupConfig.getInstance().get_dest_dir()
     self.frame.startDownloadFromMagnet(r'magnet:?xt=urn:btih:5ac55cf1b935291f6fc92ad7afd34597498ff2f7&dn=Pioneer+One+S01E01+Xvid-VODO&title=', destdir)
     self.Call(120, do_assert)
Example #46
0
    def InitStage1(self,
                   installdir,
                   autoload_discovery=True,
                   use_torrent_search=True,
                   use_channel_search=True):
        """ Stage 1 start: pre-start the session to handle upgrade.
        """

        self.gui_image_manager = GuiImageManager.getInstance(installdir)

        # Start Tribler Session
        defaultConfig = SessionStartupConfig()
        state_dir = defaultConfig.get_state_dir()

        # Switch to the state dir so relative paths can be used (IE, in LevelDB store paths)
        if not os.path.exists(state_dir):
            os.makedirs(state_dir)
        os.chdir(state_dir)

        cfgfilename = Session.get_default_config_filename(state_dir)

        self._logger.debug(u"Session config %s", cfgfilename)
        try:
            self.sconfig = SessionStartupConfig.load(cfgfilename)
        except:
            try:
                self.sconfig = convertSessionConfig(
                    os.path.join(state_dir, 'sessconfig.pickle'), cfgfilename)
                convertMainConfig(state_dir,
                                  os.path.join(state_dir, 'abc.conf'),
                                  os.path.join(state_dir, STATEDIR_GUICONFIG))
            except:
                self.sconfig = SessionStartupConfig()
                self.sconfig.set_state_dir(state_dir)

        self.sconfig.set_install_dir(self.installdir)

        # TODO(emilon): Do we still want to force limit this? With the new
        # torrent store it should be pretty fast even with more that that.

        # Arno, 2010-03-31: Hard upgrade to 50000 torrents collected
        self.sconfig.set_torrent_collecting_max_torrents(50000)

        dlcfgfilename = get_default_dscfg_filename(
            self.sconfig.get_state_dir())
        self._logger.debug("main: Download config %s", dlcfgfilename)
        try:
            defaultDLConfig = DefaultDownloadStartupConfig.load(dlcfgfilename)
        except:
            try:
                defaultDLConfig = convertDefaultDownloadConfig(
                    os.path.join(state_dir, 'dlconfig.pickle'), dlcfgfilename)
            except:
                defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        if not defaultDLConfig.get_dest_dir():
            defaultDLConfig.set_dest_dir(get_default_dest_dir())
        if not os.path.isdir(defaultDLConfig.get_dest_dir()):
            try:
                os.makedirs(defaultDLConfig.get_dest_dir())
            except:
                # Could not create directory, ask user to select a different location
                dlg = wx.DirDialog(
                    None,
                    "Could not find download directory, please select a new location to store your downloads",
                    style=wx.DEFAULT_DIALOG_STYLE)
                dlg.SetPath(get_default_dest_dir())
                if dlg.ShowModal() == wx.ID_OK:
                    new_dest_dir = dlg.GetPath()
                    defaultDLConfig.set_dest_dir(new_dest_dir)
                    defaultDLConfig.save(dlcfgfilename)
                    self.sconfig.save(cfgfilename)
                else:
                    # Quit
                    self.onError = lambda e: self._logger.error(
                        "tribler: quitting due to non-existing destination directory"
                    )
                    raise Exception()

        if not use_torrent_search:
            self.sconfig.set_enable_torrent_search(False)
        if not use_channel_search:
            self.sconfig.set_enable_channel_search(False)

        session = Session(self.sconfig, autoload_discovery=autoload_discovery)
        session.add_observer(self.show_upgrade_dialog, NTFY_UPGRADER,
                             [NTFY_STARTED])
        self.upgrader = session.prestart()

        while not self.upgrader.is_done:
            wx.SafeYield()
            sleep(0.1)

        return session
Example #47
0
    def OnExit(self):
        bm = self.gui_image_manager.getImage(u'closescreen.png')
        self.closewindow = GaugeSplash(bm, "Closing...", 6)
        self.closewindow.Show()

        self._logger.info("main: ONEXIT")
        self.ready = False
        self.done = True

        # write all persistent data to disk
        self.closewindow.tick('Write all persistent data to disk')
        if self.torrentfeed:
            self.torrentfeed.shutdown()
            self.torrentfeed.delInstance()
        if self.webUI:
            self.webUI.stop()
            self.webUI.delInstance()

        if self.frame:
            self.frame.Destroy()
            self.frame = None

        # Don't checkpoint, interferes with current way of saving Preferences,
        # see Tribler/Main/Dialogs/abcoption.py
        if self.utility:
            # Niels: lets add a max waiting time for this session shutdown.
            session_shutdown_start = time()

            try:
                self._logger.info("ONEXIT cleaning database")
                self.closewindow.tick('Cleaning database')
                torrent_db = self.utility.session.open_dbhandler(NTFY_TORRENTS)
                torrent_db._db.clean_db(randint(0, 24) == 0, exiting=True)
            except:
                print_exc()

            self.closewindow.tick('Shutdown session')
            self.utility.session.shutdown(hacksessconfcheckpoint=False)

            # Arno, 2012-07-12: Shutdown should be quick
            # Niels, 2013-03-21: However, setting it too low will prevent checkpoints from being written to disk
            waittime = 60
            while not self.utility.session.has_shutdown():
                diff = time() - session_shutdown_start
                if diff > waittime:
                    self._logger.info(
                        "main: ONEXIT NOT Waiting for Session to shutdown, took too long"
                    )
                    break

                self._logger.info(
                    "ONEXIT Waiting for Session to shutdown, will wait for an additional %d seconds",
                    waittime - diff)
                sleep(3)
            self._logger.info("ONEXIT Session is shutdown")

        self.closewindow.tick('Deleting instances')
        self._logger.debug("ONEXIT deleting instances")

        Session.del_instance()
        GUIUtility.delInstance()
        GUIDBProducer.delInstance()
        DefaultDownloadStartupConfig.delInstance()
        GuiImageManager.delInstance()

        self.closewindow.tick('Exiting now')

        self.closewindow.Destroy()

        return 0
Example #48
0
    def OnExit(self):
        bm = self.gui_image_manager.getImage(u'closescreen.png')
        self.closewindow = GaugeSplash(bm, "Closing...", 6)
        self.closewindow.Show()

        self._logger.info("main: ONEXIT")
        self.ready = False
        self.done = True

        # write all persistent data to disk
        self.closewindow.tick('Write all persistent data to disk')
        if self.torrentfeed:
            self.torrentfeed.shutdown()
            self.torrentfeed.delInstance()
        if self.webUI:
            self.webUI.stop()
            self.webUI.delInstance()

        if self.frame:
            self.frame.Destroy()
            self.frame = None

        # Don't checkpoint, interferes with current way of saving Preferences,
        # see Tribler/Main/Dialogs/abcoption.py
        if self.utility:
            # Niels: lets add a max waiting time for this session shutdown.
            session_shutdown_start = time()

            try:
                self._logger.info("ONEXIT cleaning database")
                self.closewindow.tick('Cleaning database')
                torrent_db = self.utility.session.open_dbhandler(NTFY_TORRENTS)
                torrent_db._db.clean_db(randint(0, 24) == 0, exiting=True)
            except:
                print_exc()

            self.closewindow.tick('Shutdown session')
            self.utility.session.shutdown(hacksessconfcheckpoint=False)

            # Arno, 2012-07-12: Shutdown should be quick
            # Niels, 2013-03-21: However, setting it too low will prevent checkpoints from being written to disk
            waittime = 60
            while not self.utility.session.has_shutdown():
                diff = time() - session_shutdown_start
                if diff > waittime:
                    self._logger.info("main: ONEXIT NOT Waiting for Session to shutdown, took too long")
                    break

                self._logger.info(
                    "ONEXIT Waiting for Session to shutdown, will wait for an additional %d seconds",
                    waittime - diff)
                sleep(3)
            self._logger.info("ONEXIT Session is shutdown")

        self.closewindow.tick('Deleting instances')
        self._logger.debug("ONEXIT deleting instances")

        Session.del_instance()
        GUIUtility.delInstance()
        GUIDBProducer.delInstance()
        DefaultDownloadStartupConfig.delInstance()
        GuiImageManager.delInstance()

        self.closewindow.tick('Exiting now')

        self.closewindow.Destroy()

        return 0
Example #49
0
    def _PostInit(self):
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        dialog = xrc.XRCCTRL(self, "settingsDialog")
        for element in self.elementsName:
            xrcElement = xrc.XRCCTRL(dialog, element)
            if not xrcElement:
                print 'settingsOverviewPanel: Error: Could not identify xrc element:', element
            self.elements[element] = xrcElement

        #Building tree
        self.tree = xrc.XRCCTRL(self, "settings_tree")
        root = self.tree.AddRoot('Root')
        self.tree.SelectItem(
            self.tree.AppendItem(root,
                                 'General',
                                 data=wx.TreeItemData(
                                     xrc.XRCCTRL(self, "general_panel"))),
            True)
        self.tree.AppendItem(root,
                             'Connection',
                             data=wx.TreeItemData(
                                 xrc.XRCCTRL(self, "connection_panel")))
        self.tree.AppendItem(root,
                             'Limits',
                             data=wx.TreeItemData(
                                 xrc.XRCCTRL(self, "bandwidth_panel")))
        self.tree.AppendItem(root,
                             'Seeding',
                             data=wx.TreeItemData(
                                 xrc.XRCCTRL(self, "seeding_panel")))
        self.tree.AppendItem(root,
                             'Experimental',
                             data=wx.TreeItemData(
                                 xrc.XRCCTRL(self, "exp_panel")))
        self.tree.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnSelectionChanging)

        #Bind event listeners
        self.elements['zeroUp'].Bind(wx.EVT_BUTTON,
                                     lambda event: self.setUp(0, event))
        self.elements['fiftyUp'].Bind(wx.EVT_BUTTON,
                                      lambda event: self.setUp(50, event))
        self.elements['hundredUp'].Bind(wx.EVT_BUTTON,
                                        lambda event: self.setUp(100, event))
        self.elements['unlimitedUp'].Bind(
            wx.EVT_BUTTON, lambda event: self.setUp('unlimited', event))

        self.elements['seventyfiveDown'].Bind(
            wx.EVT_BUTTON, lambda event: self.setDown(75, event))
        self.elements['threehundredDown'].Bind(
            wx.EVT_BUTTON, lambda event: self.setDown(300, event))
        self.elements['sixhundreddDown'].Bind(
            wx.EVT_BUTTON, lambda event: self.setDown(600, event))
        self.elements['unlimitedDown'].Bind(
            wx.EVT_BUTTON, lambda event: self.setDown('unlimited', event))

        self.elements['uploadCtrl'].Bind(wx.EVT_KEY_DOWN, self.removeUnlimited)
        self.elements['downloadCtrl'].Bind(wx.EVT_KEY_DOWN,
                                           self.removeUnlimited)

        self.elements['edit'].Bind(wx.EVT_BUTTON, self.EditClicked)
        self.elements['browse'].Bind(wx.EVT_BUTTON, self.BrowseClicked)

        self.Bind(wx.EVT_BUTTON, self.saveAll, id=xrc.XRCID("wxID_OK"))
        self.Bind(wx.EVT_BUTTON, self.cancelAll, id=xrc.XRCID("wxID_CANCEL"))

        #Loading settings
        self.myname = self.utility.session.get_nickname()
        mime, data = self.utility.session.get_mugshot()
        if data is None:
            im = IconsManager.getInstance()
            self.mugshot = im.get_default('PEER_THUMB')
        else:
            self.mugshot = data2wxBitmap(mime, data)

        self.elements['myNameField'].SetValue(self.myname)
        self.elements['thumb'].setBitmap(self.mugshot)

        if self.guiUtility.frame.SRstatusbar.IsReachable():
            self.elements['firewallStatus'].setSelected(2)
            self.elements['firewallStatusText'].SetLabel('Port is working')

        self.currentPortValue = str(self.guiUtility.get_port_number())
        self.elements['firewallValue'].SetValue(self.currentPortValue)

        self.elements['downloadCtrl'].SetValue(self.utility.getMaxDown())
        self.elements['uploadCtrl'].SetValue(self.utility.getMaxUp())

        self.currentDestDir = self.defaultDLConfig.get_dest_dir()
        self.elements['diskLocationCtrl'].SetValue(self.currentDestDir)
        self.elements['diskLocationChoice'].SetValue(
            self.defaultDLConfig.get_show_saveas())

        if sys.platform != "darwin":
            min_to_tray = self.utility.config.Read('mintray', "int") == 1
            self.elements['minimize_to_tray'].SetValue(min_to_tray)
        else:
            self.elements['minimize_to_tray'].Enable(False)

        self.elements['t4t0'].SetLabel(self.utility.lang.get('no_leeching'))
        self.elements['t4t0'].Refresh()
        self.elements['t4t1'].SetLabel(
            self.utility.lang.get('unlimited_seeding'))
        self.elements['t4t2'].SetLabel(self.utility.lang.get('seed_sometime'))
        self.elements['t4t3'].SetLabel(self.utility.lang.get('no_seeding'))

        self.elements['g2g0'].SetLabel(
            self.utility.lang.get('seed_for_large_ratio'))
        self.elements['g2g1'].SetLabel(
            self.utility.lang.get('boost__reputation'))
        self.elements['g2g2'].SetLabel(self.utility.lang.get('seed_sometime'))
        self.elements['g2g3'].SetLabel(self.utility.lang.get('no_seeding'))

        t4t_option = self.utility.config.Read('t4t_option', 'int')
        self.elements['t4t%d' % t4t_option].SetValue(True)
        t4t_ratio = self.utility.config.Read('t4t_ratio', 'int') / 100.0
        index = self.elements['t4t0choice'].FindString(str(t4t_ratio))
        if index != wx.NOT_FOUND:
            self.elements['t4t0choice'].Select(index)

        t4t_hours = self.utility.config.Read('t4t_hours', 'int')
        t4t_minutes = self.utility.config.Read('t4t_mins', 'int')
        self.elements['t4t2text'].SetLabel("%d:%d" % (t4t_hours, t4t_minutes))

        g2g_option = self.utility.config.Read('g2g_option', 'int')
        self.elements['g2g%d' % g2g_option].SetValue(True)
        g2g_ratio = self.utility.config.Read('g2g_ratio', 'int') / 100.0
        index = self.elements['g2g0choice'].FindString(str(g2g_ratio))
        if index != wx.NOT_FOUND:
            self.elements['g2g0choice'].Select(index)

        g2g_hours = self.utility.config.Read('g2g_hours', 'int')
        g2g_mins = self.utility.config.Read('g2g_mins', 'int')
        self.elements['g2g2text'].SetLabel("%d:%d" % (g2g_hours, g2g_mins))

        self.elements['use_webui'].SetValue(
            self.utility.config.Read('use_webui', "boolean"))
        self.elements['webui_port'].SetValue(
            str(self.utility.config.Read('webui_port', "int")))

        wx.CallAfter(self.Refresh)
Example #50
0
    def InitStage1(self, installdir, autoload_discovery=True,
                   use_torrent_search=True, use_channel_search=True):
        """ Stage 1 start: pre-start the session to handle upgrade.
        """

        # Make sure the installation dir is on the PATH
        os.environ['PATH'] += os.pathsep + os.path.abspath(installdir)

        self.gui_image_manager = GuiImageManager.getInstance(installdir)

        # Start Tribler Session
        defaultConfig = SessionStartupConfig()
        state_dir = defaultConfig.get_state_dir()

        # Switch to the state dir so relative paths can be used (IE, in LevelDB store paths)
        if not os.path.exists(state_dir):
            os.makedirs(state_dir)
        os.chdir(state_dir)

        cfgfilename = Session.get_default_config_filename(state_dir)

        self._logger.debug(u"Session config %s", cfgfilename)
        try:
            self.sconfig = SessionStartupConfig.load(cfgfilename)
        except:
            try:
                self.sconfig = convertSessionConfig(os.path.join(state_dir, 'sessconfig.pickle'), cfgfilename)
                convertMainConfig(state_dir, os.path.join(state_dir, 'abc.conf'),
                                  os.path.join(state_dir, STATEDIR_GUICONFIG))
            except:
                self.sconfig = SessionStartupConfig()
                self.sconfig.set_state_dir(state_dir)

        self.sconfig.set_install_dir(self.installdir)

        # TODO(emilon): Do we still want to force limit this? With the new
        # torrent store it should be pretty fast even with more that that.

        # Arno, 2010-03-31: Hard upgrade to 50000 torrents collected
        self.sconfig.set_torrent_collecting_max_torrents(50000)

        dlcfgfilename = get_default_dscfg_filename(self.sconfig.get_state_dir())
        self._logger.debug("main: Download config %s", dlcfgfilename)
        try:
            defaultDLConfig = DefaultDownloadStartupConfig.load(dlcfgfilename)
        except:
            try:
                defaultDLConfig = convertDefaultDownloadConfig(
                    os.path.join(state_dir, 'dlconfig.pickle'), dlcfgfilename)
            except:
                defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        if not defaultDLConfig.get_dest_dir():
            defaultDLConfig.set_dest_dir(get_default_dest_dir())
        if not os.path.isdir(defaultDLConfig.get_dest_dir()):
            try:
                os.makedirs(defaultDLConfig.get_dest_dir())
            except:
                # Could not create directory, ask user to select a different location
                dlg = wx.DirDialog(None,
                                   "Could not find download directory, please select a new location to store your downloads",
                                   style=wx.DEFAULT_DIALOG_STYLE)
                dlg.SetPath(get_default_dest_dir())
                if dlg.ShowModal() == wx.ID_OK:
                    new_dest_dir = dlg.GetPath()
                    defaultDLConfig.set_dest_dir(new_dest_dir)
                    defaultDLConfig.save(dlcfgfilename)
                    self.sconfig.save(cfgfilename)
                else:
                    # Quit
                    self.onError = lambda e: self._logger.error(
                        "tribler: quitting due to non-existing destination directory")
                    raise Exception()

        if not use_torrent_search:
            self.sconfig.set_enable_torrent_search(False)
        if not use_channel_search:
            self.sconfig.set_enable_channel_search(False)

        session = Session(self.sconfig, autoload_discovery=autoload_discovery)
        session.add_observer(self.show_upgrade_dialog, NTFY_UPGRADER, [NTFY_STARTED])
        self.upgrader = session.prestart()

        while not self.upgrader.is_done:
            wx.SafeYield()
            sleep(0.1)

        return session
Example #51
0
    def resume_download(self,
                        filename,
                        initialdlstatus=None,
                        initialdlstatus_dict={},
                        setupDelay=0):
        tdef = dscfg = pstate = None

        try:
            pstate = self.load_download_pstate(filename)

            # SWIFTPROC
            metainfo = pstate.get('state', 'metainfo')
            if 'infohash' in metainfo:
                tdef = TorrentDefNoMetainfo(metainfo['infohash'],
                                            metainfo['name'],
                                            metainfo.get('url', None))
            else:
                tdef = TorrentDef.load_from_dict(metainfo)

            if pstate.has_option('downloadconfig', 'saveas') and \
                    isinstance(pstate.get('downloadconfig', 'saveas'), tuple):
                pstate.set('downloadconfig', 'saveas',
                           pstate.get('downloadconfig', 'saveas')[-1])

            dscfg = DownloadStartupConfig(pstate)

        except:
            # pstate is invalid or non-existing
            _, file = os.path.split(filename)

            infohash = binascii.unhexlify(file[:-6])

            torrent_data = self.torrent_store.get(infohash)
            if torrent_data:
                tdef = TorrentDef.load_from_memory(torrent_data)

                defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
                dscfg = defaultDLConfig.copy()

                if self.mypref_db is not None:
                    dest_dir = self.mypref_db.getMyPrefStatsInfohash(infohash)
                    if dest_dir:
                        if os.path.isdir(dest_dir) or dest_dir == '':
                            dscfg.set_dest_dir(dest_dir)

        self._logger.debug("tlm: load_checkpoint: pstate is %s %s",
                           pstate.get('dlstate', 'status'),
                           pstate.get('dlstate', 'progress'))
        if pstate is None or pstate.get('state', 'engineresumedata') is None:
            self._logger.debug("tlm: load_checkpoint: resumedata None")
        else:
            self._logger.debug("tlm: load_checkpoint: resumedata len %d",
                               len(pstate.get('state', 'engineresumedata')))

        if tdef and dscfg:
            if dscfg.get_dest_dir() != '':  # removed torrent ignoring
                try:
                    if not self.download_exists(tdef.get_infohash()):
                        initialdlstatus = initialdlstatus_dict.get(
                            tdef.get_infohash(), initialdlstatus)
                        self.add(tdef,
                                 dscfg,
                                 pstate,
                                 initialdlstatus,
                                 setupDelay=setupDelay)
                    else:
                        self._logger.info(
                            "tlm: not resuming checkpoint because download has already been added"
                        )

                except Exception as e:
                    self._logger.exception(
                        "tlm: load check_point: exception while adding download %s",
                        tdef)
            else:
                self._logger.info("tlm: removing checkpoint %s destdir is %s",
                                  filename, dscfg.get_dest_dir())
                os.remove(filename)
        else:
            self._logger.info("tlm: could not resume checkpoint %s %s %s",
                              filename, tdef, dscfg)
Example #52
0
    def start_session(self):
        """
        This function loads any previous configuration files from the TRIBLER_STATE_DIR environment variable and then
        starts a Tribler session.
        :return: Nothing.
        """
        if self._running:
            return False

        _logger.info("Set tribler_state_dir to %s" %
                     os.environ['TRIBLER_STATE_DIR'])

        # Load configuration file (if exists)
        cfgfilename = Session.get_default_config_filename(
            os.environ['TRIBLER_STATE_DIR'])
        try:
            self._sconfig = SessionStartupConfig.load(cfgfilename)
            _logger.info("Loaded previous configuration file from %s" %
                         cfgfilename)
        except:
            self._sconfig = SessionStartupConfig()
            self._sconfig.set_state_dir(os.environ['TRIBLER_STATE_DIR'])
            _logger.info(
                "No previous configuration file found, creating one in %s" %
                os.environ['TRIBLER_STATE_DIR'])

        # Set torrent collecting directory:
        dlcfgfilename = get_default_dscfg_filename(
            self._sconfig.get_state_dir())
        _logger.debug("main: Download config %s", dlcfgfilename)
        try:
            defaultDLConfig = DefaultDownloadStartupConfig.load(dlcfgfilename)
        except:
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        if not defaultDLConfig.get_dest_dir():
            defaultDLConfig.set_dest_dir(os.environ['TRIBLER_DOWNLOAD_DIR'])
            self._sconfig.set_torrent_collecting_dir(
                os.path.join(os.environ['TRIBLER_DOWNLOAD_DIR']))

        # Create download directory:
        if not os.path.isdir(defaultDLConfig.get_dest_dir()):
            try:
                _logger.info("Creating download directory: %s" %
                             defaultDLConfig.get_dest_dir())
                os.makedirs(defaultDLConfig.get_dest_dir())
            except:
                _logger.error("Couldn't create download directory! (%s)" %
                              defaultDLConfig.get_dest_dir())

        # TODO: This is temporary for testing:
        from jnius import autoclass
        python_activity = autoclass('org.renpy.android.PythonActivity')
        files_dir = python_activity.mActivity.getFilesDir().getAbsolutePath()
        install_dir = files_dir + u'/lib/python2.7/site-packages'
        _logger.info("Set tribler_install_dir to %s" % install_dir)
        self._sconfig.set_install_dir(install_dir)
        # TODO: ^End of temporary test.

        # Disable unwanted dependencies:
        self._sconfig.set_torrent_store(True)
        self._sconfig.set_torrent_checking(True)
        self._sconfig.set_multicast_local_peer_discovery(False)
        self._sconfig.set_mainline_dht(True)
        self._sconfig.set_dht_torrent_collecting(True)
        self._sconfig.set_torrent_collecting_max_torrents(5000)

        _logger.info("Starting Tribler session..")
        self._session = Session(self._sconfig)
        upgrader = self._session.prestart()
        while not upgrader.is_done:
            time.sleep(0.1)
        self._session.start()
        _logger.info("Tribler session started!")

        self._dispersy = self._session.get_dispersy_instance()
        self.define_communities()
Example #53
0
    def _PostInit(self):
        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        dialog = xrc.XRCCTRL(self, "settingsDialog")
        for element in self.elementsName:
            xrcElement = xrc.XRCCTRL(dialog, element)
            if not xrcElement:
                print "settingsOverviewPanel: Error: Could not identify xrc element:", element
            self.elements[element] = xrcElement

        # Building tree
        self.tree = xrc.XRCCTRL(self, "settings_tree")
        root = self.tree.AddRoot("Root")
        self.tree.SelectItem(
            self.tree.AppendItem(root, "General", data=wx.TreeItemData(xrc.XRCCTRL(self, "general_panel"))), True
        )
        self.tree.AppendItem(root, "Connection", data=wx.TreeItemData(xrc.XRCCTRL(self, "connection_panel")))
        self.tree.AppendItem(root, "Limits", data=wx.TreeItemData(xrc.XRCCTRL(self, "bandwidth_panel")))
        self.tree.AppendItem(root, "Seeding", data=wx.TreeItemData(xrc.XRCCTRL(self, "seeding_panel")))
        self.tree.AppendItem(root, "Experimental", data=wx.TreeItemData(xrc.XRCCTRL(self, "exp_panel")))
        self.tree.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnSelectionChanging)

        # Bind event listeners
        self.elements["zeroUp"].Bind(wx.EVT_BUTTON, lambda event: self.setUp(0, event))
        self.elements["fiftyUp"].Bind(wx.EVT_BUTTON, lambda event: self.setUp(50, event))
        self.elements["hundredUp"].Bind(wx.EVT_BUTTON, lambda event: self.setUp(100, event))
        self.elements["unlimitedUp"].Bind(wx.EVT_BUTTON, lambda event: self.setUp("unlimited", event))

        self.elements["seventyfiveDown"].Bind(wx.EVT_BUTTON, lambda event: self.setDown(75, event))
        self.elements["threehundredDown"].Bind(wx.EVT_BUTTON, lambda event: self.setDown(300, event))
        self.elements["sixhundreddDown"].Bind(wx.EVT_BUTTON, lambda event: self.setDown(600, event))
        self.elements["unlimitedDown"].Bind(wx.EVT_BUTTON, lambda event: self.setDown("unlimited", event))

        self.elements["uploadCtrl"].Bind(wx.EVT_KEY_DOWN, self.removeUnlimited)
        self.elements["downloadCtrl"].Bind(wx.EVT_KEY_DOWN, self.removeUnlimited)

        self.elements["edit"].Bind(wx.EVT_BUTTON, self.EditClicked)
        self.elements["browse"].Bind(wx.EVT_BUTTON, self.BrowseClicked)

        self.Bind(wx.EVT_BUTTON, self.saveAll, id=xrc.XRCID("wxID_OK"))
        self.Bind(wx.EVT_BUTTON, self.cancelAll, id=xrc.XRCID("wxID_CANCEL"))

        # Loading settings
        self.myname = self.utility.session.get_nickname()
        mime, data = self.utility.session.get_mugshot()
        if data is None:
            im = IconsManager.getInstance()
            self.mugshot = im.get_default("PEER_THUMB")
        else:
            self.mugshot = data2wxBitmap(mime, data)

        self.elements["myNameField"].SetValue(self.myname)
        self.elements["thumb"].SetBitmap(self.mugshot)

        if self.guiUtility.frame.SRstatusbar.IsReachable():
            self.elements["firewallStatusText"].SetLabel("Your network connection is working properly.")
        else:
            self.elements["firewallStatusText"].SetLabel(
                "Tribler has not yet received any incoming connections. \nThis could indicate a problem with your network connection."
            )

        self.currentPortValue = str(self.utility.session.get_listen_port())
        self.elements["firewallValue"].SetValue(self.currentPortValue)

        self.elements["downloadCtrl"].SetValue(self.utility.getMaxDown())
        self.elements["uploadCtrl"].SetValue(self.utility.getMaxUp())

        self.currentDestDir = self.defaultDLConfig.get_dest_dir()
        self.elements["diskLocationCtrl"].SetValue(self.currentDestDir)
        self.elements["diskLocationChoice"].SetValue(self.defaultDLConfig.get_show_saveas())

        if sys.platform != "darwin":
            min_to_tray = self.utility.config.Read("mintray", "int") == 1
            self.elements["minimize_to_tray"].SetValue(min_to_tray)
        else:
            self.elements["minimize_to_tray"].Enable(False)

        self.elements["t4t0"].SetLabel(self.utility.lang.get("no_leeching"))
        self.elements["t4t0"].Refresh()
        self.elements["t4t1"].SetLabel(self.utility.lang.get("unlimited_seeding"))
        self.elements["t4t2"].SetLabel(self.utility.lang.get("seed_sometime"))
        self.elements["t4t3"].SetLabel(self.utility.lang.get("no_seeding"))

        self.elements["g2g0"].SetLabel(self.utility.lang.get("seed_for_large_ratio"))
        self.elements["g2g1"].SetLabel(self.utility.lang.get("boost__reputation"))
        self.elements["g2g2"].SetLabel(self.utility.lang.get("seed_sometime"))
        self.elements["g2g3"].SetLabel(self.utility.lang.get("no_seeding"))

        t4t_option = self.utility.config.Read("t4t_option", "int")
        self.elements["t4t%d" % t4t_option].SetValue(True)
        t4t_ratio = self.utility.config.Read("t4t_ratio", "int") / 100.0
        index = self.elements["t4t0choice"].FindString(str(t4t_ratio))
        if index != wx.NOT_FOUND:
            self.elements["t4t0choice"].Select(index)

        t4t_hours = self.utility.config.Read("t4t_hours", "int")
        t4t_minutes = self.utility.config.Read("t4t_mins", "int")
        self.elements["t4t2text"].SetLabel("%d:%d" % (t4t_hours, t4t_minutes))

        g2g_option = self.utility.config.Read("g2g_option", "int")
        self.elements["g2g%d" % g2g_option].SetValue(True)
        g2g_ratio = self.utility.config.Read("g2g_ratio", "int") / 100.0
        index = self.elements["g2g0choice"].FindString(str(g2g_ratio))
        if index != wx.NOT_FOUND:
            self.elements["g2g0choice"].Select(index)

        g2g_hours = self.utility.config.Read("g2g_hours", "int")
        g2g_mins = self.utility.config.Read("g2g_mins", "int")
        self.elements["g2g2text"].SetLabel("%d:%d" % (g2g_hours, g2g_mins))

        self.elements["use_webui"].SetValue(self.utility.config.Read("use_webui", "boolean"))
        self.elements["webui_port"].SetValue(str(self.utility.config.Read("webui_port", "int")))

        wx.CallAfter(self.Refresh)
Example #54
0
    def startDownload(self,torrentfilename=None,destdir=None,tdef = None,cmdline=False,clicklog=None,name=None,vodmode=False,doemode=None,fixtorrent=False,selectedFiles=None):
        if DEBUG:
            print >>sys.stderr,"mainframe: startDownload:",torrentfilename,destdir,tdef
        
        if fixtorrent and torrentfilename:
            self.fixTorrent(torrentfilename)
        try:
            if tdef is None:
                tdef = TorrentDef.load(torrentfilename)
            defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
            dscfg = defaultDLConfig.copy()
            
            cancelDownload = False
            useDefault = not dscfg.get_show_saveas()
            if not useDefault and not destdir:
                dlg = SaveAs(self, tdef, dscfg.get_dest_dir(), os.path.join(self.utility.session.get_state_dir(), 'recent_download_history'))
                dlg.CenterOnParent()
                if dlg.ShowModal() == wx.ID_OK:
                    destdir = dlg.GetPath()
                else:
                    cancelDownload = True
                dlg.Destroy()
            
            if not cancelDownload:
                if destdir is not None:
                    dscfg.set_dest_dir(destdir)
            
                # ProxyService 90s Test_
#                if doemode is not None:
#                    dscfg.set_doe_mode(doemode)
#                    dscfg.set_proxyservice_role(PROXYSERVICE_ROLE_DOE)
                # _ProxyService 90s Test
            
                videofiles = tdef.get_files(exts=videoextdefaults)
                if vodmode and len(videofiles) == 0:
                    vodmode = False
    
                if vodmode or tdef.get_live():
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in VOD mode'
                    videoplayer = VideoPlayer.getInstance()
                    result = videoplayer.start_and_play(tdef,dscfg)
    
                    # 02/03/09 boudewijn: feedback to the user when there
                    # are no playable files in the torrent
                    if not result:
                        dlg = wx.MessageDialog(self,
                                   self.utility.lang.get("invalid_torrent_no_playable_files_msg"),
                                   self.utility.lang.get("invalid_torrent_no_playable_files_title"),
                                   wx.OK|wx.ICON_ERROR)
                        dlg.ShowModal()
                        dlg.Destroy()
                else:
                    if selectedFiles:
                        dscfg.set_selected_files(selectedFiles)
                    
                    print >>sys.stderr, 'MainFrame: startDownload: Starting in DL mode'
                    result = self.utility.session.start_download(tdef,dscfg)
                
                if result:
                    self.show_saved()
                
                # store result because we want to store clicklog data
                # right after d#        self.frame.sendButton.Disable()
#        # Disabling the focused button disables keyboard navigation
#        # unless we set the focus to something else - let's put it
#        # on close button
#        self.frame.closeButton.SetFocus() 
#        self.frame.sendButton.SetLabel(_(u'Sending...'))
#        
#        try:
#            from M2Crypto import httpslib, SSL
#            # Try to load the CA certificates for secure SSL.
#            # If we can't load them, the data is hidden from casual observation,
#            # but a man-in-the-middle attack is possible.
#            ctx = SSL.Context()
#            opts = {}
#            if ctx.load_verify_locations('parcels/osaf/framework/certstore/cacert.pem') == 1:
#                ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 9)
#                opts['ssl_context'] = ctx
#            c = httpslib.HTTPSConnection('feedback.osafoundation.org', 443, opts)
#            body = buildXML(self.frame.comments, self.frame.email,
#                            self.frame.sysInfo, self.frame.text)
#            c.request('POST', '/desktop/post/submit', body)
#            response = c.getresponse()
#            
#            if response.status != 200:
#                raise Exception('response.status=' + response.status)
#            c.close()
#        except:
#            self.frame.sendButton.SetLabel(_(u'Failed to send'))
#        else:
#            self.frame.sendButton.SetLabel(_(u'Sent'))
#            self.logReport(body, response.read())ownload was started, then return result
                if clicklog is not None:
                    mypref = self.utility.session.open_dbhandler(NTFY_MYPREFERENCES)
                    mypref.addClicklogToMyPreference(tdef.get_infohash(), clicklog)

                return result  

        except DuplicateDownloadException:
            # show nice warning dialog
            dlg = wx.MessageDialog(None,
                                   self.utility.lang.get('duplicate_download_msg'),
                                   self.utility.lang.get('duplicate_download_title'),
                                   wx.OK|wx.ICON_ERROR)
            result = dlg.ShowModal()
            dlg.Destroy()
            
            # If there is something on the cmdline, all other torrents start
            # in STOPPED state. Restart
            if cmdline:
                dlist = self.utility.session.get_downloads()
                for d in dlist:
                    if d.get_def().get_infohash() == tdef.get_infohash():
                        d.restart()
                        break
        except Exception,e:
            print_exc()
            self.onWarning(e)
Example #55
0
def _upgradeVersion(self, my_version, latest_version, info):
    # check if there is a .torrent for our OS
    torrent_key = "torrent-%s" % sys.platform
    notes_key = "notes-txt-%s" % sys.platform
    if torrent_key in info:
        self._logger.info("-- Upgrade %s -> %s", my_version, latest_version)
        notes = []
        if "notes-txt" in info:
            notes.append(info["notes-txt"])
        if notes_key in info:
            notes.append(info[notes_key])
        notes = "\n".join(notes)
        if notes:
            for line in notes.split("\n"):
                self._logger.info("-- Notes: %s", line)
        else:
            notes = "No release notes found"
        self._logger.info("-- Downloading %s for upgrade", info[torrent_key])

        # prepare directory and .torrent file
        location = os.path.join(self.utility.session.get_state_dir(), "upgrade")
        if not os.path.exists(location):
            os.mkdir(location)
        self._logger.info("-- Dir: %s", location)
        filename = os.path.join(location, os.path.basename(urlparse.urlparse(info[torrent_key])[2]))
        self._logger.info("-- File: %s", filename)
        if not os.path.exists(filename):
            urllib.urlretrieve(info[torrent_key], filename)

        # torrent def
        tdef = TorrentDef.load(filename)
        defaultDLConfig = DefaultDownloadStartupConfig.getInstance()
        dscfg = defaultDLConfig.copy()

        # figure out what file to start once download is complete
        files = tdef.get_files_as_unicode()
        executable = None
        for file_ in files:
            if sys.platform == "win32" and file_.endswith(u".exe"):
                self._logger.info("-- exe: %s", file_)
                executable = file_
                break

            elif sys.platform == "linux2" and file_.endswith(u".deb"):
                self._logger.info("-- deb: %s", file_)
                executable = file_
                break

            elif sys.platform == "darwin" and file_.endswith(u".dmg"):
                self._logger.info("-- dmg: %s", file_)
                executable = file_
                break

        if not executable:
            self._logger.info("-- Abort upgrade: no file found")
            return

        # start download
        try:
            download = self.utility.session.start_download(tdef)

        except DuplicateDownloadException:
            self._logger.error("-- Duplicate download")
            download = None
            for random_download in self.utility.session.get_downloads():
                if random_download.get_def().get_infohash() == tdef.get_infohash():
                    download = random_download
                    break

        # continue until download is finished
        if download:
            def start_upgrade():
                """
                Called by python when everything is shutdown.  We
                can now start the downloaded file that will
                upgrade tribler.
                """
                executable_path = os.path.join(download.get_dest_dir(), executable)

                if sys.platform == "win32":
                    args = [executable_path]

                elif sys.platform == "linux2":
                    args = ["gdebi-gtk", executable_path]

                elif sys.platform == "darwin":
                    args = ["open", executable_path]

                self._logger.info("-- Tribler closed, starting upgrade")
                self._logger.info("-- Start: %s", args)
                subprocess.Popen(args)

            def wxthread_upgrade():
                """
                Called on the wx thread when the .torrent file is
                downloaded.  Will ask the user if Tribler can be
                shutdown for the upgrade now.
                """
                if self.Close():
                    atexit.register(start_upgrade)
                else:
                    self.shutdown_and_upgrade_notes = None

            def state_callback(state):
                """
                Called every n seconds with an update on the
                .torrent download that we need to upgrade
                """
                self._logger.debug("-- State: %s %s", dlstatus_strings[state.get_status()], state.get_progress())
                # todo: does DLSTATUS_STOPPED mean it has completely downloaded?
                if state.get_status() == DLSTATUS_SEEDING:
                    self.shutdown_and_upgrade_notes = notes
                    wx.CallAfter(wxthread_upgrade)
                    return (0.0, False)
                return (1.0, False)

            download.set_state_callback(state_callback)
Example #56
0
    def __init__(self):
        super(SettingsDialog, self).__init__(None,
                                             size=(600, 600),
                                             title="Settings",
                                             name="settingsDialog",
                                             style=wx.DEFAULT_DIALOG_STYLE)
        self.SetExtraStyle(self.GetExtraStyle()
                           | wx.WS_EX_VALIDATE_RECURSIVELY)
        self._logger = logging.getLogger(self.__class__.__name__)

        self.guiUtility = GUIUtility.getInstance()
        self.utility = self.guiUtility.utility
        self.defaultDLConfig = DefaultDownloadStartupConfig.getInstance()

        # create the dialog and widgets
        self._tree_ctrl = wx.TreeCtrl(self,
                                      style=wx.TR_DEFAULT_STYLE
                                      | wx.SUNKEN_BORDER | wx.TR_HIDE_ROOT
                                      | wx.TR_SINGLE)
        self._tree_ctrl.SetMinSize(wx.Size(150, -1))
        tree_root = self._tree_ctrl.AddRoot('Root')
        self._tree_ctrl.Bind(wx.EVT_TREE_SEL_CHANGING,
                             self.OnSelectionChanging)

        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(self._tree_ctrl, 0, wx.EXPAND | wx.RIGHT, 10)

        self._general_panel, self._general_id = self.__create_s1(
            tree_root, hsizer)
        self._conn_panel, self._conn_id = self.__create_s2(tree_root, hsizer)
        self._bandwidth_panel, self._bandwidth_id = self.__create_s3(
            tree_root, hsizer)
        self._seeding_panel, self._seeding_id = self.__create_s4(
            tree_root, hsizer)
        self._experimental_panel, self._experimental_id = self.__create_s5(
            tree_root, hsizer)
        self._tunnel_panel, self._tunnel_id = self.__create_s6(
            tree_root, hsizer)

        self._general_panel.Show(True)
        self._conn_panel.Show(False)
        self._bandwidth_panel.Show(False)
        self._seeding_panel.Show(False)
        self._experimental_panel.Show(False)
        self._tunnel_panel.Show(False)

        self._save_btn = wx.Button(self, wx.ID_OK, label="Save")
        self._cancel_btn = wx.Button(self, wx.ID_CANCEL, label="Cancel")

        btn_sizer = wx.StdDialogButtonSizer()
        btn_sizer.AddButton(self._save_btn)
        btn_sizer.AddButton(self._cancel_btn)
        btn_sizer.Realize()

        self._save_btn.Bind(wx.EVT_BUTTON, self.saveAll)
        self._cancel_btn.Bind(wx.EVT_BUTTON, self.cancelAll)

        vsizer = wx.BoxSizer(wx.VERTICAL)
        vsizer.Add(hsizer, 1, wx.EXPAND | wx.ALL, 10)
        vsizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizer(vsizer)

        # select General page by default
        self._tree_ctrl.SelectItem(self._general_id)