build>full

git-svn-id: svn://svn.jdownloader.org/jdownloader/trunk@28196 ebf7c1c2-ba36-0410-9fe8-c592906822b4

Former-commit-id: c4528e47d8d61bbcb05ccfc1ca6d49a22c2da39d
This commit is contained in:
coalado 2014-12-04 14:11:19 +00:00
parent b7dd0f9b0e
commit 91b1ce7570
27 changed files with 4019 additions and 106 deletions

View File

@ -1,103 +1,104 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="jd/plugins/optional/neembuu/|jd/plugins/optional/remoteserv/|jd/plugins/optional/remoteserv/|org/jdownloader/extensions/langfileeditor/" kind="src" path="src"/>
<classpathentry kind="src" path="src-closed"/>
<classpathentry kind="src" path="translations"/>
<classpathentry kind="src" path="themes"/>
<classpathentry excluding="org/jdownloader/nativeswing/OptionsAndPlaylistExample.java|org/jdownloader/nativeswing/SimpleVLCPlayerExample.java" kind="src" path="tests"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="jd/ressourcen/libs/dbus"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/irclib.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/mail.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/debug-1.0.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/jcip-annotations-1.0.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/Filters.jar" sourcepath="ressourcen/code-ressourcen/Filter_src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/looks.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/synthetica.jar">
<attributes>
<attribute name="javadoc_location" value="jar:platform:/resource/jd/ressourcen/code-ressourcen/synthetica_docs.zip!/"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlackMoon.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlackStar.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueIce.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueMoon.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueSteel.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaMauveMetallic.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaOrangeMetallic.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaSilverMoon.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaSimple2D.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaSkyMetallic.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaWhiteVision.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/jna.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlackEye.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaGreenDream.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/image4j.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/debug-disable.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/hexdump.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/libdbus-java.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/unix.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-assert-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-assert-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-reflect-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-reflect-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-swing-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-swing-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-swing-junit-4.5-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-swing-junit-4.5-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-util-1.1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-util-1.1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/svnkit.jar" sourcepath="ressourcen/code-ressourcen/svnkitsrc.zip"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/junit-4.8.2.jar" sourcepath="ressourcen/code-ressourcen/junit-4.8.2-src.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbinding.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/jpathwatch-0-93-rc1.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/AppleJavaExtensions.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/asc.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/swfutils.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/JDBrowser"/>
<classpathentry combineaccessrules="false" kind="src" path="/AppWorkUtils"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbindingWin.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/mqtt.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/jackson-core.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/jackson-mapper.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/miglayout.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/bcprov-jdk15on-147.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbindingLinux.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbindingMac.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/MyJDownloaderClient"/>
<classpathentry kind="lib" path="ressourcen/libs/jna_platform.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/cling-core.jar" sourcepath="dev/cling-core-2.0-SNAPSHOT-sources.jar">
<attributes>
<attribute name="source_encoding" value="UTF-8"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/cling-support.jar">
<attributes>
<attribute name="source_encoding" value="UTF-8"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/seamless-http.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/seamless-util.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/seamless-xml.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/proxyVole.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/savemytube.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/htmlunit-core-js.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/js.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaAluOxide.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueLight.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaClassy.jar"/>
<classpathentry kind="var" path="SWT_PLATFORM/swt.jar" sourcepath="/JD_WORKSPACE/dev/libs/SWT/src.zip">
<attributes>
<attribute name="source_encoding" value="UTF-8"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/swt/DJNativeSwing-SWT.jar" sourcepath="dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.src.zip">
<attributes>
<attribute name="javadoc_location" value="jar:platform:/resource/JDownloader/dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.docs.zip!/api"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/swt/DJNativeSwing.jar" sourcepath="dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.src.zip">
<attributes>
<attribute name="javadoc_location" value="jar:platform:/resource/JDownloader/dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.docs.zip!/api/"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="jd/plugins/optional/neembuu/|jd/plugins/optional/remoteserv/|jd/plugins/optional/remoteserv/|org/jdownloader/extensions/langfileeditor/" kind="src" path="src"/>
<classpathentry kind="src" path="src-closed"/>
<classpathentry kind="src" path="translations"/>
<classpathentry kind="src" path="themes"/>
<classpathentry excluding="org/jdownloader/nativeswing/OptionsAndPlaylistExample.java|org/jdownloader/nativeswing/SimpleVLCPlayerExample.java" kind="src" path="tests"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="jd/ressourcen/libs/dbus"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/irclib.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/mail.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/debug-1.0.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/jcip-annotations-1.0.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/Filters.jar" sourcepath="ressourcen/code-ressourcen/Filter_src.zip"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/looks.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/synthetica.jar">
<attributes>
<attribute name="javadoc_location" value="jar:platform:/resource/jd/ressourcen/code-ressourcen/synthetica_docs.zip!/"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlackMoon.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlackStar.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueIce.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueMoon.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueSteel.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaMauveMetallic.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaOrangeMetallic.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaSilverMoon.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaSimple2D.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaSkyMetallic.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaWhiteVision.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/jna.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlackEye.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaGreenDream.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/image4j.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/debug-disable.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/hexdump.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/libdbus-java.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/dbus/unix.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-assert-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-assert-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-reflect-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-reflect-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-swing-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-swing-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-swing-junit-4.5-1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-swing-junit-4.5-1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/fest-util-1.1.2.jar" sourcepath="ressourcen/code-ressourcen/fest-util-1.1.2-sources.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/svnkit.jar" sourcepath="ressourcen/code-ressourcen/svnkitsrc.zip"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/junit-4.8.2.jar" sourcepath="ressourcen/code-ressourcen/junit-4.8.2-src.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbinding.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/jpathwatch-0-93-rc1.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/AppleJavaExtensions.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/asc.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/swfutils.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/JDBrowser"/>
<classpathentry combineaccessrules="false" kind="src" path="/AppWorkUtils"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbindingWin.jar"/>
<classpathentry kind="lib" path="ressourcen/libs_ext/mqtt.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/jackson-core.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/jackson-mapper.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/miglayout.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/bcprov-jdk15on-147.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbindingLinux.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/sevenzipjbindingMac.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/MyJDownloaderClient"/>
<classpathentry kind="lib" path="ressourcen/libs/jna_platform.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/cling-core.jar" sourcepath="dev/cling-core-2.0-SNAPSHOT-sources.jar">
<attributes>
<attribute name="source_encoding" value="UTF-8"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/cling-support.jar">
<attributes>
<attribute name="source_encoding" value="UTF-8"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/seamless-http.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/seamless-util.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/UPNP/seamless-xml.jar"/>
<classpathentry kind="lib" path="/AppWorkUtils/libs/proxyVole.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/savemytube.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/htmlunit-core-js.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/js.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaAluOxide.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaBlueLight.jar"/>
<classpathentry kind="lib" path="ressourcen/libs/laf/syntheticaClassy.jar"/>
<classpathentry kind="var" path="SWT_PLATFORM/swt.jar" sourcepath="/JD_WORKSPACE/dev/libs/SWT/src.zip">
<attributes>
<attribute name="source_encoding" value="UTF-8"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/swt/DJNativeSwing-SWT.jar" sourcepath="dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.src.zip">
<attributes>
<attribute name="javadoc_location" value="jar:platform:/resource/JDownloader/dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.docs.zip!/api"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/swt/DJNativeSwing.jar" sourcepath="dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.src.zip">
<attributes>
<attribute name="javadoc_location" value="jar:platform:/resource/JDownloader/dev/libs/DJNativeSwing-SWT-1-0-2/DJNativeSwing-SWT-1-0-2.docs.zip!/api/"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="ressourcen/libs/jsyntaxpane.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -409,7 +409,8 @@
<target name="jarOptionals" description="Creates the Optional Plugins">
<manifest file="${dist}/Manifest.MF">
<attribute name="Created-By" value="JD-Team and Friends" />
</manifest>
</manifest>
<buildAddon package="EventScripter" include="eventscripter" />
<buildAddon package="JDChat" include="chat" />
<buildAddon package="infobar" include="infobar" />
<buildAddon package="FolderWatch" include="folderwatchV2" />

Binary file not shown.

View File

