Search in sources :

Example 1 with ExtensionInfo

use of org.pdown.gui.extension.ExtensionInfo in project proxyee-down by monkeyWie.

the class HttpDownAppCallback method commonHook.

private void commonHook(HttpDownBootstrap httpDownBootstrap, String event, boolean async) {
    DownInfo downInfo = findDownInfo(httpDownBootstrap);
    Map<String, Object> taskInfo = buildTaskInfo(downInfo);
    if (taskInfo != null) {
        // 遍历扩展模块是否有对应的处理
        List<ExtensionInfo> extensionInfos = ExtensionContent.get();
        for (ExtensionInfo extensionInfo : extensionInfos) {
            if (extensionInfo.getMeta().isEnabled()) {
                if (extensionInfo.getHookScript() != null && !StringUtils.isEmpty(extensionInfo.getHookScript().getScript())) {
                    Event e = extensionInfo.getHookScript().hasEvent(event, HttpDownUtil.getUrl(httpDownBootstrap.getRequest()));
                    if (e != null) {
                        try {
                            // 执行钩子函数
                            Object result = ExtensionUtil.invoke(extensionInfo, e, taskInfo, async);
                            if (result != null) {
                                ObjectMapper objectMapper = new ObjectMapper();
                                String temp = objectMapper.writeValueAsString(result);
                                TaskForm taskForm = objectMapper.readValue(temp, TaskForm.class);
                                if (taskForm.getRequest() != null) {
                                    httpDownBootstrap.setRequest(HttpDownUtil.buildRequest(taskForm.getRequest().getMethod(), taskForm.getRequest().getUrl(), taskForm.getRequest().getHeads(), taskForm.getRequest().getBody()));
                                }
                                if (taskForm.getResponse() != null) {
                                    httpDownBootstrap.setResponse(taskForm.getResponse());
                                }
                                if (taskForm.getData() != null) {
                                    downInfo.setData(taskForm.getData());
                                }
                                HttpDownContent.getInstance().save();
                            }
                        } catch (Exception ex) {
                            LOGGER.error("An hook exception occurred while " + event + "()", ex);
                        }
                    }
                }
            }
        }
    }
}
Also used : DownInfo(org.pdown.rest.entity.DownInfo) ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) TaskForm(org.pdown.rest.form.TaskForm) Event(org.pdown.gui.extension.HookScript.Event) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with ExtensionInfo

use of org.pdown.gui.extension.ExtensionInfo in project proxyee-down by monkeyWie.

the class ExtensionUtil method invoke.

/**
 * 运行一个js方法
 */
public static Object invoke(ExtensionInfo extensionInfo, Event event, Object param, boolean async) throws NoSuchMethodException, ScriptException, FileNotFoundException, InterruptedException {
    // 初始化js引擎
    ScriptEngine engine = ExtensionUtil.buildExtensionRuntimeEngine(extensionInfo);
    Invocable invocable = (Invocable) engine;
    // 执行resolve方法
    Object result = invocable.invokeFunction(StringUtils.isEmpty(event.getMethod()) ? event.getOn() : event.getMethod(), param);
    // 结果为null或者异步调用直接返回
    if (result == null || async) {
        return result;
    }
    final Object[] ret = { null };
    // 判断是不是返回Promise对象
    ScriptContext ctx = new SimpleScriptContext();
    ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE);
    boolean isPromise = (boolean) engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx);
    if (isPromise) {
        // 如果是返回的Promise则等待执行完成
        CountDownLatch countDownLatch = new CountDownLatch(1);
        invocable.invokeMethod(result, "then", (Function) o -> {
            try {
                ret[0] = o;
            } catch (Exception e) {
                LOGGER.error("An exception occurred while resolve()", e);
            } finally {
                countDownLatch.countDown();
            }
            return null;
        });
        invocable.invokeMethod(result, "catch", (Function) o -> {
            countDownLatch.countDown();
            return null;
        });
        // 等待解析完成
        countDownLatch.await();
    } else {
        ret[0] = result;
    }
    return ret[0];
}
Also used : ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) LoggerFactory(org.slf4j.LoggerFactory) TaskForm(org.pdown.rest.form.TaskForm) SimpleScriptContext(javax.script.SimpleScriptContext) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) FileUtil(org.pdown.core.util.FileUtil) Meta(org.pdown.gui.extension.Meta) Event(org.pdown.gui.extension.HookScript.Event) Path(java.nio.file.Path) ScriptException(javax.script.ScriptException) ExtensionContent(org.pdown.gui.extension.ExtensionContent) OutputStream(java.io.OutputStream) NativeController(org.pdown.gui.http.controller.NativeController) Logger(org.slf4j.Logger) Files(java.nio.file.Files) DownApplication(org.pdown.gui.DownApplication) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) HookScript(org.pdown.gui.extension.HookScript) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ScriptContext(javax.script.ScriptContext) ConfigUtil(org.pdown.gui.util.ConfigUtil) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHandlerUtil(org.pdown.gui.http.util.HttpHandlerUtil) Invocable(javax.script.Invocable) AppUtil(org.pdown.gui.util.AppUtil) Paths(java.nio.file.Paths) ScriptEngine(javax.script.ScriptEngine) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) JavascriptEngine(org.pdown.gui.extension.jsruntime.JavascriptEngine) PDownConfigContent(org.pdown.gui.content.PDownConfigContent) InputStream(java.io.InputStream) StringUtils(org.springframework.util.StringUtils) Invocable(javax.script.Invocable) SimpleScriptContext(javax.script.SimpleScriptContext) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) CountDownLatch(java.util.concurrent.CountDownLatch) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 3 with ExtensionInfo

