⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 files.py

📁 ABC-win32-v3.1 一个P2P软源代码
💻 PY
📖 第 1 页 / 共 2 页
字号:
import sys
import wx
import os

from cStringIO import StringIO
from threading import Thread
from time import sleep
from traceback import print_exc
from webbrowser import open_new

from Dialogs.dupfiledialog import DupFileDialog

from Utility.constants import * #IGNORE:W0611


################################################################
#
# Class: TorrentFiles
#
# Keep track of the files associated with a torrent
#
################################################################
class TorrentFiles:
    def __init__(self, torrent):
        self.torrent = torrent
        self.utility = torrent.utility
              
        self.filename = self.torrent.info['name']
        
        # Array to store file priorities
        # Just using a placeholder of 1 (Normal) for now
        if self.isFile():
            numfiles = 1
        else:
            numfiles = len(self.torrent.info['files'])
        self.filepriorities = [1] * numfiles

        self.floattotalsize = float(self.getSize())
        self.realsize = self.floattotalsize
        
        # This one is to store the download progress ; if it's not stored, the progress
        # of an inactive torrent would stay only in the display of the list, and so it would
        # be lost if the GUI wouldn't display the column "progress". In this case it couldn't
        # be saved in the torrent.lst file.
        self.progress = 0.0
        self.downsize = 0.0
        self.upsize = 0.0
        
        # Progress of individual files within torrent
        self.fileprogress = [""] * numfiles
        
        self.dest = None
        