@ -0,0 +1,2 @@
jsyntaxpane-0.9.5-b29.jar
https://code.google.com/p/jsyntaxpane/downloads/detail?name=jsyntaxpane-0.9.5-b29.jar&can=2&q=

View File

@ -122,8 +122,9 @@ public class MainToolBar extends JToolBar implements MouseListener, DownloadWatc
private MainToolBar() {
super();
logger = LogController.getInstance().getLogger("MainToolbar");
this.setRollover(true);
this.addMouseListener(this);
this.setRollover(true);
this.setFloatable(false);
setPreferredSize(new Dimension(-1, 38));
SecondLevelLaunch.GUI_COMPLETE.executeWhenReached(new Runnable() {

View File

@ -3,6 +3,7 @@ package org.jdownloader.api;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
@ -18,6 +19,8 @@ import jd.nutils.DiffMatchPatch.Patch;
import org.appwork.exceptions.WTFException;
import org.appwork.net.protocol.http.HTTPConstants.ResponseCode;
import org.appwork.remoteapi.InterfaceHandler;
import org.appwork.remoteapi.RemoteAPI;
import org.appwork.remoteapi.RemoteAPI.RemoteAPIMethod;
import org.appwork.remoteapi.RemoteAPIInterface;
import org.appwork.remoteapi.RemoteAPIRequest;
import org.appwork.remoteapi.RemoteAPIResponse;
@ -28,6 +31,7 @@ import org.appwork.remoteapi.events.EventPublisher;
import org.appwork.remoteapi.events.EventsAPI;
import org.appwork.remoteapi.events.EventsAPIInterface;
import org.appwork.remoteapi.events.json.EventObjectStorable;
import org.appwork.remoteapi.exceptions.BadParameterException;
import org.appwork.remoteapi.exceptions.BasicRemoteAPIException;
import org.appwork.storage.JSonStorage;
import org.appwork.storage.Storable;
@ -522,4 +526,45 @@ public class RemoteAPIController {
return deviceMap;
}
public Object call(final String namespace, final String methodName, Object... params) throws BasicRemoteAPIException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
RemoteAPIMethod dummyMethod = this.rapi.getRemoteAPIMethod(new HttpRequest(null) {
@Override
public String getRequestedPath() {
return "/" + namespace + "/" + methodName;
}
@Override
public String getParameterbyKey(String key) throws IOException {
return null;
}
});
InterfaceHandler<?> iface = dummyMethod.getInterfaceHandler();
Method method = iface.getMethod(methodName, params.length);
ArrayList<String> stringParams = new ArrayList<String>();
for (Object o : params) {
stringParams.add(JSonStorage.serializeToJson(o));
}
final Object[] parameters = new Object[method.getParameterTypes().length];
int count = 0;
for (int i = 0; i < parameters.length; i++) {
if (RemoteAPIRequest.class.isAssignableFrom(method.getParameterTypes()[i])) {
throw new BasicRemoteAPIException("Not Found", ResponseCode.ERROR_NOT_FOUND);
} else if (RemoteAPIResponse.class.isAssignableFrom(method.getParameterTypes()[i])) {
throw new BasicRemoteAPIException("Not Found", ResponseCode.ERROR_NOT_FOUND);
} else {
try {
parameters[i] = RemoteAPI.convert(stringParams.get(count), method.getGenericParameterTypes()[i]);
} catch (final Throwable e) {
throw new BadParameterException(e, stringParams.get(count));
}
count++;
}
}
return iface.invoke(method, parameters);
}
}

View File

@ -363,7 +363,7 @@ public class ExternInterfaceImpl implements Cnl2APIBasics, Cnl2APIFlash {
try {
response.getResponseHeaders().add(new HTTPHeader(HTTPConstants.HEADER_REQUEST_CONTENT_TYPE, "image/x-icon", false));
out = RemoteAPI.getOutputStream(response, null, false, false);
Icon logo = NewTheme.I().getIcon("logo/jd_ logo_128_128", 32);
Icon logo = NewTheme.I().getIcon("logo/jd_logo_128_128", 32);
ICOEncoder.write(IconIO.toBufferedImage(logo), out);
} catch (Throwable e) {
throw new InternalApiException(e);

View File

@ -0,0 +1,28 @@
package org.jdownloader.extensions.eventscripter;
import org.appwork.storage.config.ConfigUtils;
import org.appwork.storage.config.JsonConfig;
import org.appwork.storage.config.handler.BooleanKeyHandler;
import org.appwork.storage.config.handler.ObjectKeyHandler;
import org.appwork.storage.config.handler.StorageHandler;
import org.appwork.utils.Application;
public class CFG_EVENT_CALLER {
public static void main(String[] args) {
ConfigUtils.printStaticMappings(EventScripterConfig.class, "Application.getResource(\"cfg/\" + " + EventScripterExtension.class.getSimpleName() + ".class.getName())");
}
// Static Mappings for interface org.jdownloader.extensions.schedulerV2.SchedulerConfig
public static final EventScripterConfig CFG = JsonConfig.create(Application.getResource("cfg/" + EventScripterExtension.class.getName()), EventScripterConfig.class);
public static final StorageHandler<EventScripterConfig> SH = (StorageHandler<EventScripterConfig>) CFG._getStorageHandler();
// let's do this mapping here. If we map all methods to static handlers, access is faster, and we get an error on init if mappings are
// wrong.
public static final ObjectKeyHandler SCRIPTS = SH.getKeyHandler("Scripts", ObjectKeyHandler.class);
public static final BooleanKeyHandler FRESH_INSTALL = SH.getKeyHandler("FreshInstall", BooleanKeyHandler.class);
public static final BooleanKeyHandler ENABLED = SH.getKeyHandler("Enabled", BooleanKeyHandler.class);
public static final BooleanKeyHandler GUI_ENABLED = SH.getKeyHandler("GuiEnabled", BooleanKeyHandler.class);
}

View File

@ -0,0 +1,13 @@
package org.jdownloader.extensions.eventscripter;
import net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime;
import org.appwork.utils.Exceptions;
public class EnvironmentException extends Exception {
public EnvironmentException(Throwable e) {
super(Exceptions.getStackTrace(ScriptRuntime.constructError("Stacktrace", null)), e);
}
}

View File

@ -0,0 +1,21 @@
package org.jdownloader.extensions.eventscripter;
import java.util.ArrayList;
import jd.plugins.ExtensionConfigInterface;
import org.appwork.storage.config.annotations.AboutConfig;
public interface EventScripterConfig extends ExtensionConfigInterface {
@AboutConfig
ArrayList<ScriptEntry> getScripts();
void setScripts(ArrayList<ScriptEntry> entries);
@AboutConfig
boolean isAPIPanelVisible();
void setAPIPanelVisible(boolean b);
}

View File

@ -0,0 +1,143 @@
package org.jdownloader.extensions.eventscripter;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import jd.gui.swing.jdgui.views.settings.panels.proxy.ProxyDeleteAction;
import org.appwork.storage.config.annotations.AboutConfig;
import org.appwork.storage.config.annotations.DevConfig;
import org.appwork.storage.config.handler.KeyHandler;
import org.appwork.swing.MigPanel;
import org.appwork.swing.components.ExtButton;
import org.appwork.utils.Application;
import org.appwork.utils.swing.SwingUtils;
import org.appwork.utils.swing.dialog.Dialog;
import org.appwork.utils.swing.dialog.DialogCanceledException;
import org.appwork.utils.swing.dialog.DialogClosedException;
import org.jdownloader.extensions.ExtensionConfigPanel;
import org.jdownloader.gui.IconKey;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.gui.views.components.AbstractAddAction;
import org.jdownloader.gui.views.components.AbstractRemoveAction;
import org.jdownloader.images.AbstractIcon;
import org.jdownloader.settings.advanced.AdvancedConfigEntry;
import org.jdownloader.updatev2.gui.LAFOptions;
public class EventScripterConfigPanel extends ExtensionConfigPanel<EventScripterExtension> {
/**
*
*/
private static final long serialVersionUID = 1L;
private EventScripterTableModel model;
private ExtButton btnAdd;
private EventScripterTable table;
private AbstractRemoveAction deleteSelectionAction;
public ArrayList<AdvancedConfigEntry> register() {
ArrayList<AdvancedConfigEntry> configInterfaces = new ArrayList<AdvancedConfigEntry>();
HashMap<KeyHandler, Boolean> map = new HashMap<KeyHandler, Boolean>();
for (KeyHandler m : getExtension().getSettings()._getStorageHandler().getMap().values()) {
if (map.containsKey(m)) {
continue;
}
if (m.getAnnotation(AboutConfig.class) != null && (m.getAnnotation(DevConfig.class) == null || !Application.isJared(null))) {
if (m.getSetter() == null) {
throw new RuntimeException("Setter for " + m.getGetter().getMethod() + " missing");
} else if (m.getGetter() == null) {
throw new RuntimeException("Getter for " + m.getSetter().getMethod() + " missing");
} else {
synchronized (configInterfaces) {
configInterfaces.add(new AdvancedConfigEntry(getExtension().getSettings(), m));
}
map.put(m, true);
}
}
}
return configInterfaces;
}
public EventScripterConfigPanel(EventScripterExtension extension) {
super(extension);
JLabel lbl;
add(SwingUtils.toBold(lbl = new JLabel("THIS EXTENSION IS STILL UNDER CONSTRUCTION. Feel free to test it and to give Feedback. ")));
lbl.setForeground(LAFOptions.getInstance().getColorForErrorForeground());
add(new JScrollPane(table = new EventScripterTable(model = new EventScripterTableModel(extension)) {
@Override
protected boolean onShortcutDelete(List<ScriptEntry> selectedObjects, KeyEvent evt, boolean direct) {
deleteSelectionAction.actionPerformed(null);
return true;
}
}));
MigPanel toolbar = new MigPanel("ins 0", "0[][][grow,fill]", "[]");
toolbar.setOpaque(false);
btnAdd = new ExtButton(new AbstractAddAction() {
@Override
public void actionPerformed(ActionEvent e) {
ScriptEntry newScript = new ScriptEntry();
getExtension().addScriptEntry(newScript);
}
});
ProxyDeleteAction dl;
ExtButton btnRemove = new ExtButton(deleteSelectionAction = new AbstractRemoveAction() {
@Override
public void actionPerformed(ActionEvent e) {
List<ScriptEntry> entries = model.getSelectedObjects();
if (entries == null || entries.size() == 0) {
return;
}
try {
Dialog.getInstance().showConfirmDialog(0, _GUI._.lit_are_you_sure(), org.jdownloader.extensions.eventscripter.T._.sure_delete_entries(entries.size()), new AbstractIcon(IconKey.ICON_QUESTION, 32), null, null);
getExtension().removeScriptEntries(entries);
} catch (DialogClosedException e1) {
e1.printStackTrace();
} catch (DialogCanceledException e1) {
e1.printStackTrace();
}
}
});
toolbar.add(btnAdd, "sg 1,height 26!");
toolbar.add(btnRemove, "sg 1,height 26!");
toolbar.add(Box.createHorizontalGlue(), "pushx,growx");
//
// toolbar.add(btImport, "sg 2,height 26!");
// toolbar.add(impPopup, "height 26!,width 12!,aligny top");
//
// toolbar.add(btExport, "sg 2,height 26!");
// toolbar.add(expPopup, "height 26!,width 12!,aligny top");
add(toolbar, "gapleft 32,growx,spanx");
}
@Override
public void save() {
}
@Override
public void updateContents() {
}
}

View File

@ -0,0 +1,318 @@
// jDownloader - Downloadmanager
// Copyright (C) 2013 JD-Team support@jdownloader.org
//
// 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.eventscripter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import jd.SecondLevelLaunch;
import jd.controlling.downloadcontroller.DownloadLinkCandidate;
import jd.controlling.downloadcontroller.DownloadLinkCandidateResult;
import jd.controlling.downloadcontroller.DownloadWatchDog;
import jd.controlling.downloadcontroller.DownloadWatchDogProperty;
import jd.controlling.downloadcontroller.SingleDownloadController;
import jd.controlling.downloadcontroller.event.DownloadWatchdogListener;
import jd.plugins.AddonPanel;
import jd.plugins.DownloadLink;
import jd.plugins.FilePackage;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.Script;
import net.sourceforge.htmlunit.corejs.javascript.tools.shell.Global;
import org.appwork.storage.config.ValidationException;
import org.appwork.storage.config.events.GenericConfigEventListener;
import org.appwork.storage.config.handler.KeyHandler;
import org.appwork.utils.StringUtils;
import org.appwork.utils.swing.dialog.Dialog;
import org.jdownloader.api.downloads.v2.DownloadLinkAPIStorableV2;
import org.jdownloader.api.downloads.v2.DownloadsAPIV2Impl;
import org.jdownloader.api.downloads.v2.FilePackageAPIStorableV2;
import org.jdownloader.api.downloads.v2.LinkQueryStorable;
import org.jdownloader.api.downloads.v2.PackageQueryStorable;
import org.jdownloader.controlling.contextmenu.ContextMenuManager;
import org.jdownloader.controlling.contextmenu.MenuContainerRoot;
import org.jdownloader.controlling.contextmenu.MenuExtenderHandler;
import org.jdownloader.controlling.contextmenu.MenuItemData;
import org.jdownloader.extensions.AbstractExtension;
import org.jdownloader.extensions.ExtensionConfigPanel;
import org.jdownloader.extensions.StartException;
import org.jdownloader.extensions.StopException;
import org.jdownloader.gui.IconKey;
public class EventScripterExtension extends AbstractExtension<EventScripterConfig, EventScripterTranslation> implements MenuExtenderHandler, DownloadWatchdogListener, GenericConfigEventListener<Object> {
private Object lock = new Object();
private EventScripterConfigPanel configPanel;
private List<ScriptEntry> entries;
@Override
public boolean isHeadlessRunnable() {
return false;
}
public boolean hasConfigPanel() {
return true;
}
public EventScripterExtension() throws StartException {
setTitle("Event Caller");
}
@Override
public String getIconKey() {
return IconKey.ICON_EVENT;
}
@Override
protected void stop() throws StopException {
DownloadWatchDog.getInstance().getEventSender().removeListener(this);
CFG_EVENT_CALLER.SCRIPTS.getEventSender().removeListener(this);
}
@Override
protected void start() throws StartException {
DownloadWatchDog.getInstance().getEventSender().addListener(this);
CFG_EVENT_CALLER.SCRIPTS.getEventSender().addListener(this);
entries = getSettings().getScripts();
configPanel = new EventScripterConfigPanel(this);
SecondLevelLaunch.INIT_COMPLETE.executeWhenReached(new Runnable() {
@Override
public void run() {
for (ScriptEntry script : entries) {
if (script.isEnabled() && StringUtils.isNotEmpty(script.getScript()) && EventTrigger.ON_JDOWNLOADER_STARTED == script.getEventTrigger()) {
HashMap<String, Object> props = new HashMap<String, Object>();
runScript(script, props);
}
}
}
});
}
@Override
public String getDescription() {
return _.description();
}
@Override
public AddonPanel<EventScripterExtension> getGUI() {
// if you want an own t
return null;
}
@Override
protected void initExtension() throws StartException {
}
@Override
public boolean isQuickToggleEnabled() {
return true;
}
@Override
public MenuItemData updateMenuModel(ContextMenuManager manager, MenuContainerRoot mr) {
return null;
}
@Override
public ExtensionConfigPanel<?> getConfigPanel() {
return configPanel;
}
@Override
public void onDownloadWatchdogDataUpdate() {
}
@Override
public void onDownloadWatchdogStateIsIdle() {
}
@Override
public void onDownloadWatchdogStateIsPause() {
}
@Override
public void onDownloadWatchdogStateIsRunning() {
}
@Override
public void onDownloadWatchdogStateIsStopped() {
}
@Override
public void onDownloadWatchdogStateIsStopping() {
}
@Override
public void onDownloadControllerStart(SingleDownloadController downloadController, DownloadLinkCandidate candidate) {
if (entries == null) {
return;
}
for (ScriptEntry script : entries) {
if (script.isEnabled() && StringUtils.isNotEmpty(script.getScript()) && EventTrigger.ON_DOWNLOAD_CONTROLLER_START == script.getEventTrigger()) {
try {
HashMap<String, Object> props = new HashMap<String, Object>();
props.put("link", getLinkInfo(downloadController.getDownloadLink()));
props.put("package", getPackageInfo(downloadController.getDownloadLink().getParentNode()));
runScript(script, props);
} catch (Throwable e) {
getLogger().log(e);
}
}
}
}
public void runScript(ScriptEntry script, HashMap<String, Object> props) {
new ScriptThread(script, props, getLogger()).start();
}
private FilePackageAPIStorableV2 getPackageInfo(FilePackage pkg) {
PackageQueryStorable query = new PackageQueryStorable();
query.setBytesLoaded(true);
query.setBytesTotal(true);
query.setComment(true);
query.setEnabled(true);
query.setEta(true);
query.setFinished(true);
query.setRunning(true);
query.setSpeed(true);
query.setStatus(true);
query.setChildCount(true);
query.setHosts(true);
query.setSaveTo(true);
return DownloadsAPIV2Impl.toStorable(query, pkg, this);
}
private DownloadLinkAPIStorableV2 getLinkInfo(DownloadLink downloadLink) {
LinkQueryStorable query = new LinkQueryStorable();
query.setBytesLoaded(true);
query.setBytesTotal(true);
query.setComment(true);
query.setEnabled(true);
query.setEta(true);
query.setExtractionStatus(true);
query.setFinished(true);
query.setHost(true);
query.setPriority(true);
query.setRunning(true);
query.setSkipped(true);
query.setSpeed(true);
query.setStatus(true);
query.setUrl(true);
return DownloadsAPIV2Impl.toStorable(query, downloadLink, this);
}
@Override
public void onDownloadControllerStopped(SingleDownloadController downloadController, DownloadLinkCandidate candidate, DownloadLinkCandidateResult result) {
if (entries == null) {
return;
}
for (ScriptEntry script : entries) {
if (script.isEnabled() && StringUtils.isNotEmpty(script.getScript()) && EventTrigger.ON_DOWNLOAD_CONTROLLER_STOPPED == script.getEventTrigger()) {
HashMap<String, Object> props = new HashMap<String, Object>();
props.put("link", getLinkInfo(downloadController.getDownloadLink()));
props.put("package", getPackageInfo(downloadController.getDownloadLink().getParentNode()));
runScript(script, props);
}
}
}
@Override
public void onDownloadWatchDogPropertyChange(DownloadWatchDogProperty propertyChange) {
}
@Override
public void onConfigValidatorError(KeyHandler<Object> keyHandler, Object invalidValue, ValidationException validateException) {
}
@Override
public void onConfigValueModified(KeyHandler<Object> keyHandler, Object newValue) {
entries = getSettings().getScripts();
}
public void save(final List<ScriptEntry> tableData) {
new Thread() {
@Override
public void run() {
getSettings().setScripts(new ArrayList<ScriptEntry>(tableData));
}
}.start();
}
public void runTest(EventTrigger eventTrigger, String name, String scriptSource) {
ScriptEntry script = new ScriptEntry();
script.setEventTrigger(eventTrigger);
script.setScript(scriptSource);
script.setName(name);
runScript(script, eventTrigger.getTestProperties());
}
public void runTestCompile(EventTrigger eventTrigger, String script) {
Context cx = Context.enter();
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
Global scope = new Global();
scope.init(cx);
try {
// cx.compileString(source, sourceName, lineno, securityDomain)
Script fcn = cx.compileString(script, "", 1, null);
Dialog.getInstance().showMessageDialog("Successful");
} catch (Throwable e1) {
Dialog.getInstance().showExceptionDialog("JavaScript Syntax Error", e1.getMessage(), e1);
} finally {
Context.exit();
}
}
public void addScriptEntry(ScriptEntry newScript) {
ArrayList<ScriptEntry> newEntries = entries == null ? new ArrayList<ScriptEntry>() : new ArrayList<ScriptEntry>(entries);
newEntries.add(newScript);
save(newEntries);
}
public void removeScriptEntries(List<ScriptEntry> entries2) {
ArrayList<ScriptEntry> newEntries = entries == null ? new ArrayList<ScriptEntry>() : new ArrayList<ScriptEntry>(entries);
newEntries.removeAll(entries2);
save(newEntries);
}
}

View File

@ -0,0 +1,13 @@
package org.jdownloader.extensions.eventscripter;
import jd.gui.swing.jdgui.BasicJDTable;
import org.appwork.swing.exttable.ExtTableModel;
public class EventScripterTable extends BasicJDTable<ScriptEntry> {
public EventScripterTable(ExtTableModel<ScriptEntry> tableModel) {
super(tableModel);
}
}

View File

@ -0,0 +1,317 @@
package org.jdownloader.extensions.eventscripter;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import jsyntaxpane.syntaxkits.JavaScriptSyntaxKit;
import org.appwork.storage.config.ValidationException;
import org.appwork.storage.config.events.GenericConfigEventListener;
import org.appwork.storage.config.handler.KeyHandler;
import org.appwork.swing.MigPanel;
import org.appwork.swing.exttable.ExtTableHeaderRenderer;
import org.appwork.swing.exttable.ExtTableModel;
import org.appwork.swing.exttable.columns.ExtCheckColumn;
import org.appwork.swing.exttable.columns.ExtComboColumn;
import org.appwork.swing.exttable.columns.ExtComponentColumn;
import org.appwork.swing.exttable.columns.ExtTextColumn;
import org.appwork.uio.CloseReason;
import org.appwork.uio.UIOManager;
import org.appwork.utils.swing.EDTRunner;
import org.appwork.utils.swing.dialog.ProgressDialog;
import org.appwork.utils.swing.dialog.ProgressDialog.ProgressGetter;
import org.appwork.utils.swing.renderer.RenderLabel;
import org.appwork.utils.swing.renderer.RendererMigPanel;
import org.jdownloader.gui.IconKey;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.images.AbstractIcon;
import org.jdownloader.images.NewTheme;
public class EventScripterTableModel extends ExtTableModel<ScriptEntry> implements GenericConfigEventListener<Object> {
private EventScripterExtension extension;
public EventScripterTableModel(EventScripterExtension extension) {
super("EventCallerTableModel");
this.extension = extension;
CFG_EVENT_CALLER.SCRIPTS.getEventSender().addListener(this);
update();
}
private void update() {
new EDTRunner() {
@Override
protected void runInEDT() {
// make sure that this class is loaded. it contains the logic to restore old settings.
ArrayList<ScriptEntry> scripts = CFG_EVENT_CALLER.CFG.getScripts();
if (scripts == null || scripts.size() == 0) {
scripts = getDefaultScriptList();
}
_fireTableStructureChanged(scripts, true);
};
};
}
protected ArrayList<ScriptEntry> getDefaultScriptList() {
ArrayList<ScriptEntry> ret = new ArrayList<ScriptEntry>();
ScriptEntry dfScript = new ScriptEntry();
dfScript.setName("Example Script");
dfScript.setEventTrigger(EventTrigger.ON_DOWNLOAD_CONTROLLER_STOPPED);
dfScript.setScript(null);
dfScript.setEnabled(false);
ret.add(dfScript);
return ret;
}
@Override
protected void initColumns() {
this.addColumn(new ExtCheckColumn<ScriptEntry>("Enabled") {
private static final long serialVersionUID = 1515656228974789237L;
public ExtTableHeaderRenderer getHeaderRenderer(final JTableHeader jTableHeader) {
final ExtTableHeaderRenderer ret = new ExtTableHeaderRenderer(this, jTableHeader) {
private static final long serialVersionUID = 3224931991570756349L;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setIcon(NewTheme.I().getIcon("ok", 14));
setHorizontalAlignment(CENTER);
setText(null);
return this;
}
};
return ret;
}
@Override
public int getMaxWidth() {
return 30;
}
@Override
public boolean isHidable() {
return false;
}
@Override
public boolean isEditable(ScriptEntry obj) {
return true;
}
@Override
protected boolean getBooleanValue(ScriptEntry value) {
return value.isEnabled();
}
@Override
protected void setBooleanValue(boolean value, ScriptEntry object) {
object.setEnabled(value);
extension.save(getTableData());
}
});
this.addColumn(new ExtTextColumn<ScriptEntry>("Name") {
@Override
public String getStringValue(ScriptEntry value) {
return value.getName();
}
@Override
protected void setStringValue(String value, ScriptEntry object) {
object.setName(value);
extension.save(getTableData());
}
@Override
public boolean isEditable(ScriptEntry obj) {
return true;
}
});
this.addColumn(new ExtComboColumn<ScriptEntry, EventTrigger>("Event", new DefaultComboBoxModel<EventTrigger>(EventTrigger.values())) {
@Override
protected String modelItemToString(EventTrigger selectedItem) {
return selectedItem.getLabel();
}
@Override
protected EventTrigger getSelectedItem(org.jdownloader.extensions.eventscripter.ScriptEntry object) {
return object.getEventTrigger();
}
@Override
protected void setSelectedItem(org.jdownloader.extensions.eventscripter.ScriptEntry object, EventTrigger value) {
object.setEventTrigger(value);
extension.save(getTableData());
}
});
this.addColumn(new ExtComponentColumn<ScriptEntry>("Edit Script") {
private JButton editorBtn;
private JButton rendererBtn;
private ScriptEntry editing;
protected MigPanel editor;
protected RendererMigPanel renderer;
private RenderLabel label;
{
editorBtn = new JButton("");
editorBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (editing != null) {
ProgressDialog p = new ProgressDialog(new ProgressGetter() {
@Override
public void run() throws Exception {
JavaScriptSyntaxKit.initKit();
}
@Override
public String getString() {
return null;
}
@Override
public int getProgress() {
return -1;
}
@Override
public String getLabelString() {
return null;
}
}, 0, "Loading Editor...", "Please wait!", null);
UIOManager.I().show(null, p);
JavaScriptEditorDialog d = new JavaScriptEditorDialog(extension, editing);
UIOManager.I().show(null, d);
if (d.getCloseReason() == CloseReason.OK) {
String script = d.getScript();
if (script != null) {
editing.setScript(script);
extension.save(getTableData());
}
}
}
}
});
label = new RenderLabel();
rendererBtn = new JButton("");
this.editor = new MigPanel("ins 1", "[grow,fill]", "[18!]") {
@Override
public void requestFocus() {
}
};
editor.add(editorBtn);
this.renderer = new RendererMigPanel("ins 1", "[grow,fill]", "[18!]");
renderer.add(rendererBtn);
setClickcount(1);
}
@Override
protected boolean isDefaultResizable() {
return false;
}
@Override
public boolean isHidable() {
return false;
}
@Override
public int getDefaultWidth() {
return 80;
}
@Override
public boolean isSortable(final ScriptEntry obj) {
return false;
}
@Override
protected JComponent getInternalEditorComponent(ScriptEntry value, boolean isSelected, int row, int column) {
return editor;
}
@Override
public boolean onSingleClick(MouseEvent e, ScriptEntry obj) {
return super.onSingleClick(e, obj);
}
@Override
protected JComponent getInternalRendererComponent(ScriptEntry value, boolean isSelected, boolean hasFocus, int row, int column) {
return renderer;
}
@Override
public boolean isEnabled(ScriptEntry obj) {
return true;
}
@Override
public void configureRendererComponent(ScriptEntry value, boolean isSelected, boolean hasFocus, int row, int column) {
rendererBtn.setIcon(new AbstractIcon(IconKey.ICON_WAIT, 16));
rendererBtn.setText(_GUI._.lit_edit());
// }
}
@Override
public void configureEditorComponent(ScriptEntry value, boolean isSelected, int row, int column) {
editing = value;
editorBtn.setIcon(new AbstractIcon(IconKey.ICON_WAIT, 16));
editorBtn.setText(_GUI._.lit_edit());
}
@Override
public void resetEditor() {
}
@Override
public void resetRenderer() {
}
});
}
@Override
public void onConfigValidatorError(KeyHandler<Object> keyHandler, Object invalidValue, ValidationException validateException) {
}
@Override
public void onConfigValueModified(KeyHandler<Object> keyHandler, Object newValue) {
update();
}
}

