Lots of small changes, major ones

1) Watch as you download option added to the linkgrabber contextmenu
This results in the video starting in vlc (or some mediaplayer) directly.
2) Watch as you download option added to downloads context
This will be used to enable/disable watch as you download for a given filepackage.
Watch as you download works at filepackage level and not individual downloadlink level.
3) Internal changes in neembuu
4) Centralized watch as you download code in DownloadInterface
5) Added org.jdownloader.extensions.neembuu.postprocess.* 

git-svn-id: svn://svn.jdownloader.org/jdownloader/trunk@16254 ebf7c1c2-ba36-0410-9fe8-c592906822b4
This commit is contained in:
shashaank 2012-04-01 07:23:41 +00:00
parent afd8da0b53
commit 56ac324dc1
50 changed files with 3099 additions and 646 deletions

View File

@ -78,7 +78,6 @@
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-config.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-config.src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-diskmanager.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-diskmanager.src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-swing.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-swing.src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-test.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-test.src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-util.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-util.src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-util-logging.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-util-logging.src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs/neembuu/neembuu-util-weaklisteners.jar" sourcepath="ressourcen/code-ressourcen/neembuu/neembuu-util-weaklisteners.src.zip"/>

Binary file not shown.

Binary file not shown.

View File

@ -52,6 +52,11 @@ import org.appwork.utils.ReusableByteArrayOutputStreamPool.ReusableByteArrayOutp
import org.appwork.utils.net.httpconnection.HTTPConnection.RequestMethod;
import org.appwork.utils.net.throttledconnection.MeteredThrottledInputStream;
import org.appwork.utils.speedmeter.AverageSpeedMeter;
import org.appwork.utils.swing.dialog.Dialog;
import org.jdownloader.extensions.neembuu.DownloadSession;
import org.jdownloader.extensions.neembuu.NeembuuExtension;
import org.jdownloader.extensions.neembuu.WatchAsYouDownloadSession;
import org.jdownloader.extensions.neembuu.translate._NT;
import org.jdownloader.settings.GeneralSettings;
import org.jdownloader.settings.IfFileExistsAction;
import org.jdownloader.translate._JDT;
@ -1299,6 +1304,23 @@ abstract public class DownloadInterface {
* @throws Exception
*/
public boolean startDownload() throws Exception {
if (downloadLink.getFilePackage().getProperty(NeembuuExtension.WATCH_AS_YOU_DOWNLOAD_KEY, false).equals(true)) {
DownloadSession downloadSession = new DownloadSession(downloadLink, this, this.plugin, this.getConnection(), this.browser.cloneBrowser());
if (NeembuuExtension.tryHandle(downloadSession)) {
WatchAsYouDownloadSession watchAsYouDownloadSession = downloadSession.getWatchAsYouDownloadSession();
watchAsYouDownloadSession.waitForDownloadToFinish();
return true;
}
int o = 0;
try {
o = Dialog.I().showConfirmDialog(Dialog.LOGIC_COUNTDOWN, _NT._.neembuu_could_not_handle_title(), _NT._.neembuu_could_not_handle_message());
} catch (Exception a) {
o = Dialog.RETURN_CANCEL;
}
if (o == Dialog.RETURN_CANCEL) return false;
logger.severe("Neembuu could not handle this link/filehost. Using default download system.");
}
try {
linkStatus.addStatus(LinkStatus.DOWNLOADINTERFACE_IN_PROGRESS);
logger.finer("Start Download");

View File

@ -449,18 +449,6 @@ public class MediafireCom extends PluginForHost {
this.br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
try {
org.jdownloader.extensions.neembuu.DownloadSession downloadSession = new org.jdownloader.extensions.neembuu.DownloadSession(downloadLink, this.dl, this, this.dl.getConnection(), this.br.cloneBrowser());
if (org.jdownloader.extensions.neembuu.NeembuuExtension.tryHandle(downloadSession)) {
org.jdownloader.extensions.neembuu.WatchAsYouDownloadSession watchAsYouDownloadSession = downloadSession.getWatchAsYouDownloadSession();
watchAsYouDownloadSession.waitForDownloadToFinish();
return;
}
logger.severe("Neembuu could not handle this link/filehost. Using default download system.");
} catch (Throwable e) {
// Neembuu extension is not installed
}
this.dl.startDownload();
}

View File

@ -162,16 +162,6 @@ public class Youtube extends PluginForHost {
this.dl.getConnection().disconnect();
throw new PluginException(LinkStatus.ERROR_RETRY);
}
try {
org.jdownloader.extensions.neembuu.DownloadSession downloadSession = new org.jdownloader.extensions.neembuu.DownloadSession(downloadLink, this.dl, this, this.dl.getConnection(), this.br.cloneBrowser());
if (org.jdownloader.extensions.neembuu.NeembuuExtension.tryHandle(downloadSession)) {
org.jdownloader.extensions.neembuu.WatchAsYouDownloadSession watchAsYouDownloadSession = downloadSession.getWatchAsYouDownloadSession();
watchAsYouDownloadSession.waitForDownloadToFinish();
}
logger.severe("Neembuu could not handle this link/filehost. Using default download system.");
} catch (Throwable e) {
// Neembuu extension is not installed
}
if (this.dl.startDownload()) {
this.postprocess(downloadLink);
}

View File

@ -1,6 +1,18 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu;
@ -29,8 +41,7 @@ import jpfm.volume.vector.VectorRootDirectory;
*/
final class CheckJPfm {
synchronized static final boolean checkVirtualFileSystemCompatibility(
final Logger logger) {
static final boolean checkVirtualFileSystemCompatibility(final Logger logger) {
try {
VectorRootDirectory vrd = new VectorRootDirectory();
VeryBigFile vbf = new VeryBigFile(vrd);
@ -55,10 +66,7 @@ final class CheckJPfm {
throw new IllegalStateException("Mountlocation already exists");
// this would never happen
}
Mount m = Mounts.mount(new MountParamsBuilder()
.set(MountParams.ParamType.MOUNT_LOCATION, mntLoc)
.set(MountParams.ParamType.FILE_SYSTEM, fs)
.set(MountParams.ParamType.LISTENER, new MountListener() {
Mount m = Mounts.mount(new MountParamsBuilder().set(MountParams.ParamType.MOUNT_LOCATION, mntLoc).set(MountParams.ParamType.FILE_SYSTEM, fs).set(MountParams.ParamType.LISTENER, new MountListener() {
// @Override
public void eventOccurred(FormatterEvent event) {
@ -72,10 +80,8 @@ final class CheckJPfm {
Thread.sleep(100);
if (m.isMounted()) {
File virtualVeryBigFile = new File(m.getMountLocation()
.getAsFile(), vbf.getName());
FileChannel fc = new RandomAccessFile(virtualVeryBigFile, "r")
.getChannel();
File virtualVeryBigFile = new File(m.getMountLocation().getAsFile(), vbf.getName());
FileChannel fc = new RandomAccessFile(virtualVeryBigFile, "r").getChannel();
ByteBuffer bb_virtual = ByteBuffer.allocate(1024);
long offset = (long) (Math.random() * vbf.getFileSize());
if (offset != 0) {
@ -85,22 +91,15 @@ final class CheckJPfm {
// we read at 0
fc.position(offset);
int r = fc.read(bb_virtual);
if (r == -1) {
return false;
}
if (r == -1) { return false; }
ByteBuffer bb_actual = ByteBuffer.allocate(1);
SimpleReadRequest readRequest = new SimpleReadRequest(
bb_actual, offset);
SimpleReadRequest readRequest = new SimpleReadRequest(bb_actual, offset);
vbf.read(readRequest);
m.unMount();
logger.log(Level.INFO, "at offset = " + offset
+ " read actual=" + bb_actual.get(0) + " virtual="
+ bb_virtual.get(0));
if (bb_actual.get(0) == bb_virtual.get(0)) {
return true;
}
logger.log(Level.INFO, "at offset = " + offset + " read actual=" + bb_actual.get(0) + " virtual=" + bb_virtual.get(0));
if (bb_actual.get(0) == bb_virtual.get(0)) { return true; }
}
return false;

View File

@ -22,8 +22,7 @@ public final class DownloadSession {
private final URLConnectionAdapter connection;
private final Browser b;
private final AtomicReference<WatchAsYouDownloadSession> watchAsYouDownloadSessionRef
= new AtomicReference<WatchAsYouDownloadSession>(null);
private final AtomicReference<WatchAsYouDownloadSession> watchAsYouDownloadSessionRef = new AtomicReference<WatchAsYouDownloadSession>(null);
public DownloadSession(DownloadLink downloadLink, DownloadInterface di, PluginForHost plugin, URLConnectionAdapter connection, Browser b) {
this.downloadLink = downloadLink;
@ -54,14 +53,11 @@ public final class DownloadSession {
}
void setWatchAsYouDownloadSession(WatchAsYouDownloadSession wayds) {
if(!watchAsYouDownloadSessionRef.compareAndSet(null, wayds)){
throw new IllegalStateException("Already initialized");
}
if (!watchAsYouDownloadSessionRef.compareAndSet(null, wayds)) { throw new IllegalStateException("Already initialized"); }
}
public final WatchAsYouDownloadSession getWatchAsYouDownloadSession() {
if(watchAsYouDownloadSessionRef.get()==null)
throw new IllegalArgumentException("Not initialized");
if (watchAsYouDownloadSessionRef.get() == null) throw new IllegalArgumentException("Not initialized");
return watchAsYouDownloadSessionRef.get();
}

View File

@ -1,6 +1,18 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu;
@ -13,6 +25,7 @@ import javax.swing.SwingUtilities;
import jpfm.operations.readwrite.ReadRequest;
import neembuu.vfs.connection.NewConnectionParams;
import neembuu.vfs.file.TroubleHandler;
import org.jdownloader.extensions.neembuu.translate._NT;
/**
*
@ -27,47 +40,37 @@ public final class NBTroubleHandler implements TroubleHandler {
}
// @Override
public final void cannotCreateANewConnection(final NewConnectionParams ncp,
final int numberOfRetries) {
final String mess = "Cannot create a new connection, unmounting as we already retried "
+ numberOfRetries + " times.";
public final void cannotCreateANewConnection(final NewConnectionParams ncp, final int numberOfRetries) {
final String mess = _NT._.troubleHandler_retriedConnection() + numberOfRetries + _NT._.troubleHandler_retriedConnection_times();
final String mess2 = ncp.toString();
SwingUtilities.invokeLater(new Runnable() {
// @Override
public void run() {
JOptionPane.showMessageDialog(null, mess + "\n" + mess2,
"Unmount initiated on " + jdds, JOptionPane.ERROR);
JOptionPane.showMessageDialog(null, mess + "\n" + mess2, _NT._.failed_WatchAsYouDownload_Title() + " " + jdds, JOptionPane.ERROR);
}
});
jdds.getDownloadInterface().logger
.log(Level.SEVERE, mess + " " + mess2);
jdds.getDownloadInterface().logger.log(Level.SEVERE, mess + " " + mess2);
try {
jdds.getWatchAsYouDownloadSession().unMount();
jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().unmountAndEndSessions();
} catch (Exception a) {
jdds.getDownloadInterface().logger.log(Level.SEVERE,
"unmounting problem", a);
jdds.getDownloadInterface().logger.log(Level.SEVERE, "unmounting problem", a);
}
}
// @Override
public final void readRequestsPendingSinceALongTime(
List<ReadRequest> pendingReadRequest, long atleastMillisec) {
public final void readRequestsPendingSinceALongTime(List<ReadRequest> pendingReadRequest, long atleastMillisec) {
long maxMillisecWait = atleastMillisec;
for (ReadRequest rr : pendingReadRequest) {
if (!rr.isCompleted()) {
long pendingSince = rr.getCreationTime()
- System.currentTimeMillis();
long pendingSince = rr.getCreationTime() - System.currentTimeMillis();
maxMillisecWait = Math.max(maxMillisecWait, pendingSince);
}
}
final String mess = "Some read request pending since past "
+ (maxMillisecWait / 60000d) + "minute(s)";
final String mess2 = "Try watching the file after completely downloading it.\n"
+ "\"Watch as you download\" is difficult on this file.\n"
+ "Unmounting to prevent Not Responding state of the application used to open this file.";
final String mess = _NT._.troubleHandler_pendingRequests() + (maxMillisecWait / 60000d) + _NT._.troubleHandler_pendingRequests_minutes();
final String mess2 = _NT._.troubleHandler_pendingRequests_Solution();
jdds.getDownloadInterface().logger.log(Level.SEVERE, mess);
@ -77,18 +80,16 @@ public final class NBTroubleHandler implements TroubleHandler {
SwingUtilities.invokeLater(new Runnable() {
// @Override
public void run() {
JOptionPane.showMessageDialog(null, mess + "\n" + mess2,
"Unmount initiated on " + jdds, JOptionPane.ERROR);
JOptionPane.showMessageDialog(null, mess + "\n" + mess2, _NT._.failed_WatchAsYouDownload_Title() + " " + jdds, JOptionPane.ERROR);
}
});
jdds.getDownloadInterface().logger.log(Level.SEVERE, mess2);
try {
jdds.getWatchAsYouDownloadSession().unMount();
jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().unmountAndEndSessions();
} catch (Exception a) {
jdds.getDownloadInterface().logger.log(Level.SEVERE,
"unmounting problem", a);
jdds.getDownloadInterface().logger.log(Level.SEVERE, "unmounting problem", a);
}
}
}

View File

@ -4,18 +4,21 @@
*/
package org.jdownloader.extensions.neembuu;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import jd.controlling.JDLogger;
import jd.http.Browser;
import jd.http.Request;
import jd.http.URLConnectionAdapter;
import jd.plugins.DownloadLink;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.download.DownloadInterface;
import org.appwork.utils.Exceptions;
import org.appwork.utils.net.httpconnection.HTTPConnection.RequestMethod;
/**

View File

@ -1,29 +0,0 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jdownloader.extensions.neembuu;
import jpfm.DirectoryStream;
import jpfm.fs.SimpleReadOnlyFileSystem;
import jpfm.volume.vector.VectorRootDirectory;
/**
*
* @author Shashank Tulsyan
*/
public final class NBVirtualFileSystem extends SimpleReadOnlyFileSystem {
static NBVirtualFileSystem newInstance(){
return new NBVirtualFileSystem(new VectorRootDirectory());
}
private NBVirtualFileSystem(DirectoryStream rootDirectoryStream) {
super(rootDirectoryStream);
}
public final VectorRootDirectory getVectorRootDirectory() {
return (VectorRootDirectory)rootDirectoryStream;
}
}

View File

@ -0,0 +1,206 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import jpfm.DirectoryStream;
import jpfm.fs.SimpleReadOnlyFileSystem;
import jpfm.mount.Mount;
import jpfm.volume.vector.VectorRootDirectory;
import neembuu.vfs.file.ConstrainUtility;
import org.jdownloader.extensions.neembuu.gui.VirtualFilesPanel;
import org.jdownloader.extensions.neembuu.postprocess.PostProcessors;
/**
*
* @author Shashank Tulsyan
*/
public final class NB_VirtualFileSystem extends SimpleReadOnlyFileSystem {
static NB_VirtualFileSystem newInstance() {
return new NB_VirtualFileSystem(new VectorRootDirectory());
}
private final LinkedList<DownloadSession> sessions = new LinkedList<DownloadSession>();
private Mount mount = null;
private boolean removedAllSessions = false;
private String mountLocation = null;
private VirtualFilesPanel virtualFilesPanel = null;
private NB_VirtualFileSystem(DirectoryStream rootDirectoryStream) {
super(rootDirectoryStream);
}
public final DirectoryStream getRootDirectory() {
return /* (VectorRootDirectory) */rootDirectoryStream;
}
public String getMountLocation(DownloadSession jdds) throws IOException {
synchronized (sessions) {
if (mountLocation == null) {
mountLocation = makeMountLocation(jdds);
}
return mountLocation;
}
}
public VirtualFilesPanel getVirtualFilesPanel() {
synchronized(sessions){
return virtualFilesPanel;
}
}
public void setVirtualFilesPanel(VirtualFilesPanel virtualFilesPanel) {
synchronized(sessions){
if(this.virtualFilesPanel!=null)throw new IllegalStateException("Already set");
this.virtualFilesPanel = virtualFilesPanel;
}
}
private static String makeMountLocation(DownloadSession jdds) throws IOException {
File baseDir = new File(NeembuuExtension.getInstance().getBasicMountLocation());
if (!baseDir.exists()) baseDir.mkdir();
File mountLoc = new File(baseDir, jdds.getDownloadLink().getFilePackage().getName());
mountLoc.deleteOnExit();
if (mountLoc.exists()) {
try {
java.nio.file.Files.delete(mountLoc.toPath());
} catch (Exception a) {
mountLoc = new File(mountLoc.toString() + Math.random());
}
}
if (!jpfm.util.PreferredMountTypeUtil.isFolderAPreferredMountLocation()) {
mountLoc.createNewFile();
} else {
mountLoc.mkdir();
}
return mountLoc.getAbsolutePath();
}
public void addSession(DownloadSession session) {
synchronized (sessions) {
sessions.add(session);
}
session.getWatchAsYouDownloadSession().getSeekableConnectionFile().setParent(rootDirectoryStream);
((VectorRootDirectory) rootDirectoryStream).add(session.getWatchAsYouDownloadSession().getSeekableConnectionFile());
postProcess();
}
public boolean sessionsCompleted() throws Exception {
synchronized (sessions) {
Iterator<DownloadSession> it = sessions.iterator();
while (it.hasNext()) {
DownloadSession session = it.next();
if (session.getWatchAsYouDownloadSession().getTotalDownload() != session.getDownloadLink().getDownloadSize()) { return false; }
}
// sessions.remove(session);
// NeembuuExtension.getInstance().getGUI().removeSession(session);
}
unmountAndEndSessions();
return true;
// ((VectorRootDirectory)rootDirectoryStream).remove(session.getWatchAsYouDownloadSession().getSeekableConnectionFile());
}
Mount getMount() {
if (mount != null) {
if (!mount.isMounted()) mount = null;
}
return mount;
}
private void unMount() throws Exception {
synchronized (sessions) {
if (mount.isMounted()) mount.unMount();
}
}
public void setMount(Mount mount) {
this.mount = mount;
}
public void unmountAndEndSessions() {
unmountAndEndSessions(false);
}
public void unmountAndEndSessions(boolean alreadyUnmounted) {
DownloadSession jdds = null;
synchronized (sessions) {
if (removedAllSessions) return;
removedAllSessions = true;
virtualFilesPanel = null;
Iterator<DownloadSession> it = sessions.iterator();
while (it.hasNext()) {
DownloadSession session = it.next();
if (jdds == null) jdds = session;
((VectorRootDirectory) rootDirectoryStream).remove(session.getWatchAsYouDownloadSession().getSeekableConnectionFile());
session.getDownloadLink().setEnabled(false);
try {
session.getWatchAsYouDownloadSession().getSeekableConnectionFile().close();
} catch (IllegalStateException exception) {
// ignore
}
it.remove();
}
}
if (jdds != null) {
try {
if (!alreadyUnmounted) unMount();
} catch (Exception a) {
a.printStackTrace(System.err);
}
NeembuuExtension.getInstance().getGUI().removeSession(jdds.getWatchAsYouDownloadSession().getFilePanel());
}
}
private void postProcess() {
synchronized (sessions) {
if (sessions.size() == sessions.get(0).getDownloadLink().getFilePackage().size()) {
// all files of the package added
// post processing can be done now
PostProcessors.postProcess(sessions, sessions.get(0).getWatchAsYouDownloadSession().getVirtualFileSystem(), sessions.get(0).getWatchAsYouDownloadSession().getMountLocation().getAbsolutePath());
}
}
// if(sessions.size() >= 2)
ConstrainUtility.constrain(rootDirectoryStream); // this makes
// each file aware of existence of other filein the same virtual
// directory. This way
// if user is watching a few splits like movie.avi.001,movie.avi.002
// ...movie.avi.007
// and he forwards video from movie.avi.001 to movie.avi.002 , download
// at .001 will stop,
// as .001 will sense the movement of requests from it to other file.
// If this line is commented out, then, watch as you download might be
// inefficient
// in slower connections OR when large number of splits exist
}
@Override
public String toString() {
return mount == null ? "not mounted" : mount.getMountLocation().toString();
}
}

View File

@ -12,10 +12,10 @@ public interface NeembuuConfig extends ExtensionConfigInterface {
// adds the enbtry to jd advanced config table
@AboutConfig
// default value
@DefaultIntValue(4)
// will be shown in the advanced config
// default value
@Description("This is a bla value")
// will be shown in the advanced config
int getBlaNum();
void setBlaNum(int num);

View File

@ -1,14 +1,27 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.*;
import java.util.logging.Level;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import jd.gui.swing.SwingGui;
import jd.plugins.DownloadLink;
import jd.plugins.FilePackage;
import org.appwork.utils.logging.Log;
import org.appwork.utils.swing.EDTRunner;
@ -18,16 +31,21 @@ import org.jdownloader.extensions.ExtensionController;
import org.jdownloader.extensions.StartException;
import org.jdownloader.extensions.StopException;
import org.jdownloader.extensions.neembuu.gui.NeembuuGui;
import org.jdownloader.extensions.neembuu.gui.VirtualFilesPanel;
import org.jdownloader.extensions.neembuu.translate._NT;
import org.jdownloader.images.NewTheme;
public class NeembuuExtension extends AbstractExtension<NeembuuConfig> {
private NeembuuGui tab;
// 0=not checked,1=checked once but failed ... -1= works :)
private int numberOfRetries = 0;
private int number_of_retries = 0; // 0=not
// checked, 1=checked once but failed ... -1 =works :)
private String basicMntLoc = new java.io.File(System.getProperty("user.home") + java.io.File.separator + "NeembuuWatchAsYouDownload").getAbsolutePath();
private String vlcLoc = null;
private final LinkedList<WatchAsYouDownloadSession> watchAsYouDownloadSessions = new LinkedList<WatchAsYouDownloadSession>();
public static final String WATCH_AS_YOU_DOWNLOAD_KEY = "WATCH_AS_YOU_DOWNLOAD";
private final Map<FilePackage,NB_VirtualFileSystem> virtualFileSystems = new HashMap<FilePackage,NB_VirtualFileSystem>();
private final Map<DownloadLink,DownloadSession> downloadSessions = new HashMap<DownloadLink,DownloadSession>();
public NeembuuExtension() {
super(_NT._.title());
@ -41,51 +59,113 @@ public class NeembuuExtension extends AbstractExtension<NeembuuConfig> {
System.setProperty("neembuu.vfs.test.MoniorFrame.resumepolicy", "resumeFromPreviousState");
}
public final boolean isUsable() {
if (numberOfRetries > 10) {
public String getBasicMountLocation() {
return basicMntLoc;
}
public String getVlcLocation() {
return vlcLoc;
}
public void setVlcLocation(String vlcl){
this.vlcLoc = vlcl;
}
public void setBasicMountLocation(String basicMntLoc) throws Exception {
java.io.File f = new java.io.File(basicMntLoc);
if (!f.exists()) { throw new IllegalArgumentException("Basic mount location does not exist"); }
if (!f.isDirectory()) { throw new IllegalArgumentException("Basic mount location must be a directory"); }
// test basic mount location
java.io.File f_test = new java.io.File(basicMntLoc, "testfile" + Math.random());
f_test.createNewFile();
if (f.exists()) {
// ok
}
boolean del = f_test.delete();
if (!del) {
logger.severe("could not delete " + f_test);
java.nio.file.Files.delete(f_test.toPath());
}
this.basicMntLoc = basicMntLoc;
}
public synchronized final boolean isUsable() {
if (number_of_retries > 10) {
logger.fine("Virtual File system checked more than 10 times, and it is not working");
return false;
// we just simply assume
// that it is not going to work
}
if (numberOfRetries != -1) {
if (number_of_retries != -1) {
if (CheckJPfm.checkVirtualFileSystemCompatibility(logger)) {
numberOfRetries = -1;
} else
numberOfRetries++;
number_of_retries = -1;
} else {
number_of_retries++;
}
return numberOfRetries == -1;
}
return number_of_retries == -1;
}
public static boolean canHandle(ArrayList<FilePackage> fps){
if (!isActive()) { return false; }
NeembuuExtension ne = getInstance();
if (!ne.isUsable()) { return false; }
for(FilePackage fp : fps){
if(fp==null)continue;//ignore empty entries
for(DownloadLink dl : fp.getChildren()){
//todo : make this better. Check other features of host to ensure
// it can support watch as you download. It would be best if hosts
// that have been tested successfully/unsuccessfully are added to
// a whitelist/blacklist.
int c = dl.getDefaultPlugin().getMaxSimultanPremiumDownloadNum();
if(c < 5 && c!=-1)
return false;
}
}
return true;
}
public static boolean tryHandle(final DownloadSession jdds) {
if (!isActive()) return false;
if (!isActive()) { return false; }
NeembuuExtension ne = getInstance();
if (!ne.isUsable()) return false;
if (!ne.isUsable()) { return false; }
return ne.tryHandle_(jdds);
}
private boolean tryHandle_(final DownloadSession jdds) {
synchronized (watchAsYouDownloadSessions) {
int o = JOptionPane.showConfirmDialog(SwingGui.getInstance().getMainFrame(), "Do you wish to watch as you download this file?", "Neembuu watch as you download", JOptionPane.YES_NO_OPTION);
if (o != JOptionPane.YES_OPTION) { return false; }
int o = 0;
//try{
//o = Dialog.I().showConfirmDialog(Dialog.LOGIC_COUNTDOWN, _NT._.approve_WatchAsYouDownload_Title(), _NT._.approve_WatchAsYouDownload_Message());
//}catch(Exception a){
//ignore
//}
//int o = JOptionPane.showConfirmDialog(SwingGui.getInstance().getMainFrame(), _NT._.approve_WatchAsYouDownload_Message(), _NT._.approve_WatchAsYouDownload_Title(), JOptionPane.YES_NO_OPTION);
//if (o != /*JOptionPane.YES_OPTION*/ Dialog.RETURN_OK) { return false; }
try {
WatchAsYouDownloadSessionImpl.makeNew(jdds);
watchAsYouDownloadSessions.add(jdds.getWatchAsYouDownloadSession());
} catch (Exception a) {
SwingUtilities.invokeLater(new Runnable() {
/*SwingUtilities.invokeLater(new Runnable() {
// @Override
public void run() {
JOptionPane.showMessageDialog(SwingGui.getInstance().getMainFrame(), "Could not start a watch as you download session for\n" + jdds.toString(), "Neembuu watch as you download failed.", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(SwingGui.getInstance().getMainFrame(), _NT._.failed_WatchAsYouDownload_Message() + "\n" + jdds.toString(), _NT._.failed_WatchAsYouDownload_Title(), JOptionPane.ERROR_MESSAGE);
}
});
});*/
logger.log(Level.SEVERE, "Could not start a watch as you download session", a);
return false;
}
tab.addSession(jdds);
downloadSessions.put(jdds.getDownloadLink(),jdds);
return true;
}
}
@ -98,6 +178,14 @@ public class NeembuuExtension extends AbstractExtension<NeembuuConfig> {
return (NeembuuExtension) ExtensionController.getInstance().getExtension(NeembuuExtension.class)._getExtension();
}
public final Map<FilePackage, NB_VirtualFileSystem> getVirtualFileSystems() {
return virtualFileSystems;
}
public final Map<DownloadLink, DownloadSession> getDownloadSessions() {
return downloadSessions;
}
/**
* Action "onStop". Is called each time the user disables the extension
*/
@ -107,7 +195,9 @@ public class NeembuuExtension extends AbstractExtension<NeembuuConfig> {
Iterator<WatchAsYouDownloadSession> it = watchAsYouDownloadSessions.iterator();
while (it.hasNext()) {
try {
it.next().unMount();
NB_VirtualFileSystem fs = it.next().getVirtualFileSystem();
Log.L.info("unmounting " + fs.getMount());
fs.unmountAndEndSessions();
} catch (Exception a) {
// ignore
}
@ -136,7 +226,7 @@ public class NeembuuExtension extends AbstractExtension<NeembuuConfig> {
@Override
public boolean isDefaultEnabled() {
return false;
return true;
}
@Override
@ -194,5 +284,4 @@ public class NeembuuExtension extends AbstractExtension<NeembuuConfig> {
public NeembuuGui getGUI() {
return tab;
}
}

View File

@ -1,12 +1,25 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu;
import java.io.File;
import javax.swing.JPanel;
import neembuu.vfs.file.SeekableConnectionFile;
import org.jdownloader.extensions.neembuu.gui.HttpFilePanel;
/**
*
@ -14,12 +27,18 @@ import neembuu.vfs.file.SeekableConnectionFile;
*/
public interface WatchAsYouDownloadSession {
SeekableConnectionFile getSeekableConnectionFile();
NBVirtualFileSystem getVirtualFileSystem();
NB_VirtualFileSystem getVirtualFileSystem();
JPanel getFilePanel();
HttpFilePanel getHttpFilePanel();
boolean isMounted();
void mount()throws Exception;
void unMount()throws Exception;
File getMountLocation();
void waitForDownloadToFinish() throws Exception;
long getTotalDownload();
}

View File

@ -1,12 +1,25 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
@ -29,9 +42,11 @@ import neembuu.vfs.file.TroubleHandler;
import neembuu.vfs.progresscontrol.ThrottleFactory;
import neembuu.vfs.readmanager.ReadRequestState;
import neembuu.vfs.readmanager.impl.SeekableConnectionFileImplBuilder;
import neembuu.vfs.test.MonitoredSeekableHttpFilePanel;
import org.jdownloader.extensions.neembuu.gui.HttpFilePanel;
import org.jdownloader.extensions.neembuu.gui.VirtualFilesPanel;
import org.jdownloader.extensions.neembuu.newconnectionprovider.JD_HTTP_Download_Manager;
import org.jdownloader.extensions.neembuu.postprocess.PostProcessors;
/**
*
@ -39,20 +54,39 @@ import org.jdownloader.extensions.neembuu.newconnectionprovider.JD_HTTP_Download
* @author Coalado
*/
final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
private final SeekableConnectionFile file;
// private final SeekableConnectionFile file;// not used
private final MonitoredHttpFile httpFile;
private final MonitoredSeekableHttpFilePanel filePanel;
private final NBVirtualFileSystem virtualFileSystem;
private JPanel filePanel;
private final HttpFilePanel monitoredSeekableHttpFilePanel;
private final NB_VirtualFileSystem virtualFileSystem;
private final DownloadSession jdds;
private final Object lock = new Object();
private Mount mount = null;
private volatile long totalDownload = 0;
static WatchAsYouDownloadSessionImpl makeNew(DownloadSession jdds) throws Exception {
NBVirtualFileSystem fileSystem = NBVirtualFileSystem.newInstance();
NB_VirtualFileSystem fileSystem = null;
try {
// fileSystem = (NB_VirtualFileSystem)
// jdds.getDownloadLink().getFilePackage().getProperty("NB_VirtualFileSystem");
fileSystem = NeembuuExtension.getInstance().getVirtualFileSystems().get(jdds.getDownloadLink().getFilePackage());
} catch (ClassCastException cce) {
}
if (fileSystem == null) {
fileSystem = NB_VirtualFileSystem.newInstance();
// jdds.getDownloadLink().getFilePackage().setProperty("NB_VirtualFileSystem",
// fileSystem);
NeembuuExtension.getInstance().getVirtualFileSystems().put(jdds.getDownloadLink().getFilePackage(), fileSystem);
jdds.getDownloadInterface().logger.info("Using new filesystem " + fileSystem);
} else {
jdds.getDownloadInterface().logger.info("Using previous created filesystem " + fileSystem);
}
// read the javadoc to know what this does
// Briefly : sometimes the filesystem is hung because of big sized
// requests or because a new connection cannot
// be made. In such cases it decides
// what must be done.
TroubleHandler troubleHandler = new NBTroubleHandler(jdds);
// JD team might like to change this to something they like.
@ -60,21 +94,18 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
// for this reason, chucks are placed in a directory.
// In the default implementation, I chose not to save in a single file
// because that would require to also matin progress information in a
// separete file.
// The name of the file contains the offset from which it starts, and
// size of the file
// tells us how much was downloaded. Very important logs are also saved
// along with these files.
// separete file. The name of the file contains the offset from which
// it starts, and size of the file tells us how much was downloaded.
// Very important logs are also saved along with these files.
// They are in html format, and I would strongly suggest if an alternate
// implementation to
// this is provided, leave the html logs as they are. 2 log files are
// created for every unique chunk,
// implementation to this is provided, leave the html logs as they
// are. 2 log files are created for every unique chunk,
// and one for each file which logs overall working of differnt
// chunks/regions.
// For this reason the download folder would contain a lot of files.
// These logs are highly essential.
// chunks/regions. For this reason the download folder would contain
// a lot of files. These logs are highly essential.
DiskManager diskManager = DiskManagers.getDefaultManager(new File(jdds.getDownloadLink().getFileOutput()).getParentFile().getAbsolutePath());
// Is used to create new connections at some arbitary offset
// this is the only thing that neembuu requires JD to provide
// all other things are handled by neembuu.
// You will notice that the code is not much.
@ -82,54 +113,63 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
// for FTP and other protocols as the case maybe.
JD_HTTP_Download_Manager newConnectionProvider = new JD_HTTP_Download_Manager(jdds);
// throttle is a very unique speed measuring, and controlling unit.
// Limiting download speed is crucial to prevent starvation of regions
// which really require speed, and make the system respond quickly. The
// main work of throttle is not to limit speed as much as it is to kill
// connections to improve speed where it is actually required. This
// makes a HUGE difference in watch as you download experience of the
// user.
// Making a decent throttle is one of the biggest challenges. The
// program as such is simple, but the key issue is same approach doesn't
// work for all files. For avi's you might need a different approach,
// for mkv still another. This GeneralThrottle is however pretty decent
// and should be able to handle most of the files.
ThrottleFactory throttleFactory = ThrottleFactory.General.SINGLETON;
// all paramters below are compulsary. None of these may be left
// unspecified.
SeekableConnectionFile file = new SeekableConnectionFileImplBuilder().build(new SeekableConnectionFileParams.Builder().setDiskManager(diskManager).setTroubleHandler(troubleHandler).setFileName(jdds.getDownloadLink().getFinalFileName()).setFileSize(jdds.getDownloadLink().getDownloadSize()).setNewConnectionProvider(newConnectionProvider).setThrottleFactory(ThrottleFactory.General.SINGLETON).setParent(fileSystem.getVectorRootDirectory())
// throttle is a very unique speed
// measuring, and controlling unit. Limiting
// download speed is crucial
// to prevent starvation of regions which really require
// speed, and make the system respond quickly.
// The main work of throttle is not to limit
// speed as much as it is to kill connections to improve
// speed where it is actually
// required. This makes a HUGE difference in watch as
// you download experience of the user.
// Making a decent throttle is one
// of the biggest challenges. The program as such is
// simple, but the key issue is same
// approach doesn't work for all files.
// For avi's you might need a different approach, for
// mkv still another.
// This GeneralThrottle is however pretty decent and
// should be able to
// handle most of the files.
.build());
SeekableConnectionFile file = SeekableConnectionFileImplBuilder.build(new SeekableConnectionFileParams.Builder().setDiskManager(diskManager).setTroubleHandler(troubleHandler).setFileName(jdds.getDownloadLink().getFinalFileName()).setFileSize(jdds.getDownloadLink().getDownloadSize()).setNewConnectionProvider(newConnectionProvider).setParent(fileSystem.getRootDirectory()).setThrottleFactory(throttleFactory).build());
MonitoredHttpFile httpFile = new MonitoredHttpFile(file, newConnectionProvider);
MonitoredSeekableHttpFilePanel httpFilePanel = new MonitoredSeekableHttpFilePanel(httpFile);
fileSystem.getVectorRootDirectory().add(httpFile);
final String mountLocation = fileSystem.getMountLocation(jdds);
HttpFilePanel httpFilePanel = new HttpFilePanel(httpFile);
WatchAsYouDownloadSessionImpl sessionImpl = new WatchAsYouDownloadSessionImpl(file, httpFile, httpFilePanel, fileSystem, jdds);
jdds.setWatchAsYouDownloadSession(sessionImpl);
sessionImpl.mount();
JPanel virtualFilesPanel = VirtualFilesPanel.getOrCreate(jdds, mountLocation, httpFilePanel);
sessionImpl.filePanel = virtualFilesPanel;
jdds.getWatchAsYouDownloadSession().getHttpFilePanel().setVirtualPathOfFile(new File(mountLocation, jdds.getDownloadLink().getFinalFileName()).getAbsolutePath());
// mount might have been already initiated by some other downloadlink in
// this same filepackage
if (!sessionImpl.isMounted()) sessionImpl.mount(mountLocation);
fileSystem.addSession(jdds);
return sessionImpl;
}
WatchAsYouDownloadSessionImpl(SeekableConnectionFile file, MonitoredHttpFile httpFile, MonitoredSeekableHttpFilePanel filePanel, NBVirtualFileSystem virtualFileSystem, DownloadSession jdds) {
this.file = file;
WatchAsYouDownloadSessionImpl(SeekableConnectionFile file, MonitoredHttpFile httpFile, HttpFilePanel monitoredSeekableHttpFilePanel, NB_VirtualFileSystem virtualFileSystem, DownloadSession jdds) {
// this.file = file;
this.httpFile = httpFile;
this.filePanel = filePanel;
this.virtualFileSystem = virtualFileSystem;
this.jdds = jdds;
this.monitoredSeekableHttpFilePanel = monitoredSeekableHttpFilePanel;
}
public final long getTotalDownload() {
return totalDownload;
}
// @Override
public final NBVirtualFileSystem getVirtualFileSystem() {
public final NB_VirtualFileSystem getVirtualFileSystem() {
return virtualFileSystem;
}
public final HttpFilePanel getHttpFilePanel() {
return monitoredSeekableHttpFilePanel;
}
// @Override
public final SeekableConnectionFile getSeekableConnectionFile() {
return httpFile;
@ -143,6 +183,7 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
// @Override
public boolean isMounted() {
synchronized (lock) {
Mount mount = virtualFileSystem.getMount();
if (mount == null) return false;
return mount.isMounted();
}
@ -150,55 +191,29 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
// @Override
public File getMountLocation() {
return mount.getMountLocation().getAsFile();
return virtualFileSystem.getMount().getMountLocation().getAsFile();
}
// @Override
public void mount() throws Exception {
private void mount(final String mountLocation) throws Exception {
synchronized (lock) {
if (isMounted()) { throw new IllegalStateException("Already mounted"); }
final String mountLocation = makeMountLocation();
Mount m = Mounts.mount(new MountParamsBuilder().set(ParamType.LISTENER, new MountListener() {
// @Override
public void eventOccurred(FormatterEvent event) {
if (event.getEventType() == FormatterEvent.EVENT.SUCCESSFULLY_MOUNTED) {
try {
java.awt.Desktop.getDesktop().open(new File(mountLocation));
} catch (IOException ioe) {
// jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().removeAllSessions();
} catch (Exception ioe) {
jdds.getDownloadInterface().logger.log(Level.INFO, event.getMessage(), event.getException());
}
} else if (event.getEventType() == FormatterEvent.EVENT.DETACHED) {
NeembuuExtension.getInstance().getGUI().removeSession(jdds);
virtualFileSystem.unmountAndEndSessions(true);
}
}
}).set(ParamType.FILE_SYSTEM, virtualFileSystem).set(ParamType.MOUNT_LOCATION, mountLocation).build());
this.mount = m;
}
}
private String makeMountLocation() throws IOException {
File baseDir = new File(System.getProperty("user.home") + File.separator + "NeembuuWatchAsYouDownload");
if (!baseDir.exists()) baseDir.mkdir();
File mountLoc = new File(baseDir, jdds.getDownloadLink().getFinalFileName());
mountLoc.deleteOnExit();
if (mountLoc.exists()) {
mountLoc = new File(mountLoc.toString() + Math.random());
}
if (!jpfm.util.PreferredMountTypeUtil.isFolderAPreferredMountLocation()) {
mountLoc.createNewFile();
} else {
mountLoc.mkdir();
}
return mountLoc.getAbsolutePath();
}
// @Override
public void unMount() throws Exception {
synchronized (lock) {
mount.unMount();
virtualFileSystem.setMount(m);
}
}
@ -206,14 +221,12 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
public void waitForDownloadToFinish() throws Exception {
jdds.getDownloadInterface().addChunksDownloading(1);
Chunk ch = jdds.getDownloadInterface().new Chunk(0, 0, null, null) {
/*
* @Override public long getBytesLoaded() { return totalDownload; }
*
* @Override public long getCurrentBytesPosition() { return
* totalDownload; }
*/
// @Override
// public long getSpeed() {
// return (long)
// jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().getTotalFileReadStatistics().getTotalAverageDownloadSpeedProvider().getDownloadSpeed_KiBps()
// * 1024;
// }
};
ch.setInProgress(true);
jdds.getDownloadInterface().getChunks().add(ch);
@ -238,16 +251,43 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
jdds.getDownloadLink().getLinkStatus().setStatusText(null);
ch.setInProgress(false);
if (jdds.getWatchAsYouDownloadSession().isMounted()) {
jdds.getWatchAsYouDownloadSession().unMount();
if (totalDownload >= jdds.getDownloadLink().getDownloadSize()) {
jdds.getDownloadLink().getLinkStatus().addStatus(LinkStatus.FINISHED);
}
// make sure that the file is close
// jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().close();
// wait for other splits to finish
WAIT_FOR_SPLITS_TO_FINISH: while (jdds.getWatchAsYouDownloadSession().isMounted()) {
if (virtualFileSystem.sessionsCompleted()) {
virtualFileSystem.unmountAndEndSessions();
break WAIT_FOR_SPLITS_TO_FINISH;
}
Thread.sleep(1000);
}
if (totalDownload >= jdds.getDownloadLink().getDownloadSize()) {
jdds.getDownloadLink().getLinkStatus().addStatus(LinkStatus.FINISHED);
final AtomicBoolean done = new AtomicBoolean(false);
new Thread() {
@Override
public void run() {
try {
jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().getFileStorageManager().completeSession(new File(jdds.getDownloadLink().getFileOutput()), jdds.getDownloadLink().getDownloadSize());
done.set(true);
} catch (Exception i) {
Logger.getGlobal().log(Level.SEVERE, "Problem in completing session", i);
}
}
}.start();
for (int j = 0; !done.get() /* && j < 20 */; j++) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// ignore
}
}
PostProcessors.downloadComplete(jdds.getDownloadLink());
} else {
jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().getFileStorageManager().close();
throw new PluginException(LinkStatus.ERROR_DOWNLOAD_INCOMPLETE);
@ -267,7 +307,8 @@ final class WatchAsYouDownloadSessionImpl implements WatchAsYouDownloadSession {
jdds.getDownloadLink().setDownloadCurrent(total);
jdds.getDownloadLink().setChunksProgress(new long[] { total });
jdds.getDownloadInterface().addToChunksInProgress(total);
// jdds.getDownloadLink().requestGuiUpdate();
// jdds.getDownloadInterface().addToChunksInProgress(total);
}
}

View File

@ -1,6 +1,18 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.gui;
@ -25,18 +37,16 @@ import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.event.*;
import org.jdownloader.extensions.neembuu.DownloadSession;
import org.jdownloader.extensions.neembuu.translate._NT;
/**
* Component to be used as tabComponent; Contains a JLabel to show the text and
* a JButton to close the tab it belongs to
*/
public class ButtonTabComponent extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1672135537070393545L;
private final JTabbedPane pane;
private final DownloadSession jdds;
private final NeembuuGui neembuuGui;
@ -101,18 +111,9 @@ public class ButtonTabComponent extends JPanel {
}
public void actionPerformed(ActionEvent e) {
int ret = JOptionPane.showConfirmDialog(null, jdds.toString(), "Are you sure you want to unmount?", JOptionPane.YES_NO_OPTION);
int ret = JOptionPane.showConfirmDialog(null, jdds.getDownloadLink().getFilePackage().getName(), _NT._.unmountConfirm(), JOptionPane.YES_NO_OPTION);
if (ret == JOptionPane.YES_OPTION) {
try {
jdds.getWatchAsYouDownloadSession().unMount();
} catch (Exception a) {
}
try {
neembuuGui.removeSession(jdds);
} catch (Exception a) {
}
jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().unmountAndEndSessions();
}
/*
* int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i

View File

@ -0,0 +1,411 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.SoftBevelBorderInfo">
<BevelBorder/>
</Border>
</Property>
<Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[628, 10000]"/>
</Property>
<Property name="verifyInputWhenFocusTarget" type="boolean" value="false"/>
</Properties>
<AccessibilityProperties>
<Property name="AccessibleContext.accessibleDescription" type="java.lang.String" value=""/>
</AccessibilityProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,2,63,0,0,2,113"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Container class="javax.swing.JPanel" name="normalControls">
<Properties>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[619, 250]"/>
</Property>
<Property name="name" type="java.lang.String" value=""/>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[619, 250]"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout">
<Property name="useNullLayout" type="boolean" value="true"/>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="downloadSpeedVal">
<Properties>
<Property name="text" type="java.lang.String" value="KiBps"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="220" y="210" width="170" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="filenameLabel">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_linkFileName()" type="code"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="3" y="55" width="84" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="fileSizeValue">
<Properties>
<Property name="text" type="java.lang.String" value="filesize"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="115" y="32" width="230" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="urlLabel">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_link()" type="code"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="3" y="6" width="57" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="requestRateVal">
<Properties>
<Property name="text" type="java.lang.String" value="KiBps"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="220" y="230" width="170" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="totalRequestRateLabel">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_totalRequestRate()" type="code"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="10" y="230" width="190" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="totalDownloadSpeedLabel">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_totalDownloadSpeed()" type="code"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="10" y="210" width="200" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JToggleButton" name="toggleAdvancedView">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_advancedViewButton()" type="code"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="toggleAdvancedViewActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="402" y="210" width="190" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="filesizeLabel">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_linkFileSize()" type="code"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="3" y="32" width="74" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="fileNameValue">
<Properties>
<Property name="text" type="java.lang.String" value="filename_"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="115" y="55" width="290" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JTextField" name="connectionDescText">
<Properties>
<Property name="editable" type="boolean" value="false"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="115" y="3" width="483" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JButton" name="openFile">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_openFile()" type="code"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="openFileActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="440" y="60" width="160" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JToggleButton" name="autoCompleteEnabledButton">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_autoCompleteButtonEnabled()" type="code"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="autoCompleteEnabledButtonActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="360" y="30" width="240" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Container class="javax.swing.JPanel" name="jPanel1">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
<TitledBorder justification="2" title="&lt;User Code&gt;">
<Connection PropertyName="titleX" code="_NT._.filePanel_regionDownloadedTitle()" type="code"/>
</TitledBorder>
</Border>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="10" y="80" width="590" height="65"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Component class="javax.swing.JProgressBar" name="regionDownloadedBar">
<Properties>
<Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[32767, 10]"/>
</Property>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[10, 10]"/>
</Property>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[146, 10]"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new neembuu.swing.RangeArrayComponent(file.getRegionHandlers(),downloadedRegionColorProvider,true)"/>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="jPanel2">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
<TitledBorder justification="2" title="&lt;User Code&gt;">
<Connection PropertyName="titleX" code="_NT._.filePanel_regionRequestedTitle()" type="code"/>
</TitledBorder>
</Border>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="10" y="145" width="590" height="65"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Component class="javax.swing.JProgressBar" name="regionRequestedBar">
<AuxValues>
<AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new neembuu.swing.RangeArrayComponent(file.getRequestedRegion(),requestedRegionColorProvider,true)"/>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="graphAndAdvancedPanel">
<Properties>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[619, 300]"/>
</Property>
<Property name="name" type="java.lang.String" value=""/>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[619, 300]"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new JXCollapsiblePane()"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="South"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout">
<Property name="useNullLayout" type="boolean" value="true"/>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="connectionStatusLabel">
<Properties>
<Property name="text" type="java.lang.String" value="No connection selected"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="0" y="32" width="590" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JButton" name="previousButton">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_selectPreviousRegionButton()" type="code"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="previousButtonActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="396" y="0" width="190" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JLabel" name="throttleStateLable">
<Properties>
<Property name="text" type="java.lang.String" value="Throttle state"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="0" y="55" width="379" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JButton" name="nextButton">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_selectNextRegionButton()" type="code"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="nextButtonActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="122" y="0" width="260" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JButton" name="killConnection">
<Properties>
<Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="_NT._.filePanel_killConnection()" type="code"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="killConnectionActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="430" y="50" width="163" height="-1"/>
</Constraint>
</Constraints>
</Component>
<Container class="javax.swing.JPanel" name="speedGraphPanel">
<Properties>
<Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[412, 350]"/>
</Property>
<Property name="name" type="java.lang.String" value="" noResource="true"/>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[412, 200]"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new javax.swing.JPanel()"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="0" y="78" width="600" height="213"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
</Container>
<Component class="javax.swing.JButton" name="printStateButton">
<Properties>
<Property name="text" type="java.lang.String" value="Print State"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="printStateButtonActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout" value="org.netbeans.modules.form.compat2.layouts.DesignAbsoluteLayout$AbsoluteConstraintsDescription">
<AbsoluteConstraints x="10" y="10" width="-1" height="19"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>

View File

@ -0,0 +1,577 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import neembuu.rangearray.ModificationType;
import neembuu.rangearray.Range;
import neembuu.rangearray.RangeArrayListener;
import neembuu.rangearray.RangeUtils;
import neembuu.rangearray.UnsyncRangeArrayCopy;
import neembuu.swing.RangeArrayComponent;
import neembuu.swing.RangeArrayElementColorProvider;
import neembuu.swing.RangeSelectedListener;
import neembuu.util.logging.LoggerUtil;
import neembuu.vfs.file.MonitoredHttpFile;
import neembuu.vfs.readmanager.RegionHandler;
import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdownloader.extensions.neembuu.translate._NT;
/**
*
* @author Shashank Tulsyan
*/
public final class HttpFilePanel extends javax.swing.JPanel implements RangeSelectedListener {
private final MonitoredHttpFile file;
private SpeedGraphJFluid graphJFluid = null;
private volatile String virtualPathOfFile = null;
private static final Logger LOGGER = LoggerUtil.getLogger();
private volatile Range lastRegionSelected = null;
private volatile RegionHandler lastRegionHandler = null;
// private final Object rangeSelectedLock = new Object();
RegionHandler previousRegionOfInterest;
// Map<Long,Color> rm = new
private final RequestedRegionColorProvider requestedRegionColorProvider = new RequestedRegionColorProvider();
private final JLabel activateLable = new JLabel(_NT._.filePanel_graph_noRegionSelected());
// ,new
// ImageIcon(HttpFilePanel.class.getResource("activate.png")),SwingConstants.CENTER
private final RangeArrayElementColorProvider downloadedRegionColorProvider = new DownloadedRegionColorProvider();
private static final class DownloadedRegionColorProvider implements RangeArrayElementColorProvider {
// @Override
public Color getColor(Color defaultColor, Range element, SelectionState selectionState) {
RegionHandler rh = (RegionHandler) element.getProperty();
Color base = defaultColor;
try {
if (rh.isAlive()) {
base = new Color(102, 93, 149);
// base=new
// Color(126,193,160);//RangeArrayComponent.lightenColor(Color.GREEN,0.56f);
}
} catch (NullPointerException npe) {
return defaultColor;
}
if (rh.isMainDirectionOfDownload()) {
if (!rh.isAlive()) {
base = new Color(168, 122, 92);
} else {
// base=new Color(30,50,200);//
// RangeArrayComponent.lightenColor(Color.BLUE,0.56f);
base = new Color(138, 170, 231);
}
}
switch (selectionState) {
case LIST:
base = RangeArrayComponent.lightenColor(base, 0.9f);
break;
case MOUSE_OVER:
base = RangeArrayComponent.lightenColor(base, 0.8f);
break;
case SELECTED:
base = RangeArrayComponent.lightenColor(base, 0.7f);
break;
case NONE:
break;
}
return base;
}
};
private static final class RequestedRegionColorProvider implements RangeArrayElementColorProvider, RangeArrayListener {
long lastModStart, lastModEnd;
// @Override
public void rangeArrayModified(long modificationResultStart, long modificationResultEnd, Range elementOperated, ModificationType modificationType, boolean removed, long modCount) {
lastModEnd = modificationResultEnd;
lastModStart = modificationResultStart;
}
// @Override
public Color getColor(Color defaultColor, Range element, SelectionState selectionState) {
Color base = defaultColor;
if (RangeUtils.contains(element, lastModStart, lastModEnd)) {
base = new Color(138, 170, 231);
}
switch (selectionState) {
case LIST:
base = RangeArrayComponent.lightenColor(base, 0.9f);
break;
case MOUSE_OVER:
base = RangeArrayComponent.lightenColor(base, 0.8f);
break;
case SELECTED:
break;
case NONE:
break;
}
return base;
}
};
final Timer updateGraphTimer = new Timer(500, new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
double d = file.getTotalFileReadStatistics().getTotalAverageDownloadSpeedProvider().getDownloadSpeed_KiBps(),r=file.getTotalFileReadStatistics().getTotalAverageRequestSpeedProvider().getRequestSpeed_KiBps();
downloadSpeedVal.setText(new DecimalFormat("###,###,###.###").format(d) + " KiBps");
requestRateVal.setText(new DecimalFormat("###,###,###.###").format(r) + " KiBps");
RegionHandler currentlySelectedRegion = lastRegionHandler;
if (currentlySelectedRegion == null) {
throttleStateLable.setText("");
return;
}
if (graphJFluid != null) {
graphJFluid.speedChanged(currentlySelectedRegion.getThrottleStatistics().getDownloadSpeed_KiBps(), currentlySelectedRegion.getThrottleStatistics().getRequestSpeed_KiBps());
}
throttleStateLable.setText(currentlySelectedRegion.getThrottleStatistics().getThrottleState().toString());
}
});
/**
* Creates new form MonitoredHttpFilePanel
*/
public HttpFilePanel(MonitoredHttpFile par) {
this.file = par;
initComponents();
((JXCollapsiblePane) graphAndAdvancedPanel).setCollapsed(true);
printStateButton.setVisible(false);
this.speedGraphPanel.setLayout(new BorderLayout());
activateLable.setFont(new Font(activateLable.getFont().getName(), activateLable.getFont().getStyle(), (int) (activateLable.getFont().getSize() * 1.5)));
this.speedGraphPanel.add(activateLable);
if (par != null) {
fileNameValue.setText(par.getName());
fileSizeValue.setText(formatSize(par.getFileSize()));
connectionDescText.setText(par.getSourceDescription());
}
((RangeArrayComponent) regionDownloadedBar).addRangeSelectedListener(this);
updateGraphTimer.start();
file.getRequestedRegion().addRangeArrayListener(requestedRegionColorProvider);
translate();
}
private String formatSize(long fsz) {
int dig = (int) (Math.log10(fsz)) + 1;
if (dig > 3 && dig <= 6) { return fsz / 1024d + " KiB"; }
if (dig > 6 && dig <= 9) { return fsz / (1024*1024d) + " MiB"; }
if (dig > 9 && dig <= 12) { return fsz /(1024*1024*1024d) + " GiB"; }
if (dig > 12) { return fsz / (1024*1024*1024*1024d) + " TiB"; }
return fsz + "Bytes";
}
private void translate() {
// /regionDownloadedLbl.setText("Region\nDownloaded");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed"
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
normalControls = new javax.swing.JPanel();
downloadSpeedVal = new javax.swing.JLabel();
filenameLabel = new javax.swing.JLabel();
fileSizeValue = new javax.swing.JLabel();
urlLabel = new javax.swing.JLabel();
requestRateVal = new javax.swing.JLabel();
totalRequestRateLabel = new javax.swing.JLabel();
totalDownloadSpeedLabel = new javax.swing.JLabel();
toggleAdvancedView = new javax.swing.JToggleButton();
filesizeLabel = new javax.swing.JLabel();
fileNameValue = new javax.swing.JLabel();
connectionDescText = new javax.swing.JTextField();
openFile = new javax.swing.JButton();
autoCompleteEnabledButton = new javax.swing.JToggleButton();
jPanel1 = new javax.swing.JPanel();
regionDownloadedBar = new neembuu.swing.RangeArrayComponent(file.getRegionHandlers(),downloadedRegionColorProvider,true);
jPanel2 = new javax.swing.JPanel();
regionRequestedBar = new neembuu.swing.RangeArrayComponent(file.getRequestedRegion(),requestedRegionColorProvider,true);
graphAndAdvancedPanel = new JXCollapsiblePane();
connectionStatusLabel = new javax.swing.JLabel();
previousButton = new javax.swing.JButton();
throttleStateLable = new javax.swing.JLabel();
nextButton = new javax.swing.JButton();
killConnection = new javax.swing.JButton();
speedGraphPanel = new javax.swing.JPanel();
printStateButton = new javax.swing.JButton();
setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
setMaximumSize(new java.awt.Dimension(628, 10000));
setVerifyInputWhenFocusTarget(false);
setLayout(new java.awt.BorderLayout());
normalControls.setMinimumSize(new java.awt.Dimension(619, 250));
normalControls.setName("");
normalControls.setPreferredSize(new java.awt.Dimension(619, 250));
normalControls.setLayout(null);
downloadSpeedVal.setText("KiBps");
normalControls.add(downloadSpeedVal);
downloadSpeedVal.setBounds(220, 210, 170, 16);
filenameLabel.setText(_NT._.filePanel_linkFileName());
normalControls.add(filenameLabel);
filenameLabel.setBounds(3, 55, 84, 16);
fileSizeValue.setText("filesize");
normalControls.add(fileSizeValue);
fileSizeValue.setBounds(115, 32, 230, 16);
urlLabel.setText(_NT._.filePanel_link());
normalControls.add(urlLabel);
urlLabel.setBounds(3, 6, 57, 16);
requestRateVal.setText("KiBps");
normalControls.add(requestRateVal);
requestRateVal.setBounds(220, 230, 170, 16);
totalRequestRateLabel.setText(_NT._.filePanel_totalRequestRate());
normalControls.add(totalRequestRateLabel);
totalRequestRateLabel.setBounds(10, 230, 190, 16);
totalDownloadSpeedLabel.setText(_NT._.filePanel_totalDownloadSpeed());
normalControls.add(totalDownloadSpeedLabel);
totalDownloadSpeedLabel.setBounds(10, 210, 200, 16);
toggleAdvancedView.setText(_NT._.filePanel_advancedViewButton());
toggleAdvancedView.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
toggleAdvancedViewActionPerformed(evt);
}
});
normalControls.add(toggleAdvancedView);
toggleAdvancedView.setBounds(402, 210, 190, 25);
filesizeLabel.setText(_NT._.filePanel_linkFileSize());
normalControls.add(filesizeLabel);
filesizeLabel.setBounds(3, 32, 74, 16);
fileNameValue.setText("filename_");
normalControls.add(fileNameValue);
fileNameValue.setBounds(115, 55, 290, 16);
connectionDescText.setEditable(false);
normalControls.add(connectionDescText);
connectionDescText.setBounds(115, 3, 483, 22);
openFile.setText(_NT._.filePanel_openFile());
openFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openFileActionPerformed(evt);
}
});
normalControls.add(openFile);
openFile.setBounds(440, 60, 160, 25);
autoCompleteEnabledButton.setText(_NT._.filePanel_autoCompleteButtonEnabled());
autoCompleteEnabledButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoCompleteEnabledButtonActionPerformed(evt);
}
});
normalControls.add(autoCompleteEnabledButton);
autoCompleteEnabledButton.setBounds(360, 30, 240, 25);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, _NT._.filePanel_regionDownloadedTitle(), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
jPanel1.setLayout(new java.awt.BorderLayout());
regionDownloadedBar.setMaximumSize(new java.awt.Dimension(32767, 10));
regionDownloadedBar.setMinimumSize(new java.awt.Dimension(10, 10));
regionDownloadedBar.setPreferredSize(new java.awt.Dimension(146, 10));
jPanel1.add(regionDownloadedBar, java.awt.BorderLayout.CENTER);
normalControls.add(jPanel1);
jPanel1.setBounds(10, 80, 590, 65);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, _NT._.filePanel_regionRequestedTitle(), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel2.add(regionRequestedBar, java.awt.BorderLayout.CENTER);
normalControls.add(jPanel2);
jPanel2.setBounds(10, 145, 590, 65);
add(normalControls, java.awt.BorderLayout.CENTER);
graphAndAdvancedPanel.setMinimumSize(new java.awt.Dimension(619, 300));
graphAndAdvancedPanel.setName("");
graphAndAdvancedPanel.setPreferredSize(new java.awt.Dimension(619, 300));
graphAndAdvancedPanel.setLayout(null);
connectionStatusLabel.setText("No connection selected");
graphAndAdvancedPanel.add(connectionStatusLabel);
connectionStatusLabel.setBounds(0, 32, 590, 16);
previousButton.setText(_NT._.filePanel_selectPreviousRegionButton());
previousButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousButtonActionPerformed(evt);
}
});
graphAndAdvancedPanel.add(previousButton);
previousButton.setBounds(396, 0, 190, 25);
throttleStateLable.setText("Throttle state");
graphAndAdvancedPanel.add(throttleStateLable);
throttleStateLable.setBounds(0, 55, 379, 16);
nextButton.setText(_NT._.filePanel_selectNextRegionButton());
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
graphAndAdvancedPanel.add(nextButton);
nextButton.setBounds(122, 0, 260, 25);
killConnection.setText(_NT._.filePanel_killConnection());
killConnection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
killConnectionActionPerformed(evt);
}
});
graphAndAdvancedPanel.add(killConnection);
killConnection.setBounds(430, 50, 163, 25);
speedGraphPanel.setMaximumSize(new java.awt.Dimension(412, 350));
speedGraphPanel.setName(""); // NOI18N
speedGraphPanel.setPreferredSize(new java.awt.Dimension(412, 200));
speedGraphPanel.setLayout(new java.awt.BorderLayout());
graphAndAdvancedPanel.add(speedGraphPanel);
speedGraphPanel.setBounds(0, 78, 600, 213);
printStateButton.setText("Print State");
printStateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
printStateButtonActionPerformed(evt);
}
});
graphAndAdvancedPanel.add(printStateButton);
printStateButton.setBounds(10, 10, 93, 19);
add(graphAndAdvancedPanel, java.awt.BorderLayout.SOUTH);
getAccessibleContext().setAccessibleDescription("");
}// </editor-fold>//GEN-END:initComponents
public void enableOpenButton(boolean enable) {
openFile.setEnabled(enable);
}
private void printStateButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_printStateButtonActionPerformed
System.out.println("+++++++" + file.getName() + file.getFileDescriptor().getFileId() + "++++++");
System.out.println("Requested Region");
System.out.println(file.getRequestedRegion());
System.out.println("-------------------------------");
System.out.println("Downloaded Region");
System.out.println(file.getRegionHandlers());
System.out.println("-------" + file.getName() + "------");
System.out.println();
System.out.println("Pending regions in each connection");
try {
UnsyncRangeArrayCopy<RegionHandler> downloadedRegions = file.getRegionHandlers().tryToGetUnsynchronizedCopy();
Range<RegionHandler> downloadedRegion;
for (int j = 0; j < downloadedRegions.size(); j++) {
downloadedRegion = downloadedRegions.get(j);
System.out.println("In Channel=" + downloadedRegion);
String[] pendingRqs = downloadedRegion.getProperty().getPendingOperationsAsString();
System.out.println("++++++++++++++++++");
for (int i = 0; i < pendingRqs.length; i++) {
System.out.println(pendingRqs[i]);
}
System.out.println("------------------");
// ((neembuu.vfs.readmanager.impl.BasicRegionHandler)downloadedRegion.getProperty()).printPendingOps(System.out);
}
} catch (Exception l) {
System.out.println("could not print");
}
System.out.println("-------------------------------");
}// GEN-LAST:event_printStateButtonActionPerformed
final Object regionTraversalLock = new Object();
@SuppressWarnings(value = "unchecked")
private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_previousButtonActionPerformed
// TODO add your handling code here:
synchronized (regionTraversalLock) {
if (lastRegionSelected == null) {
if (file.getRequestedRegion().isEmpty()) { return; }
((RangeArrayComponent) regionDownloadedBar).selectRange(file.getRegionHandlers().getFirst());
}
try {
Range previouselement = file.getRegionHandlers().getPrevious(lastRegionSelected);
((RangeArrayComponent) regionDownloadedBar).selectRange(previouselement);
lastRegionSelected = previouselement;
} catch (ArrayIndexOutOfBoundsException exception) {
// ignore
} catch (Exception anyother) {
LOGGER.log(Level.SEVERE, "problem in region traversing", anyother);
}
}
}// GEN-LAST:event_previousButtonActionPerformed
@SuppressWarnings(value = "unchecked")
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextButtonActionPerformed
synchronized (regionTraversalLock) {
if (lastRegionSelected == null) {
if (file.getRequestedRegion().isEmpty()) { return; }
((RangeArrayComponent) regionDownloadedBar).selectRange(file.getRegionHandlers().getFirst());
}
try {
System.out.println("previous=" + lastRegionSelected);
// System.out.println("(previousindex)="+file.getDownloadedRegion().get(file.getRequestedRegion().getIndexOf(lastRegionSelected)));
Range nextElement = file.getRegionHandlers().getNext(lastRegionSelected);
System.out.println("next=" + nextElement);
System.out.println("last=" + lastRegionSelected);
lastRegionSelected = nextElement;
((RangeArrayComponent) regionDownloadedBar).selectRange(nextElement);
} catch (ArrayIndexOutOfBoundsException exception) {
// ignore
} catch (Exception anyother) {
LOGGER.log(Level.SEVERE, "problem in region traversing", anyother);
}
}
}// GEN-LAST:event_nextButtonActionPerformed
private void killConnectionActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_killConnectionActionPerformed
System.err.println("kill button pressed for region=" + lastRegionSelected);
try {
((neembuu.vfs.readmanager.impl.BasicRegionHandler) lastRegionSelected.getProperty()).getConnection().abort();
} catch (Exception any) {
LOGGER.log(Level.SEVERE, "Connection killing exception", any);
}
}// GEN-LAST:event_killConnectionActionPerformed
private void toggleAdvancedViewActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_toggleAdvancedViewActionPerformed
// TODO add your handling code here:
graphAndAdvancedPanel.getActionMap().get("toggle").actionPerformed(evt);
}// GEN-LAST:event_toggleAdvancedViewActionPerformed
private void autoCompleteEnabledButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_autoCompleteEnabledButtonActionPerformed
// TODO add your handling code here:
file.setAutoCompleteEnabled(!file.isAutoCompleteEnabled());
if (file.isAutoCompleteEnabled()) {
autoCompleteEnabledButton.setText(_NT._.filePanel_autoCompleteButtonEnabled());
} else {
autoCompleteEnabledButton.setText(_NT._.filePanel_autoCompleteButtonDisabled());
}
}// GEN-LAST:event_autoCompleteEnabledButtonActionPerformed
private void openFileActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_openFileActionPerformed
// TODO add your handling code here:
try {
java.awt.Desktop.getDesktop().open(new java.io.File(virtualPathOfFile));
} catch (Exception a) {
JOptionPane.showMessageDialog(this, "Could not show the file");
a.printStackTrace(System.err);
}
}// GEN-LAST:event_openFileActionPerformed
public void setVirtualPathOfFile(String virtualPathOfFile) {
this.virtualPathOfFile = virtualPathOfFile;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton autoCompleteEnabledButton;
private javax.swing.JTextField connectionDescText;
private javax.swing.JLabel connectionStatusLabel;
public javax.swing.JLabel downloadSpeedVal;
private javax.swing.JLabel fileNameValue;
private javax.swing.JLabel fileSizeValue;
private javax.swing.JLabel filenameLabel;
private javax.swing.JLabel filesizeLabel;
private javax.swing.JPanel graphAndAdvancedPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JButton killConnection;
private javax.swing.JButton nextButton;
private javax.swing.JPanel normalControls;
private javax.swing.JButton openFile;
private javax.swing.JButton previousButton;
private javax.swing.JButton printStateButton;
public javax.swing.JProgressBar regionDownloadedBar;
public javax.swing.JProgressBar regionRequestedBar;
private javax.swing.JLabel requestRateVal;
private javax.swing.JPanel speedGraphPanel;
private javax.swing.JLabel throttleStateLable;
private javax.swing.JToggleButton toggleAdvancedView;
private javax.swing.JLabel totalDownloadSpeedLabel;
private javax.swing.JLabel totalRequestRateLabel;
private javax.swing.JLabel urlLabel;
// End of variables declaration//GEN-END:variables
// @Override
public void rangeSelected(Range arrayElement) {
LOGGER.log(Level.INFO, "region selected {0}", arrayElement);
lastRegionSelected = arrayElement;
RegionHandler regionOfInterest;
if (arrayElement == null) {
connectionStatusLabel.setText("No connection selected");
this.speedGraphPanel.removeAll();
this.speedGraphPanel.add(activateLable, BorderLayout.CENTER);
lastRegionHandler = null;
graphJFluid = null;
this.repaint();
return;
}
regionOfInterest = (RegionHandler) arrayElement.getProperty();
lastRegionHandler = regionOfInterest;
LOGGER.info("Channel of interest=" + regionOfInterest);
connectionStatusLabel.setText("Connection " + arrayElement.starting() + " selected. This connection is " + (regionOfInterest.isAlive() ? "alive." : "dead."));
throttleStateLable.setText(regionOfInterest.getThrottleStatistics().getThrottleState().toString());
graphJFluid = new SpeedGraphJFluid();
this.speedGraphPanel.removeAll();
this.speedGraphPanel.add(graphJFluid, BorderLayout.CENTER);
this.repaint();
}
}

View File

@ -2,12 +2,19 @@ package org.jdownloader.extensions.neembuu.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import jd.gui.swing.jdgui.interfaces.SwitchPanel;
import jd.plugins.AddonPanel;
@ -20,10 +27,6 @@ import org.jdownloader.extensions.neembuu.translate._NT;
public class NeembuuGui extends AddonPanel<NeembuuExtension> {
/**
*
*/
private static final long serialVersionUID = -3729817467785635683L;
private static final String ID = "NEEMBUUGUI";
private SwitchPanel panel;
private final JTabbedPane tabbedPane = new JTabbedPane();
@ -32,11 +35,6 @@ public class NeembuuGui extends AddonPanel<NeembuuExtension> {
super(plg);
this.panel = new SwitchPanel(new MigLayout("ins 0,wrap 1", "[grow,fill]", "[grow,fill][]")) {
/**
*
*/
private static final long serialVersionUID = -3679648663863943775L;
@Override
protected void onShow() {
@ -53,41 +51,146 @@ public class NeembuuGui extends AddonPanel<NeembuuExtension> {
}
public void addSession(DownloadSession jdds) {
tabbedPane.add(jdds.getDownloadLink().getBrowserUrl(), jdds.getWatchAsYouDownloadSession().getFilePanel());
/*
* tabbedPane.setTabComponentAt(
* tabbedPane.indexOfTab(jdds.getDownloadLink().getBrowserUrl()), new
* ButtonTabComponent(tabbedPane, jdds, this));
*/
synchronized (tabbedPane) {
if (tabbedPane.indexOfComponent(jdds.getWatchAsYouDownloadSession().getFilePanel()) == -1) {
tabbedPane.add(jdds.getDownloadLink().getFilePackage().getName(), jdds.getWatchAsYouDownloadSession().getFilePanel());
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(jdds.getWatchAsYouDownloadSession().getFilePanel()), new ButtonTabComponent(tabbedPane, jdds, this));
}
}
}
public void removeSession(DownloadSession jdds) {
tabbedPane.removeTabAt(tabbedPane.indexOfTab(jdds.getDownloadLink().getBrowserUrl()));
public void removeSession(JComponent jc) {
synchronized (tabbedPane) {
tabbedPane.removeTabAt(tabbedPane.indexOfComponent(jc));
}
}
private void layoutPanel() {
panel.add(tabbedPane);
JPanel settingsPanel = new JPanel();
final JLabel jl = new JLabel("Virtual fielsystem unchecked");
JButton testJpfm = new JButton("Check virtual filesystem capability");
tabbedPane.addTab("Settings", settingsPanel);
settingsPanel.add(new JLabel("TODO:A few basic settings to be added here."));
settingsPanel.add(testJpfm);
settingsPanel.add(jl);
JPanel settingsPanel = new JPanel(new MigLayout());
tabbedPane.addTab(_NT._.settingsPanelTitle(), settingsPanel);
final JLabel jl = new JLabel(_NT._.vfsUnchecked());
settingsPanel.add(jl, "wrap");
JButton testJpfm = new JButton(_NT._.checkVFSButton());
settingsPanel.add(testJpfm, "wrap");
JLabel basicMntLoc = new JLabel(_NT._.basicMountLocation());
settingsPanel.add(basicMntLoc, "split 2");
final JTextField bml = new JTextField();
bml.setEditable(false);
bml.setText(getExtension().getBasicMountLocation());
settingsPanel.add(bml, "span 2");
JButton bml_b = new JButton(_NT._.browse());
settingsPanel.add(bml_b, "wrap");
JButton openBml = new JButton(_NT._.openBasicMountLocation());
settingsPanel.add(openBml, "wrap");
JButton pismowebsite = new JButton("<html><U><FONT COLOR=\"0000ff\">" + _NT._.poweredByPismo() + "</FONT></U></html>", new ImageIcon(NeembuuGui.class.getResource("pfm.png")));
pismowebsite.setBorderPainted(false);
settingsPanel.add(pismowebsite, "span");
JLabel vlc = new JLabel(_NT._.worksBestWithVlc(), new ImageIcon(NeembuuGui.class.getResource("vlc.png")), JLabel.LEFT);
settingsPanel.add(vlc, "span");
JLabel vlc_option = new JLabel(_NT._.vlcPathOption());
settingsPanel.add(vlc_option, "span");
final JTextField vlcPath = new JTextField();
vlcPath.setEditable(false);
JButton browseVlc = new JButton(_NT._.browse());
settingsPanel.add(vlcPath, "width 200::");
settingsPanel.add(browseVlc, "wrap");
testJpfm.addActionListener(new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
boolean usable = getExtension().isUsable();
if (usable) {
jl.setText("Virtual fielsystem works");
jl.setText(_NT._.vfsWorking());
} else {
jl.setText("Virtual fielsystem not working");
jl.setText(_NT._.vfsNotWorking());
}
}
});
bml_b.addActionListener(new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int ret = jfc.showOpenDialog(panel);
if (ret == JFileChooser.APPROVE_OPTION) {
try {
getExtension().setBasicMountLocation(jfc.getSelectedFile().getAbsolutePath());
bml.setText(getExtension().getBasicMountLocation());
} catch (Exception a) {
JOptionPane.showMessageDialog(panel, jfc.getSelectedFile() + "\nCannot be used. Reason :" + a.getMessage(), "Cannot set basic mount location", JOptionPane.ERROR_MESSAGE);
}
}
}
});
browseVlc.addActionListener(new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
jfc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
String n = f.getName();
if (f.isFile()) {
if (n.equalsIgnoreCase("vlc.exe") || n.equalsIgnoreCase("vlc") || n.equalsIgnoreCase("vlc.app")) return true;
} else
return true;// else
// if(n.equalsIgnoreCase("vlc.app"))return
// true;//mac
return false;
}
@Override
public String getDescription() {
return "VLC (vlc.exe or vlc)";
}
});
int ret = jfc.showOpenDialog(panel);
if (ret == JFileChooser.APPROVE_OPTION) {
try {
String vlcLoc = jfc.getSelectedFile().getAbsolutePath();
if (vlcLoc.toLowerCase().endsWith(".app")) {
if (!vlcLoc.endsWith("/")) vlcLoc += '/';
vlcLoc += "Contents/MacOS/VLC";
}
getExtension().setVlcLocation(vlcLoc);
vlcPath.setText(getExtension().getVlcLocation());
} catch (Exception a) {
JOptionPane.showMessageDialog(panel, jfc.getSelectedFile() + "\nCannot be used. Reason :" + a.getMessage(), "Cannot set basic mount location", JOptionPane.ERROR_MESSAGE);
}
} else {
getExtension().setVlcLocation(null);
vlcPath.setText(getExtension().getVlcLocation());
}
}
});
openBml.addActionListener(new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().open(new java.io.File(getExtension().getBasicMountLocation()));
} catch (Exception a) {
// ignore
}
}
});
pismowebsite.addActionListener(new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().browse(new java.net.URI("http://www.pismotechnic.com/pfm/"));
} catch (Exception a) {
// ignore
}
}
});
// panel.add(new JLabel("Hello WOrld"));
}
/**

View File

@ -0,0 +1,188 @@
/*
* Copyright (C) 2011 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.gui;
import com.sun.tools.visualvm.charts.ChartFactory;
import com.sun.tools.visualvm.charts.SimpleXYChartDescriptor;
import com.sun.tools.visualvm.charts.SimpleXYChartSupport;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdownloader.extensions.neembuu.translate._NT;
import org.netbeans.lib.profiler.charts.xy.synchronous.SynchronousXYChart;
/**
* Comments by Jiri Sedlacek
*
* <pre>
* JFreeCharts are great for creating any kind of static graphs (typically for reports).
* They provide support for all types of existing chart types.
* The benefit of using JFreeChart is fully customizable appearance and
* export to various formats. The only problem of this library is that
* it's not primarily designed for displaying live data. You can hack it to
* display data in real time, but the performance is poor.
*
* That's why I've created the VisualVM charts. The primary (and so far only)
* goal is to provide charts optimized for displaying live data with minimal
* performance and memory overhead. You can easily display a fullscreen graph
* and it will still scroll smoothly while running and adding new values
* (when running on physical hardware, virtualized environment may give
* slightly worse results). There's a real rendering engine behind the
* charts which ensures that only the changed areas of the chart are repainted
* (no full-repaints because of a 1px change). Scrolling the chart means moving
* the already rendered image and only painting the newly displayed area. Last
* but not least, the charts are optimized for displaying over a remote X session -
* rendering is automatically switched to low-quality ensuring good response
* times and interactivity.
*
* The Tracer engine introduced in VisualVM 1.3 further improves
* performance of the charts. I've intensively profiled and optimized
* the charts to minimize the cpu cycles/memory allocations for each repaint.
* As of now, I believe that the VisualVM charts are the fastest real time
* Java charts with the lowest cpu/memory footprint.
* </pre>
*
* @author Shashank Tulsyan
* @author Geertjan
*/
public final class SpeedGraphJFluid extends JPanel {
private static final int VALUES_LIMIT = 10;
private final SimpleXYChartSupport support;
private final SynchronousXYChart actual_chart;
public SpeedGraphJFluid() {
SimpleXYChartDescriptor descriptor =
// SimpleXYChartDescriptor.decimal(0,true,VALUES_LIMIT);
SimpleXYChartDescriptor.decimal(0, 10/* 24*8 */, 10, 1d, true, VALUES_LIMIT);
descriptor.addLineFillItems(_NT._.filePanel_graph_downloadSpeed());
descriptor.addLineFillItems(_NT._.filePanel_graph_requestSpeed());
// descriptor.setDetailsItems(new String[]{"Download Speed(KiB/s)",
// "Request Speed(KiB/s)"});
// descriptor.setChartTitle("<html><font size='+1'><b>SpeedGraph</b></font></html>");
// descriptor.setXAxisDescription("<html>Time</html>");
descriptor.setYAxisDescription(_NT._.filePanel_graph_yaxis());
support = ChartFactory.createSimpleXYChart(descriptor);
// new Generator(support).start();
setLayout(new BorderLayout());
add(support.getChart(), BorderLayout.CENTER);
actual_chart = findSynchronousXYChart(support.getChart(), 0);
if (actual_chart == null) throw new RuntimeException("Could not find actual chart");
}
private static SynchronousXYChart findSynchronousXYChart(Container k, int depth) {
/*
* for (int i = 0; i < depth; i++) { System.out.print("\t"); }
* System.out.println("+++++"+k+"+++++++");
*/
for (Component c : k.getComponents()) {
/*
* for (int i = 0; i < depth; i++) { System.out.print("\t"); }
* System.out.println(c);
*/
if (c instanceof SynchronousXYChart) return (SynchronousXYChart) c;
if (c instanceof Container) {
SynchronousXYChart chart = findSynchronousXYChart((Container) c, depth + 1);
if (chart != null) return chart;
}
}
return null;
// System.out.println("-----"+k+"-------");
}
// @Override
public void speedChanged(double downloadSpeedInKiBps, double requestSpeedInKiBps) {
recentDownloadSpeedObservation = downloadSpeedInKiBps;
recentRequestSpeedObservation = requestSpeedInKiBps;
support.addValues(System.currentTimeMillis(), new long[] { (long) (recentDownloadSpeedObservation), (long) (recentRequestSpeedObservation) });
maxValues[index % VALUES_LIMIT] = Math.max(recentRequestSpeedObservation, recentDownloadSpeedObservation);
index++;
double max = 0;
for (int i = 0; i < maxValues.length; i++) {
max = Math.max(maxValues[i], max);
}
if (max < previousHeight / 2 || previousHeight == -1) {
previousHeight = max * 1.1;
// System.out.println("contracting to "+previousHeight);
changeHeight(previousHeight);
}
if (previousHeight < max) {
previousHeight = max * 1.1;
// System.out.println("expanding to "+previousHeight);
changeHeight(previousHeight);
}
}
private void changeHeight(double h) {
/*
* try{ System.out.println("before="+actual_chart.getDataHeight());
* Field f =
* TransformableCanvasComponent.class.getDeclaredField("dataHeight");
* f.setAccessible(true); f.setLong(actual_chart, (long)h);
*
* Method m =
* ChartComponent.class.getDeclaredMethod("dataBoundsChanged",
* long.class,long.class,long.class,long.class
* ,long.class,long.class,long.class,long.class); m.setAccessible(true);
* m.invoke(actual_chart,
* actual_chart.getOffsetX(),actual_chart.getOffsetY(),
* actual_chart.getDataWidth(),(long)h,
* actual_chart.getOffsetX(),actual_chart.getOffsetY(),
* actual_chart.getDataWidth(),actual_chart.getDataHeight()); f =
* TransformableCanvasComponent.class.getDeclaredField("maxOffsetY");
* f.setAccessible(true); f.setLong(actual_chart, (long)h);
* //pendingDataHeight f =
* TransformableCanvasComponent.class.getDeclaredField
* ("pendingDataHeight"); f.setAccessible(true); f.setLong(actual_chart,
* (long)h);
*
* System.out.println("after="+actual_chart.getDataHeight());
* }catch(Exception a){ a.printStackTrace(System.err); }
* actual_chart.setDataBounds(actual_chart.getDataOffsetX(),
* actual_chart.getDataOffsetY(), actual_chart.getDataWidth(),
* (long)(h));
*/
}
private volatile double recentDownloadSpeedObservation = 0;
private volatile double recentRequestSpeedObservation = 0;
double[] maxValues = new double[VALUES_LIMIT];
double previousHeight = -1;
int index = 0;
public static void main(String[] args) {
JFrame fr = new JFrame();
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setSize(600, 400);
fr.getContentPane().add(new SpeedGraphJFluid());
fr.setVisible(true);
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;
import org.jdownloader.extensions.neembuu.DownloadSession;
import org.jdownloader.extensions.neembuu.NeembuuExtension;
import org.jdownloader.extensions.neembuu.translate._NT;
/**
*
* @author Shashank Tulsyan
*/
public class VirtualFilesPanel extends JPanel {
private JPanel centre;
private int cnt;
public VirtualFilesPanel(LayoutManager layout) {
super(layout);
}
public static VirtualFilesPanel getOrCreate(DownloadSession jdds, final String mountLocation, JPanel httpFilePanel) {
VirtualFilesPanel virtualFilesPanel = null;
try {
virtualFilesPanel = jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().getVirtualFilesPanel();
//virtualFilesPanel = NeembuuExtension.getInstance().getVirtualFileSystems().get(jdds.getDownloadLink().getFilePackage());//.getProperty("virtualFilesPanel");
} catch (Exception e) {
e.printStackTrace(System.err);
}
if (virtualFilesPanel == null) {
virtualFilesPanel = new VirtualFilesPanel(new BorderLayout());
JPanel north = new JPanel(new FlowLayout());
virtualFilesPanel.centre = new JPanel(new MigLayout());
virtualFilesPanel.add(north, BorderLayout.NORTH);
virtualFilesPanel.add(new JScrollPane(virtualFilesPanel.centre), BorderLayout.CENTER);
JLabel mntLoc = new JLabel(_NT._.mountLocation());
north.add(mntLoc, "span 2");
JLabel mntLocVal = new JLabel(mountLocation);
north.add(mntLocVal, "span 4");
JButton openF = new JButton(_NT._.openMountLocation());
north.add(openF);
//jdds.getDownloadLink().getFilePackage().setProperty("virtualFilesPanel", virtualFilesPanel);
//NeembuuExtension.getInstance().getVirtualFilesPanels().put(jdds.getDownloadLink().getFilePackage(),virtualFilesPanel);
try{
jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().setVirtualFilesPanel(virtualFilesPanel);
}catch(IllegalStateException a){
virtualFilesPanel = jdds.getWatchAsYouDownloadSession().getVirtualFileSystem().getVirtualFilesPanel();
}
openF.addActionListener(new ActionListener() {
// @Override
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().open(new File(mountLocation));
} catch (Exception a) {
JOptionPane.showMessageDialog(null, _NT._.couldNotOpenMountLocation());
}
}
});
}
if (virtualFilesPanel.cnt % 2 == 0) {
virtualFilesPanel.centre.add(httpFilePanel);
} else {
virtualFilesPanel.centre.add(httpFilePanel, "wrap");
}
virtualFilesPanel.cnt++;
return virtualFilesPanel;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -1,3 +1,19 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.newconnectionprovider;
import java.io.IOException;
@ -23,7 +39,6 @@ public final class JD_HTTP_Connection extends AbstractConnection{
this.jddm = jddm;
}
@Override
protected final void abortImpl() {
urlca.disconnect();
@ -36,13 +51,7 @@ public final class JD_HTTP_Connection extends AbstractConnection{
InputStream is = null;
while (firstByte == -1) {
urlca = NBUtils.copyConnection(
jddm.jdds.getDownloadLink(),
jddm.jdds.getDownloadInterface(),
jddm.jdds.getPluginForHost(),
cp.getOffset(),
jddm.jdds.getBrowser(),
jddm.jdds.getURLConnectionAdapter());
urlca = NBUtils.copyConnection(jddm.jdds.getDownloadLink(), jddm.jdds.getDownloadInterface(), jddm.jdds.getPluginForHost(), cp.getOffset(), jddm.jdds.getBrowser(), jddm.jdds.getURLConnectionAdapter());
if (urlca != null) {
is = urlca.getInputStream();
firstByte = is.read();
@ -50,7 +59,8 @@ public final class JD_HTTP_Connection extends AbstractConnection{
firstByte = -1;
}
if (firstByte != -1) {
// when the first byte is send to {@link neembuu.vfs.connection.AbstractConnection#write }
// when the first byte is send to {@link
// neembuu.vfs.connection.AbstractConnection#write }
// cp.getTransientConnectionListener().success is called
} else if (retriesMade > 10) {
cp.getTransientConnectionListener().failed(new IllegalStateException("EOF"), cp);

View File

@ -1,6 +1,18 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.newconnectionprovider;
@ -21,8 +33,7 @@ import org.jdownloader.extensions.neembuu.DownloadSession;
public final class JD_HTTP_Download_Manager implements NewConnectionProvider {
final DownloadSession jdds;
private static final Logger LOGGER = Logger
.getLogger(JD_HTTP_Download_Manager.class.getName());
private static final Logger LOGGER = Logger.getLogger(JD_HTTP_Download_Manager.class.getName());
private final ConcurrentLinkedQueue<JD_HTTP_Connection> connection_list = new ConcurrentLinkedQueue<JD_HTTP_Connection>();
@ -43,13 +54,11 @@ public final class JD_HTTP_Download_Manager implements NewConnectionProvider {
// @Override
public final String getSourceDescription() {
return "JD_DownloadManager{" + jdds.getDownloadLink().getDownloadURL()
+ "}";
return jdds.getDownloadLink().getDownloadURL();
}
// @Override
public final void provideNewConnection(
final NewConnectionParams connectionParams) {
public final void provideNewConnection(final NewConnectionParams connectionParams) {
class StartNewJDBrowserConnectionThread extends Thread {
StartNewJDBrowserConnectionThread() {
@ -61,8 +70,7 @@ public final class JD_HTTP_Download_Manager implements NewConnectionProvider {
@Override
public final void run() {
try {
JD_HTTP_Connection c = new JD_HTTP_Connection(
JD_HTTP_Download_Manager.this, connectionParams);
JD_HTTP_Connection c = new JD_HTTP_Connection(JD_HTTP_Download_Manager.this, connectionParams);
connection_list.add(c);
connectionsRequested();
c.connectAndSupply();
@ -89,11 +97,16 @@ public final class JD_HTTP_Download_Manager implements NewConnectionProvider {
i++;
}
}
if (i == 0) {
return 0;// creation time is unknown
if (i == 0) { return 0;// creation time is unknown
}
return ((totalTime) / i);
}
long[] totalProgress = { 0 };
@Override
public String toString() {
return JD_HTTP_Download_Manager.class.getName()+"{"+jdds.getDownloadLink()+ "}";
}
}

View File

@ -0,0 +1,92 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.postprocess;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import jpfm.FileAttributesProvider;
import jpfm.fs.BasicFileSystem;
import jpfm.fs.splitfs.CascadableSplitFS;
import jpfm.volume.vector.VectorRootDirectory;
import org.jdownloader.extensions.neembuu.DownloadSession;
import org.jdownloader.extensions.neembuu.NB_VirtualFileSystem;
/**
*
* @author Shashank Tulsyan
*/
public class HJSplitsHandler implements PostProcessor {
// @Override
public boolean canHandle(List<DownloadSession> sessions) {
if (sessions.size() < 1) return false;
synchronized (sessions) {
for (DownloadSession jdds : sessions) {
int index = -2;
String n = jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().getName();
try {
index = Integer.parseInt(n.substring(n.length() - 3));
} catch (Exception a) {
return false;
}
if (jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().getDownloadConstrainHandler().index() < 0) {
jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile().getDownloadConstrainHandler().setIndex(index);
}
if (index < 0) { return false; }
}
}
return true;
}
// @Override
public boolean handle(List<DownloadSession> sessions, BasicFileSystem bfs, String mntLoc) {
if (!canHandle(sessions)) { throw new IllegalArgumentException("Cannot handle"); }
Set<FileAttributesProvider> files = new LinkedHashSet<FileAttributesProvider>();
synchronized (sessions) {
for (DownloadSession jdds : sessions) {
files.add(jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile());
}
}
String name = sessions.get(0).getDownloadLink().getFinalFileName();
name = name.substring(0, name.lastIndexOf("."));
CascadableSplitFS.CascadableSplitFSProvider cascadableSplitFS = new CascadableSplitFS.CascadableSplitFSProvider(files, name);
bfs.cascadeMount(cascadableSplitFS);
// remove splited files .001 , .002 ... from virtual folder
// to avoid confusion
NB_VirtualFileSystem fileSystem = (NB_VirtualFileSystem) bfs;
VectorRootDirectory vrd = (VectorRootDirectory) fileSystem.getRootDirectory();
synchronized (sessions) {
for (DownloadSession jdds : sessions) {
vrd.remove(jdds.getWatchAsYouDownloadSession().getSeekableConnectionFile());
// the file does not exist, therefore the open button should be
// disabled
jdds.getWatchAsYouDownloadSession().getHttpFilePanel().enableOpenButton(false);
}
}
return true;
}
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.postprocess;
import java.util.List;
import jpfm.fs.BasicFileSystem;
import org.jdownloader.extensions.neembuu.DownloadSession;
/**
*
* @author Shashank Tulsyan
*/
public interface PostProcessor {
boolean canHandle(List<DownloadSession> sessions);
boolean handle(List<DownloadSession> sessions, BasicFileSystem bfs, String mountLocation);
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.postprocess;
import java.io.File;
import java.util.List;
import jd.plugins.DownloadLink;
import jpfm.fs.BasicFileSystem;
import org.jdownloader.extensions.neembuu.DownloadSession;
/**
*
* @author Shashank Tulsyan
*/
public class PostProcessors {
public static void postProcess(List<DownloadSession> sessions, BasicFileSystem bfs, String mountLocation) {
boolean success = true;
HJSplitsHandler hjsh = new HJSplitsHandler();
if (hjsh.canHandle(sessions)) {
hjsh.handle(sessions, bfs, mountLocation);
}
SimplyOpenTheVideoFile simplyOpenTheVideoFile = new SimplyOpenTheVideoFile();
if (!simplyOpenTheVideoFile.handle(sessions, bfs, mountLocation)) {
// open mount location can we cannot find even one file that we can
// open
try {
java.awt.Desktop.getDesktop().open(new java.io.File(mountLocation));
} catch (Exception a) {
// ignore
}
}
}
public static void downloadComplete(DownloadLink downloadLink){
File f = new File(downloadLink.getFileOutput());
if (f.exists()) {
if(!SimplyOpenTheVideoFile.tryOpeningUsingVLC(f)){
try{
java.awt.Desktop.getDesktop().open(f);
}catch(Exception ignore){
}
}
}
}
}

View File

@ -0,0 +1,101 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.extensions.neembuu.postprocess;
import java.io.File;
import java.util.List;
import jpfm.DirectoryStream;
import jpfm.FileAttributesProvider;
import jpfm.FileType;
import jpfm.fs.BasicFileSystem;
import org.jdownloader.extensions.neembuu.DownloadSession;
import org.jdownloader.extensions.neembuu.NeembuuExtension;
/**
*
* @author Shashank Tulsyan
*/
public class SimplyOpenTheVideoFile implements PostProcessor {
private static String[] knownExtension = { "avi", "mpg", "mpeg", "webm", "mp4", "mp3", "rmvb", "mkv", "flv", "wma", "wmv", "ogg", "ogm", "flac" };
// @Override
public boolean canHandle(List<DownloadSession> sessions) {
return true;
}
// @Override
public boolean handle(List<DownloadSession> sessions, BasicFileSystem bfs, String mountLocation) {
DirectoryStream root = (DirectoryStream) bfs.getRootAttributes();
String vlcPath = null;// todo : put internal vlc path here
if (vlcPath != null) {
if (vlcPath.trim().length() == 0) {
vlcPath = null;
}
}
return findAndOpenVideo(root, mountLocation, bfs);
}
private boolean findAndOpenVideo(DirectoryStream ds, String path, BasicFileSystem bfs) {
System.out.println("inside " + ds);
for (FileAttributesProvider fap : ds) {
if (fap.getFileType() == FileType.FOLDER) {
return findAndOpenVideo((DirectoryStream) fap, path + File.separatorChar + fap.getName(), bfs);
} else if (canBeOpenedInMediaPlayer(fap.getName())) {
try {
File f = new File(path, fap.getName());
if(!tryOpeningUsingVLC(f))
java.awt.Desktop.getDesktop().open(f);
return true;
} catch (Exception a) {
a.printStackTrace();
return false;
}
} else {
System.out.println("cannot open " + fap.getName());
}
}
return false;
}
public static boolean tryOpeningUsingVLC(File f){
String vlcLoc = NeembuuExtension.getInstance().getVlcLocation();
if(vlcLoc!=null){
try{
ProcessBuilder pb = new ProcessBuilder(vlcLoc,f.getAbsolutePath());
Process p = pb.start();
return true;
}catch(Exception any){
return false;
}
}
return false;
}
private boolean canBeOpenedInMediaPlayer(String name) {
name = name.toLowerCase();
for (int i = 0; i < knownExtension.length; i++) {
if (name.endsWith(knownExtension[i])) { return true; }
}
return false;
}
}

View File

@ -16,4 +16,136 @@ public interface NeembuuTranslation extends TranslateInterface {
@Default(lngs = { "en" }, values = { "Stream Data - Watch as you download" })
String gui_tooltip();
@Default(lngs = { "en" }, values = { "Virtual filesystem unchecked" })
String vfsUnchecked();
@Default(lngs = { "en" }, values = { "Virtual filesystem not working" })
String vfsNotWorking();
@Default(lngs = { "en" }, values = { "Virtual filesystem works" })
String vfsWorking();
@Default(lngs = { "en" }, values = { "Settings" })
String settingsPanelTitle();
@Default(lngs = { "en" }, values = { "Check virtual filesystem capability" })
String checkVFSButton();
@Default(lngs = { "en" }, values = { "Basic Mount Location" })
String basicMountLocation();
@Default(lngs = { "en" }, values = { "Browse" })
String browse();
@Default(lngs = { "en" }, values = { "Open basic mount location folder" })
String openBasicMountLocation();
@Default(lngs = { "en" }, values = { "Mount location" })
String mountLocation();
@Default(lngs = { "en" }, values = { "Open mount location" })
String openMountLocation();
@Default(lngs = { "en" }, values = { "Are you sure you want to unmount?" })
String unmountConfirm();
@Default(lngs = { "en" }, values = { "Neembuu could not handle this link"})
String neembuu_could_not_handle_title();
@Default(lngs = { "en" }, values = { "Do you want to download this file instead ?"})
String neembuu_could_not_handle_message();
@Default(lngs = { "en" }, values = { "Do you wish to watch as you download this file?" })
String approve_WatchAsYouDownload_Message();
@Default(lngs = { "en" }, values = { "Neembuu watch as you download" })
String approve_WatchAsYouDownload_Title();
@Default(lngs = { "en" }, values = { "Could not start a watch as you download session for\n" })
String failed_WatchAsYouDownload_Message();
@Default(lngs = { "en" }, values = { "Neembuu watch as you download failed." })
String failed_WatchAsYouDownload_Title();
@Default(lngs = { "en" }, values = { "Could not open mount location" })
String couldNotOpenMountLocation();
@Default(lngs = { "en" }, values = { "Neembuu watch as you download is powered by <b>Pismo File Mount</b>" })
String poweredByPismo();
@Default(lngs = { "en" }, values = { "Neembuu Watch as you download works best with vlc"})
String worksBestWithVlc();
@Default(lngs = { "en" }, values = { "You can set vlc\'s location (this is not compulsary) so that vlc may be used to play videos while they are downloaded."})
String vlcPathOption();
@Default(lngs = { "en" }, values = { "Link" })
String filePanel_link();
@Default(lngs = { "en" }, values = { "FileSize" })
String filePanel_linkFileSize();
@Default(lngs = { "en" }, values = { "FileName" })
String filePanel_linkFileName();
@Default(lngs = { "en" }, values = { "Region Downloaded" })
String filePanel_regionDownloadedTitle();
@Default(lngs = { "en" }, values = { "Region Requested" })
String filePanel_regionRequestedTitle();
@Default(lngs = { "en" }, values = { "Download entire file" })
String filePanel_autoCompleteButtonEnabled();
@Default(lngs = { "en" }, values = { "Download as less as possible" })
String filePanel_autoCompleteButtonDisabled();
@Default(lngs = { "en" }, values = { "Open File" })
String filePanel_openFile();
@Default(lngs = { "en" }, values = { "Advanced Controls" })
String filePanel_advancedViewButton();
@Default(lngs = { "en" }, values = { "Total Download Speed" })
String filePanel_totalDownloadSpeed();
@Default(lngs = { "en" }, values = { "Total Request Rate" })
String filePanel_totalRequestRate();
@Default(lngs = { "en" }, values = { "Select Next Downloaded Region" })
String filePanel_selectNextRegionButton();
@Default(lngs = { "en" }, values = { "Previous Region" })
String filePanel_selectPreviousRegionButton();
@Default(lngs = { "en" }, values = { "Kill Connection" })
String filePanel_killConnection();
@Default(lngs = { "en" }, values = { "<html>Click on a <b>downloaded region</b> to activate speed chart</html>" })
String filePanel_graph_noRegionSelected();
@Default(lngs = { "en" }, values = { "Download Speed" })
String filePanel_graph_downloadSpeed();
@Default(lngs = { "en" }, values = { "Request speed" })
String filePanel_graph_requestSpeed();
@Default(lngs = { "en" }, values = { "<html>Speed (KiB/s)</html>" })
String filePanel_graph_yaxis();
@Default(lngs = { "en" }, values = { "Cannot create a new connection, unmounting as we already retried" })
String troubleHandler_retriedConnection();
@Default(lngs = { "en" }, values = { " times" })
String troubleHandler_retriedConnection_times();
@Default(lngs = { "en" }, values = { "Cannot create a new connection, unmounting as we already retried" })
String troubleHandler_pendingRequests();
@Default(lngs = { "en" }, values = { " minute(s)" })
String troubleHandler_pendingRequests_minutes();
@Default(lngs = { "en" }, values = { "Try watching the file after completely downloading it.\n\"Watch as you download\" is difficult on this file.\nUnmounting to prevent Not Responding state of the application used to open this file." })
String troubleHandler_pendingRequests_Solution();
}

View File

@ -1158,6 +1158,9 @@ public interface GuiTranslation extends TranslateInterface {
@Default(lngs = { "en" }, values = { "Unset Stopmark" })
String gui_table_contextmenu_stopmark_unset();
@Default(lngs = { "en" }, values = { "Watch As you download" })
String gui_table_contextmenu_watch_as_you_download();
@Default(lngs = { "en" }, values = { "Force download" })
String gui_table_contextmenu_tryforce();
@ -1983,6 +1986,9 @@ public interface GuiTranslation extends TranslateInterface {
@Default(lngs = { "en" }, values = { "Size" })
String SizeColumn_SizeColumn();
@Default(lngs = { "en" }, values = { "Watch As You Download" })
String WatchAsYouDownloadColumn_WatchAsYouDownloadColumn();
@Default(lngs = { "en" }, values = { "Bytes Left" })
String RemainingColumn_RemainingColumn();
@ -2995,6 +3001,9 @@ public interface GuiTranslation extends TranslateInterface {
@Default(lngs = { "en" }, values = { "Open Download Directory" })
String OpenDownloadFolderAction_OpenDownloadFolderAction_();
@Default(lngs = { "en" }, values = { "Watch As You Download" })
String WatchAsYouDownload_WatchAsYouDownloadAction_();
@Default(lngs = { "en" }, values = { "Enabled" })
String EnabledAction_EnabledAction_object_();

View File

@ -0,0 +1,99 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.gui.views.downloads.columns;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import jd.controlling.packagecontroller.AbstractNode;
import org.appwork.swing.exttable.ExtColumn;
import org.appwork.swing.exttable.ExtTableModel;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.images.NewTheme;
/**
*
* @author Shashank Tulsyan
*/
public class WatchAsYouDownloadColumn extends ExtColumn<AbstractNode> {
public WatchAsYouDownloadColumn() {
super(_GUI._.WatchAsYouDownloadColumn_WatchAsYouDownloadColumn(), null);
}
@Override
public void configureEditorComponent(AbstractNode value, boolean isSelected, int row, int column) {
//
}
@Override
public void configureRendererComponent(AbstractNode value, boolean isSelected, boolean hasFocus, int row, int column) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getCellEditorValue() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public JComponent getEditorComponent(AbstractNode value, boolean isSelected, int row, int column) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public JComponent getRendererComponent(AbstractNode value, boolean isSelected, boolean hasFocus, int row, int column) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isEditable(AbstractNode obj) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isEnabled(AbstractNode obj) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isSortable(AbstractNode obj) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void resetEditor() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void resetRenderer() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setValue(Object value, AbstractNode object) {
throw new UnsupportedOperationException("Not supported yet.");
}
private static final class Renderer {
private JCheckBox checkBox;
public Renderer() {
checkBox = new JCheckBox(NewTheme.I().getIcon("mediaplayer", 24), true);
}
}
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.gui.views.downloads.context;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import jd.controlling.downloadcontroller.DownloadWatchDog;
import jd.gui.swing.jdgui.interfaces.ContextMenuAction;
import jd.plugins.DownloadLink;
import jd.plugins.FilePackage;
import org.jdownloader.extensions.neembuu.NeembuuExtension;
import org.jdownloader.gui.translate._GUI;
/**
*
* @author Shashank Tulsyan
*/
public class WatchAsYouDownloadAction extends ContextMenuAction {
private final ArrayList<FilePackage> fps;
private final boolean canHandle;
private final ArrayList<DownloadLink> dls = new ArrayList<DownloadLink>();
public WatchAsYouDownloadAction(ArrayList<FilePackage> fps) {
this.fps = fps;
if (fps != null && fps.size() > 0) {
canHandle = NeembuuExtension.canHandle(fps);
for (FilePackage fp : fps) {
if (fp == null) continue;// ignore empty entries.
fp.setProperty(NeembuuExtension.WATCH_AS_YOU_DOWNLOAD_KEY, canHandle);
dls.addAll(fp.getChildren());
}
} else
canHandle = false;
init();
}
@Override
protected String getIcon() {
return "mediaplayer";
}
@Override
protected String getName() {
return _GUI._.gui_table_contextmenu_watch_as_you_download() + (fps.size() > 1 ? " (" + fps.size() + ")" : "");
}
public void actionPerformed(ActionEvent e) {
DownloadWatchDog.getInstance().forceDownload(dls);
}
@Override
public boolean isEnabled() {
return fps != null && fps.size() > 0 && canHandle;
}
}

View File

@ -36,6 +36,7 @@ import org.jdownloader.gui.views.downloads.context.ResetAction;
import org.jdownloader.gui.views.downloads.context.ResumeAction;
import org.jdownloader.gui.views.downloads.context.SetPasswordAction;
import org.jdownloader.gui.views.downloads.context.StopsignAction;
import org.jdownloader.gui.views.downloads.context.WatchAsYouDownloadAction;
public class DownloadTableContextMenuFactory {
private static final DownloadTableContextMenuFactory INSTANCE = new DownloadTableContextMenuFactory();
@ -84,6 +85,9 @@ public class DownloadTableContextMenuFactory {
popup.add(new ForceDownloadAction(links));
popup.add(new ResumeAction(links));
popup.add(new ResetAction(links));
if (contextObject instanceof FilePackage) {
popup.add(new WatchAsYouDownloadAction(fps));
}
popup.add(new JSeparator());
popup.add(new NewPackageAction(links));
popup.add(new CheckStatusAction(links));

View File

@ -51,6 +51,8 @@ public class ContextMenuFactory {
}
p.add(new JSeparator());
p.add(new WatchAsYouDownloadAction(isShift, selection).toContextMenuAction());
p.add(new JSeparator());
p.add(new OpenDownloadFolderAction(contextObject, selection).toContextMenuAction());

View File

@ -0,0 +1,124 @@
/*
* Copyright (C) 2012 Shashank Tulsyan
*
* 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 3 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jdownloader.gui.views.linkgrabber.contextmenu;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import jd.controlling.IOEQ;
import jd.controlling.downloadcontroller.DownloadController;
import jd.controlling.downloadcontroller.DownloadWatchDog;
import jd.controlling.linkcollector.LinkCollector;
import jd.controlling.linkcrawler.CrawledLink;
import jd.controlling.linkcrawler.CrawledPackage;
import jd.controlling.packagecontroller.AbstractNode;
import jd.plugins.FilePackage;
import org.appwork.utils.ImageProvider.ImageProvider;
import org.jdownloader.actions.AppAction;
import org.jdownloader.extensions.neembuu.NeembuuExtension;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.images.NewTheme;
/**
*
* @author Shashank Tulsyan
*/
public class WatchAsYouDownloadAction extends AppAction {
/**
*
*/
private static final long serialVersionUID = -1123905158192679571L;
private ArrayList<AbstractNode> values;
private boolean autostart;
public WatchAsYouDownloadAction(boolean autostart, ArrayList<AbstractNode> arrayList) {
// if
// ((org.jdownloader.settings.staticreferences.CFG_LINKFILTER.LINKGRABBER_AUTO_START_ENABLED.getValue()
// && !autostart) || (autostart &&
// !org.jdownloader.settings.staticreferences.CFG_LINKFILTER.LINKGRABBER_AUTO_START_ENABLED.getValue()))
// {
setName(_GUI._.WatchAsYouDownload_WatchAsYouDownloadAction_());
Image add = NewTheme.I().getImage("mediaplayer", 20);
Image play = NewTheme.I().getImage("add", 12);
setSmallIcon(new ImageIcon(ImageProvider.merge(add, play, 0, 0, 9, 10)));
this.autostart = true;
/*
* } else { setName(_GUI._.ConfirmAction_ConfirmAction_context_add());
* setSmallIcon(NewTheme.I().getIcon("add", 20)); this.autostart =
* false; }
*/
this.values = arrayList;
}
public void actionPerformed(ActionEvent e) {
if (!isEnabled()) return;
IOEQ.add(new Runnable() {
public void run() {
boolean addTop = org.jdownloader.settings.staticreferences.CFG_LINKFILTER.LINKGRABBER_ADD_AT_TOP.getValue();
ArrayList<FilePackage> fpkgs = new ArrayList<FilePackage>();
ArrayList<CrawledLink> clinks = new ArrayList<CrawledLink>();
for (AbstractNode node : values) {
if (node instanceof CrawledPackage) {
/* first convert all CrawledPackages to FilePackages */
ArrayList<CrawledLink> links = new ArrayList<CrawledLink>(((CrawledPackage) node).getView().getItems());
ArrayList<FilePackage> packages = LinkCollector.getInstance().removeAndConvert(links);
if (packages != null) fpkgs.addAll(packages);
} else if (node instanceof CrawledLink) {
/* collect all CrawledLinks */
clinks.add((CrawledLink) node);
}
}
/* convert all selected CrawledLinks to FilePackages */
ArrayList<FilePackage> frets = LinkCollector.getInstance().removeAndConvert(clinks);
boolean canHandle = false;
if (frets != null) fpkgs.addAll(frets);
if (fpkgs != null && fpkgs.size() > 0) {
canHandle = NeembuuExtension.canHandle(fpkgs);
for (FilePackage fp : fpkgs) {
if (fp == null) continue;// ignore empty entries.
fp.setProperty(NeembuuExtension.WATCH_AS_YOU_DOWNLOAD_KEY, canHandle);
}
} else
canHandle = false;
/* add the converted FilePackages to DownloadController */
DownloadController.getInstance().addAllAt(fpkgs, addTop ? 0 : -(fpkgs.size() + 10));
if (autostart) {
IOEQ.add(new Runnable() {
public void run() {
/* start DownloadWatchDog if wanted */
DownloadWatchDog.getInstance().startDownloads();
}
}, true);
}
}
}, true);
}
@Override
public boolean isEnabled() {
if (!NeembuuExtension.isActive()) return false;
return values != null && values.size() > 0;
}
}