Changeset 946961


Ignore:
Timestamp:
02/02/2008 01:30:18 AM (17 years ago)
Author:
Andrew Resch <andrewresch@gmail.com>
Branches:
2.0.x, develop, extjs4-port, master
Children:
8ab923
Parents:
e2eaa9a
Message:

Use new torrent states instead of using libtorrent's.

Location:
deluge
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • deluge/common.py

    re2eaa9a r946961  
    4040
    4141
    42 TORRENT_STATE = [
    43     "Queued",
    44     "Checking",
    45     "Connecting",
    46     "Downloading Metadata",
    47     "Downloading",
    48     "Finished",
    49     "Seeding",
    50     "Allocating",
    51     "Paused"
    52 ]
    53 
     42LT_TORRENT_STATE = {
     43    "Queued": 0,
     44    "Checking": 1,
     45    "Connecting": 2,
     46    "Downloading Metadata": 3,
     47    "Downloading": 4,
     48    "Finished": 5,
     49    "Seeding": 6,
     50    "Allocating": 7,
     51    "Paused": 8
     52}
     53
     54TORRENT_STATE = {
     55    "Allocating": 0,
     56    "Checking": 1,
     57    "Downloading": 2,
     58    "Seeding": 3,
     59    "Paused": 4,
     60    "Error": 5
     61}
    5462def get_version():
    5563    """Returns the program version from the egg metadata"""
  • deluge/core/core.py

    re2eaa9a r946961  
    345345    def export_force_reannounce(self, torrent_id):
    346346        log.debug("Forcing reannouncment to trackers of torrent %s", torrent_id)
    347         self.torrents.force_reannounce(torrent_id)
     347        self.torrents[torrent_id].force_reannounce()
    348348
    349349    def export_pause_torrent(self, torrent_id):
    350350        log.debug("Pausing torrent %s", torrent_id)
    351         if not self.torrents.pause(torrent_id):
     351        if not self.torrents[torrent_id].pause():
    352352            log.warning("Error pausing torrent %s", torrent_id)
    353353   
    354     def export_move_torrent(self, torrent_id, folder):
    355         log.debug("Moving torrent %s to %s", torrent_id, folder)
    356         if not self.torrents.move(torrent_id, folder):
    357             log.warning("Error moving torrent %s to %s", torrent_id, folder)
     354    def export_move_torrent(self, torrent_id, dest):
     355        log.debug("Moving torrent %s to %s", torrent_id, dest)
     356        if not self.torrents[torrent_id].move(dest):
     357            log.warning("Error moving torrent %s to %s", torrent_id, dest)
    358358   
    359359    def export_pause_all_torrents(self):
     
    370370    def export_resume_torrent(self, torrent_id):
    371371        log.debug("Resuming torrent %s", torrent_id)
    372         if self.torrents.resume(torrent_id):
     372        if self.torrents[torrent_id].resume():
    373373            self.torrent_resumed(torrent_id)
    374374
     
    478478    def export_set_torrent_trackers(self, torrent_id, trackers):
    479479        """Sets a torrents tracker list.  trackers will be [{"url", "tier"}]"""
    480         return self.torrents.set_trackers(torrent_id, trackers)
     480        return self.torrents[torrent_id].set_trackers(trackers)
    481481       
    482482    # Signals
  • deluge/core/torrent.py

    re2eaa9a r946961  
    3434"""Internal Torrent class"""
    3535
     36import os
     37
     38import deluge.libtorrent as lt
    3639import deluge.common
     40from deluge.configmanager import ConfigManager
     41from deluge.log import LOG as log
     42
     43TORRENT_STATE = deluge.common.TORRENT_STATE
    3744
    3845class Torrent:
     
    4148    def __init__(self, filename, handle, compact, save_path, total_uploaded=0,
    4249        trackers=None):
     50        # Get the core config
     51        self.config = ConfigManager("core.conf")
     52       
    4353        # Set the filename
    4454        self.filename = filename
     
    5363        # Where the torrent is being saved to
    5464        self.save_path = save_path
    55        
     65        # The state of the torrent
     66        self.state = None
     67       
     68        # Holds status info so that we don't need to keep getting it from lt
     69        self.status = self.handle.status()
     70        self.torrent_info = self.handle.torrent_info()
     71       
     72        # Set the initial state
     73        if self.status.state == deluge.common.LT_TORRENT_STATE["Allocating"]:
     74            self.set_state("Allocating")
     75        elif self.status.state == deluge.common.LT_TORRENT_STATE["Checking"]:
     76            self.set_state("Checking")
     77        else:
     78            self.set_state("Paused")
     79       
     80        # Various torrent options
    5681        self.max_connections = -1
    5782        self.max_upload_slots = -1
     
    7499        else:
    75100            self.trackers = trackers
    76 
    77         # Holds status info so that we don't need to keep getting it from lt
    78         self.status = None
    79         self.torrent_info = None
    80101               
    81102        # Files dictionary
     
    115136        self.file_priorities = file_priorities
    116137        self.handle.prioritize_files(file_priorities)
    117            
    118     def get_state(self):
     138   
     139    def set_state(self, state):
     140        """Accepts state strings, ie, "Paused", "Seeding", etc."""
     141
     142        # Only set 'Downloading' or 'Seeding' state if not paused
     143        if state == "Downloading" or state == "Seeding":
     144            if self.handle.is_paused():
     145                state = "Paused"
     146               
     147        try:
     148            self.state = TORRENT_STATE[state]
     149        except:
     150            pass
     151       
     152    def get_save_info(self):
    119153        """Returns the state of this torrent for saving to the session state"""
    120154        status = self.handle.status()
     
    189223        progress = self.status.progress * 100
    190224       
    191         # Set the state to 'Paused' if the torrent is paused.
    192         state = self.status.state
    193         if self.status.paused:
    194             state = deluge.common.TORRENT_STATE.index("Paused")
    195        
    196225        # Adjust status.distributed_copies to return a non-negative value
    197226        distributed_copies = self.status.distributed_copies
     
    208237            "total_done": self.status.total_done,
    209238            "total_uploaded": self.total_uploaded + self.status.total_payload_upload,
    210             "state": int(state),
     239            "state": self.state,
    211240            "paused": self.status.paused,
    212241            "progress": progress,
     
    243272
    244273        return status_dict
     274       
     275    def pause(self):
     276        """Pause this torrent"""
     277        try:
     278            self.handle.pause()
     279        except Exception, e:
     280            log.debug("Unable to pause torrent: %s", e)
     281            return False
     282       
     283        return True
     284   
     285    def resume(self):
     286        """Resumes this torrent"""
     287        if self.state != TORRENT_STATE["Paused"]:
     288            return False
     289       
     290        try:
     291            self.handle.resume()
     292        except:
     293            return False
     294       
     295        # Set the state
     296        if self.handle.is_seed():
     297            self.set_state("Seeding")
     298        else:
     299            self.set_state("Downloading")
     300       
     301        status = self.get_status(["total_done", "total_wanted"])
     302       
     303        # Only delete the .fastresume file if we're still downloading stuff
     304        if status["total_done"] < status["total_wanted"]:
     305            self.delete_fastresume()
     306        return True
     307       
     308    def move_storage(self, dest):
     309        """Move a torrent's storage location"""
     310        try:
     311            self.handle.move_storage(dest)
     312        except:
     313            return False
     314
     315        return True
     316
     317    def write_fastresume(self):
     318        """Writes the .fastresume file for the torrent"""
     319        resume_data = lt.bencode(self.handle.write_resume_data())
     320        path = "%s/%s.fastresume" % (
     321            self.config["torrentfiles_location"],
     322            self.filename)
     323        log.debug("Saving fastresume file: %s", path)
     324        try:
     325            fastresume = open(path, "wb")
     326            fastresume.write(resume_data)
     327            fastresume.close()
     328        except IOError:
     329            log.warning("Error trying to save fastresume file")       
     330
     331    def delete_fastresume(self):
     332        """Deletes the .fastresume file"""
     333        path = "%s/%s.fastresume" % (
     334            self.config["torrentfiles_location"],
     335            self.filename)
     336        log.debug("Deleting fastresume file: %s", path)
     337        try:
     338            os.remove(path)
     339        except Exception, e:
     340            log.warning("Unable to delete the fastresume file: %s", e)
     341
     342    def force_reannounce(self):
     343        """Force a tracker reannounce"""
     344        try:
     345            self.handle.force_reannounce()
     346        except Exception, e:
     347            log.debug("Unable to force reannounce: %s", e)
     348            return False
     349       
     350        return True
     351   
     352    def scrape_tracker(self):
     353        """Scrape the tracker"""
     354        try:
     355            self.handle.scrape_tracker()
     356        except Exception, e:
     357            log.debug("Unable to scrape tracker: %s", e)
     358            return False
     359       
     360        return True
     361       
     362    def set_trackers(self, trackers):
     363        """Sets trackers"""
     364        if trackers == None:
     365            trackers = []
     366           
     367        log.debug("Setting trackers for %s: %s", self.torrent_id, trackers)
     368        tracker_list = []
     369
     370        for tracker in trackers:
     371            new_entry = lt.announce_entry(tracker["url"])
     372            new_entry.tier = tracker["tier"]
     373            tracker_list.append(new_entry)
     374           
     375        self.handle.replace_trackers(tracker_list)
     376       
     377        # Print out the trackers
     378        for t in self.handle.trackers():
     379            log.debug("tier: %s tracker: %s", t.tier, t.url)
     380        # Set the tracker list in the torrent object
     381        self.trackers = trackers
     382        if len(trackers) > 0:
     383            # Force a reannounce if there is at least 1 tracker
     384            self.force_reannounce()
     385
     386    def save_torrent_file(self, filedump=None):
     387        """Saves a torrent file"""
     388        log.debug("Attempting to save torrent file: %s", self.filename)
     389        # Test if the torrentfiles_location is accessible
     390        if os.access(
     391            os.path.join(self.config["torrentfiles_location"]), os.F_OK) \
     392                                                                    is False:
     393            # The directory probably doesn't exist, so lets create it
     394            try:
     395               os.makedirs(os.path.join(self.config["torrentfiles_location"]))
     396            except IOError, e:
     397                log.warning("Unable to create torrent files directory: %s", e)
     398       
     399        # Write the .torrent file to the torrent directory
     400        try:
     401            save_file = open(os.path.join(self.config["torrentfiles_location"],
     402                    self.filename),
     403                    "wb")
     404            if filedump == None:
     405                filedump = self.handle.torrent_info().create_torrent()
     406            save_file.write(lt.bencode(filedump))
     407            save_file.close()
     408        except IOError, e:
     409            log.warning("Unable to save torrent file: %s", e)
  • deluge/core/torrentmanager.py

    re2eaa9a r946961  
    9494        self.alerts.register_handler("torrent_paused_alert",
    9595            self.on_alert_torrent_paused)
     96        self.alerts.register_handler("torrent_checked_alert",
     97            self.on_alert_torrent_checked)
    9698        self.alerts.register_handler("tracker_reply_alert",
    9799            self.on_alert_tracker_reply)
     
    117119        self.pause_all()
    118120        for key in self.torrents.keys():
    119             self.write_fastresume(key)
     121            self.torrents[key].write_fastresume()
    120122       
    121123    def shutdown(self):
     
    229231        # Set the trackers
    230232        if trackers != None:
    231             self.set_trackers(str(handle.info_hash()), trackers)
     233            torrent.set_trackers(trackers)
    232234                   
    233235        # Set per-torrent options
     
    251253           
    252254        # Save the torrent file       
    253         self.save_torrent(filename, filedump)
     255        torrent.save_torrent_file(filedump)
    254256
    255257        # Save the session state
    256258        self.save_state()
    257259        return torrent.torrent_id
    258    
    259     def save_torrent(self, filename, filedump):
    260         """Saves a torrent file"""
    261         log.debug("Attempting to save torrent file: %s", filename)
    262         # Test if the torrentfiles_location is accessible
    263         if os.access(
    264             os.path.join(self.config["torrentfiles_location"]), os.F_OK) \
    265                                                                     is False:
    266             # The directory probably doesn't exist, so lets create it
    267             try:
    268                os.makedirs(os.path.join(self.config["torrentfiles_location"]))
    269             except IOError, e:
    270                 log.warning("Unable to create torrent files directory: %s", e)
    271        
    272         # Write the .torrent file to the torrent directory
    273         try:
    274             save_file = open(os.path.join(self.config["torrentfiles_location"],
    275                     filename),
    276                     "wb")
    277             save_file.write(lt.bencode(filedump))
    278             save_file.close()
    279         except IOError, e:
    280             log.warning("Unable to save torrent file: %s", e)
    281260
    282261    def load_torrent(self, filename):
     
    323302
    324303        # Remove the .fastresume if it exists
    325         self.delete_fastresume(torrent_id)
     304        self.torrents[torrent_id].delete_fastresume()
    326305       
    327306        # Remove the torrent from deluge's session
     
    333312        # Save the session state
    334313        self.save_state()
    335         return True
    336 
    337     def pause(self, torrent_id):
    338         """Pause a torrent"""
    339         try:
    340             self.torrents[torrent_id].handle.pause()
    341         except:
    342             return False
    343            
    344         return True
    345    
    346     def move(self, torrent_id, folder):
    347         """Move a torrent"""
    348         try:
    349             self.torrents[torrent_id].handle.move_storage(folder)
    350         except:
    351             return False
    352 
    353314        return True
    354315   
     
    364325       
    365326        return torrent_was_paused
    366        
    367     def resume(self, torrent_id):
    368         """Resume a torrent"""
    369         try:
    370             self.torrents[torrent_id].handle.resume()
    371         except:
    372             return False
    373        
    374         status = self.torrents[torrent_id].get_status(
    375             ["total_done", "total_wanted"])
    376        
    377         # Only delete the .fastresume file if we're still downloading stuff
    378         if status["total_done"] < status["total_wanted"]:
    379             self.delete_fastresume(torrent_id)
    380         return True
    381327
    382328    def resume_all(self):
    383         """Resumes all torrents.. Returns a list of torrents resumed"""
     329        """Resumes all torrents.. Returns True if at least 1 torrent is resumed"""
    384330        torrent_was_resumed = False
    385331        for key in self.torrents.keys():
     
    390336
    391337        return torrent_was_resumed
    392    
    393     def set_trackers(self, torrent_id, trackers):
    394         """Sets trackers"""
    395         if trackers == None:
    396             trackers = []
    397            
    398         log.debug("Setting trackers for %s: %s", torrent_id, trackers)
    399         tracker_list = []
    400 
    401         for tracker in trackers:
    402             new_entry = lt.announce_entry(tracker["url"])
    403             new_entry.tier = tracker["tier"]
    404             tracker_list.append(new_entry)
    405            
    406         self.torrents[torrent_id].handle.replace_trackers(tracker_list)
    407         # Print out the trackers
    408         for t in self.torrents[torrent_id].handle.trackers():
    409             log.debug("tier: %s tracker: %s", t.tier, t.url)
    410         # Set the tracker list in the torrent object
    411         self.torrents[torrent_id].trackers = trackers
    412         if len(trackers) > 0:
    413             # Force a reannounce if there is at least 1 tracker
    414             self.force_reannounce(torrent_id)
    415        
    416     def force_reannounce(self, torrent_id):
    417         """Force a tracker reannounce"""
    418         try:
    419             self.torrents[torrent_id].handle.force_reannounce()
    420         except Exception, e:
    421             log.debug("Unable to force reannounce: %s", e)
    422             return False
    423        
    424         return True
    425    
    426     def scrape_tracker(self, torrent_id):
    427         """Scrape the tracker"""
    428         try:
    429             self.torrents[torrent_id].handle.scrape_tracker()
    430         except Exception, e:
    431             log.debug("Unable to scrape tracker: %s", e)
    432             return False
    433        
    434         return True
    435        
     338       
    436339    def force_recheck(self, torrent_id):
    437340        """Forces a re-check of the torrent's data"""
     
    444347                 "/" + torrent.filename), os.F_OK) is False:
    445348            torrent_info = torrent.handle.get_torrent_info().create_torrent()
    446             self.save_torrent(torrent.filename, torrent_info)
     349            torrent.save_torrent_file()
    447350
    448351        # We start by removing it from the lt session           
     
    454357
    455358        # Remove the fastresume file if there
    456         self.delete_fastresume(torrent_id)
     359        torrent.delete_fastresume()
    457360       
    458361        # Load the torrent info from file if needed
     
    482385            return False       
    483386       
     387        # Set the state to Checking
     388        torrent.set_state("Checking")
     389       
    484390        return True
    485391       
     
    509415        # Create the state for each Torrent and append to the list
    510416        for torrent in self.torrents.values():
    511             torrent_state = TorrentState(*torrent.get_state())
     417            torrent_state = TorrentState(*torrent.get_save_info())
    512418            state.torrents.append(torrent_state)
    513419       
     
    525431        return True
    526432   
    527     def delete_fastresume(self, torrent_id):
    528         """Deletes the .fastresume file"""
    529         torrent = self.torrents[torrent_id]
    530         path = "%s/%s.fastresume" % (
    531             self.config["torrentfiles_location"],
    532             torrent.filename)
    533         log.debug("Deleting fastresume file: %s", path)
    534         try:
    535             os.remove(path)
    536         except Exception, e:
    537             log.warning("Unable to delete the fastresume file: %s", e)
    538            
    539     def write_fastresume(self, torrent_id):
    540         """Writes the .fastresume file for the torrent"""
    541         torrent = self.torrents[torrent_id]
    542         resume_data = lt.bencode(torrent.handle.write_resume_data())
    543         path = "%s/%s.fastresume" % (
    544             self.config["torrentfiles_location"],
    545             torrent.filename)
    546         log.debug("Saving fastresume file: %s", path)
    547         try:
    548             fastresume = open(path,"wb")
    549             fastresume.write(resume_data)
    550             fastresume.close()
    551         except IOError:
    552             log.warning("Error trying to save fastresume file")
    553 
    554433    def on_set_max_connections_per_torrent(self, key, value):
    555434        """Sets the per-torrent connection limit"""
     
    572451        torrent_id = str(alert.handle.info_hash())
    573452        log.debug("%s is finished..", torrent_id)
     453        # Set the torrent state
     454        self.torrents[torrent_id].set_state("Seeding")
    574455        # Write the fastresume file
    575         self.write_fastresume(torrent_id)
     456        self.torrents[torrent_id].write_fastresume()
    576457       
    577458    def on_alert_torrent_paused(self, alert):
     
    579460        # Get the torrent_id
    580461        torrent_id = str(alert.handle.info_hash())
     462        # Set the torrent state
     463        self.torrents[torrent_id].set_state("Paused")
    581464        # Write the fastresume file
    582         self.write_fastresume(torrent_id)
    583            
     465        self.torrents[torrent_id].write_fastresume()
     466           
     467    def on_alert_torrent_checked(self, alert):
     468        log.debug("on_alert_torrent_checked")
     469        # Get the torrent_id
     470        torrent_id = str(alert.handle.info_hash())
     471        # Set the torrent state
     472        self.torrents[torrent_id].set_state("Downloading")
     473               
    584474    def on_alert_tracker_reply(self, alert):
    585475        log.debug("on_alert_tracker_reply")
  • deluge/ui/gtkui/sidebar.py

    re2eaa9a r946961  
    3838import deluge.common
    3939from deluge.log import LOG as log
     40
     41TORRENT_STATE = deluge.common.TORRENT_STATE
    4042
    4143class SideBar(component.Component):
     
    103105        if value == "Downloading":
    104106            component.get("TorrentView").set_filter("state",
    105                 deluge.common.TORRENT_STATE.index("Downloading"))
    106            
     107                TORRENT_STATE["Downloading"])
    107108        if value == "Seeding":
    108109            component.get("TorrentView").set_filter("state",
    109                 deluge.common.TORRENT_STATE.index("Seeding"))
    110 
     110                TORRENT_STATE["Seeding"])
    111111        if value == "Paused":
    112112            component.get("TorrentView").set_filter("state",
    113                 deluge.common.TORRENT_STATE.index("Paused"))
     113                TORRENT_STATE["Paused"])
    114114
  • deluge/ui/gtkui/toolbar.py

    re2eaa9a r946961  
    4343
    4444class ToolBar(component.Component):
    45     STATE_FINISHED = TORRENT_STATE.index("Finished")
    46     STATE_SEEDING = TORRENT_STATE.index("Seeding")
    47     STATE_PAUSED = TORRENT_STATE.index("Paused")
    4845    def __init__(self):
    4946        component.Component.__init__(self, "ToolBar")
     
    176173                    log.debug("Error getting torrent state: %s", e)
    177174                    continue
    178                 if status == self.STATE_PAUSED:
     175                if status == TORRENT_STATE["Paused"]:
    179176                    resume = True
    180177                else:
  • deluge/ui/gtkui/torrentview.py

    re2eaa9a r946961  
    4949import deluge.ui.gtkui.listview as listview
    5050
     51TORRENT_STATE = deluge.common.TORRENT_STATE
     52
    5153# Status icons.. Create them from file only once to avoid constantly
    5254# re-creating them.
     
    5759icon_inactive = gtk.gdk.pixbuf_new_from_file(
    5860    deluge.common.get_pixmap("inactive16.png"))
     61icon_alert = gtk.gdk.pixbuf_new_from_file(
     62    deluge.common.get_pixmap("alert16.png"))
    5963
    6064# Holds the info for which status icon to display based on state
    6165ICON_STATE = [
    6266    icon_inactive,
    63     icon_downloading,
    64     icon_downloading,
    65     icon_downloading,
     67    icon_inactive,
    6668    icon_downloading,
    6769    icon_seeding,
    68     icon_seeding,
    69     icon_downloading,
    70     icon_inactive
     70    icon_inactive,
     71    icon_alert
    7172]
    7273 
     
    7980def cell_data_progress(column, cell, model, row, data):
    8081    """Display progress bar with text"""
    81     # Translated state strings
    82     TORRENT_STATE = [
    83         _("Queued"),
    84         _("Checking"),
    85         _("Connecting"),
    86         _("Downloading Metadata"),
    87         _("Downloading"),
    88         _("Finished"),
    89         _("Seeding"),
    90         _("Allocating"),
    91         _("Paused")
    92     ]
    9382    (value, text) = model.get(row, *data)
    9483    if cell.get_property("value") != value:
    9584        cell.set_property("value", value)
    96     textstr = "%s" % TORRENT_STATE[text]
    97     if TORRENT_STATE[text] != "Seeding" and TORRENT_STATE[text] != "Finished":
     85    state_str = ""
     86    for key in TORRENT_STATE.keys():
     87        if TORRENT_STATE[key] == text:
     88            state_str = key
     89            break
     90    textstr = "%s" % state_str
     91    if state_str != "Seeding" and state_str != "Finished" and value < 100:
    9892        textstr = textstr + " %.2f%%" % value       
    9993    if cell.get_property("text") != textstr:
Note: See TracChangeset for help on using the changeset viewer.