View File

@ -0,0 +1,39 @@
package org.jdownloader.extensions.eventscripter;
import org.appwork.txtresource.Default;
import org.appwork.txtresource.Defaults;
import org.appwork.txtresource.TranslateInterface;
@Defaults(lngs = { "en" })
public interface EventScripterTranslation extends TranslateInterface {
@Default(lngs = { "en" }, values = { "Listens to internal JDownloader event, and allows to execute relevant scripts (Javascript)" })
String description();
@Default(lngs = { "en" }, values = { "A Download started" })
String ON_DOWNLOAD_CONTROLLER_START();
@Default(lngs = { "en" }, values = { "A Download stopped" })
String ON_DOWNLOAD_CONTROLLER_STOPPED();
@Default(lngs = { "en" }, values = { "None" })
String NONE();
@Default(lngs = { "en" }, values = { "Script Editor: %s1" })
String script_editor_title(String name);
@Default(lngs = { "en" }, values = { "Do you really want to delete %s1 script(s)?" })
String sure_delete_entries(int size);
@Default(lngs = { "en" }, values = { "Security Warning!" })
String securityLoading_title();
@Default(lngs = { "en" }, values = { "Your are trying to load and execute JavaScript from %s1. Please keep in mind, that this script has full access to the current Enviroment Properties and Functions. Do only load trusted code! We recommend to only load local trusted JavaScript files." })
String securityLoading(String fileOrUrl);
@Default(lngs = { "en" }, values = { "Alert message from %s1@%s2" })
String showMessageDialog_title(String name, String trigger);
@Default(lngs = { "en" }, values = { "JDownloader started" })
String ON_JDOWNLOADER_STARTED();
}

