private void process_removals() throws Exception { FileChange change = removalsToProcess.poll(1, TimeUnit.SECONDS); if (change == null) { return; } logger.fine("process removals: " + change.tree); String comp_path = change.tree.thisFile.getAbsolutePath(); List<DownloadManager> toRemove = new ArrayList<DownloadManager>(); GlobalManager gm = AzureusCoreImpl.getSingleton().getGlobalManager(); for (DownloadManager dm : (List<DownloadManager>) gm.getDownloadManagers()) { if (dm.getSaveLocation().getAbsolutePath().startsWith(comp_path)) { logger.fine( "saveLocation.startsWith() delete of: " + dm.getSaveLocation().getAbsolutePath() + " / " + comp_path); toRemove.add(dm); } else if (comp_path.startsWith(dm.getSaveLocation().getAbsolutePath())) // deleted // a // file // in // the // torrent // directory // we // created, // need // to // remove // (and // possibly // rehash) { logger.fine( "comp_path.startsWith delete of: " + dm.getSaveLocation().getAbsolutePath() + " / " + comp_path); toRemove.add(dm); } } for (DownloadManager dm : toRemove) { logger.info("delete causes removal of: " + dm.getTorrentFileName()); try { gm.removeDownloadManager(dm, true, false); // remove torrent // file (which we // created), but not // data } catch (Exception e) { e.printStackTrace(); } } }
private static void writeTorrentIfExists(TOTorrent torrent) { AzureusCore core = AzureusCoreFactory.getSingleton(); if (core == null || !core.isStarted()) { return; } GlobalManager gm = core.getGlobalManager(); if (gm == null || gm.getDownloadManager(torrent) == null) { return; } try { TorrentUtils.writeToFile(torrent); } catch (TOTorrentException e) { Debug.out(e); } }
private static boolean canPlay(TOTorrent torrent, int file_index) { if (!PlatformTorrentUtils.isContent(torrent, false)) { return false; } if (!AzureusCoreFactory.isCoreRunning()) { return false; } GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager(); DownloadManager dm = gm.getDownloadManager(torrent); if (dm != null) { return dm.getAssumedComplete() || canUseEMP(torrent, file_index); } return canUseEMP(torrent, file_index); }
public UserAlerts(GlobalManager global_manager) { final DownloadManagerAdapter download_manager_listener = new DownloadManagerAdapter() { public void downloadComplete(DownloadManager manager) { if (!manager.getDownloadState().getFlag(DownloadManagerState.FLAG_LOW_NOISE)) { activityFinished(true, manager.getDisplayName(), manager); } } // @see // org.gudy.azureus2.core3.download.impl.DownloadManagerAdapter#stateChanged(org.gudy.azureus2.core3.download.DownloadManager, int) public void stateChanged(final DownloadManager manager, int state) { boolean lowNoise = manager.getDownloadState().getFlag(DownloadManagerState.FLAG_LOW_NOISE); if (lowNoise) { return; } // if state == STARTED, then open the details window (according to config) if (state == DownloadManager.STATE_DOWNLOADING || state == DownloadManager.STATE_SEEDING) { Utils.execSWTThread( new AERunnable() { public void runSupport() { boolean complete = manager.isDownloadComplete(false); if (!complete && COConfigurationManager.getBooleanParameter("Open Details")) { UIFunctionsManagerSWT.getUIFunctionsSWT() .openView(UIFunctions.VIEW_DM_DETAILS, manager); } if (((!complete) && COConfigurationManager.getBooleanParameter("Open Bar Incomplete")) || (complete && COConfigurationManager.getBooleanParameter("Open Bar Complete"))) { DownloadBar.open(manager, Utils.findAnyShell()); } } }); } } }; final DiskManagerListener disk_listener = new DiskManagerListener() { public void stateChanged(int oldState, int newState) {} public void filePriorityChanged(DiskManagerFileInfo file) {} public void pieceDoneChanged(DiskManagerPiece piece) {} public void fileAccessModeChanged(DiskManagerFileInfo file, int old_mode, int new_mode) { DownloadManager dm = file.getDownloadManager(); if (old_mode == DiskManagerFileInfo.WRITE && new_mode == DiskManagerFileInfo.READ) { if (dm == null || !dm.getDownloadState().getFlag(DownloadManagerState.FLAG_LOW_NOISE)) { activityFinished(false, file.getFile(true).getName(), file.getDiskManager()); } } /* System.out.println( "amc:" + file.getDownloadManager().getDisplayName() + "/" + file.getName() + ":" + old_mode + " -> " + new_mode ); */ } }; final DownloadManagerDiskListener dm_disk_listener = new DownloadManagerDiskListener() { public void diskManagerAdded(DiskManager dm) { dm.addListener(disk_listener); } public void diskManagerRemoved(DiskManager dm) { dm.removeListener(disk_listener); } }; global_manager.addListener( new GlobalManagerAdapter() { public void downloadManagerAdded(DownloadManager manager) { // don't pop up for non-persistent as these get added late in the day every time // so we'll notify for each download every startup if (!startup && manager.isPersistent()) { boolean bPopup = COConfigurationManager.getBooleanParameter("Popup Download Added"); if (bPopup) { if (!manager.getDownloadState().getFlag(DownloadManagerState.FLAG_LOW_NOISE)) { String popup_text = MessageText.getString( "popup.download.added", new String[] {manager.getDisplayName()}); Logger.log(new LogAlert(manager, true, LogAlert.AT_INFORMATION, popup_text)); } } } manager.addListener(download_manager_listener); manager.addDiskListener(dm_disk_listener); } public void downloadManagerRemoved(DownloadManager manager) { manager.removeListener(download_manager_listener); manager.removeDiskListener(dm_disk_listener); } public void destroyed() { tidyUp(); } }); startup = false; }
private static void updateMetaData_handleReply( TOTorrent torrent, String hash, String replyType, Map mapHashes) { if (hash == null && torrent != null) { try { hash = torrent.getHashWrapper().toBase32String(); } catch (Exception e) { } } GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager(); DownloadManager dm = gm.getDownloadManager(new HashWrapper(Base32.decode(hash))); if (torrent == null && dm != null) { torrent = dm.getTorrent(); } Map contentMap = PlatformTorrentUtils.getContentMap(torrent); final TOTorrent torrentFinal = torrent; if (replyType.equals(PlatformMessenger.REPLY_EXCEPTION)) { if (torrent != null) { // try again in a bit log(torrent, "Exception, retrying later"); SimpleTimer.addEvent( "Update MD Retry", SystemTime.getCurrentTime() + RETRY_METADATA, new TimerEventPerformer() { public void perform(TimerEvent event) { log(torrentFinal, "retry time"); PlatformTorrentUtils.updateMetaData(torrentFinal, 15000); } }); } } else { Map jsonMapMetaData = hash == null ? null : (Map) mapHashes.get(hash); if (jsonMapMetaData != null) { long oldLastUpdated = getContentLastUpdated(torrent); long expireyMins = 0; for (Iterator iter = jsonMapMetaData.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); Object value = jsonMapMetaData.get(key); if (value == null || value.equals(null)) { contentMap.remove(key); } else if ((key.equals("Thumbnail") || key.endsWith(".B64")) && value instanceof String) { contentMap.put(key, Base64.decode((String) value)); } else if (key.equals("expires-in-mins") && value instanceof Long) { expireyMins = ((Long) value).longValue(); } else { contentMap.put(key, value); } writeTorrentIfExists(torrent); } // crappy way of updating the display name if (dm != null) { String title = PlatformTorrentUtils.getContentTitle(torrent); if (title != null && title.length() > 0 && dm.getDownloadState().getDisplayName() == null) { dm.getDownloadState().setDisplayName(title); } } triggerMetaDataUpdateListeners(torrent); if (torrent != null) { // setup next refresh long refreshOn; if (expireyMins > 0) { refreshOn = SystemTime.getCurrentTime() + (expireyMins * 60 * 1000L); } else { long newLastUpdated = getContentLastUpdated(torrent); long diff = newLastUpdated - oldLastUpdated; log( torrent, "Last Updated: new " + new Date(newLastUpdated) + ";old " + new Date(oldLastUpdated) + ";diff=" + diff); if (diff > 0 && oldLastUpdated != 0) { diff *= 2; if (diff < MIN_MD_REFRESH_MS) { diff = MIN_MD_REFRESH_MS; } else if (diff > MAX_MD_REFRESH_MS) { diff = MAX_MD_REFRESH_MS; } refreshOn = SystemTime.getOffsetTime(diff); } else { refreshOn = SystemTime.getCurrentTime() + (7 * 24 * 60 * 60 * 1000L); } } log(torrent, "got MD. Next refresh in " + (refreshOn - SystemTime.getCurrentTime())); setMetaDataRefreshOn(torrent, refreshOn); SimpleTimer.addEvent( "Update MD", refreshOn, new TimerEventPerformer() { public void perform(TimerEvent event) { PlatformTorrentUtils.updateMetaData(torrentFinal, 15000); } }); } } else if (torrent != null) { long refreshOn = SystemTime.getCurrentTime() + (30 * 24 * 60 * 60 * 1000L); setMetaDataRefreshOn(torrent, refreshOn); log(torrent, "no hash in reply. Next refresh on " + new Date(refreshOn)); } } }
private void create_swarm_synchronously(final File file, String[] tags) throws Exception { /** Trying to create these causes a TOTorrentException */ if (file.isDirectory() == false) { if (file.length() == 0) { return; } } TOTorrentCreator currentCreator = null; cancelled = false; try { currentCreator = TOTorrentFactory.createFromFileOrDirWithComputedPieceLength( file, new URL("http://tracker.invalid/announce"), true); } catch (java.net.MalformedURLException e) { throw new TOTorrentException("malformed tracker url (should _never_ happen)", 0); } final TOTorrentCreator creator_shadow = currentCreator; final BackendTaskManager tasks = BackendTaskManager.get(); final int task_id = tasks.createTask( "Hashing...", new CancellationListener() { public void cancelled(int inID) { mExclusions.add(file.getAbsolutePath()); creator_shadow.cancel(); } }); tasks.getTask(task_id).setSummary("Watch directory hash: " + file.getName()); currentCreator.addListener( new TOTorrentProgressListener() { public void reportCurrentTask(String task_description) { System.out.println("creating: " + task_description); } public void reportProgress(int percent_complete) { if ((percent_complete % 10) == 0) { logger.fine("progress: " + percent_complete); } if (tasks.getTask(task_id) != null) { tasks.getTask(task_id).setProgress(percent_complete + "%"); } if (stopping && !cancelled) { creator_shadow.cancel(); cancelled = true; } } }); TOTorrent created = null; try { created = currentCreator.create(); } catch (TOTorrentException e) { if (e.getReason() == TOTorrentException.RT_ZERO_LENGTH) { logger.warning("Skipping creation of zero-length swarm: " + file.getAbsolutePath()); return; } throw e; } logger.finer("create finished, removing task_id: " + task_id); tasks.removeTask(task_id); if (created == null || cancelled) { System.err.println("created == null, canceled?"); return; } String configSavePath = COConfigurationManager.getStringParameter("General_sDefaultTorrent_Directory"); File outTorrent = null; if (configSavePath == null) { outTorrent = new File(file.getParentFile().getAbsolutePath(), file.getName() + ".torrent"); } else { outTorrent = new File(configSavePath, file.getName() + ".torrent"); } logger.finer("saving to: " + outTorrent.getAbsolutePath()); try { LocaleTorrentUtil.setDefaultTorrentEncoding(created); } catch (LocaleUtilEncodingException e1) { e1.printStackTrace(); } logger.finer("setdefaultencoding, serializing..."); created.serialiseToBEncodedFile(outTorrent); logger.finest("done that"); /** * very small chance of this happening -- most of the time the quit will come during the hashing * (which will cancel it, which will result in null and immediate return) */ if (!stopping) { generate_preview_for_torrent(created, file); logger.finer("settings perms"); ArrayList<GroupBean> typed = new ArrayList<GroupBean>(); typed.add(GroupBean.ALL_FRIENDS); PermissionsDAO.get() .setGroupsForHash(ByteFormatter.encodeString(created.getHash()), typed, true); /** Finally add that swarm and make sure the permissions are f2f only */ GlobalManager gm = AzureusCoreImpl.getSingleton().getGlobalManager(); logger.finer( "calling add download manager, file: " + file.getAbsolutePath() + " save: " + file.getParentFile().getAbsolutePath()); try { final DownloadManager dm = gm.addDownloadManager( outTorrent.getAbsolutePath(), created.getHash(), file.getAbsolutePath(), org.gudy.azureus2.core3.download.DownloadManager.STATE_WAITING, true, true, null); if (tags != null) { DownloadManagerState dmState = dm.getDownloadState(); if (dmState != null) { dm.getDownloadState().setListAttribute(FileCollection.ONESWARM_TAGS_ATTRIBUTE, tags); logger.finer("set tags: " + tags.length + " first: " + tags[0]); } } dm.addListener( new DownloadManagerListener() { public void completionChanged(DownloadManager manager, boolean completed) {} public void downloadComplete(DownloadManager manager) {} public void filePriorityChanged(DownloadManager download, DiskManagerFileInfo file) {} public void positionChanged( DownloadManager download, int oldPosition, int newPosition) {} public void stateChanged(DownloadManager manager, int state) { if (state == org.gudy.azureus2.core3.download.DownloadManager.STATE_SEEDING) { logger.fine("binding audio data for: " + dm.getDisplayName()); MagicDirectoryManager.bind_audio_xml(dm); dm.stopIt( org.gudy.azureus2.core3.download.DownloadManager.STATE_STOPPED, false, false); dm.removeListener(this); } } }); dm.setForceStart(true); } catch (Exception e) { logger.warning(e.toString()); e.printStackTrace(); throw e; } // logger.finest("force start"); // dm.setForceStart(true); } else { logger.finer("was stopping"); } // coreInterface.getF2FInterface().setTorrentPrivacy(dm.getTorrent().getHash(), // false, true); // start doesn't matter here, f2f should start it automatically if // there's a request }
public boolean addTorrentWithOptions(boolean force, final TorrentOpenOptions torrentOptions) { if (AzureusCoreFactory.isCoreRunning()) { GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager(); // Check if torrent already exists in gm, and add if not DownloadManager existingDownload = gm.getDownloadManager(torrentOptions.getTorrent()); if (existingDownload != null) { final String fExistingName = existingDownload.getDisplayName(); final DownloadManager fExistingDownload = existingDownload; fExistingDownload.fireGlobalManagerEvent(GlobalManagerEvent.ET_REQUEST_ATTENTION); Utils.execSWTThread( new AERunnable() { public void runSupport() { boolean can_merge = TorrentUtils.canMergeAnnounceURLs( torrentOptions.getTorrent(), fExistingDownload.getTorrent()); Shell mainShell = UIFunctionsManagerSWT.getUIFunctionsSWT().getMainShell(); if ((Display.getDefault().getActiveShell() == null || !mainShell.isVisible() || mainShell.getMinimized()) && (!can_merge)) { new MessageSlideShell( Display.getCurrent(), SWT.ICON_INFORMATION, MSG_ALREADY_EXISTS, null, new String[] { ":" + torrentOptions.sOriginatingLocation, fExistingName, MessageText.getString(MSG_ALREADY_EXISTS_NAME), }, new Object[] {fExistingDownload}, -1); } else { if (can_merge) { String text = MessageText.getString( MSG_ALREADY_EXISTS + ".text", new String[] { ":" + torrentOptions.sOriginatingLocation, fExistingName, MessageText.getString(MSG_ALREADY_EXISTS_NAME), }); text += "\n\n" + MessageText.getString("openTorrentWindow.mb.alreadyExists.merge"); MessageBoxShell mb = new MessageBoxShell( SWT.YES | SWT.NO, MessageText.getString(MSG_ALREADY_EXISTS + ".title"), text); mb.open( new UserPrompterResultListener() { public void prompterClosed(int result) { if (result == SWT.YES) { TorrentUtils.mergeAnnounceURLs( torrentOptions.getTorrent(), fExistingDownload.getTorrent()); } } }); } else { MessageBoxShell mb = new MessageBoxShell( SWT.OK, MSG_ALREADY_EXISTS, new String[] { ":" + torrentOptions.sOriginatingLocation, fExistingName, MessageText.getString(MSG_ALREADY_EXISTS_NAME), }); mb.open(null); } } } }); if (torrentOptions.bDeleteFileOnCancel) { File torrentFile = new File(torrentOptions.sFileName); torrentFile.delete(); } return true; } } if (!force) { String showAgainMode = COConfigurationManager.getStringParameter( ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS); if (showAgainMode != null && ((showAgainMode.equals(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS_NEVER)) || (showAgainMode.equals(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS_MANY) && torrentOptions.getFiles() != null && torrentOptions.getFiles().length == 1))) { // we're about to silently add the download - ensure that it is going to be saved somewhere // vaguely sensible // as the current save location is simply taken from the 'default download' config which can // be blank (for example) boolean looks_good = false; String save_loc = torrentOptions.getParentDir().trim(); if (save_loc.length() == 0) { // blank :( } else if (save_loc.startsWith(".")) { // relative to who knows where } else { File f = new File(save_loc); if (!f.exists()) { f.mkdirs(); } if (f.isDirectory() && FileUtil.canWriteToDirectory(f)) { if (!f.equals(AETemporaryFileHandler.getTempDirectory())) { looks_good = true; } } } if (looks_good) { return TorrentOpener.addTorrent(torrentOptions); } else { torrentOptions.setParentDir(""); MessageBoxShell mb = new MessageBoxShell( SWT.OK | SWT.ICON_ERROR, "OpenTorrentWindow.mb.invaliddefsave", new String[] {save_loc}); mb.open( new UserPrompterResultListener() { public void prompterClosed(int result) { OpenTorrentOptionsWindow.addTorrent(torrentOptions); } }); return (true); } } } OpenTorrentOptionsWindow.addTorrent(torrentOptions); return true; }