torrentopener.java

来自「Azureus is a powerful, full-featured, cr」· Java 代码 · 共 529 行 · 第 1/2 页

JAVA
529
字号
/*
 * Created on 3 mai 2004
 * Created by Olivier Chalouhi
 * 
 * Copyright (C) 2004 Aelitis SARL, All rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details ( see the LICENSE file ).
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * AELITIS, SARL au capital de 30,000 euros,
 * 8 Alle Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
 */
package org.gudy.azureus2.ui.swt.mainwindow;

import java.io.File;
import java.io.FileFilter;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;

import com.aelitis.azureus.core.*;
import org.gudy.azureus2.core3.config.COConfigurationManager;
import org.gudy.azureus2.core3.download.DownloadManager;
import org.gudy.azureus2.core3.global.GlobalManager;
import org.gudy.azureus2.core3.internat.LocaleUtil;
import org.gudy.azureus2.core3.internat.LocaleUtilDecoder;
import org.gudy.azureus2.core3.internat.MessageText;
import org.gudy.azureus2.core3.logging.LGLogger;
import org.gudy.azureus2.core3.torrent.TOTorrent;
import org.gudy.azureus2.core3.util.AERunnable;
import org.gudy.azureus2.core3.util.Debug;
import org.gudy.azureus2.core3.util.FileUtil;
import org.gudy.azureus2.core3.util.AESemaphore;
import org.gudy.azureus2.core3.util.TorrentUtils;
import org.gudy.azureus2.ui.swt.FileDownloadWindow;
import org.gudy.azureus2.ui.swt.OpenTorrentWindow;
import org.gudy.azureus2.ui.swt.OpenUrlWindow;
import org.gudy.azureus2.ui.swt.URLTransfer;
import org.gudy.azureus2.ui.swt.sharing.ShareUtils;
import org.gudy.azureus2.core3.util.AEThread;

/**
 * @author Olivier Chalouhi
 *
 */
public class TorrentOpener {
  
  private static Display display;
  private static Shell mainWindow;
  private static GlobalManager globalManager;
  
  public static void init(Shell _mainWindow,GlobalManager gm) {
    display = SWTThread.getInstance().getDisplay();
    mainWindow = _mainWindow;
    globalManager = gm;
  }
  
  
  public static void 
  openTorrent(
  	AzureusCore		azureus_core,
	String 			fileName) 
  {
  	boolean	default_start_stopped = COConfigurationManager.getBooleanParameter( "Default Start Torrents Stopped" );
  	
    openTorrent(azureus_core,fileName, default_start_stopped, false);
  }

  public static void 
  openTorrent(
  	  final AzureusCore	azureus_core,
      final String  fileName, 
	  final boolean   startInStoppedState,
	  boolean     from_drag_and_drop ) 
  {
    //catch a http url
    int http_index = fileName.toUpperCase().lastIndexOf( "HTTP:" );
    int https_index = fileName.toUpperCase().lastIndexOf( "HTTPS:" );
    int index = Math.max( http_index, https_index );
    if( index > -1 ) {
      String url = fileName.substring( index );
      
      //clean up accidental left-facing slashes
      url = url.replace( (char)92, (char)47 );
      
      //find the root
      int root_index = url.indexOf( 58 ) + 1;  //start searching after the colon, ":"
      while( url.charAt( root_index) == (char)47 )  root_index++;  //pass over all "/"s
      url = url.substring( root_index );
      
      String protocol;
      if( http_index > -1 )  protocol = "http://";
      else  protocol = "https://";
      
      final String full_url = protocol + url;
      
      AERunnable r = new AERunnable() {
        public void runSupport() {
          openUrl( azureus_core, full_url );
        }
      };
      display.asyncExec( r );
      return;
    }
    
    try {
      if (!FileUtil.isTorrentFile(fileName)){
        
        if ( from_drag_and_drop ){
          
          LGLogger.log( "MainWindow::openTorrent: file it not a torrent file, sharing" );

          ShareUtils.shareFile( azureus_core, fileName );
        
          return;
        }
      }
    } catch (Exception e) {
      
      LGLogger.log( "MainWindow::openTorrent: check fails", e );

      return;
    }

    if(display != null && ! display.isDisposed())
      display.asyncExec(new AERunnable(){
        public void runSupport() {          
          new AEThread("TorrentOpener::openTorrent") {
            public void runSupport() {
              try{
                String savePath = getSavePath(fileName);
                if (savePath == null){
                  LGLogger.log( "MainWindow::openTorrent: save path not set, aborting" );
  
                  return;
                }
                // set to STATE_WAITING if we don't want to startInStoppedState
                // so that auto-open details will work (even if the torrent
                // immediately goes to queued)
                
                LGLogger.log( "MainWindow::openTorrent: adding download '" + fileName + "' --> '" + savePath + "'" );
 
                try{
	                globalManager.addDownloadManager(fileName, savePath, 
	                                                 startInStoppedState ? DownloadManager.STATE_STOPPED 
	                                                                     : DownloadManager.STATE_WAITING);
                }catch( Throwable e ){
    	          	
    	          	LGLogger.logUnrepeatableAlert("Torrent open fails for '" + fileName + "'", e );
    	        }
	          }catch( Throwable e ){
                
               LGLogger.log( "MainWindow::openTorrent: torrent addition fails", e );

              }
            }
          }
          .start();
        }
      });
  }
  
