File size: 10,538 Bytes
19c8b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import json
import traceback


class PluginManager(object):

    def __init__(self, APP_VERSION, PROD, CPU_ONLY, logger):
        super(PluginManager, self).__init__()

        self.APP_VERSION = APP_VERSION
        self.CPU_ONLY = CPU_ONLY
        self.PROD = PROD
        self.path = "./resources/app" if PROD else "."
        self.modules_path = "resources.app." if PROD else ""
        self.logger = logger
        self.setupModules = set()
        self.enabledPlugins = set()
        self.teardownModules = {}
        self.refresh_active_plugins()

    def reset_plugins (self):
        self.plugins = {
            "custom-event": [],
            "start": {
                "pre": [],
                "mid": [],
                "post": []
            },
            "load-model": {
                "pre": [],
                "mid": [],
                "post": []
            },
            "synth-line": {
                "pre": [],
                "mid": [],
                "pre_energy": [],
                "post": []
            },
            "batch-synth-line": {
                "pre": [],
                "mid": [],
                "post": []
            },
            "mp-output-audio": {
                "pre": [],
                "post": []
            },
            "arpabet-replace": {
                "pre": [],
                "post": []
            },
            "output-audio": {
                "pre": [],
                "mid": [],
                "post": []
            },
        }

        self.plugins_context_cache = {}
        for key in self.plugins.keys():
            if key=="custom-event":
                pass
            else:
                self.plugins_context_cache[key] = {}
                for sub_key in self.plugins[key].keys():
                    self.plugins_context_cache[key][sub_key] = {}

    def set_context_cache (self, event, hook, plugin_id, data):
        self.plugins_context_cache[event][hook][plugin_id] = data


    def get_active_plugins_count (self):
        active_plugins = []

        for _ in self.plugins["custom-event"]:
            active_plugins.append(["custom-event", None])

        for key in self.plugins.keys():
            if key=="custom-event":
                continue
            plugin_triggers = list(self.plugins[key].keys())

            for trigger_type in plugin_triggers:
                for plugin in self.plugins[key][trigger_type]:
                    active_plugins.append([key, trigger_type])
        return len(active_plugins)

    # For ease of access
    def set_context (self, data):
        self.context = data


    def refresh_active_plugins (self):

        with open("plugins.txt") as f:
            lines = f.read().split("\n")

        removed_plugins = []
        for line in lines:
            if not line.startswith("*") and line in self.enabledPlugins:
                removed_plugins.append(line)

        for plugin_id in removed_plugins:
            if plugin_id in self.teardownModules:
                for func in self.teardownModules[plugin_id]:
                    params = {"logger": self.logger, "appVersion": self.APP_VERSION, "isCPUonly": self.CPU_ONLY, "isDev": not self.PROD}
                    func(params)

        self.reset_plugins()
        status = []


        for line in lines:
            if line.startswith("*"):
                plugin_id = line[1:]
                self.logger.info(f'plugin_id: {plugin_id}')
                try:
                    with open(f'{self.path}/plugins/{plugin_id}/plugin.json') as f:
                        plugin_json = f.read()
                        plugin_json = json.loads(plugin_json)

                        minVersionOk = checkVersionRequirements(plugin_json["min-app-version"] if "min-app-version" in plugin_json else None, self.APP_VERSION)
                        maxVersionOk = checkVersionRequirements(plugin_json["max-app-version"] if "max-app-version" in plugin_json else None, self.APP_VERSION, True)

                        if not minVersionOk or not maxVersionOk:
                            self.logger.info(f'minVersionOk {minVersionOk}')
                            self.logger.info(f'maxVersionOk {maxVersionOk}')
                            continue


                        for key in self.plugins.keys():
                            if key=="custom-event":
                                self.load_module_function(plugin_json, plugin_id, ["back-end-hooks", "custom-event"], [])
                            else:
                                plugin_triggers = list(self.plugins[key].keys())

                                for trigger_type in plugin_triggers:
                                    self.load_module_function(plugin_json, plugin_id, ["back-end-hooks", key, trigger_type], [])

                        self.enabledPlugins.add(plugin_id)

                    status.append("OK")
                except:
                    self.logger.info(traceback.format_exc())
                    status.append(plugin_id)

        return status

    def load_module_function (self, plugin_json, plugin_name, structure, structure2):

        if structure[0] in plugin_json and plugin_json[structure[0]] is not None:
            key = structure[0]
            structure2.append(key)
            plugin_json = plugin_json[key]
            del structure[0]
            if len(structure):
                return self.load_module_function(plugin_json, plugin_name, structure, structure2)
            else:
                file_name = plugin_json["file"]
                function = plugin_json["function"]

                if not file_name:
                    return

                if file_name.endswith(".py"):
                    setup = {"logger": self.logger, "appVersion": self.APP_VERSION, "isCPUonly": self.CPU_ONLY, "isDev": not self.PROD}

                    with open(f'{self.path}/plugins/{plugin_name}/{file_name}') as f:

                        locals_data = locals()
                        locals_data["setupData"] = setup
                        locals_data["plugins"] = self.plugins

                        exec(f.read(), None, locals_data)

                        import types
                        for key in list(locals_data.keys()):
                            if isinstance(locals_data[key], types.FunctionType):
                                if key==function:
                                    if structure2[-1]=="custom-event":
                                        self.plugins[structure2[-1]].append([plugin_name, file_name, locals_data[key]])
                                    else:
                                        self.plugins[structure2[-2]][structure2[-1]].append([plugin_name, file_name, locals_data[key]])
                                elif key=="setup":
                                    if f'{plugin_name}/{file_name}' not in self.setupModules:
                                        self.setupModules.add(f'{plugin_name}/{file_name}')
                                        locals_data[key](setup)
                                elif key=="teardown":
                                    if plugin_name not in self.teardownModules.keys():
                                        self.teardownModules[plugin_name] = []
                                    self.teardownModules[plugin_name].append(locals_data[key])


                else:
                    self.logger.info(f'[Plugin: {plugin_name}]: Cannot import {file_name} file for {structure2[-1]} {structure2[-2]} entry-point: Only python files are supported right now.')


    def run_plugins (self, plist, event="", data=None):
        response = None
        if event=="custom-event" and "pluginId" not in data:
            self.logger.info(f'Custom event called, but "pluginId" not specified. Not running.')
            return None

        if len(plist):
            self.logger.info("Running plugins for event:" + event)

        for [plugin_name, file_name, function] in plist:

            if event=="custom-event" and plugin_name!=data["pluginId"]:
                continue

            hook, eventName = event.split(" ")
            if plugin_name in self.plugins_context_cache[eventName][hook].keys():
                data["context_cache"] = self.plugins_context_cache[eventName][hook][plugin_name]
            # else:
            #     data["context_cache"] = None

            try:
                self.logger.info(plugin_name)
                self.logger.set_logger_prefix(plugin_name)
                function(data)

                if "context_cache" in data.keys():
                    self.plugins_context_cache[eventName][hook][plugin_name] = data["context_cache"]

                self.logger.set_logger_prefix("")
            except:
                self.logger.info(f'[Plugin run error at event "{event}": {plugin_name}]')
                self.logger.info(traceback.format_exc())

        return response


