Package org.gudy.azureus2.plugins.torrent

Examples of org.gudy.azureus2.plugins.torrent.Torrent


   
    for (int i=0;i<downloads.length;i++){
     
      Download download = downloads[i];
     
      Torrent torrent = download.getTorrent();
     
      if ( torrent == null ){
       
        continue;
      }
     
      String dl_cat = download.getAttribute( ta_category );
   
      if (   category.equalsIgnoreCase( "all" ) ||
          ( dl_cat != null && dl_cat.equals( category ))){
       
        if ( !TorrentUtils.isReallyPrivate( PluginCoreUtils.unwrap( torrent ))){
         
          selected_dls.add( download );
         
          byte[] hash = torrent.getHash();
         
          int  num = (hash[0]<<24)&0xff000000 | (hash[1] << 16)&0x00ff0000 | (hash[2] << 8)&0x0000ff00 | hash[3]&0x000000ff;

          fingerprint += num;
        }
      }
    }
   
    PluginConfig pc = plugin_interface.getPluginconfig();

    String  feed_finger_key = "feed_finger.category." + category;
    String  feed_date_key   = "feed_date.category." + category;

    long  existing_fingerprint   = pc.getPluginLongParameter( feed_finger_key, 0 );
    long  feed_date         = pc.getPluginLongParameter( feed_date_key, 0 );

    long  now = SystemTime.getCurrentTime();

    if ( existing_fingerprint == fingerprint ){
     
        // update every now and then to pick up new peer/seed values
     
      if ( selected_dls.size() > 0 ){

        if (   now < feed_date ||
            now - feed_date > FEED_UPDATE_MIN_MILLIS ){
         
          feed_date = now;
       
          pc.setPluginParameter( feed_date_key, feed_date );
        }
      }
    }else{
     
      pc.setPluginParameter( feed_finger_key, fingerprint );
     
     
        // ensure feed date goes up
     
      if ( now <= feed_date ){
       
        feed_date++;
       
      }else{
       
        feed_date = now;
      }
     
      pc.setPluginParameter( feed_date_key, feed_date );
    }
   
    String last_modified = TimeFormatter.getHTTPDate( feed_date );

    if ( if_mod != null && if_mod.equals( last_modified )){
     
      return( new feedDetails( new byte[0], last_modified ));
    }
       
    ByteArrayOutputStream  os = new ByteArrayOutputStream();
     
    try{
      PrintWriter pw = new PrintWriter(new OutputStreamWriter( os, "UTF-8" ));
     
      pw.println( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" );
     
      pw.println( "<rss version=\"2.0\" xmlns:vuze=\"http://www.vuze.com\">" );
     
      pw.println( "<channel>" );
     
      pw.println( "<title>" + escape( category ) + "</title>" );
     
      Collections.sort(
        selected_dls,
        new Comparator<Download>()
        {
          public int
          compare(
            Download d1,
            Download d2)
          {
            long  added1 = getAddedTime( d1 )/1000;
            long  added2 = getAddedTime( d2 )/1000;
   
            return((int)(added2 - added1 ));
          }
        });
               
             
      pw.println"<pubDate>" + last_modified + "</pubDate>" );
   
      for (int i=0;i<selected_dls.size();i++){
       
        Download download = (Download)selected_dls.get( i );
       
        DownloadManager  core_download = PluginCoreUtils.unwrap( download );
       
        Torrent torrent = download.getTorrent();
       
        String  hash_str = Base32.encode( torrent.getHash());
       
        pw.println( "<item>" );
       
        pw.println( "<title>" + escape( download.getName()) + "</title>" );
       
        pw.println( "<guid>" + hash_str + "</guid>" );
       
        long added = core_download.getDownloadState().getLongParameter(DownloadManagerState.PARAM_DOWNLOAD_ADDED_TIME);
       
        pw.println"<pubDate>" + TimeFormatter.getHTTPDate( added ) + "</pubDate>" );
       
        pw.println"<vuze:size>" + torrent.getSize()+ "</vuze:size>" );
        pw.println"<vuze:assethash>" + hash_str + "</vuze:assethash>" );
       
        String url = "azplug:?id=azbuddy&name=Friends&arg=";
       
        String arg = "pk=" + getPublicKey() + "&cat=" + category + "&hash=" + Base32.encode(torrent.getHash());

        url += URLEncoder.encode( arg, "UTF-8" );
     
        pw.println( "<vuze:downloadurl>" + escape( url ) + "</vuze:downloadurl>" );
   