View File

@ -0,0 +1,89 @@
package org.jdownloader.extensions.eventscripter;
import java.util.HashMap;
import java.util.Map.Entry;
import org.appwork.storage.SimpleMapper;
import org.appwork.storage.TypeRef;
import org.appwork.storage.config.annotations.LabelInterface;
import org.jdownloader.api.downloads.v2.DownloadLinkAPIStorableV2;
import org.jdownloader.api.downloads.v2.FilePackageAPIStorableV2;
public enum EventTrigger implements LabelInterface {
ON_DOWNLOAD_CONTROLLER_START {
@Override
public String getLabel() {
return T._.ON_DOWNLOAD_CONTROLLER_START();
}
public HashMap<String, Object> getTestProperties() {
HashMap<String, Object> ret = new HashMap<String, Object>();
ret.put("link", new DownloadLinkAPIStorableV2());
ret.put("package", new FilePackageAPIStorableV2());
return ret;
}
public String getAPIDescription() {
StringBuilder sb = new StringBuilder();
sb.append("// ========= Properties for the EventTrigger '" + getLabel() + "' =========\r\n");
sb.append("// DownloadLink\r\n");
SimpleMapper mapper = new SimpleMapper();
for (Entry<String, Object> es : mapper.convert(new DownloadLinkAPIStorableV2(), TypeRef.HASHMAP).entrySet()) {
sb.append("link." + es.getKey() + ";\r\n");
}
sb.append("// FilePackage \r\n");
for (Entry<String, Object> es : mapper.convert(new FilePackageAPIStorableV2(), TypeRef.HASHMAP).entrySet()) {
sb.append("package." + es.getKey() + ";\r\n");
}
return sb.toString();
}
},
ON_DOWNLOAD_CONTROLLER_STOPPED {
@Override
public String getLabel() {
return T._.ON_DOWNLOAD_CONTROLLER_STOPPED();
}
public HashMap<String, Object> getTestProperties() {
return ON_DOWNLOAD_CONTROLLER_START.getTestProperties();
}
public String getAPIDescription() {
return ON_DOWNLOAD_CONTROLLER_START.getAPIDescription();
}
},
ON_JDOWNLOADER_STARTED {
@Override
public String getLabel() {
return T._.ON_JDOWNLOADER_STARTED();
}
public HashMap<String, Object> getTestProperties() {
return NONE.getTestProperties();
}
public String getAPIDescription() {
return NONE.getAPIDescription();
}
},
NONE {
@Override
public String getLabel() {
return T._.NONE();
}
};
public String getAPIDescription() {
return "//This Event will never be Triggered.";
}
public HashMap<String, Object> getTestProperties() {
return new HashMap<String, Object>();
}
}