def checkVersionRequirements (requirements, appVersion, checkMax=False):

    if not requirements:
        return True

    appVersionRequirement = [int(val) for val in str(requirements).split(".")]
    appVersionInts = [int(val) for val in str(appVersion).split(".")]
    appVersionOk = True

    if checkMax:

        if appVersionRequirement[0] >= appVersionInts[0]:
            if len(appVersionRequirement)>1 and int(appVersionRequirement[0])==appVersionInts[0]:
                if appVersionRequirement[1] >= appVersionInts[1]:
                    if len(appVersionRequirement)>2 and int(appVersionRequirement[1])==appVersionInts[1]:
                        if appVersionRequirement[2] >= appVersionInts[2]:
                            pass
                        else:
                            appVersion = False
                else:
                    appVersionOk = False
        else:
            appVersionOk = False

    else:

        if appVersionRequirement[0] <= appVersionInts[0]:
            if len(appVersionRequirement)>1 and int(appVersionRequirement[0])==appVersionInts[0]:
                if appVersionRequirement[1] <= appVersionInts[1]:
                    if len(appVersionRequirement)>2 and int(appVersionRequirement[1])==appVersionInts[1]:
                        if appVersionRequirement[2] <= appVersionInts[2]:
                            pass
                        else:
                            appVersion = False
                else:
                    appVersionOk = False
        else:
            appVersionOk = False

    return appVersionOk