View Full Code Here


    try{
      Download download = plugin_interface.getDownloadManager().getDownload( hash );
     
      if ( download != null ){
       
        Torrent  torrent = download.getTorrent();
     
        if ( torrent != null ){
               
          String dl_cat = download.getAttribute( ta_category );
         
          if (   category.equalsIgnoreCase( "all" ) ||
              ( dl_cat != null && dl_cat.equals( category ))){
           
            if ( !TorrentUtils.isReallyPrivate( PluginCoreUtils.unwrap( torrent ))){
             
              torrent = torrent.removeAdditionalProperties();
             
              return( torrent.writeToBEncodedData());
            }
          }
        }
      }
    }catch( Throwable e ){
View Full Code Here

          if ( download == null || download.getTorrent() == null ){
           
            return;
          }
         
          Torrent torrent = download.getTorrent();
         
          String  cb_data = "magnet:?xt=urn:btih:" + Base32.encode( torrent.getHash());

          // removed this as well - nothing wrong with allowing magnet copy
          // for private torrents - they still can't be tracked if you don't
          // have permission
         
         
          /*if ( torrent.isPrivate()){
           
            cb_data = getMessageText( "private_torrent" );
           
          }else if ( torrent.isDecentralised()){
          */ 
            // ok
           
            /* relaxed this as we allow such torrents to be downloaded via magnet links
             * (as opposed to tracked in the DHT)
            
          }else if ( torrent.isDecentralisedBackupEnabled()){
             
            TorrentAttribute ta_peer_sources   = plugin_interface.getTorrentManager().getAttribute( TorrentAttribute.TA_PEER_SOURCES );

            String[]  sources = download.getListAttribute( ta_peer_sources );
   
            boolean  ok = false;
               
            for (int i=0;i<sources.length;i++){
                 
              if ( sources[i].equalsIgnoreCase( "DHT")){
                   
                ok  = true;
                   
                break;
              }
            }
   
            if ( !ok ){
             
              cb_data = getMessageText( "decentral_disabled" );
            }
          }else{
           
            cb_data = getMessageText( "decentral_backup_disabled" );
            */
          // }
         
          // System.out.println( "MagnetPlugin: export = " + url );
         
          try{
            plugin_interface.getUIManager().copyToClipBoard( cb_data );
           
          }catch( Throwable  e ){
           
            e.printStackTrace();
          }
        }
      };
   
    final TableContextMenuItem menu1 = plugin_interface.getUIManager().getTableManager().addContextMenuItem(TableManager.TABLE_MYTORRENTS_INCOMPLETE, "MagnetPlugin.contextmenu.exporturi" );
    final TableContextMenuItem menu2 = plugin_interface.getUIManager().getTableManager().addContextMenuItem(TableManager.TABLE_MYTORRENTS_COMPLETE,   "MagnetPlugin.contextmenu.exporturi" );
     
    menu1.addListener( listener );
    menu2.addListener( listener );

    MagnetURIHandler.getSingleton().addListener(
      new MagnetURIHandlerListener()
      {
        public byte[]
        badge()
        {
          InputStream is = getClass().getClassLoader().getResourceAsStream( "com/aelitis/azureus/plugins/magnet/Magnet.gif" );
         
          if ( is == null ){
           
            return( null );
          }
         
          try{
            ByteArrayOutputStream  baos = new ByteArrayOutputStream();
           
            try{
              byte[]  buffer = new byte[8192];
             
              while( true ){
 
                int  len = is.read( buffer );
       
                if ( len <= 0 ){
                 
                  break;
                }
   
                baos.write( buffer, 0, len );
              }
            }finally{
             
              is.close();
            }
           
            return( baos.toByteArray());
           
          }catch( Throwable e ){
           
            Debug.printStackTrace(e);
           
            return( null );
          }
        }
             
        public byte[]
        download(
          final MagnetURIHandlerProgressListener    muh_listener,
          final byte[]                hash,
          final String                args,
          final InetSocketAddress[]          sources,
          final long                  timeout )
       
          throws MagnetURIHandlerException
        {
            // see if we've already got it!
         
          try{
            Download  dl = plugin_interface.getDownloadManager().getDownload( hash );
         
            if ( dl != null ){
             
              Torrent  torrent = dl.getTorrent();
             
              if ( torrent != null ){
               
                return( torrent.writeToBEncodedData());
              }
            }
          }catch( Throwable e ){
         
            Debug.printStackTrace(e);
View Full Code Here

 
  public URL
  getMagnetURL(
    Download    d )
  {
    Torrent  torrent = d.getTorrent();
   
    if ( torrent == null ){
     
      return( null );
    }
   
    return( getMagnetURL( torrent.getHash()));
  }
View Full Code Here

 
  public void
  addDownload(
    final Download  download )
  {
    Torrent  torrent = download.getTorrent();

    boolean  is_decentralised = false;
   
    if ( torrent != null ){
     
      is_decentralised = TorrentUtils.isDecentralised( torrent.getAnnounceURL());
    }
   
      // bail on our low noise ones, these don't require decentralised tracking unless that's what they are
 
    if ( download.getFlag( Download.FLAG_LOW_NOISE ) && !is_decentralised ){
   
      return;
    }
   
    if ( track_only_decentralsed ){
   
      if ( torrent != null ){
       
        if ( !is_decentralised ){
         
          return;
        }
      }
    }
 
    if ( is_running ){
     
      String[]  networks = download.getListAttribute( ta_networks );
           
      if ( torrent != null && networks != null ){
       
        boolean  public_net = false;
       
        for (int i=0;i<networks.length;i++){
         
          if ( networks[i].equalsIgnoreCase( "Public" )){
             
            public_net  = true;
           
            break;
          }
        }
       
        if ( public_net && !torrent.isPrivate()){
 
          boolean  our_download =  torrent.wasCreatedByUs();
 
          long  delay;
         
          if ( our_download ){
           
            if ( download.getCreationTime() > start_time ){
             
              delay = 0;
           
            }else{
           
              delay = plugin_interface.getUtilities().getCurrentSystemTime() +
                  INTERESTING_INIT_MIN_OURS +
                  random.nextInt( INTERESTING_INIT_RAND_OURS );
 
            }
          }else{
           
            int  min;
            int  rand;
           
            if ( TorrentUtils.isDecentralised( torrent.getAnnounceURL())){
             
              min    = INTERESTING_DHT_INIT_MIN; 
              rand  = INTERESTING_DHT_INIT_RAND;

            }else{
             
              min    = INTERESTING_INIT_MIN_OTHERS; 
              rand  = INTERESTING_INIT_RAND_OTHERS;
            }
           
            delay = plugin_interface.getUtilities().getCurrentSystemTime() +
                  min + random.nextInt( rand );
          }
         
          try{
            this_mon.enter();
     
            interesting_downloads.put( download, new Long( delay ));
           
          }finally{
           
            this_mon.exit();
          }
        }
      }
     
      download.addAttributeListener(DHTTrackerPlugin.this, ta_networks, DownloadAttributeListener.WRITTEN);
      download.addAttributeListener(DHTTrackerPlugin.this, ta_peer_sources, DownloadAttributeListener.WRITTEN);
     
      download.addTrackerListener( DHTTrackerPlugin.this );
     
      download.addListener( DHTTrackerPlugin.this );
     
      checkDownloadForRegistration( download, true );
     
    }else{
           
      if ( torrent != null && torrent.isDecentralised()){
       
        download.addListener(
          new DownloadListener()
          {
            public void
View Full Code Here

        // state == Download.ST_QUEUED     || 
        download.isPaused()){  // pause is a transitory state, don't dereg
           
      String[]  networks = download.getListAttribute( ta_networks );
     
      Torrent  torrent = download.getTorrent();
     
      if ( torrent != null && networks != null ){
       
        boolean  public_net = false;
       
        for (int i=0;i<networks.length;i++){
         
          if ( networks[i].equalsIgnoreCase( "Public" )){
             
            public_net  = true;
           
            break;
          }
        }
       
        if ( public_net && !torrent.isPrivate()){
         
          if ( torrent.isDecentralised()){
           
              // peer source not relevant for decentralised torrents
           
            register_type  = REG_TYPE_FULL;
           
            register_reason = "decentralised";
             
          }else{
           
            if ( torrent.isDecentralisedBackupEnabled() || TEST_ALWAYS_TRACK ){
               
              String[]  sources = download.getListAttribute( ta_peer_sources );
 
              boolean  ok = false;
             
              for (int i=0;i<sources.length;i++){
               
                if ( sources[i].equalsIgnoreCase( "DHT")){
                 
                  ok  = true;
                 
                  break;
                }
              }
 
              if ( !( ok || TEST_ALWAYS_TRACK )){
                     
                register_reason = "decentralised peer source disabled";
               
              }else{
                  // this will always be true since change to exclude queued...
               
                boolean  is_active =
                      state == Download.ST_DOWNLOADING ||
                      state == Download.ST_SEEDING ||
                      download.isPaused();

                if ( is_active ){
                 
                  register_type = REG_TYPE_DERIVED;
                }
               
                if( torrent.isDecentralisedBackupRequested() || TEST_ALWAYS_TRACK ){
                 
                  register_type  = REG_TYPE_FULL;
                 
                  register_reason = TEST_ALWAYS_TRACK?"testing always track":"torrent requests decentralised tracking";
                 
View Full Code Here

    Download    download )
  {
      // metric between -100 and + 100. Note that all -ve mean 'don't do it'
      // they're just indicating different reasons
 
    Torrent t = download.getTorrent();
   
    if ( t == null ){
     
      return( -100 );
    }
   
    if ( t.getSize() < 10*1024*1024 ){
     
      return( -99 );
    }
   
    DownloadAnnounceResult announce = download.getLastAnnounceResult();
View Full Code Here

    final RegistrationDetails    details,
    final boolean          derived_only )
  {
    final   long  start = SystemTime.getCurrentTime();

    final Torrent  torrent = download.getTorrent();
   
    final URL  url_to_report = torrent.isDecentralised()?torrent.getAnnounceURL():DEFAULT_URL;

    trackerTarget[] targets = details.getTargets( false );
   
    final long[]  max_retry = { 0 };
   
    int  num_done = 0;
   
    for (int i=0;i<targets.length;i++){
     
      final trackerTarget target = targets[i];
 
      if ( target.getType() == REG_TYPE_FULL && derived_only ){
       
        continue;
      }
     
      increaseActive( download );
     
      num_done++;
     
      dht.get(target.getHash(),
          "Tracker announce for '" + download.getName() + "'" + target.getDesc(),
          isComplete( download )?DHTPlugin.FLAG_SEEDING:DHTPlugin.FLAG_DOWNLOADING,
          NUM_WANT,
          target.getType()==REG_TYPE_FULL?ANNOUNCE_TIMEOUT:ANNOUNCE_DERIVED_TIMEOUT,
          false, false,
          new DHTPluginOperationListener()
          {
            List<String>  addresses   = new ArrayList<String>();
            List<Integer>  ports    = new ArrayList<Integer>();
            List<Integer>  udp_ports  = new ArrayList<Integer>();
            List<Boolean>  is_seeds  = new ArrayList<Boolean>();
            List<String>  flags    = new ArrayList<String>();
           
            int    seed_count;
            int    leecher_count;
           
            boolean  complete;
           
            public void
            diversified()
            {
            }
           
            public void
            starts(
              byte[]         key )
            {
            }
           
            public void
            valueRead(
              DHTPluginContact  originator,
              DHTPluginValue    value )
            {
              synchronized( this ){
               
                if ( complete ){
                 
                  return;
                }

                try{                   
                  String[]  tokens = new String(value.getValue()).split(";");
               
                  String  tcp_part = tokens[0].trim();
                 
                  int  sep = tcp_part.indexOf(':');
                 
                  String  ip_str    = null;
                  String  tcp_port_str;
                 
                  if ( sep == -1 ){
                   
                    tcp_port_str = tcp_part;
                   
                  }else{
                   
                    ip_str       = tcp_part.substring( 0, sep );             
                    tcp_port_str  = tcp_part.substring( sep+1 )
                  }
                 
                  int  tcp_port = Integer.parseInt( tcp_port_str );
                   
                  if ( tcp_port > 0 && tcp_port < 65536 ){
   
                    String  flag_str  = null;
                    int    udp_port  = -1;
                   
                    try{
                      for (int i=1;i<tokens.length;i++){
                     
                        String  token = tokens[i].trim();
                       
                        if ( token.length() > 0 ){
                         
                          if ( Character.isDigit( token.charAt( 0 ))){
                           
                            udp_port = Integer.parseInt( token );
                           
                            if ( udp_port <= 0 || udp_port >=65536 ){
                             
                              udp_port = -1;
                            }
                          }else{
                           
                            flag_str = token;
                          }
                        }
                      }
                    }catch( Throwable e ){
                    }
                 
                    addresses.add(
                        ip_str==null?originator.getAddress().getAddress().getHostAddress():ip_str);
                   
                    ports.add( new Integer( tcp_port ));
                   
                    udp_ports.add( new Integer( udp_port==-1?originator.getAddress().getPort():udp_port));
                   
                    flags.add( flag_str );
                   
                    if (( value.getFlags() & DHTPlugin.FLAG_DOWNLOADING ) == 1 ){
                     
                      leecher_count++;
                     
                      is_seeds.add( new Boolean( false ));
   
                    }else{
                     
                      is_seeds.add( new Boolean( true ));
                     
                      seed_count++;
                    }
                  }
               
                }catch( Throwable e ){
                 
                  // in case we get crap back (someone spamming the DHT) just
                  // silently ignore
                }
              }
            }
           
            public void
            valueWritten(
              DHTPluginContact  target,
              DHTPluginValue    value )
            {
            }
 
            public void
            complete(
              byte[]  key,
              boolean  timeout_occurred )
            {
              synchronized( this ){
               
                if ( complete ){
                 
                  return;
                }
               
                complete = true;
              }
             
              if (   target.getType() == REG_TYPE_FULL ||
                  target.getType() == REG_TYPE_DERIVED &&
                    seed_count + leecher_count > 1 )){
               
                log(   download,
                    "Get of '" + target.getDesc() + " completed (elapsed=" + TimeFormatter.formatColonMillis(SystemTime.getCurrentTime() - start)
                        + "), addresses=" + addresses.size() + ", seeds="
                        + seed_count + ", leechers=" + leecher_count);
              }
           
              decreaseActive(download);
             
              int  peers_found = addresses.size();
             
              List<DownloadAnnounceResultPeer>  peers_for_announce = new ArrayList<DownloadAnnounceResultPeer>();
             
                // scale min and max based on number of active torrents
                // we don't want more than a few announces a minute
             
              int  announce_per_min = 4;
             
              int  num_active = query_map.size();
             
              int  announce_min = Math.max( ANNOUNCE_MIN_DEFAULT, ( num_active / announce_per_min )*60*1000 );
             
              int  announce_max = derived_only?ANNOUNCE_MAX_DERIVED_ONLY:ANNOUNCE_MAX;
             
              announce_min = Math.min( announce_min, announce_max );
               
              current_announce_interval = announce_min;

              final long  retry = announce_min + peers_found*(announce_max-announce_min)/NUM_WANT;
             
              int download_state = download.getState();
             
              boolean  we_are_seeding = download_state == Download.ST_SEEDING;

              try{
                this_mon.enter();
             
                int[] run_data = running_downloads.get( download );
               
                if ( run_data != null ){

                  boolean full = target.getType() == REG_TYPE_FULL;
                 
                  int peer_count = we_are_seeding?leecher_count:(seed_count+leecher_count);
                 
                  run_data[1] = full?seed_count:Math.max( run_data[1], seed_count);
                  run_data[2= full?leecher_count:Math.max( run_data[2], leecher_count);
                  run_data[3] = full?peer_count:Math.max( run_data[3], peer_count);
                   
                  long  absolute_retry = SystemTime.getCurrentTime() + retry;
               
                  if ( absolute_retry > max_retry[0] ){
                     
                      // only update next query time if none set yet
                      // or we appear to have set the existing one. If we
                      // don't do this then we'll overwrite any rescheduled
                      // announces
                   
                    Long  existing = (Long)query_map.get( download );
                   
                    if (   existing == null ||
                        existing.longValue() == max_retry[0] ){
                     
                      max_retry[0] = absolute_retry;
                 
                      query_map.put( download, new Long( absolute_retry ));
                    }
                  }
                }           
              }finally{
               
                this_mon.exit();
              }
                           
              putDetails put_details = details.getPutDetails();
             
              String  ext_address = put_details.getIPOverride();
             
              if ( ext_address == null ){
               
                ext_address = dht.getLocalAddress().getAddress().getAddress().getHostAddress();
              }
             
              for (int i=0;i<addresses.size();i++){
               
                  // when we are seeding ignore seeds
               
                if ( we_are_seeding && ((Boolean)is_seeds.get(i)).booleanValue()){
                 
                  continue;
                }
               
                  // remove ourselves
               
                String  ip = (String)addresses.get(i);
               
                if ( ip.equals( ext_address )){
                 
                  if ( ((Integer)ports.get(i)).intValue() == put_details.getTCPPort() &&
                     ((Integer)udp_ports.get(i)).intValue() == put_details.getUDPPort()){
                 
                    continue;
                  }
                }
               
                final int f_i = i;
               
                peers_for_announce.add(
                  new DownloadAnnounceResultPeer()
                  {
                    public String
                    getSource()
                    {
                      return( PEPeerSource.PS_DHT );
                    }
                   
                    public String
                    getAddress()
                    {
                      return((String)addresses.get(f_i));
                    }
                   
                    public int
                    getPort()
                    {
                      return(((Integer)ports.get(f_i)).intValue());
                    }
                   
                    public int
                    getUDPPort()
                    {
                      return(((Integer)udp_ports.get(f_i)).intValue());
                    }
                   
                    public byte[]
                    getPeerID()
                    {
                      return( null );
                    }
                   
                    public short
                    getProtocol()
                    {
                      String  flag = (String)flags.get(f_i);
                     
                      short protocol;
                     
                      if ( flag != null && flag.indexOf("C") != -1 ){
                       
                        protocol = PROTOCOL_CRYPT;
                       
                      }else{
                       
                        protocol = PROTOCOL_NORMAL;
                      }
                     
                      return( protocol );
                    }
                  });
               
              }
               
              if ( target.getType() == REG_TYPE_DERIVED && peers_for_announce.size() > 0 ){
               
                PeerManager pm = download.getPeerManager();
               
                if ( pm != null ){
                   
                    // try some limited direct injection
                 
                  List<DownloadAnnounceResultPeer>  temp = new ArrayList<DownloadAnnounceResultPeer>( peers_for_announce );
                 
                  Random rand = new Random();
                 
                  for (int i=0;i<DIRECT_INJECT_PEER_MAX && temp.size() > 0; i++ ){
                   
                    DownloadAnnounceResultPeer peer = temp.remove( rand.nextInt( temp.size()));
                   
                    log( download, "Injecting derived peer " + peer.getAddress() + " into " + download.getName());
                   
                    Map<Object,Object>  user_data = new HashMap<Object,Object>();
                                       
                    user_data.put( Peer.PR_PRIORITY_CONNECTION, new Boolean( true ));

                    pm.addPeer(
                        peer.getAddress(),
                        peer.getPort(),
                        peer.getUDPPort(),
                        peer.getProtocol() == DownloadAnnounceResultPeer.PROTOCOL_CRYPT,
                        user_data );
                  }
                }
              }
             
              if (   download_state == Download.ST_DOWNLOADING ||
                  download_state == Download.ST_SEEDING ){
             
                final DownloadAnnounceResultPeer[]  peers = new DownloadAnnounceResultPeer[peers_for_announce.size()];
               
                peers_for_announce.toArray( peers );
               
                download.setAnnounceResult(
                    new DownloadAnnounceResult()
                    {
                      public Download
                      getDownload()
                      {
                        return( download );
                      }
                                           
                      public int
                      getResponseType()
                      {
                        return( DownloadAnnounceResult.RT_SUCCESS );
                      }
                                         
                      public int
                      getReportedPeerCount()
                      {
                        return( peers.length);
                      }
                         
                      public int
                      getSeedCount()
                      {
                        return( seed_count );
                      }
                     
                      public int
                      getNonSeedCount()
                      {
                        return( leecher_count )
                      }
                     
                      public String
                      getError()
                      {
                        return( null );
                      }
                                           
                      public URL
                      getURL()
                      {
                        return( url_to_report );
                      }
                     
                      public DownloadAnnounceResultPeer[]
                      getPeers()
                      {
                        return( peers );
                      }
                     
                      public long
                      getTimeToWait()
                      {
                        return( retry/1000 );
                      }
                     
                      public Map
                      getExtensions()
                      {
                        return( null );
                      }
                    });
              }
               
                // only inject the scrape result if the torrent is decentralised. If we do this for
                // "normal" torrents then it can have unwanted side-effects, such as stopping the torrent
                // due to ignore rules if there are no downloaders in the DHT - bthub backup, for example,
                // isn't scrapable...
             
                // hmm, ok, try being a bit more relaxed about this, inject the scrape if
                // we have any peers.
                               
              boolean  inject_scrape = leecher_count > 0;
             
              DownloadScrapeResult result = download.getLastScrapeResult();
                               
              if result == null ||
                  result.getResponseType() == DownloadScrapeResult.RT_ERROR ){                 
 
              }else{
             
                  // if the currently reported values are the same as the
                  // ones we previously injected then overwrite them
                  // note that we can't test the URL to see if we originated
                  // the scrape values as this gets replaced when a normal
                  // scrape fails :(
                 
                int[]  prev = (int[])scrape_injection_map.get( download );
                 
                if (   prev != null &&
                    prev[0] == result.getSeedCount() &&
                    prev[1] == result.getNonSeedCount()){
                                           
                  inject_scrape  = true;
                }
              }
             
              if ( torrent.isDecentralised() || inject_scrape ){
               
               
                  // make sure that the injected scrape values are consistent
                  // with our currently connected peers
               
View Full Code Here

     
      while( it.hasNext() && ready_download == null ){
       
        Download  download = it.next();
       
        Torrent  torrent = download.getTorrent();
       
        if ( torrent == null ){
         
          continue;
        }
       
        int[] run_data = running_downloads.get( download );

        if ( run_data == null || run_data[0] == REG_TYPE_DERIVED ){
         
            // looks like we'll need the scrape below
         
          to_scrape.add( download );
        }
      }
    }finally{
     
      this_mon.exit();
    }
   
    Map<Download,DownloadScrapeResult> scrapes = new HashMap<Download,DownloadScrapeResult>();
   
    for (int i=0;i<to_scrape.size();i++){
     
      Download  download = (Download)to_scrape.get(i);
           
      scrapes.put( download, download.getLastScrapeResult());   
    }
   
    try{
      this_mon.enter();

      Iterator<Download>  it = interesting_downloads.keySet().iterator();
     
      while( it.hasNext() && ready_download == null ){
       
        Download  download = it.next();
       
        Torrent  torrent = download.getTorrent();
       
        if ( torrent == null ){
         
          continue;
        }
       
        int[] run_data = running_downloads.get( download );
       
        if ( run_data == null || run_data[0] == REG_TYPE_DERIVED ){
         
          boolean  force =  torrent.wasCreatedByUs();
         
          if ( !force ){
           
            if ( false && !dht.isReachable()){
             
              continue;
            }
           
            if ( interesting_pub_max > 0 && interesting_published > interesting_pub_max ){
             
              continue;
            }
           
            DownloadScrapeResult  scrape = (DownloadScrapeResult)scrapes.get( download );
           
            if ( scrape == null ){
             
                // catch it next time round
             
              continue;
            }
           
            if ( scrape.getSeedCount() + scrape.getNonSeedCount() > NUM_WANT ){
             
              continue;
            }
          }
         
          long  target = ((Long)interesting_downloads.get( download )).longValue();
         
          long check_period = TorrentUtils.isDecentralised( torrent.getAnnounceURL())?INTERESTING_DHT_CHECK_PERIOD:INTERESTING_CHECK_PERIOD;
         
          if ( target <= now ){
           
            ready_download        = download;
            ready_download_next_check   = now + check_period;
           
            interesting_downloads.put( download, new Long( ready_download_next_check ));
           
          }else if ( target - now > check_period ){
           
            interesting_downloads.put( download, new Long( now + (target%check_period)));
          }
        }
      }
     
    }finally{
     
      this_mon.exit();
    }
   
    if ( ready_download != null ){
     
      final Download  f_ready_download = ready_download;
     
      final Torrent torrent = ready_download.getTorrent();
     
      if ( dht.isDiversified( torrent.getHash())){
       
        // System.out.println( "presence query for " + f_ready_download.getName() + "-> diversified pre start" );

        try{
          this_mon.enter();

          interesting_downloads.remove( f_ready_download );
         
        }finally{
         
          this_mon.exit();
        }
      }else{
     
        //System.out.println( "presence query for " + ready_download.getName());
       
        final long start     = now;
        final long f_next_check = ready_download_next_check;
       
        dht.gettorrent.getHash(),
              "Presence query for '" + ready_download.getName() + "'",
              (byte)0,
              INTERESTING_AVAIL_MAX,
              ANNOUNCE_TIMEOUT,
              false, false,
              new DHTPluginOperationListener()
              {
                private boolean diversified;
                private int   leechers = 0;
                private int   seeds   = 0;
               
                public void
                diversified()
                {
                  diversified  = true;
                }
               
                public void
                starts(
                  byte[]         key )
                {
                }
               
                public void
                valueRead(
                  DHTPluginContact  originator,
                  DHTPluginValue    value )
                {
                  if (( value.getFlags() & DHTPlugin.FLAG_DOWNLOADING ) == 1 ){

                    leechers++;
                   
                  }else{
                   
                    seeds++;
                  }
                }
               
                public void
                valueWritten(
                  DHTPluginContact  target,
                  DHTPluginValue    value )
                {
                }
               
                public void
                complete(
                  byte[]  key,
                  boolean  timeout_occurred )
                {
                  // System.out.println( "    presence query for " + f_ready_download.getName() + "->" + total + "/div = " + diversified );
 
                  int  total = leechers + seeds;
                 
                  log( torrent,
                      "Presence query: availability="+
                      (total==INTERESTING_AVAIL_MAX?(INTERESTING_AVAIL_MAX+"+"):(total+"")) + ",div=" + diversified +
                      " (elapsed=" + TimeFormatter.formatColonMillis(SystemTime.getCurrentTime() - start) + ")");
                     
                  if ( diversified ){
                   
                    try{
                      this_mon.enter();
 
                      interesting_downloads.remove( f_ready_download );
                     
                    }finally{
                     
                      this_mon.exit();
                    }
                   
                  }else if ( total < INTERESTING_AVAIL_MAX ){
                   
                      // once we're registered we don't need to process this download any
                      // more unless it goes active and then inactive again
                   
                    try{
                      this_mon.enter();
 
                      interesting_downloads.remove( f_ready_download );
                     
                    }finally{
                     
                      this_mon.exit();
                    }
                   
                    interesting_published++;
                   
                    if ( !disable_put ){
                     
                      dht.put(
                        torrent.getHash(),
                        "Presence store '" + f_ready_download.getName() + "'",
                        "0".getBytes()// port 0, no connections
                        (byte)0,
                        new DHTPluginOperationListener()
                        {
                          public void
                          diversified()
                          {
                          }
                         
                          public void
                          starts(
                            byte[]         key )
                          {
                          }
                         
                          public void
                          valueRead(
                            DHTPluginContact  originator,
                            DHTPluginValue    value )
                          {
                          }
                         
                          public void
                          valueWritten(
                            DHTPluginContact  target,
                            DHTPluginValue    value )
                          {
                          }
                         
                          public void
                          complete(
                            byte[]  key,
                            boolean  timeout_occurred )
                          {
                          }
                        });
                    }
                  }
                 
                 
                  try{
                    this_mon.enter();
                 
                    int[] run_data = running_downloads.get( f_ready_download );
                   
                    if ( run_data == null ){
                     
                      run_data = run_data_cache.get( f_ready_download );
                    }
                   
                    if ( run_data != null ){

                      if ( total < INTERESTING_AVAIL_MAX ){
                     
                        run_data[1] = seeds;
                        run_data[2= leechers;
                        run_data[3] = total;
                       
                      }else{
                       
                        run_data[1] = Math.max( run_data[1], seeds );
                        run_data[2] = Math.max( run_data[2], leechers );
                      }
                    }
                  }finally{
                   
                    this_mon.exit();
                  }
                 
                  f_ready_download.setScrapeResult(
                    new DownloadScrapeResult()
                    {
                      public Download
                      getDownload()
                      {
                        return( null );
                      }
                     
                      public int
                      getResponseType()
                      {
                        return( RT_SUCCESS );
                      }
                     
                      public int
                      getSeedCount()
                      {
                        return( seeds );
                      }
                     
                      public int
                      getNonSeedCount()
                      {
                        return( leechers );
                      }
 
                      public long
                      getScrapeStartTime()
                      {
                        return( SystemTime.getCurrentTime());
                      }
                       
                      public void
                      setNextScrapeStartTime(
                        long nextScrapeStartTime)
                      {
                      }
                     
                      public long
                      getNextScrapeStartTime()
                      {
                        return( f_next_check );
                      }
                     
                      public String
                      getStatus()
                      {
                        return( "OK" );
                      }
 
                      public URL
                      getURL()
                      {
                        URL  url_to_report = torrent.isDecentralised()?torrent.getAnnounceURL():DEFAULT_URL;

                        return( url_to_report );
                      }
                    });
                }
View Full Code Here

    download  = _download;
    reader    = _reader;
       
    connection_mon  = plugin.getPluginInterface().getUtilities().getMonitor();
   
    Torrent  torrent = reader.getTorrent();
       
    available  = new boolean[(int)torrent.getPieceCount()];
   
    Arrays.fill( available, true );
   
    peer_id  = new byte[20];
   
View Full Code Here

TOP

Related Classes of org.gudy.azureus2.plugins.torrent.Torrent

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.