addtorrents.py

来自「ABC-win32-v3.1 一个P2P软源代码」· Python 代码 · 共 422 行 · 第 1/2 页

PY
422
字号
import sys
import wx
import os

from shutil import copy2
from string import join as stjoin
from urlparse import urlsplit, urlunsplit
from urllib import quote, unquote
from sha import sha
#from traceback import print_exc
#from cStringIO import StringIO

from BitTornado.bencode import bencode, bdecode
from BitTornado.zurllib import urlopen

from ABC.Torrent.abctorrent import ABCTorrent

from Utility.compat import convertOldList
from Utility.constants import * #IGNORE:W0611

#
# Get a .torrent file from a url
#
def getTorrentFromURL(url):
    # Copy file from web and call addnewproc
    #########################################
    btmetafile = None
    try:
        url_splitted = urlsplit(url)
        h = urlopen(urlunsplit([url_splitted[0], url_splitted[1], quote(unquote(url_splitted[2])), url_splitted[3], url_splitted[4]]))
        
        btmetafile = h.read()
        h.close()
    except:
        try:
            h.close()
        except:
            pass

    return btmetafile


################################################################
#
# Class: AddTorrents
#
# Deal with adding torrents to the list
#
################################################################
class AddTorrents:
    def __init__(self, queue):
        self.queue = queue
        self.utility = queue.utility
                  
    def AddTorrentURL(self, url, caller=""):
        # Strip any leading/trailing spaces from the URL
        url = url.strip()
        
        # Copy file from web and call addnewproc
        #########################################
        btmetafile = getTorrentFromURL(url)
        if btmetafile is None:
            if caller != "web":
                #display error can't connect to server
                dialog = wx.MessageDialog(None, self.utility.lang.get('cantgettorrentfromurl') + ":\n" + url, 
                                      self.utility.lang.get('error'), wx.ICON_ERROR)
                dialog.ShowModal()
                dialog.Destroy()
                return
            return "Error=Can't get torrent from URL"

        # Backup metainfo from URL to local directory
        url_splitted = urlsplit(url)
        filename = os.path.split(stjoin([unquote(url_splitted[2]), url_splitted[3]], ''))[1]
        # If the filename is blank, then don't continue
        if not filename:
            if caller != "web":
                dialog = wx.MessageDialog(None, self.utility.lang.get('failedinvalidtorrent') + ":\n" + url, 
                                      self.utility.lang.get('error'), wx.ICON_ERROR)
                dialog.ShowModal()
                dialog.Destroy()
                return
            else:
                return "Error=Invalid torrent file"
            
        torrentsrc = os.path.join(self.utility.getConfigPath(), "torrent", filename)

        fileexists = os.access(torrentsrc, os.R_OK)

        if not fileexists:
            f = open(torrentsrc, "wb")
            f.write(btmetafile)
            f.close()
        
        # Torrent either already existed or should exist now
        dotTorrentDuplicate = True
        
        return self.AddTorrentFromFile(torrentsrc, False, dotTorrentDuplicate, caller = caller)
    
    def AddTorrentLink(self, event = None):
        starturl = ""
        try:
            # See if there's a url in the clipboard
            # If there is, use that as the default for the dialog
            text = None
            if wx.TheClipboard.Open():
                data = wx.TextDataObject()
                gotdata = wx.TheClipboard.GetData(data)
                wx.TheClipboard.Close()
                if gotdata:
                    text = data.GetText()
            if text is not None:
                if text.startswith("http://") and text.endswith(".torrent"):
                    starturl = text
        except:
            pass
        
        dialog = wx.TextEntryDialog(None, 
                                    self.utility.lang.get('enterurl'), 
                                    self.utility.lang.get('addtorrenturl_short'),
                                    starturl)

        result = dialog.ShowModal()
        btlink = dialog.GetValue()
        dialog.Destroy()
        
        if result != wx.ID_OK:
            return
        
        if btlink != "":
            self.AddTorrentURL(btlink)

    def AddTorrentNoneDefault(self, event = None):
        self.AddTorrentFile(event, True)
            
    def AddTorrentFile(self, event = None, forceasklocation = False):
        dialog = wx.FileDialog(None, 
                               self.utility.lang.get('choosetorrentfile'), 
                               self.utility.getLastDir("open"), 
                               '', 
                               self.utility.lang.get('torrentfileswildcard') + ' (*.torrent)|*.torrent', 
                               wx.OPEN|wx.MULTIPLE)
        result = dialog.ShowModal()
        dialog.Destroy()
        if result != wx.ID_OK:
            return
        
        filelocation = dialog.GetPaths()

        for filepath in filelocation:
            self.AddTorrentFromFile(filepath, forceasklocation)
           
    def AddTorrentFromFile(self, filepath, forceasklocation = False, dotTorrentDuplicate = False, caller = "", dest = None):
        # Check to make sure that the source file exists
        sourcefileexists = os.access(filepath, os.R_OK)
        
        if not sourcefileexists:
            if caller != "web":
                dlg = wx.MessageDialog(None, 
                                       filepath + '\n' + self.utility.lang.get('failedtorrentmissing'), 
                                       self.utility.lang.get('error'), 
                                       wx.OK|wx.ICON_ERROR)
                result = dlg.ShowModal()
                dlg.Destroy()
            # What do we do if the source file doesn't exist?
            # Just return if the source file doesn't exist?
            return "Error=The source file for this torrent doesn't exist"

        # Make torrent directory if necessary
        self.utility.MakeTorrentDir()
      
        torrentpath = os.path.join(self.utility.getConfigPath(), "torrent")    
        filename     = os.path.split(filepath)[1]
        torrentsrc   = os.path.join(torrentpath, filename)
        dontremove = False

        fileexists = os.access(torrentsrc, os.R_OK)
        
        # If the two files are identical, just point to the
        # .torrent file in the /torrent directory
        sametorrent = self.isSameTorrent(filepath, torrentsrc)
        if sametorrent:
            filepath = torrentsrc
        
        # Is the torrent already present in the list?
        torrentinlist = self.checkForDuplicateInList(src = filepath)
        if torrentinlist:
            self.dupFileInList(filepath, caller)
            return "Error=This torrent is duplicate"
        
        if fileexists and not dotTorrentDuplicate:
            if caller != "web":
                # ignore if the src and dest files are the same
                # this means that files in the torrent directory
                # will only give a duplicate torrent error if
                # they are already loaded in the list
                # (dotTorrentDuplicate stays False and the check to
                #  see if it's in the list is performed in addNewProc)
                ##############################################
                if (filepath == torrentsrc):
                    # If addNewProc finds that the torrent is already in the proctab,
                    # we don't want to remove it otherwise the torrent that is running
                    # will be in trouble
                    dontremove = True
                else:
                    # There is a duplicate .torrent file in /torrent
                    dialog = wx.MessageDialog(None, 
                                              self.utility.lang.get('duplicatetorrentmsg'), 
                                              self.utility.lang.get('duplicatetorrent'), 
                                              wx.YES_NO|wx.ICON_EXCLAMATION)
                    result = dialog.ShowModal()

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?