#        self.skipcheck = False
        
            
    def setupDest(self, dest, forceasklocation, caller):
        self.dest = dest
        
        # Try reading the config file
        if self.dest is None:
            self.dest = self.torrent.torrentconfig.Read("dest")

        # Treat an empty string for dest the same as
        # not having one defined
        if not self.dest:
            self.dest = None

        # For new torrents, get the destination where to save the torrent
        if self.dest is None or forceasklocation:
            self.getDestination(forceasklocation, caller)

        # Treat an empty string for dest the same as
        # not having one defined
        if not self.dest:
            self.dest = None

    def onOpenDest(self, event = None, index = 0):
        return self.onOpenFileDest(index, pathonly = True)

    def onOpenFileDest(self, event = None, index = 0, pathonly = False):
        dest = self.getSingleFileDest(index, pathonly, checkexists = False)
        
        # Check to make sure that what we're trying to get exists
        if dest is None or not os.access(dest, os.R_OK):
            # Error : file not found
            dialog = wx.MessageDialog(None, 
                                      str(dest) + '\n\n' + self.utility.lang.get('filenotfound'), 
                                      self.utility.lang.get('error'), 
                                      wx.ICON_ERROR)
            dialog.ShowModal()
            dialog.Destroy()
            return False
            
        # A file is completed if it either is a single file flagged as completed,
        # or is a file within a multi-file torrent flagged as "Done"
        # (i.e.: file is in-place)
        if self.isFile():
            completed = self.torrent.status.completed
        else:
            completed = (self.fileprogress[index] == self.utility.lang.get('done'))
            
        # Don't need to check if the torrent is complete if we're only
        # opening the path
        if not pathonly and not completed:
            #Display Warning file is not complete yet
            dialog = wx.MessageDialog(None, 
                                      self.torrent.getColumnText(COL_TITLE) + '\n\n'+ self.utility.lang.get('warningopenfile'), 
                                      self.utility.lang.get('warning'), 
                                      wx.YES_NO|wx.ICON_EXCLAMATION)

            result = dialog.ShowModal()
            dialog.Destroy()
            if result != wx.ID_YES:
                return False

        try:
            if pathonly and (sys.platform == 'win32'):
                dest = self.getSingleFileDest(index, pathonly = False, checkexists = False)
                os.popen('explorer.exe /select,"' + dest + '"')
            else:
                Thread(target = open_new(dest)).start()
        except:
            pass
            
        return True
        
    def changeProcDest(self, dest, rentorrent = False):
        self.dest = dest
        self.torrent.updateColumns([COL_DEST])
        self.torrent.torrentconfig.writeBasicInfo()
        
        details = self.torrent.dialogs.details
        if details is not None:
            try:
                details.fileInfoPanel.opendirbtn.SetLabel(self.torrent.files.getProcDest(pathonly = True, checkexists = False))
                details.updateTorrentName()
            except wx.PyDeadObjectError:
                pass
        
        if rentorrent:
            # Update torrent name
            self.torrent.changeTitle(os.path.split(dest)[1])
            
    def move(self, dest = None):
        if dest is None:
            dest = self.utility.config.Read('defaultmovedir')
        
        if not os.access(dest, os.F_OK):
            try:
                os.makedirs(dest)
            except:
                return False
       
        #Wait thread a little bit for returning resource
        ##################################################
        sleep(0.5)

        if self.isFile():
            self.moveSingleFile(dest)
        else:
            self.moveDir(dest)

        self.changeProcDest(os.path.join(dest, self.filename))
        
        return True
                               
    def moveSingleFile(self, dest):
        if not self.isFile():
            self.moveDir(dest)
            return
        
        filename = os.path.split(self.dest)[1]
        source = os.path.split(self.dest)[0]
        size = int(self.torrent.info['length'])
        
        self.moveFiles({filename: size}, source, dest)
            
    def moveFiles(self, filearray, source, dest):
        dummyname = os.path.join(os.path.split(self.dest)[0], 'dummy')
        try:
            file(dummyname, 'w').close()
        except:
            pass
       
        overwrite = "ask"
       
        for filename in filearray:
            oldloc = os.path.join(source, filename)
            newloc = os.path.join(dest, filename)
            size = filearray[filename]

            done = False
            firsttime = True
                
            while not done:
                try:
                    # File exists
                    if os.access(oldloc, os.R_OK):
                        copyfile = True
                        
                        # Something already exists where we're trying to copy:
                        if os.access(newloc, os.F_OK):
                            # Default to "No"
                            result = -1
                            
                            if overwrite == "ask":
                                single = len(filearray) > 1
                                dialog = DupFileDialog(self.torrent, filename, single)
                                result = dialog.ShowModal()
                                dialog.Destroy()
                                if result == 2:
                                    overwrite = "yes"
                                elif result == -2:
                                    overwrite = "no"
                                    
                            if overwrite == "yes" or result > 0:
                                os.remove(newloc)
                            elif overwrite == "no" or result < 0:
                                copyfile = False
                                
                        if copyfile:
                            os.renames(oldloc, newloc)
                    done = True
                except:
                    # There's a very special case for a file with a null size referenced in the torrent
                    # but not retrieved just because of this null size : It can't be renamed so we
                    # just skip it.
                    if size == 0:
                        done = True
                    else:
                        #retry >_<;
                        if firsttime:
                            firsttime = False
                            sleep(0.1)
                        else:
                            done = True
                            
                            data = StringIO()
                            print_exc(file = data)
                            
                            dialog = wx.MessageDialog(None, self.utility.lang.get('errormovefile') + "\n" + data.getvalue(), self.utility.lang.get('error'), wx.ICON_ERROR)
                            dialog.ShowModal()
                            dialog.Destroy()
                            
        try:
            os.remove(dummyname)
        except:
            pass
                   
    def moveDir(self, dest):
        if self.isFile():
            self.moveSingleFile(dest)
            return
           
        destname = self.getProcDest()
       
        if destname is None:
            return
        
        filearray = {}
        
        movename = os.path.join(dest, self.filename)
        for f in self.torrent.info['files']:
            for item in f['path']:
                size = int(f['length'])
                filearray[item] = size

        self.moveFiles(filearray, destname, movename)

        self.utility.RemoveEmptyDir(destname, True)
        
            
    def removeFiles(self):

⌨️ 快捷键说明

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