View File

@ -0,0 +1,27 @@
/**
* Copyright (c) 2009 - 2011 AppWork UG(haftungsbeschränkt) <e-mail@appwork.org>
*
* This file is part of org.appwork.storage.config.test
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.jdownloader.extensions.eventscripter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
public @interface GlobalField {
String description();
String[] parameters() default {};
String example() default "";
}

View File

@ -0,0 +1,311 @@
package org.jdownloader.extensions.eventscripter;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.Script;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import net.sourceforge.htmlunit.corejs.javascript.tools.shell.Global;
import org.appwork.swing.MigPanel;
import org.appwork.swing.components.ExtButton;
import org.appwork.utils.IO;
import org.appwork.utils.StringUtils;
import org.appwork.utils.swing.EDTHelper;
import org.appwork.utils.swing.EDTRunner;
import org.appwork.utils.swing.dialog.AbstractDialog;
import org.appwork.utils.swing.dialog.Dialog;
import org.appwork.utils.swing.dialog.dimensor.RememberLastDialogDimension;
import org.appwork.utils.swing.dialog.locator.RememberAbsoluteDialogLocator;
import org.jdownloader.actions.AppAction;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.scripting.JSHtmlUnitPermissionRestricter;
public class JavaScriptEditorDialog extends AbstractDialog<Object> {
private static final String CLEANUP = "[^\\w\\d\\(\\)\\+\\-\\[\\]\\;\\,/\\\\]";
private ScriptEntry entry;
private JEditorPane editor;
private org.appwork.scheduler.DelayedRunnable delayer;
private JToolBar toolbar;
private Global scope;
private MigPanel p;
private JScrollPane apiScrollbar;
private JScrollPane scrollpane;
private EventScripterExtension extension;
public JavaScriptEditorDialog(EventScripterExtension extension, ScriptEntry entry) {
super(Dialog.STYLE_HIDE_ICON, T._.script_editor_title(entry.getName()), null, _GUI._.lit_save(), null);
this.entry = entry;
this.extension = extension;
setLocator(new RememberAbsoluteDialogLocator(getClass().getSimpleName()));
setDimensor(new RememberLastDialogDimension(getClass().getSimpleName()));
}
@Override
protected ScriptEntry createReturnValue() {
return null;
}
@Override
protected int getPreferredHeight() {
return 300;
}
@Override
protected int getPreferredWidth() {
return 1024;
}
@Override
public JComponent layoutDialogContent() {
p = new MigPanel("ins 0,wrap 1", "[grow,fill]", "[][grow,fill][grow,fill]");
toolbar = new JToolBar();
toolbar.setRollover(true);
toolbar.setFloatable(false);
toolbar.setPreferredSize(new Dimension(-1, 22));
p.add(toolbar);
final JEditorPane defaults = new JEditorPane();
// defaults.setFocusable(false);
p.add(apiScrollbar = new JScrollPane(defaults) {
@Override
public Dimension getPreferredSize() {
Dimension ret = defaults.getPreferredSize();
ret.width += 10;
ret.height += 10;
return super.getPreferredSize();
}
});
defaults.setEditable(false);
defaults.setContentType("text/javascript");
defaults.setText(ScriptEnvironment.getAPIDescription() + "\r\n" + entry.getEventTrigger().getAPIDescription());
editor = new JEditorPane();
// editor.setContentType("text/html");
p.add(scrollpane = new JScrollPane(editor) {
@Override
public Dimension getPreferredSize() {
Dimension ret = editor.getPreferredSize();
ret.width += 10;
ret.height += 10;
ret.height = Math.max(ret.height, 200);
return super.getPreferredSize();
}
});
delayer = new org.appwork.scheduler.DelayedRunnable(1000, 5000) {
@Override
public void delayedrun() {
updateHighlighter();
}
};
editor.setContentType("text/javascript");
String txt = entry.getScript();
if (StringUtils.isEmpty(txt)) {
txt = "//Add your script here. Feel free to use the available api properties and methods";
}
editor.setText(txt);
delayer.resetAndStart();
// toolbar
toolbar.add(new ExtButton(new AppAction() {
{
// setIconKey(IconKey.ICON_TEXT);
setSelected(CFG_EVENT_CALLER.CFG.isAPIPanelVisible());
setName("Show/Hide Help");
}
@Override
public void actionPerformed(ActionEvent e) {
CFG_EVENT_CALLER.CFG.setAPIPanelVisible(!CFG_EVENT_CALLER.CFG.isAPIPanelVisible());
relayout();
}
}));
toolbar.add(new ExtButton(new AppAction() {
{
setName("Auto Format");
}
@Override
public void actionPerformed(ActionEvent e) {
updateHighlighter();
}
}));
toolbar.add(new ExtButton(new AppAction() {
{
setName("Test Compile");
}
@Override
public void actionPerformed(ActionEvent e) {
extension.runTestCompile(entry.getEventTrigger(), editor.getText());
}
}));
toolbar.add(new ExtButton(new AppAction() {
{
setName("Test Run");
}
@Override
public void actionPerformed(ActionEvent e) {
extension.runTest(entry.getEventTrigger(), entry.getName(), editor.getText());
}
}));
relayout();
return p;
}
protected void relayout() {
p.removeAll();
if (CFG_EVENT_CALLER.CFG.isAPIPanelVisible()) {
p.setLayout("ins 0,wrap 1", "[grow,fill]", "[][][grow,fill]");
} else {
p.setLayout("ins 0,wrap 1", "[grow,fill]", "[][grow,fill]");
}
p.add(toolbar);
if (CFG_EVENT_CALLER.CFG.isAPIPanelVisible()) {
p.add(apiScrollbar, "height 200:n:n");
}
p.add(scrollpane, "height 200:n:n");
p.revalidate();
p.repaint();
}
protected void updateHighlighter() {
final AtomicInteger caretPosition = new AtomicInteger();
String text = new EDTHelper<String>() {
@Override
public String edtRun() {
caretPosition.set(editor.getCaretPosition());
return editor.getText();
}
}.getReturnValue();
String before = text.substring(0, caretPosition.get()).replaceAll(CLEANUP, "");
final String formatedText = format(text);
if (!formatedText.equals(text)) {
for (int i = 0; i < formatedText.length(); i++) {
String sb = formatedText.substring(0, i).replaceAll(CLEANUP, "");
if (sb.length() == before.length()) {
final int caret = i;
new EDTRunner() {
@Override
protected void runInEDT() {
editor.setText(formatedText);
editor.setCaretPosition(caret);
}
}.waitForEDT();
return;
}
}
new EDTRunner() {
@Override
protected void runInEDT() {
editor.setText(formatedText);
}
}.waitForEDT();
}
}
private synchronized String format(String script) {
try {
Context cx = Context.enter();
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
if (scope == null) {
scope = new Global();
scope.init(cx);
String lib;
lib = IO.readURLToString(ScriptEntry.class.getResource("js_beautifier.js"));
Script compiledLibrary = JSHtmlUnitPermissionRestricter.compileTrustedString(cx, scope, lib, "", 1, null);
JSHtmlUnitPermissionRestricter.evaluateTrustedString(cx, scope, "global=this;", "", 1, null);
compiledLibrary.exec(cx, scope);
}
//
// Class[] classes = new Class[] { Boolean.class, Integer.class, Long.class, String.class, Double.class, Float.class,
// net.sourceforge.htmlunit.corejs.javascript.EcmaError.class, ProcessRunner.class, DownloadLinkAPIStorableV2.class };
// String preloadClasses = "";
// for (Class c : classes) {
// preloadClasses += "load=" + c.getName() + ";\r\n";
// }
// preloadClasses += "var call=" + ProcessRunner.class.getName() + ".call;var alert=" + ProcessRunner.class.getName() +
// ".alert;delete load;";
ScriptableObject.putProperty(scope, "text", script);
String formated = (String) JSHtmlUnitPermissionRestricter.evaluateTrustedString(cx, scope, "js_beautify(text, { });", "", 1, null);
return formated;
// ProcessBuilderFactory.runCommand(commandline);
} catch (Throwable e) {
e.printStackTrace();
} finally {
Context.exit();
}
return script;
}
@Override
protected boolean isResizable() {
return true;
}
public void pack() {
this.getDialog().pack();
}
public String getScript() {
return new EDTHelper<String>() {
@Override
public String edtRun() {
return editor.getText();
}
}.getReturnValue();
}
}

View File

@ -0,0 +1,23 @@
/**
* Copyright (c) 2009 - 2011 AppWork UG(haftungsbeschränkt) <e-mail@appwork.org>
*
* This file is part of org.appwork.storage.config.test
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.jdownloader.extensions.eventscripter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface Parameters {
String[] value();
}

View File

@ -0,0 +1,51 @@
package org.jdownloader.extensions.eventscripter;
import org.appwork.storage.Storable;
public class ScriptEntry implements Storable {
public ScriptEntry(/* Storable */) {
}
private EventTrigger eventTrigger;
private boolean enabled;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
private String script;
public EventTrigger getEventTrigger() {
if (eventTrigger == null) {
return EventTrigger.NONE;
}
return eventTrigger;
}
public void setEventTrigger(EventTrigger eventTrigger) {
this.eventTrigger = eventTrigger;
}
}

