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

📄 diskmanagerimpl.java

📁 一个基于JAVA的多torrent下载程序
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
	        	Debug.printStackTrace(e);
	        }
	        
	        if (!rPath.equals(defSaveDir)){
	        	
	        	if (Logger.isEnabled())
							Logger.log(new LogEvent(this, LOGID, LogEvent.LT_WARNING,
									"Not moving-on-complete since "
											+ "data is not within default save dir"));
	          
	        	return;
	        }
	        
	    	// Debug.out( "Moving data files: " + rPath + " -> " + moveToDir +", def = " + defSaveDir ); 
	    }
	    
	    boolean moveTorrent = COConfigurationManager.getBooleanParameter("Move Torrent When Done", true);

	    moveFiles( moveToDir, moveTorrent, true );
	    
	  }finally{
		  
		  start_stop_mon.exit();
	  }
    }
    
	public void
	moveDataFiles(
		File	new_parent_dir )
	{
		moveFiles( new_parent_dir.toString(), false, false );
	}
	
    protected void
    moveFiles(
    	String	move_to_dir,
    	boolean	move_torrent,
    	boolean	change_to_read_only )
    {
	    File save_location = download_manager.getAbsoluteSaveLocation();

	    String move_from_dir = save_location.getParent();

    	try{
    	  start_stop_mon.enter();
	      
	      	// first of all check that no destination files already exist
	      
	      File[]	new_files 	= new File[files.length];
	      File[]	old_files	= new File[files.length];
	      
	      for (int i=0; i < files.length; i++) {
	          	    	  
	          File old_file = files[i].getFile(false);
	          
	          File linked_file = FMFileManagerFactory.getSingleton().getFileLink( torrent, old_file );
	            
	          boolean	skip = false;
	            
	          if ( linked_file != old_file ){
	        	  
		       	  if ( save_location.isDirectory()){
		                       		
		        	  	// if we are linked to a file outside of the torrent's save directory then we don't
		        	  	// move the file
		        	  
		        	  if ( !linked_file.getCanonicalPath().startsWith( save_location.getCanonicalPath())){
		            			
		        		  skip = true;
		        	  }
		          }

           		  old_file	= linked_file;
	          }
	          
	          if ( skip ){
	        	  
	        	  	// actual file is outside the dir, ignore it
	        	  
	        	  continue;
	          }
	          
	          old_files[i]	= old_file;
	          
	          	//get old file's parent path
	          
	          String fullPath = old_file.getParent();
	          
	           	//compute the file's sub-path off from the default save path
	          
	          String subPath = fullPath.substring(fullPath.indexOf(move_from_dir) + move_from_dir.length());
	    
	          	//create the destination dir
	          
	          if ( subPath.startsWith( File.separator )){
	          	
	          	subPath = subPath.substring(1);
	          }
	          
	          File destDir = new File(move_to_dir, subPath);
	     
	          	//create the destination file pointer
	          
	          File newFile = new File(destDir, old_file.getName());
	
	          new_files[i]	= newFile;

		          if ( newFile.exists()){
		          	
	            String msg = "" + linked_file.getName() + " already exists in MoveTo destination dir";
		            
		            if (Logger.isEnabled())
		            	Logger.log(new LogEvent(this, LOGID, LogEvent.LT_ERROR,
		            			msg));
		            
		            Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
		            		LogAlert.AT_ERROR, "DiskManager.alert.movefileexists"),
		            		new String[] { old_file.getName() });
	            
		            
		            Debug.out(msg);
		            
		            return;
		            
		          }  
	    		  destDir.mkdirs();
	    	  }
	      
	      for (int i=0; i < files.length; i++){
	      		 	          
	          File new_file = new_files[i];
	          	          
	          if ( new_file == null ){
	        	
	        	  	// not moving this one
	        	  
	        	  continue;
	          }
	          
	          try{
	          	
	          	files[i].moveFile( new_file );
	           	
	          	if ( change_to_read_only ){
	          		
	          		files[i].setAccessMode(DiskManagerFileInfo.READ);
	          	}
	            
	          }catch( CacheFileManagerException e ){
	          	
	            String msg = "Failed to move " + old_files[i].toString() + " to destination dir";
	            
	            if (Logger.isEnabled())
								Logger.log(new LogEvent(this, LOGID, LogEvent.LT_ERROR,
										msg));
	            
	            Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
								LogAlert.AT_ERROR, "DiskManager.alert.movefilefails"),
								new String[] { old_files[i].toString(),
										Debug.getNestedExceptionMessage(e) });
	
	            Debug.out(msg);
	            
	            	// try some recovery by moving any moved files back...
	            
	            for (int j=0;j<i;j++){
	            	
	            	if (new_files[j] == null ){
	            		
	            		continue;
	            	}
	            	
	            	try{
	            		files[j].moveFile( old_files[j]);
		         		
	            	}catch( CacheFileManagerException f ){
	              
	            		Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
										LogAlert.AT_ERROR,
										"DiskManager.alert.movefilerecoveryfails"),
										new String[] { old_files[j].toString(),
												Debug.getNestedExceptionMessage(f) });
	           		
	            	}
	            }
	            
	            return;
	          }
	      }
	      
	      	//remove the old dir
	      
	      if (	save_location.isDirectory()){
	      
	    	  FileUtil.recursiveEmptyDirDelete( save_location, false );
	      }
	        
	      download_manager.setTorrentSaveDir( move_to_dir );
	      
	      	//move the torrent file as well
	      
	      
	      if ( move_torrent ){
	      	
	          String oldFullName = download_manager.getTorrentFileName();
	          
	          File oldTorrentFile = new File(oldFullName);
	          
	          String oldFileName = oldTorrentFile.getName();
	          
	          File newTorrentFile = new File(move_to_dir, oldFileName);
	          
	          if (!newTorrentFile.equals(oldTorrentFile)){
	          	
	          	if ( TorrentUtils.move( oldTorrentFile, newTorrentFile )){
	            	            
	          		download_manager.setTorrentFileName(newTorrentFile.getCanonicalPath());
	          		
	          	}else{
	          
		            String msg = "Failed to move " + oldTorrentFile.toString() + " to " + newTorrentFile.toString();
		            
		            if (Logger.isEnabled())
		            	Logger.log(new LogEvent(this, LOGID, LogEvent.LT_ERROR, msg));
		            
		            Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
									LogAlert.AT_ERROR, "DiskManager.alert.movefilefails"),
									new String[] { oldTorrentFile.toString(),
											newTorrentFile.toString() });
		
		            Debug.out(msg);
	          	}
	          }
	      }
	}catch( Exception e){
	    	
	  	Debug.printStackTrace( e );
	  	
    }finally{
    	
    	try{
            boolean resumeEnabled = COConfigurationManager.getBooleanParameter("Use Resume", true);
            
            	//update resume data
            
            if ( resumeEnabled ){
            	
            	try{
            		dumpResumeDataToDisk(true, false);
            		
            	}catch( Exception e ){
            		
            			// won't go wrong here due to cache write fails as these must have completed
            			// prior to the files being moved. Possible problems with torrent save but
            			// if this fails we can live with it (just means that on restart we'll do
            			// a recheck )
            		
            		Debug.out( "dumpResumeDataToDisk fails" );
            	}
            }
    	}catch( Throwable e ){
    		
    		Debug.printStackTrace(e);
    	}
    	
    	start_stop_mon.exit();
    }
  }
  
	public TOTorrent
	getTorrent()
	{
		return( torrent );
	}


	public void
	addListener(
		DiskManagerListener	l )
	{
		listeners.addListener( l );

		int params[] = {getState(), getState()};
  		
		listeners.dispatch( l, LDT_STATECHANGED, params);
	}
  
	public void
	removeListener(
		DiskManagerListener	l )
	{
		listeners.removeListener(l);
	}

		  /** Deletes all data files associated with torrent.
		   * Currently, deletes all files, then tries to delete the path recursively
		   * if the paths are empty.  An unexpected result may be that a empty
		   * directory that the user created will be removed.
		   *
		   * TODO: only remove empty directories that are created for the torrent
		   */
  
	public static void 
	deleteDataFiles(
		TOTorrent 	torrent, 
		String		torrent_save_dir,		// enclosing dir, not for deletion 
		String		torrent_save_file ) 	// file or dir for torrent
	{	
		if (torrent == null || torrent_save_file == null ){
	  
			return;
		}
	  	  
		try{
			if (torrent.isSimpleTorrent()){

				File	target = new File( torrent_save_dir, torrent_save_file );

				target = FMFileManagerFactory.getSingleton().getFileLink( torrent, target.getCanonicalFile());
				
				FileUtil.deleteWithRecycle( target );

			}else{

                PlatformManager mgr = PlatformManagerFactory.getPlatformManager();
                if( Constants.isOSX &&
                      torrent_save_file.length() > 0 &&
                      COConfigurationManager.getBooleanParameter("Move Deleted Data To Recycle Bin" ) &&
                      mgr.hasCapability(PlatformManagerCapabilities.RecoverableFileDelete) ) {

                    try
                    {
                    	String	dir = torrent_save_dir + File.separatorChar + torrent_save_file + File.separatorChar;
                    	
                    		// only delete the dir if there's only this torrent's files in it!
                    	
                    	if ( countFiles( new File(dir)) == countDataFiles( torrent, torrent_save_dir, torrent_save_file )){
                    		
                    		mgr.performRecoverableFileDelete( dir );
                    		
                    	}else{
                    		
                    		deleteDataFileContents( torrent, torrent_save_dir, torrent_save_file );
                    }
                    }
                    catch(PlatformManagerException ex)
                    {
                        deleteDataFileContents( torrent, torrent_save_dir, torrent_save_file );
                    }
                }
                else{
                    deleteDataFileContents(torrent, torrent_save_dir, torrent_save_file);
                }

            }
		}catch( Throwable e ){
		
			Debug.printStackTrace( e );
		}
	}

	private static int
	countFiles(
		File	f )
	{
		if ( f.isFile()){
			
			return( 1 );
		}else{
			
			int	res = 0;
			
			File[]	files = f.listFiles();
			
			if ( files != null ){
				
				for (int i=0;i<files.length;i++){
					
					res += countFiles( files[i] );
				}
			}
			
			return( res );
		}
	}
	
	private static int 
	countDataFiles(
		TOTorrent torrent, 
	    String torrent_save_dir, 
	    String torrent_save_file )
	{
		try{
			int	res = 0;
			
			LocaleUtilDecoder locale_decoder = LocaleUtil.getSingleton().getTorrentEncoding( torrent );

	        TOTorrentFile[] files = torrent.getFiles();

	        for (int i=0;i<files.length;i++){

	            byte[][]path_comps = files[i].getPathComponents();

	            String	path_str = torrent_save_dir + File.separator + torrent_save_file + File.separator;

	            for (int j=0;j<path_comps.length;j++){

                    String comp = locale_decoder.decodeString( path_comps[j] );

                    comp = FileUtil.convertOSSpecificChars( comp );

                    path_str += (j==0?"":File.separator) + comp;
	            }

	            File file = new File(path_str).getCanonicalFile();

	            File linked_file = FMFileManagerFactory.getSingleton().getFileLink( torrent, file );
	            
	            boolean	skip = false;
	            
	            if ( linked_file != file ){
	                       		            	
	           		if ( !linked_file.getCanonicalPath().startsWith(new File( torrent_save_dir ).getCanonicalPath())){
	            			
	           			skip = true;
	           		}
	            }
	            
	            if ( !skip && file.exists() && !file.isDirectory()){

	            	res++;
	            }
	        }
	        
	        return( res );
	        
		}catch( Throwable e ){
			
			Debug.printStackTrace(e);
			
			return( -1 );
		} 
	}

    private static void 
    deleteDataFileContents(
    	TOTorrent torrent, 
    	String torrent_save_dir, 
    	String torrent_save_file )
    
            throws TOTorrentException, UnsupportedEncodingException, LocaleUtilEncodingException
    {
        LocaleUtilDecoder locale_decoder = LocaleUtil.getSingleton().getTorrentEncoding( torrent );

        TOTorrentFile[] files = torrent.getFiles();

        String	root_path = torrent_save_dir + File.separator + torrent_save_file + File.separator;

        // delete all files, then empty directories

        for (int i=0;i<files.length;i++){

            byte[][]path_comps = files[i].getPathComponents();

            String	path_str	= root_path;

            for (int j=0;j<path_comps.length;j++){

                try{

                    String comp = locale_decoder.decodeString( path_comps[j] );

                    comp = FileUtil.convertOSSpecificChars( comp );

                    path_str += (j==0?"":File.separator) + comp;

                }catch( UnsupportedEncodingException e ){

                    Debug.out( "file - unsupported encoding!!!!");
                }
            }

            File file = new File(path_str);

            File linked_file = FMFileManagerFactory.getSingleton().getFileLink( torrent, file );

            boolean	delete;
            
            if ( linked_file == file ){
            	
            	delete	= true;
            	
            }else{
            	
            		// only consider linked files for deletion if they are in the torrent save dir
            		// i.e. a rename probably instead of a retarget to an existing file elsewhere
            	
                try{
            		if ( linked_file.getCanonicalPath().startsWith(new File( root_path ).getCanonicalPath())){
            			
            			file	= linked_file;
            			
            			delete 	= true;
            			
            		}else{
            			
            			delete = false;
            		}
            	}catch( Throwable e ){
            		
            		Debug.printStackTrace(e);
            		
            		delete = false;
            	}
            }
            
            if ( delete && file.exists() && !file.isDirectory()){

⌨️ 快捷键说明

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