  public static String getSavePath(String fileName) {
    return getSavePathSupport(fileName,true,false);
  }
  
  protected static String 
  getSavePathSupport(
    String fileName,
    boolean useDefault,
    boolean forSeeding) 
  {
      // This *musn't* run on the swt thread as the torrent decoder stuff can need to 
      // show a window...
    boolean has_default = COConfigurationManager.getBooleanParameter("Use default data dir");
    final String[] default_dir = { COConfigurationManager.getStringParameter( "Default save path" ) };
    if( default_dir[0] == null || default_dir[0].length() == 0 ) has_default = false;
      
    if ( has_default ){
    	File	f = new File(default_dir[0]);
    	if ( !f.exists()){
    		f.mkdirs();
    	}
    }
    
    if ( !useDefault || !has_default ) {

      boolean singleFile = false;
      
      String singleFileName = ""; //$NON-NLS-1$

      try {
        TOTorrent torrent = TorrentUtils.readFromFile( new File(fileName), false );
        
        singleFile = torrent.isSimpleTorrent();
        
        LocaleUtilDecoder locale_decoder = LocaleUtil.getSingleton().getTorrentEncoding( torrent );
            
        singleFileName = locale_decoder.decodeString(torrent.getName());
        
        singleFileName = FileUtil.convertOSSpecificChars( singleFileName );
      }
      catch (Exception e) {
      	Debug.printStackTrace( e );
      }

    
      final boolean f_singleFile    = singleFile;
      final boolean f_forSeeding = forSeeding;
      final String  f_singleFileName  = singleFileName;

      final AESemaphore sem = new AESemaphore("TorrentOpener");
    
      display.asyncExec(new AERunnable() {
        public void runSupport()
        {
          try{
            if (f_singleFile) {
              int style = (f_forSeeding) ? SWT.OPEN : SWT.SAVE;
              FileDialog fDialog = new FileDialog(mainWindow, SWT.SYSTEM_MODAL | style);             
              fDialog.setFilterPath( getFilterPathData() );
              fDialog.setFileName(f_singleFileName);
              fDialog.setText(MessageText.getString("MainWindow.dialog.choose.savepath") + " (" + f_singleFileName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              default_dir[0] = setFilterPathData( fDialog.open() );
            }
            else {
              DirectoryDialog dDialog = new DirectoryDialog(mainWindow, SWT.SYSTEM_MODAL);
              dDialog.setFilterPath( getFilterPathData() );
              dDialog.setText(MessageText.getString("MainWindow.dialog.choose.savepath") + " (" + f_singleFileName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              default_dir[0] = setFilterPathData( dDialog.open() );
            }
          }finally{
            sem.release();
          }
        }
      });
 
    
      sem.reserve();
    }
    
    return default_dir[0];
  }

  
  protected static void openTorrents(final String path, final String fileNames[]) {
    openTorrents(path,fileNames,true);
  }

  protected static void openTorrentsForSeeding(final String path, final String fileNames[]) {

⌨️ 快捷键说明

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