View File

@ -0,0 +1,243 @@
package org.jdownloader.extensions.eventscripter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;
import javax.swing.JTextPane;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.NativeJSON;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import org.appwork.storage.JSonStorage;
import org.appwork.storage.jackson.JacksonMapper;
import org.appwork.uio.ConfirmDialogInterface;
import org.appwork.uio.UIOManager;
import org.appwork.utils.Application;
import org.appwork.utils.Exceptions;
import org.appwork.utils.StringUtils;
import org.appwork.utils.os.CrossSystem;
import org.appwork.utils.os.CrossSystem.OSFamily;
import org.appwork.utils.processes.ProcessBuilderFactory;
import org.appwork.utils.processes.ProcessOutput;
import org.appwork.utils.reflection.Clazz;
import org.appwork.utils.swing.dialog.ConfirmDialog;
import org.jdownloader.api.RemoteAPIController;
import org.jdownloader.gui.IconKey;
import org.jdownloader.images.AbstractIcon;
public class ScriptEnvironment {
@GlobalField(description = "JDownloader Installation Directory")
public static String JD_HOME = Application.getResource("").getAbsolutePath();
@GlobalField(description = "Call the MyJDownloader API", parameters = { "\"namespace\"", "\"methodname\"", "parameter1", "parameter2", "..." }, example = "callAPI(\"downloadsV2\", \"queryLinks\", { \"name\": true})")
public static Object callAPI(String namespace, String method, Object... parameters) throws EnvironmentException {
String js;
try {
Object ret = RemoteAPIController.getInstance().call(namespace, method, parameters);
final ScriptThread env = getScriptThread();
// convert to javascript object
js = "(function(){ return " + JSonStorage.serializeToJson(ret) + ";}());";
Object retObject = env.evalTrusted(js);
return retObject;
} catch (Throwable e) {
throw new EnvironmentException(e);
}
}
@GlobalField(description = "Show a Message Box", parameters = { "myObject1", "MyObject2", "..." }, example = "alert(JD_HOME);")
public static void alert(Object... objects) {
final ScriptThread env = getScriptThread();
if (objects.length == 1) {
if (Clazz.isPrimitiveWrapper(objects[0].getClass()) || Clazz.isString(objects[0].getClass())) {
showMessageDialog(objects[0] + "");
return;
} else {
try {
showMessageDialog(new JacksonMapper().objectToString(objects[0]));
} catch (Throwable e) {
showMessageDialog(format(NativeJSON.stringify(env.getContext(), env.getScope(), objects[0], null, null) + ""));
}
return;
}
}
try {
showMessageDialog(new JacksonMapper().objectToString(objects));
} catch (Throwable e) {
showMessageDialog(format(NativeJSON.stringify(env.getContext(), env.getScope(), objects, null, null) + ""));
}
return;
}
private static String format(String js) {
final ScriptThread env = getScriptThread();
try {
env.ensureLibrary("js_beautifier.js");
String parametername;
ScriptableObject.putProperty(env.getScope(), parametername = "text_" + System.currentTimeMillis(), js);
String ret = env.evalTrusted("js_beautify(" + parametername + ", { });") + "";
return ret;
} catch (Throwable e) {
e.printStackTrace();
}
return js;
}
private static void showMessageDialog(String string) {
final ScriptThread env = getScriptThread();
UIOManager.I().show(ConfirmDialogInterface.class, new ConfirmDialog(UIOManager.BUTTONS_HIDE_CANCEL | ConfirmDialog.STYLE_SCROLLPANE, T._.showMessageDialog_title(env.getScript().getName(), env.getScript().getEventTrigger().getLabel()), string, new AbstractIcon(IconKey.ICON_INFO, 32), null, null) {
@Override
protected void modifyTextPane(JTextPane textField) {
}
@Override
public void pack() {
this.getDialog().pack();
}
@Override
protected int getPreferredWidth() {
return 600;
}
});
}
@GlobalField(description = "Loads a Javascript file or url. ATTENTION. The loaded script can access the API as well.", parameters = { "myFilePathOrUrl" }, example = "require(\"https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json.js\");")
public static void require(String fileOrUrl) throws EnvironmentException {
try {
getScriptThread().requireJavascript(fileOrUrl);
} catch (Throwable e) {
throw new EnvironmentException(e);
}
}
@GlobalField(description = "Call a local Process asynchronous", parameters = { "\"myCallBackFunction\"|null", "\"commandline1\"", "\"commandline2\"", "\"...\"" }, example = "callAsync(function(exitCode,stdOut,errOut){ alert(\"Closed Notepad\");},\"notepad.exe\",JD_HOME+\"\\\\license.txt\");")
public static void callAsync(final Function callback, final String... commands) throws EnvironmentException {
try {
final ScriptThread env = getScriptThread();
if (commands != null && commands.length > 0) {
new ScriptReferenceThread(env) {
@Override
public void run() {
try {
try {
ProcessOutput ret = ProcessBuilderFactory.runCommand(commands);
if (callback != null) {
if (CrossSystem.getOSFamily() == OSFamily.WINDOWS) {
executeCallback(callback, ret.getExitCode(), new String(new String(ret.getStdOutData(), "cp850").getBytes("UTF-8"), "UTF-8"), new String(new String(ret.getErrOutData(), "cp850").getBytes("UTF-8"), "UTF-8"));
} else {
executeCallback(callback, ret.getExitCode(), new String(ret.getStdOutData(), "UTF-8"), new String(ret.getErrOutData(), "UTF-8"));
}
}
} catch (IOException e) {
if (callback != null) {
executeCallback(callback, -1, null, Exceptions.getStackTrace(e));
}
env.getLogger().log(e);
env.notifyAboutException(e);
}
} catch (Throwable e) {
env.notifyAboutException(e);
}
}
}.start();
}
} catch (Throwable e) {
throw new EnvironmentException(e);
}
}
private static ScriptThread getScriptThread() {
Thread ct = Thread.currentThread();
if (ct instanceof ScriptThread) {
return (ScriptThread) ct;
} else if (ct instanceof ScriptReferenceThread) {
return ((ScriptReferenceThread) ct).getScriptThread();
} else {
throw new IllegalStateException();
}
}
@GlobalField(description = "Call a local Process. Blocks Until the process returns", parameters = { "\"commandline1\"", "\"commandline2\"", "\"...\"" }, example = "var pingResult = callSync(\"ping\",\"jdownloader.org\");")
public static String callSync(final String... commands) throws EnvironmentException {
try {
ProcessBuilder pb = ProcessBuilderFactory.create(commands);
pb.redirectErrorStream();
ProcessOutput ret = ProcessBuilderFactory.runCommand(pb);
if (CrossSystem.getOSFamily() == OSFamily.WINDOWS) {
return new String(new String(ret.getStdOutData(), "cp850").getBytes("UTF-8"), "UTF-8");
} else {
return ret.getStdOutString("UTF-8");
}
} catch (Throwable e) {
throw new EnvironmentException(e);
}
}
public static String getAPIDescription() {
StringBuilder sb = new StringBuilder();
sb.append("// ========= Global Methods =========\r\n");
for (Method f : ScriptEnvironment.class.getDeclaredMethods()) {
GlobalField ann = f.getAnnotation(GlobalField.class);
if (ann != null) {
sb.append("//").append(ann.description()).append("\r\n");
if (!Clazz.isVoid(f.getReturnType())) {
sb.append("// var my").append(f.getReturnType().getSimpleName().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(f.getReturnType().getSimpleName().substring(1)).append(" = ");
} else {
sb.append("// ");
}
sb.append(f.getName()).append("(");
boolean first = true;
if (ann.parameters() != null) {
for (String s : ann.parameters()) {
if (!first) {
sb.append(", ");
}
sb.append(s);
first = false;
}
}
sb.append(");\r\n");
if (StringUtils.isNotEmpty(ann.example())) {
sb.append(ann.example()).append("\r\n");
}
}
}
sb.append("// ========= Global Properties =========\r\n");
for (Field f : ScriptEnvironment.class.getDeclaredFields()) {
GlobalField ann = f.getAnnotation(GlobalField.class);
if (ann != null) {
sb.append("var my").append(f.getType().getSimpleName().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(f.getType().getSimpleName().substring(1)).append(" = ");
sb.append(ann.description()).append(";\r\n");
if (StringUtils.isNotEmpty(ann.example())) {
sb.append(ann.example()).append("\r\n");
}
}
}
return sb.toString();
}
}

View File

@ -0,0 +1,27 @@
package org.jdownloader.extensions.eventscripter;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.Function;
public class ScriptReferenceThread extends Thread {
private ScriptThread scriptThread;
public ScriptThread getScriptThread() {
return scriptThread;
}
public ScriptReferenceThread(ScriptThread env) {
this.scriptThread = env;
}
public void executeCallback(Function callback, Object... params) {
Context cx = Context.enter();
try {
callback.call(cx, getScriptThread().getScope(), getScriptThread().getScope(), params);
} finally {
Context.exit();
}
}
}

View File

@ -0,0 +1,235 @@
package org.jdownloader.extensions.eventscripter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import jd.http.Browser;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import net.sourceforge.htmlunit.corejs.javascript.tools.shell.Global;
import org.appwork.exceptions.WTFException;
import org.appwork.storage.SimpleMapper;
import org.appwork.uio.CloseReason;
import org.appwork.uio.UIOManager;
import org.appwork.utils.IO;
import org.appwork.utils.logging2.LogSource;
import org.appwork.utils.swing.dialog.ConfirmDialog;
import org.appwork.utils.swing.dialog.Dialog;
import org.jdownloader.gui.IconKey;
import org.jdownloader.images.AbstractIcon;
import org.jdownloader.scripting.JSHtmlUnitPermissionRestricter;
public class ScriptThread extends Thread {
private ScriptEntry script;
private HashMap<String, Object> props;
private Global scope;
private Context cx;
private LogSource logger;
private ScriptThread delegate;
public LogSource getLogger() {
return logger;
}
public ScriptThread(ScriptEntry script, HashMap<String, Object> props, LogSource logSource) {
this.script = script;
this.props = props;
this.logger = logSource;
}
@Override
public void run() {
scope = new Global();
cx = Context.enter();
cx.setOptimizationLevel(-1);
scope.init(cx);
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
try {
String preloadClasses = preInitClasses();
evalTrusted(preloadClasses);
// required by some libraries
evalTrusted("global=this;");
cleanupClasses();
initEnvironment();
evalUNtrusted(script.getScript());
// ProcessBuilderFactory.runCommand(commandline);
} catch (Throwable e) {
logger.log(e);
notifyAboutException(e);
} finally {
Context.exit();
}
}
public void notifyAboutException(Throwable e) {
Dialog.getInstance().showExceptionDialog("An Error Occured", e.getMessage(), e);
}
private String preInitClasses() {
Class[] classes = new Class[] { Boolean.class, Integer.class, Long.class, String.class, Double.class, Float.class, net.sourceforge.htmlunit.corejs.javascript.EcmaError.class, ScriptEnvironment.class, EnvironmentException.class };
String preloadClasses = "";
for (Class c : classes) {
preloadClasses += "load=" + c.getName() + ";\r\n";
}
for (Entry<String, Object> es : props.entrySet()) {
preloadClasses += "load=" + es.getValue().getClass().getName() + ";\r\n";
}
for (Method f : ScriptEnvironment.class.getDeclaredMethods()) {
if (f.getAnnotation(GlobalField.class) != null) {
preloadClasses += "var " + f.getName() + "=" + ScriptEnvironment.class.getName() + "." + f.getName() + ";";
}
}
preloadClasses += "delete load;";
return preloadClasses;
}
private void initEnvironment() throws IllegalAccessException {
for (Field f : ScriptEnvironment.class.getDeclaredFields()) {
if (f.getAnnotation(GlobalField.class) != null) {
evalTrusted(f.getName() + " = " + new SimpleMapper().objectToString(f.get(null)) + ";");
}
}
for (Entry<String, Object> es : props.entrySet()) {
// convert to real js objects
evalTrusted(es.getKey() + " = " + new SimpleMapper().objectToString(es.getValue()) + ";");
}
}
private void evalUNtrusted(String script) {
cx.evaluateString(getScope(), script, "", 1, null);
}
public Object evalTrusted(String preloadClasses) {
return JSHtmlUnitPermissionRestricter.evaluateTrustedString(cx, getScope(), preloadClasses, "", 1, null);
}
private void cleanupClasses() {
ArrayList<String> list = new ArrayList<String>(JSHtmlUnitPermissionRestricter.LOADED);
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
// Cleanup
ScriptableObject.deleteProperty(scope, "Packages");
for (String s : list) {
while (true) {
System.out.println("Delete " + s);
try {
ScriptableObject.deleteProperty(scope, s);
} catch (Throwable e) {
// e.printStackTrace();
}
int index = s.lastIndexOf(".");
if (index > 0) {
s = s.substring(0, index);
} else {
break;
}
}
}
}
public void requireJavascript(String fileOrUrl) throws IOException {
ConfirmDialog d = new ConfirmDialog(0 | Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN | UIOManager.LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL, T._.securityLoading_title(), T._.securityLoading(fileOrUrl), new AbstractIcon(IconKey.ICON_SERVER, 32), null, null) {
@Override
public String getDontShowAgainKey() {
return super.getDontShowAgainKey();
}
@Override
protected int getPreferredWidth() {
return 600;
}
public void windowClosing(final WindowEvent arg0) {
setReturnmask(false);
this.dispose();
}
};
d.setDoNotShowAgainSelected(true);
// Integer ret = JSonStorage.getPlainStorage("Dialogs").get(d.getDontShowAgainKey(), -1);
// if (ret != null && ret > 0) {
// return;
// }
if (d.show().getCloseReason() == CloseReason.OK) {
if (fileOrUrl.matches("^https?\\:\\/\\/.+")) {
// url
Browser br = new Browser();
String js = br.getPage(fileOrUrl);
logger.info(js);
evalUNtrusted(js);
} else {
String js = IO.readFileToString(new File(fileOrUrl));
logger.info(js);
evalUNtrusted(js);
}
}
}
public Context getContext() {
return cx;
}
public Global getScope() {
return scope;
}
public ScriptEntry getScript() {
return script;
}
private HashSet<String> loadedLibrary = new HashSet<String>();
public void ensureLibrary(String string) {
synchronized (this) {
if (loadedLibrary.add(string)) {
try {
evalTrusted(IO.readURLToString(ScriptEntry.class.getResource(string)));
} catch (IOException e) {
throw new WTFException(e);
}
}
}
}
}

View File

@ -0,0 +1,8 @@
package org.jdownloader.extensions.eventscripter;
import org.appwork.txtresource.TranslationFactory;
public class T {
public static final EventScripterTranslation _ = TranslationFactory.create(EventScripterTranslation.class);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
package org.jdownloader.gui.views.components;
import org.jdownloader.actions.AppAction;
import org.jdownloader.gui.translate._GUI;
public abstract class AbstractRemoveAction extends AppAction {
public AbstractRemoveAction() {
super();
setName(_GUI._.literally_remove());
setIconKey("remove");
}
}

View File

@ -303,4 +303,15 @@ public class JSHtmlUnitPermissionRestricter {
return CONTEXT_FACTORY.makeContext(contextCallback);
}
public static Script compileTrustedString(Context cx, Global scope, String source, String sourceName, int lineno, Object securityDomain) {
try {
TRUSTED_THREAD.put(Thread.currentThread(), true);
return cx.compileString(source, sourceName, lineno, securityDomain);
} finally {
TRUSTED_THREAD.remove(Thread.currentThread());
}
}
}