use of org.pdown.gui.extension.ExtensionInfo in project proxyee-down by monkeyWie.

the class NativeController method onResolve.

@RequestMapping("onResolve")
public FullHttpResponse onResolve(Channel channel, FullHttpRequest request) throws Exception {
    HttpRequestForm taskRequest = getJSONParams(request, HttpRequestForm.class);
    // 遍历扩展模块是否有对应的处理
    List<ExtensionInfo> extensionInfos = ExtensionContent.get();
    for (ExtensionInfo extensionInfo : extensionInfos) {
        if (extensionInfo.getMeta().isEnabled()) {
            if (extensionInfo.getHookScript() != null && !StringUtils.isEmpty(extensionInfo.getHookScript().getScript())) {
                Event event = extensionInfo.getHookScript().hasEvent(HookScript.EVENT_RESOLVE, taskRequest.getUrl());
                if (event != null) {
                    try {
                        // 执行resolve方法
                        Object result = ExtensionUtil.invoke(extensionInfo, event, taskRequest, false);
                        if (result != null && !(result instanceof Undefined)) {
                            ObjectMapper objectMapper = new ObjectMapper();
                            String temp = objectMapper.writeValueAsString(result);
                            TaskForm taskForm = objectMapper.readValue(temp, TaskForm.class);
                            // 有一个扩展解析成功的话直接返回
                            return HttpHandlerUtil.buildJson(taskForm, Include.NON_DEFAULT);
                        }
                    } catch (Exception e) {
                        LOGGER.error("An exception occurred while resolve()", e);
                    }
                }
            }
        }
    }
    return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
}
Also used : Undefined(jdk.nashorn.internal.runtime.Undefined) ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) HttpRequestForm(org.pdown.rest.form.HttpRequestForm) TaskForm(org.pdown.rest.form.TaskForm) Event(org.pdown.gui.extension.HookScript.Event) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with ExtensionInfo

use of org.pdown.gui.extension.ExtensionInfo in project proxyee-down by monkeyWie.

the class NativeController method installLocalExtension.

/**
 * 加载本地扩展
 */
@RequestMapping("installLocalExtension")
public FullHttpResponse installLocalExtension(Channel channel, FullHttpRequest request) throws Exception {
    Map<String, Object> data = new HashMap<>();
    Map<String, Object> map = getJSONParams(request);
    String path = (String) map.get("path");
    // 刷新扩展content
    ExtensionInfo loadExt = ExtensionContent.refresh(path, true);
    if (loadExt == null) {
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
    }
    data.put("data", loadExt);
    // 刷新系统pac代理
    AppUtil.refreshPAC();
    return HttpHandlerUtil.buildJson(data);
}
Also used : HashMap(java.util.HashMap) ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with ExtensionInfo

use of org.pdown.gui.extension.ExtensionInfo in project proxyee-down by monkeyWie.

the class NativeController method toggleExtension.

/**
 * 启用或禁用插件
 */
@RequestMapping("toggleExtension")
public FullHttpResponse toggleExtension(Channel channel, FullHttpRequest request) throws Exception {
    Map<String, Object> map = getJSONParams(request);
    String path = (String) map.get("path");
    boolean enabled = (boolean) map.get("enabled");
    boolean local = map.get("local") != null ? (boolean) map.get("local") : false;
    ExtensionInfo extensionInfo = ExtensionContent.get().stream().filter(e -> e.getMeta().getPath().equals(path)).findFirst().get();
    extensionInfo.getMeta().setEnabled(enabled).save();
    // 刷新pac
    ExtensionContent.refresh(extensionInfo.getMeta().getFullPath(), local);
    AppUtil.refreshPAC();
    return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
}
Also used : ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ExtensionInfo (org.pdown.gui.extension.ExtensionInfo)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 IOException (java.io.IOException)3 Event (org.pdown.gui.extension.HookScript.Event)3 TaskForm (org.pdown.rest.form.TaskForm)3 File (java.io.File)2 HashMap (java.util.HashMap)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 BufferedReader (java.io.BufferedReader)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1