]> git.basschouten.com Git - openhab-addons.git/blob
d2d14011426d9b1e7e6c6b51861ddb4ed06e2732
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.automation.jsscripting.internal;
14
15 import java.io.IOException;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.Optional;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.graalvm.polyglot.Context;
22 import org.graalvm.polyglot.Source;
23 import org.graalvm.polyglot.Value;
24 import org.openhab.automation.jsscripting.internal.threading.ThreadsafeWrappingScriptedAutomationManagerDelegate;
25 import org.openhab.core.automation.module.script.ScriptExtensionAccessor;
26 import org.openhab.core.automation.module.script.rulesupport.shared.ScriptedAutomationManager;
27
28 /**
29  * Class providing script extensions via CommonJS modules.
30  *
31  * @author Jonathan Gilbert - Initial contribution
32  */
33
34 @NonNullByDefault
35 public class ScriptExtensionModuleProvider {
36
37     private static final String RUNTIME_MODULE_PREFIX = "@runtime";
38     private static final String DEFAULT_MODULE_NAME = "Defaults";
39
40     private final ScriptExtensionAccessor scriptExtensionAccessor;
41
42     public ScriptExtensionModuleProvider(ScriptExtensionAccessor scriptExtensionAccessor) {
43         this.scriptExtensionAccessor = scriptExtensionAccessor;
44     }
45
46     public ModuleLocator locatorFor(Context ctx, String engineIdentifier) {
47         return name -> {
48             String[] segments = name.split("/");
49             if (segments[0].equals(RUNTIME_MODULE_PREFIX)) {
50                 if (segments.length == 1) {
51                     return runtimeModule(DEFAULT_MODULE_NAME, engineIdentifier, ctx);
52                 } else {
53                     return runtimeModule(segments[1], engineIdentifier, ctx);
54                 }
55             }
56
57             return Optional.empty();
58         };
59     }
60
61     private Optional<Value> runtimeModule(String name, String scriptIdentifier, Context ctx) {
62
63         Map<String, Object> symbols;
64
65         if (DEFAULT_MODULE_NAME.equals(name)) {
66             symbols = scriptExtensionAccessor.findDefaultPresets(scriptIdentifier);
67         } else {
68             symbols = scriptExtensionAccessor.findPreset(name, scriptIdentifier);
69         }
70
71         return Optional.of(symbols).map(this::processValues).map(v -> toValue(ctx, v));
72     }
73
74     private Value toValue(Context ctx, Map<String, Object> map) {
75         try {
76             return ctx.eval(Source.newBuilder( // convert to Map to JS Object
77                     "js",
78                     "(function (mapOfValues) {\n" + "let rv = {};\n" + "for (var key in mapOfValues) {\n"
79                             + "    rv[key] = mapOfValues.get(key);\n" + "}\n" + "return rv;\n" + "})",
80                     "<generated>").build()).execute(map);
81         } catch (IOException e) {
82             throw new IllegalArgumentException("Failed to generate exports", e);
83         }
84     }
85
86     /**
87      * Some specific objects need wrapping when exposed to a GraalJS environment. This method does this.
88      *
89      * @param values the map of names to values of things to process
90      * @return a map of the processed keys and values
91      */
92     private Map<String, Object> processValues(Map<String, Object> values) {
93         Map<String, Object> rv = new HashMap<>(values);
94
95         for (Map.Entry<String, Object> entry : rv.entrySet()) {
96             if (entry.getValue() instanceof ScriptedAutomationManager) {
97                 entry.setValue(new ThreadsafeWrappingScriptedAutomationManagerDelegate(
98                         (ScriptedAutomationManager) entry.getValue()));
99             }
100         }
101
102         return rv;
103     }
104 }