diff --git "a/PythonDataset/train/ProjectAlice-task-instances.jsonl.all" "b/PythonDataset/train/ProjectAlice-task-instances.jsonl.all" new file mode 100644--- /dev/null +++ "b/PythonDataset/train/ProjectAlice-task-instances.jsonl.all" @@ -0,0 +1 @@ +{"repo": "project-alice-assistant/ProjectAlice", "pull_number": 201, "instance_id": "project-alice-assistant__ProjectAlice-201", "issue_numbers": "", "base_commit": "81259c6a188faed224b572035195caa0c67816da", "patch": "diff --git a/ProjectAliceConsole.py b/ProjectAliceConsole.py\n--- a/ProjectAliceConsole.py\n+++ b/ProjectAliceConsole.py\n@@ -7,7 +7,7 @@\n from core.console.SyncCommand import Sync\n from core.console.UpdateCommand import Update\n \n-@click.group(context_settings={'help_option_names':['--help', '-h']})\n+@click.group(context_settings={'help_option_names': ['--help', '-h']})\n def cli():\n \t\t\"\"\"\n \t\tThis is the Command Line Interface of Project Alice.\ndiff --git a/configTemplate.py b/configTemplate.py\n--- a/configTemplate.py\n+++ b/configTemplate.py\n@@ -1,262 +1,274 @@\n settings = {\n \t'autoReportSkillErrors': {\n \t\t'defaultValue': False,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'If true, an error thrown by a skill will automatically post a github issue and ping the author'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'If true, an error thrown by a skill will automatically post a github issue and ping the author'\n \t},\n-\t'notUnderstoodRetries' : {\n+\t'notUnderstoodRetries' : {\n \t\t'defaultValue': 3,\n \t\t'dataType' : 'integer',\n \t\t'description' : 'Defines how many times Alice will ask to repeat if not understood before she gives up'\n \t},\n-\t'ssid' : {\n+\t'ssid' : {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'string',\n \t\t'description' : 'Your Wifi name'\n \t},\n-\t'wifipassword' : {\n+\t'debug' : {\n+\t\t'defaultValue': False,\n+\t\t'dataType' : 'boolean',\n+\t\t'description' : 'If true debug logs will show'\n+\t},\n+\t'wifipassword' : {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'password',\n \t\t'description' : 'Your Wifi password'\n \t},\n-\t'mqttHost' : {\n+\t'mqttHost' : {\n \t\t'defaultValue': 'localhost',\n \t\t'dataType' : 'string',\n-\t\t'description' : 'Mqtt server ip adress'\n+\t\t'description' : 'Mqtt server ip adress',\n+\t\t'onUpdate' : 'reconnectMqtt'\n \t},\n-\t'mqttPort' : {\n+\t'mqttPort' : {\n \t\t'defaultValue': 1883,\n \t\t'dataType' : 'integer',\n-\t\t'description' : 'Mqtt server port'\n+\t\t'description' : 'Mqtt server port',\n+\t\t'onUpdate' : 'reconnectMqtt'\n \t},\n-\t'mqttUser' : {\n+\t'mqttUser' : {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'string',\n-\t\t'description' : 'Mqtt user. Leave blank if not password protected'\n+\t\t'description' : 'Mqtt user. Leave blank if not password protected',\n+\t\t'onUpdate' : 'reconnectMqtt'\n \t},\n-\t'mqttPassword' : {\n+\t'mqttPassword': {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'password',\n-\t\t'description' : 'Mqtt password. Leave blank if not password protected'\n+\t\t'description' : 'Mqtt password. Leave blank if not password protected',\n+\t\t'onUpdate' : 'reconnectMqtt'\n \t},\n-\t'mqttTLSFile' : {\n+\t'mqttTLSFile': {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'string',\n-\t\t'description' : 'Mqtt TLS file path for SSL'\n+\t\t'description' : 'Mqtt TLS file path for SSL',\n+\t\t'onUpdate' : 'reconnectMqtt'\n \t},\n-\t'micSampleRate' : {\n+\t'micSampleRate': {\n \t\t'defaultValue': 44100,\n-\t\t'dataType' : 'integer',\n-\t\t'description' : 'Your microphone sample rate'\n+\t\t'dataType': 'integer',\n+\t\t'description': 'Your microphone sample rate'\n \t},\n-\t'micChannels' : {\n+\t'micChannels': {\n \t\t'defaultValue': 1,\n-\t\t'dataType' : 'integer',\n-\t\t'description' : 'How many channel does your microphone support'\n+\t\t'dataType': 'integer',\n+\t\t'description': 'How many channel does your microphone support'\n \t},\n-\t'enableDataStoring' : {\n+\t'enableDataStoring': {\n \t\t'defaultValue': False,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Enables local telemetry data storing'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Enables local telemetry data storing'\n \t},\n-\t'autoPruneStoredData' : {\n+\t'autoPruneStoredData': {\n \t\t'defaultValue': 0,\n-\t\t'dataType' : 'integer',\n-\t\t'description' : 'Set to max entries to keep, 0 to disable pruning'\n+\t\t'dataType': 'integer',\n+\t\t'description': 'Set to max entries to keep, 0 to disable pruning'\n \t},\n-\t'probabilityThreshold' : {\n+\t'probabilityThreshold': {\n \t\t'defaultValue': 0.45,\n-\t\t'dataType' : 'float',\n-\t\t'description' : 'Capture intents with lower probability score than this settings will trigger Alice not understood'\n+\t\t'dataType': 'float',\n+\t\t'description': 'Capture intents with lower probability score than this settings will trigger Alice not understood'\n \t},\n-\t'stayCompletlyOffline' : {\n+\t'stayCompletlyOffline': {\n \t\t'defaultValue': False,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Nothing goes out! Well, that also means no skill updates, no access to web APIs'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Nothing goes out! Well, that also means no skill updates, no access to web APIs'\n \t},\n-\t'keepASROffline' : {\n+\t'keepASROffline': {\n \t\t'defaultValue': True,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Do not use any online ASR such as Google ASR'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Do not use any online ASR such as Google ASR'\n \t},\n-\t'keepTTSOffline' : {\n+\t'keepTTSOffline': {\n \t\t'defaultValue': True,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Do not use any online TTS such as Google Wavenet or Amazon Polly'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Do not use any online TTS such as Google Wavenet or Amazon Polly'\n \t},\n-\t'shortReplies' : {\n+\t'shortReplies': {\n \t\t'defaultValue': False,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Use only short replies from Alice, when available'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Use only short replies from Alice, when available'\n \t},\n-\t'whisperWhenSleeping' : {\n+\t'whisperWhenSleeping': {\n \t\t'defaultValue': True,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Only available with Amazon Polly'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Only available with Amazon Polly'\n \t},\n \t'newDeviceBroadcastPort': {\n \t\t'defaultValue': 12354,\n-\t\t'dataType' : 'integer',\n-\t\t'description' : 'Should be left as default, this is the port used to find new devices'\n-\t},\n-\t'intentsOwner' : {\n-\t\t'defaultValue': '',\n-\t\t'dataType' : 'string',\n-\t\t'description' : 'Your Snips account username'\n+\t\t'dataType': 'integer',\n+\t\t'description': 'Should be left as default, this is the port used to find new devices'\n \t},\n-\t'asr' : {\n-\t\t'defaultValue': 'snips',\n+\t'asr': {\n+\t\t'defaultValue': 'pocketsphinx',\n \t\t'dataType' : 'list',\n-\t\t'values' : ['snips', 'google'],\n-\t\t'description' : 'The ASR to use. Can\\'t use an online ASR if you have set keepASROffline to true!'\n+\t\t'values' : ['pocketsphinx', 'google'],\n+\t\t'description' : 'The ASR to use. Can\\'t use an online ASR if you have set keepASROffline to true!',\n+\t\t'onUpdate' : 'reloadASR'\n \t},\n-\t'tts' : {\n+\t'tts': {\n \t\t'defaultValue': 'pico',\n-\t\t'dataType' : 'list',\n-\t\t'values' : {'Pico': 'pico', 'Mycroft': 'mycroft', 'Amazon Polly': 'amazon', 'Google Wavenet': 'google', 'Snips Makers TTS': 'snips'},\n-\t\t'description' : 'The TTS to use. Can\\'t use an online TTS if you have set keepTTSOffline!'\n+\t\t'dataType': 'list',\n+\t\t'values': {'Pico': 'pico', 'Mycroft': 'mycroft', 'Amazon Polly': 'amazon', 'Google Wavenet': 'google', 'Snips Makers TTS': 'snips'},\n+\t\t'description': 'The TTS to use. Can\\'t use an online TTS if you have set keepTTSOffline!'\n \t},\n-\t'ttsLanguage' : {\n+\t'ttsLanguage': {\n \t\t'defaultValue': 'en-US',\n-\t\t'dataType' : 'string',\n-\t\t'description' : 'Language for the TTS to use'\n+\t\t'dataType': 'string',\n+\t\t'description': 'Language for the TTS to use'\n \t},\n-\t'ttsType' : {\n+\t'ttsType': {\n \t\t'defaultValue': 'male',\n-\t\t'dataType' : 'list',\n-\t\t'values' : ['male', 'female'],\n-\t\t'description' : 'Choose the voice gender you want'\n+\t\t'dataType': 'list',\n+\t\t'values': ['male', 'female'],\n+\t\t'description': 'Choose the voice gender you want'\n \t},\n-\t'ttsVoice' : {\n+\t'ttsVoice' : {\n \t\t'defaultValue': 'en-US',\n-\t\t'dataType' : 'string',\n-\t\t'description' : 'The voice the TTS should use. Find lists on respective TTS websites'\n+\t\t'dataType': 'string',\n+\t\t'description': 'The voice the TTS should use. Find lists on respective TTS websites'\n \t},\n-\t'awsRegion' : {\n+\t'awsRegion' : {\n \t\t'defaultValue': 'eu-central-1',\n-\t\t'dataType' : 'list',\n-\t\t'values' : ['eu-central-1', 'eu-west-1', ' eu-west-2', 'eu-west-3', 'eu-north-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'],\n-\t\t'description' : 'Region to use for Amazon Polly'\n+\t\t'dataType': 'list',\n+\t\t'values': ['eu-central-1', 'eu-west-1', ' eu-west-2', 'eu-west-3', 'eu-north-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'],\n+\t\t'description': 'Region to use for Amazon Polly'\n \t},\n-\t'awsAccessKey' : {\n+\t'awsAccessKey' : {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'password',\n \t\t'description' : 'Your Amazon services access key'\n \t},\n-\t'awsSecretKey' : {\n+\t'awsSecretKey' : {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'password',\n \t\t'description' : 'Your Amazon services secret key'\n \t},\n-\t'useSLC' : {\n+\t'useHLC' : {\n \t\t'defaultValue': False,\n \t\t'dataType' : 'boolean',\n-\t\t'description' : 'Enables Snips Led Control for visual feedback from your assistant'\n+\t\t'description' : 'Enables Hermes Led Control for visual feedback from your assistant'\n \t},\n-\t'activeLanguage' : {\n+\t'activeLanguage' : {\n \t\t'defaultValue': 'en',\n \t\t'dataType' : 'list',\n \t\t'values' : ['en', 'fr', 'de', 'it', 'pt'],\n \t\t'description' : 'Project Alice active language'\n \t},\n-\t'activeCountryCode' : {\n+\t'activeCountryCode' : {\n \t\t'defaultValue': 'US',\n \t\t'dataType' : 'string',\n \t\t'description' : 'Project Alice active country code'\n \t},\n-\t'skillAutoUpdate' : {\n+\t'aliceAutoUpdate' : {\n+\t\t'defaultValue': False,\n+\t\t'dataType' : 'boolean',\n+\t\t'description' : 'Whether Alice should auto update, checked every hour'\n+\t},\n+\t'skillAutoUpdate': {\n \t\t'defaultValue': False,\n \t\t'dataType' : 'boolean',\n \t\t'description' : 'Whether skills should auto update, checked every 15 minutes'\n \t},\n-\t'githubUsername' : {\n+\t'githubUsername': {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'string',\n \t\t'description' : 'Not mendatory, your github username and token allows you to use Github API much more, such as checking for skills, updating them etc etc'\n \t},\n-\t'githubToken' : {\n+\t'githubToken': {\n \t\t'defaultValue': '',\n \t\t'dataType' : 'password',\n \t\t'description' : 'Not mendatory, your github username and token allows you to use Github API much more, such as checking for skills, updating them etc etc'\n \t},\n-\t'updateChannel' : {\n+\t'aliceUpdateChannel': {\n \t\t'defaultValue': 'master',\n \t\t'dataType' : 'list',\n-\t\t'values' : {'Release': 'master', 'Release candidate': 'rc', 'Beta': 'beta', 'Alpha': 'alpha'},\n+\t\t'values' : {'Stable': 'master', 'Release candidate': 'rc', 'Beta': 'beta', 'Alpha': 'alpha'},\n \t\t'description' : 'Choose your update frequency. Release is the only supposedly safe option! But if you like to live on the edge, alpha will allow you to preview what\\'s coming next!'\n \t},\n-\t'supportedLanguages' : {\n+\t'skillsUpdateChannel': {\n+\t\t'defaultValue': 'master',\n+\t\t'dataType' : 'list',\n+\t\t'values' : {'Stable': 'master', 'Release candidate': 'rc', 'Beta': 'beta', 'Alpha': 'alpha'},\n+\t\t'description' : 'Choose your skill update frequency. Release is the only supposedly safe option! But if you like to live on the edge, alpha will allow you to preview what\\'s coming next!',\n+\t\t'onUpdate' : 'refreshStoreData'\n+\t},\n+\t'supportedLanguages': {\n \t\t'defaultValue': 'en',\n \t\t'dataType' : 'list',\n \t\t'values' : {\n \t\t\t'en': {\n-\t\t\t\t'snipsProjectId': '',\n-\t\t\t\t'default' : True,\n-\t\t\t\t'countryCode' : 'US'\n+\t\t\t\t'default': True,\n+\t\t\t\t'countryCode': 'US'\n \t\t\t},\n \t\t\t'fr': {\n-\t\t\t\t'snipsProjectId': '',\n-\t\t\t\t'default' : False,\n-\t\t\t\t'countryCode' : 'FR'\n+\t\t\t\t'default': False,\n+\t\t\t\t'countryCode': 'FR'\n \t\t\t},\n \t\t\t'de': {\n-\t\t\t\t'snipsProjectId': '',\n-\t\t\t\t'default' : False,\n-\t\t\t\t'countryCode' : 'DE'\n+\t\t\t\t'default': False,\n+\t\t\t\t'countryCode': 'DE'\n \t\t\t}\n \t\t},\n-\t\t'display' : 'hidden'\n-\t},\n-\t'snipsConsoleLogin' : {\n-\t\t'defaultValue': '',\n-\t\t'dataType' : 'string',\n-\t\t'description' : 'Your Snips Console login'\n-\t},\n-\t'snipsConsolePassword' : {\n-\t\t'defaultValue': '',\n-\t\t'dataType' : 'password',\n-\t\t'description' : 'Your Snips Console password'\n+\t\t'display': 'hidden'\n \t},\n \n-\t'baseCurrency' : {\n+\t'baseCurrency': {\n \t\t'defaultValue': 'CHF',\n-\t\t'dataType' : 'list',\n-\t\t'values' : ['CHF', 'EUR', 'USD', 'GBP', 'AUD'],\n-\t\t'description' : 'The currency used by Project Alice'\n+\t\t'dataType': 'list',\n+\t\t'values': ['CHF', 'EUR', 'USD', 'GBP', 'AUD'],\n+\t\t'description': 'The currency used by Project Alice'\n \t},\n \n-\t'baseUnits' : {\n+\t'baseUnits': {\n \t\t'defaultValue': 'metric',\n-\t\t'dataType' : 'list',\n-\t\t'values' : ['metric', 'kelvin', 'imperial'],\n-\t\t'description' : 'Units to use with Project Alice'\n+\t\t'dataType': 'list',\n+\t\t'values': ['metric', 'kelvin', 'imperial'],\n+\t\t'description': 'Units to use with Project Alice'\n \t},\n \n-\t'onReboot' : {\n+\t'nluEngine': {\n+\t\t'defaultValue': 'snips',\n+\t\t'dataType': 'list',\n+\t\t'values': ['snips'],\n+\t\t'description': 'Natural Language Understanding engine to use'\n+\t},\n+\n+\t'onReboot': {\n \t\t'defaultValue': '',\n-\t\t'dataType' : 'string',\n-\t\t'display' : 'hidden'\n+\t\t'dataType': 'string',\n+\t\t'display': 'hidden'\n \t},\n \n-\t'webInterfaceActive' : {\n+\t'webInterfaceActive': {\n \t\t'defaultValue': True,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Activates the web interface to be reached by browsing to x.x.x.x:webInterfacePort, e.g. 192.168.1.2:5000'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Activates the web interface to be reached by browsing to x.x.x.x:webInterfacePort, e.g. 192.168.1.2:5000'\n \t},\n-\t'webInterfacePort' : {\n+\t'webInterfacePort': {\n \t\t'defaultValue': 5000,\n-\t\t'dataType' : 'integer',\n-\t\t'description' : 'Change the web interface port to be used'\n+\t\t'dataType': 'integer',\n+\t\t'description': 'Change the web interface port to be used'\n \t},\n-\t'devMode' : {\n+\t'devMode': {\n \t\t'defaultValue': False,\n-\t\t'dataType' : 'boolean',\n-\t\t'description' : 'Activates the developer part of the interface, for skill development'\n+\t\t'dataType': 'boolean',\n+\t\t'description': 'Activates the developer part of the interface, for skill development'\n \t},\n \n \t# -----------------------\n \t# Skills\n \t# -----------------------\n \n-\t'skills' : {}\n+\t'skills': {}\n }\ndiff --git a/core/Initializer.py b/core/Initializer.py\n--- a/core/Initializer.py\n+++ b/core/Initializer.py\n@@ -6,6 +6,7 @@\n import time\n from pathlib import Path\n \n+import pkg_resources\n import requests\n \n from core.base.model.TomlFile import TomlFile\n@@ -21,7 +22,7 @@\n from core.base.model.ProjectAliceObject import ProjectAliceObject\n \n \n-class initDict(dict):\n+class InitDict(dict):\n \n \tdef __init__(self, default: dict):\n \t\tsuper().__init__(default)\n@@ -60,7 +61,7 @@ def __init__(self):\n \t\tself._confsFile = Path(self._rootDir, 'config.py')\n \t\tself._confsSample = Path(self._rootDir, 'configTemplate.py')\n \t\tself._initFile = Path('/boot/ProjectAlice.yaml')\n-\t\tself._latest = 1.11\n+\t\tself._latest = 1.14\n \n \n \tdef initProjectAlice(self) -> bool:\n@@ -74,9 +75,9 @@ def initProjectAlice(self) -> bool:\n \t\t\ttry:\n \t\t\t\tload = yaml.safe_load(f)\n \t\t\t\tif not load:\n-\t\t\t\t\traise yaml.YAMLError\n+\t\t\t\t\traise yaml.YAMLError\n \n-\t\t\t\tinitConfs = initDict(load)\n+\t\t\t\tinitConfs = InitDict(load)\n \t\t\texcept yaml.YAMLError as e:\n \t\t\t\tself.fatal(f'Failed loading init configurations: {e}')\n \n@@ -104,7 +105,7 @@ def initProjectAlice(self) -> bool:\n \t\t\tsubprocess.run(['sudo', 'mv', str(file), bootWpaSupplicant])\n \t\t\tself.logInfo('Successfully initialized wpa_supplicant.conf')\n \t\t\ttime.sleep(1)\n-\t\t\tsubprocess.run(['/usr/bin/sudo', '/sbin/shutdown', '-r', 'now'])\n+\t\t\tsubprocess.run(['sudo', 'shutdown', '-r', 'now'])\n \t\t\texit(0)\n \n \t\ttry:\n@@ -114,17 +115,14 @@ def initProjectAlice(self) -> bool:\n \t\t\tconnected = False\n \n \t\tif not connected:\n-\t\t\tself.fatal('Your device needs internet access to continue, to download the updates and create the assistant')\n-\n-\t\tif not initConfs['snipsConsoleLogin'] or not initConfs['snipsConsolePassword'] or not initConfs['intentsOwner']:\n-\t\t\tself.fatal('You must specify a Snips console login, password and intent owner')\n+\t\t\tself.fatal('Your device needs internet access to continue')\n \n \t\t# Update our system and sources\n \t\tsubprocess.run(['sudo', 'apt-get', 'update'])\n \t\tsubprocess.run(['sudo', 'apt-get', 'dist-upgrade', '-y'])\n \t\tsubprocess.run(['git', 'clean', '-df'])\n \t\tsubprocess.run(['git', 'stash'])\n-\t\tsubprocess.run(['git', 'checkout', self.getUpdateSource(initConfs['updateChannel'])])\n+\t\tsubprocess.run(['git', 'checkout', self.getUpdateSource(initConfs['aliceUpdateChannel'])])\n \t\tsubprocess.run(['git', 'pull'])\n \t\tsubprocess.run(['git', 'stash', 'clear'])\n \n@@ -138,7 +136,7 @@ def initProjectAlice(self) -> bool:\n \t\telif not self._confsFile.exists() and self._confsSample.exists():\n \t\t\tself.warning('No config file found, creating it from sample file')\n \t\t\tconfs = self.newConfs()\n-\t\t\tPath('config.py').write_text(f\"settings = {json.dumps(confs, indent=4).replace('false', 'False').replace('true', 'True')}\")\n+\t\t\tself._confsFile.write_text(f\"settings = {json.dumps(confs, indent=4).replace('false', 'False').replace('true', 'True')}\")\n \n \t\telif self._confsFile.exists() and not initConfs['forceRewrite']:\n \t\t\tself.warning('Config file already existing and user not wanting to rewrite, aborting')\n@@ -146,9 +144,9 @@ def initProjectAlice(self) -> bool:\n \n \t\telif self._confsFile.exists() and initConfs['forceRewrite']:\n \t\t\tself.warning('Config file found and force rewrite specified, let\\'s restart all this!')\n-\t\t\tPath(self._rootDir, 'config.py').unlink()\n+\t\t\tself._confsFile.unlink()\n \t\t\tconfs = self.newConfs()\n-\t\t\tPath('config.py').write_text(f\"settings = {json.dumps(confs, indent=4).replace('false', 'False').replace('true', 'True')}\")\n+\t\t\tself._confsFile.write_text(f\"settings = {json.dumps(confs, indent=4).replace('false', 'False').replace('true', 'True')}\")\n \n \t\tconfig = importlib.import_module('config')\n \t\tconfs = config.settings.copy()\n@@ -178,7 +176,6 @@ def initProjectAlice(self) -> bool:\n \t\t\tsubprocess.run(['sudo', 'apt-get', 'install', '-y', '--allow-unauthenticated'] + reqs)\n \n \t\t\tsubprocess.run(['sudo', 'systemctl', 'stop', 'snips-*'])\n-\t\t\tsubprocess.run(['sudo', 'systemctl', 'disable', 'snips-asr'])\n \t\t\tsubprocess.run(['sudo', 'systemctl', 'disable', 'snips-nlu'])\n \t\t\tsubprocess.run(['sudo', 'systemctl', 'disable', 'snips-dialogue'])\n \t\t\tsubprocess.run(['sudo', 'systemctl', 'disable', 'snips-injection'])\n@@ -186,21 +183,18 @@ def initProjectAlice(self) -> bool:\n \t\t\tsubprocess.run(['sudo', 'systemctl', 'disable', 'snips-audio-server'])\n \t\t\tsubprocess.run(['sudo', 'systemctl', 'disable', 'snips-tts'])\n \n+\n \t\t# Now let's dump some values to their respective places\n \t\t# First those that need some checks and self filling in case unspecified\n \t\tconfs['mqttHost'] = str(initConfs['mqttHost']) or 'localhost'\n \t\tconfs['mqttPort'] = initConfs['mqttPort'] or 1883\n \n-\t\tconfs['snipsConsoleLogin'] = initConfs['snipsConsoleLogin']\n-\t\tconfs['snipsConsolePassword'] = initConfs['snipsConsolePassword']\n-\t\tconfs['intentsOwner'] = initConfs['intentsOwner']\n-\n \t\tconfs['stayCompletlyOffline'] = bool(initConfs['stayCompletlyOffline'])\n \t\tif initConfs['stayCompletlyOffline']:\n \t\t\tconfs['keepASROffline'] = True\n \t\t\tconfs['keepTTSOffline'] = True\n \t\t\tconfs['skillAutoUpdate'] = False\n-\t\t\tconfs['asr'] = 'snips'\n+\t\t\tconfs['asr'] = 'pocketsphinx'\n \t\t\tconfs['tts'] = 'pico'\n \t\t\tconfs['awsRegion'] = ''\n \t\t\tconfs['awsAccessKey'] = ''\n@@ -209,53 +203,87 @@ def initProjectAlice(self) -> bool:\n \t\t\tconfs['keepASROffline'] = bool(initConfs['keepASROffline'])\n \t\t\tconfs['keepTTSOffline'] = bool(initConfs['keepTTSOffline'])\n \t\t\tconfs['skillAutoUpdate'] = bool(initConfs['skillAutoUpdate'])\n-\t\t\tconfs['asr'] = initConfs['asr'] if initConfs['asr'] in ('snips', 'google') else 'snips'\n-\t\t\tconfs['tts'] = initConfs['tts'] if initConfs['tts'] in ('pico', 'snips', 'mycroft', 'amazon', 'google') else 'pico'\n+\t\t\tconfs['tts'] = initConfs['tts'] if initConfs['tts'] in {'pico', 'snips', 'mycroft', 'amazon', 'google'} else 'pico'\n \t\t\tconfs['awsRegion'] = initConfs['awsRegion']\n \t\t\tconfs['awsAccessKey'] = initConfs['awsAccessKey']\n \t\t\tconfs['awsSecretKey'] = initConfs['awsSecretKey']\n \n+\t\t\tconfs['asr'] = initConfs['asr'] if initConfs['asr'] in {'pocketsphinx', 'google'} else 'pocketsphinx'\n+\t\t\tif confs['asr'] == 'google' and not initConfs['googleServiceFile']:\n+\t\t\t\tself.logInfo('You cannot use Google ASR without a google service file, falling back to pocket sphinx')\n+\t\t\t\tconfs['asr'] = 'pocketsphinx'\n+\n \t\t\tif initConfs['googleServiceFile']:\n \t\t\t\tgoogleCreds = Path(self._rootDir, 'credentials/googlecredentials.json')\n \t\t\t\tgoogleCreds.write_text(json.dumps(initConfs['googleServiceFile']))\n \n+\n \t\t# Those that don't need checking\n-\t\tconfs['ssid'] = initConfs['wifiNetworkName'] or ''\n-\t\tconfs['wifipassword'] = str(initConfs['wifiWPAPass']) or ''\n-\t\tconfs['micSampleRate'] = int(initConfs['micSampleRate']) or 16000\n-\t\tconfs['micChannels'] = int(initConfs['micChannels']) or 1\n-\t\tconfs['useSLC'] = bool(initConfs['useSLC'])\n+\t\tconfs['ssid'] = initConfs['wifiNetworkName']\n+\t\tconfs['wifipassword'] = str(initConfs['wifiWPAPass'])\n+\t\tconfs['micSampleRate'] = int(initConfs['micSampleRate'] or 16000)\n+\t\tconfs['micChannels'] = int(initConfs['micChannels'] or 1)\n+\t\tconfs['useHLC'] = bool(initConfs['useHLC'])\n \t\tconfs['webInterfaceActive'] = bool(initConfs['webInterfaceActive'])\n \t\tconfs['devMode'] = bool(initConfs['devMode'])\n-\t\tconfs['newDeviceBroadcastPort'] = int(initConfs['newDeviceBroadcastPort']) or 12354\n-\t\tconfs['activeLanguage'] = initConfs['activeLanguage'] if initConfs['activeLanguage'] in ('en', 'de', 'fr') else 'en'\n+\t\tconfs['newDeviceBroadcastPort'] = int(initConfs['newDeviceBroadcastPort'] or 12354)\n+\t\tconfs['activeLanguage'] = initConfs['activeLanguage'] if initConfs['activeLanguage'] in {'en', 'de', 'fr'} else 'en'\n \t\tconfs['activeCountryCode'] = initConfs['activeCountryCode'] or 'US'\n \t\tconfs['baseCurrency'] = initConfs['baseCurrency'] or 'USD'\n-\t\tconfs['baseUnits'] = initConfs['baseUnits'] if initConfs['baseUnits'] in ('metric', 'kelvin', 'imperial') else 'metric'\n+\t\tconfs['baseUnits'] = initConfs['baseUnits'] if initConfs['baseUnits'] in {'metric', 'kelvin', 'imperial'} else 'metric'\n \t\tconfs['enableDataStoring'] = bool(initConfs['enableDataStoring'])\n \t\tconfs['autoPruneStoredData'] = initConfs['autoPruneStoredData'] or 1000\n-\t\tconfs['probabilityThreshold'] = float(initConfs['probabilityThreshold']) or 0.5\n+\t\tconfs['probabilityThreshold'] = float(initConfs['probabilityThreshold'] or 0.5)\n \t\tconfs['shortReplies'] = bool(initConfs['shortReplies'])\n \t\tconfs['whisperWhenSleeping'] = bool(initConfs['whisperWhenSleeping'])\n \t\tconfs['ttsLanguage'] = initConfs['ttsLanguage'] or confs['activeLanguage']\n-\t\tconfs['ttsType'] = initConfs['ttsType'] if initConfs['ttsType'] in ('female', 'male') else 'female'\n-\t\tconfs['ttsVoice'] = initConfs['ttsVoice'] or ''\n-\t\tconfs['githubUsername'] = initConfs['githubUsername'] or ''\n-\t\tconfs['githubToken'] = initConfs['githubToken'] or ''\n-\t\tconfs['ttsLanguage'] = initConfs['ttsLanguage'] or ''\n-\n-\t\tupdateChannel = initConfs['updateChannel']\n-\t\tif updateChannel not in ('master', 'rc', 'beta', 'alpha'):\n-\t\t\tself.logWarning(f'{updateChannel} is no supported updateChannel, only master, rc, beta and alpha are supported. Reseting to master')\n-\t\t\tconfs['updateChannel'] = 'master'\n+\t\tconfs['ttsType'] = initConfs['ttsType'] if initConfs['ttsType'] in {'female', 'male'} else 'female'\n+\t\tconfs['ttsVoice'] = initConfs['ttsVoice']\n+\t\tconfs['githubUsername'] = initConfs['githubUsername']\n+\t\tconfs['githubToken'] = initConfs['githubToken']\n+\n+\t\taliceUpdateChannel = initConfs['aliceUpdateChannel']\n+\t\tif aliceUpdateChannel not in {'master', 'rc', 'beta', 'alpha'}:\n+\t\t\tself.logWarning(f'{aliceUpdateChannel} is not a supported updateChannel, only master, rc, beta and alpha are supported. Reseting to master')\n+\t\t\tconfs['aliceUpdateChannel'] = 'master'\n \t\telse:\n-\t\t\tconfs['updateChannel'] = updateChannel\n-\t\tconfs['mqtt_username'] = str(initConfs['mqttUser']) or ''\n-\t\tconfs['mqttPassword'] = str(initConfs['mqttPassword']) or ''\n-\t\tconfs['mqttTLSFile'] = initConfs['mqttTLSFile'] or ''\n+\t\t\tconfs['aliceUpdateChannel'] = aliceUpdateChannel\n \n-\t\tif initConfs['snipsProjectId'] and confs['activeLanguage'] in confs['supportedLanguages']:\n-\t\t\tconfs['supportedLanguages'][confs['activeLanguage']]['snipsProjectId'] = initConfs['snipsProjectId']\n+\t\tskillsUpdateChannel = initConfs['skillsUpdateChannel']\n+\t\tif skillsUpdateChannel not in {'master', 'rc', 'beta', 'alpha'}:\n+\t\t\tself.logWarning(f'{skillsUpdateChannel} is not a supported updateChannel, only master, rc, beta and alpha are supported. Reseting to master')\n+\t\t\tconfs['skillsUpdateChannel'] = 'master'\n+\t\telse:\n+\t\t\tconfs['skillsUpdateChannel'] = skillsUpdateChannel\n+\n+\t\tconfs['mqtt_username'] = str(initConfs['mqttUser'])\n+\t\tconfs['mqttPassword'] = str(initConfs['mqttPassword'])\n+\t\tconfs['mqttTLSFile'] = initConfs['mqttTLSFile']\n+\n+\t\ttry:\n+\t\t\tpkg_resources.require('snips-nlu')\n+\t\t\tsubprocess.run(['./venv/bin/snips-nlu', 'download', confs['activeLanguage']])\n+\t\texcept:\n+\t\t\tself.logInfo(\"Snips NLU not installed, let's do this\")\n+\t\t\tsubprocess.run(['sudo', 'apt-get', 'install', 'libatlas3-base', 'libgfortran5'])\n+\t\t\tsubprocess.run(['wget', '--content-disposition', 'https://github.com/project-alice-assistant/snips-nlu-rebirth/blob/master/wheels/scikit_learn-0.22.1-cp37-cp37m-linux_armv7l.whl?raw=true'])\n+\t\t\tsubprocess.run(['wget', '--content-disposition', 'https://github.com/project-alice-assistant/snips-nlu-rebirth/blob/master/wheels/scikit_learn-0.22.1-cp37-cp37m-linux_armv7l.whl?raw=true'])\n+\t\t\tsubprocess.run(['wget', '--content-disposition', 'https://github.com/project-alice-assistant/snips-nlu-rebirth/blob/master/wheels/snips_nlu_utils-0.9.1-cp37-cp37m-linux_armv7l.whl?raw=true'])\n+\t\t\tsubprocess.run(['wget', '--content-disposition', 'https://github.com/project-alice-assistant/snips-nlu-rebirth/blob/master/wheels/snips_nlu_parsers-0.4.3-cp37-cp37m-linux_armv7l.whl?raw=true'])\n+\t\t\tsubprocess.run(['wget', '--content-disposition', 'https://github.com/project-alice-assistant/snips-nlu-rebirth/blob/master/wheels/snips_nlu-0.20.2-py3-none-any.whl?raw=true'])\n+\t\t\ttime.sleep(1)\n+\t\t\tsubprocess.run(['./venv/bin/pip3', 'install', 'scipy-1.3.3-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['./venv/bin/pip3', 'install', 'scikit_learn-0.22.1-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['./venv/bin/pip3', 'install', 'snips_nlu_utils-0.9.1-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['./venv/bin/pip3', 'install', 'snips_nlu_parsers-0.4.3-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['./venv/bin/pip3', 'install', 'snips_nlu-0.20.2-py3-none-any.whl'])\n+\t\t\ttime.sleep(1)\n+\t\t\tsubprocess.run(['rm', 'scipy-1.3.3-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['rm', 'scikit_learn-0.22.1-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['rm', 'snips_nlu_utils-0.9.1-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['rm', 'snips_nlu_parsers-0.4.3-cp37-cp37m-linux_armv7l.whl'])\n+\t\t\tsubprocess.run(['rm', 'snips_nlu-0.20.2-py3-none-any.whl'])\n+\t\t\tsubprocess.run(['./venv/bin/snips-nlu', 'download', confs['activeLanguage']])\n \n \t\tsnipsConf = self.loadSnipsConfigurations()\n \t\tif not snipsConf:\n@@ -293,40 +321,40 @@ def initProjectAlice(self) -> bool:\n \t\t\t\taudioHardware = hardware\n \t\t\t\tbreak\n \n-\t\tslcServiceFilePath = Path('/etc/systemd/system/snipsledcontrol.service')\n-\t\tif initConfs['useSLC']:\n+\t\thlcServiceFilePath = Path('/etc/systemd/system/hermesledcontrol.service')\n+\t\tif initConfs['useHLC']:\n \n-\t\t\tif not Path('/home', getpass.getuser(), 'snipsLedControl'):\n-\t\t\t\tsubprocess.run(['git', 'clone', 'https://github.com/Psychokiller1888/snipsLedControl.git', str(Path('/home', getpass.getuser(), 'snipsLedControl'))])\n+\t\t\tif not Path('/home', getpass.getuser(), 'hermesLedControl').exists():\n+\t\t\t\tsubprocess.run(['git', 'clone', 'https://github.com/project-alice-assistant/hermesLedControl.git', str(Path('/home', getpass.getuser(), 'hermesLedControl'))])\n \t\t\telse:\n-\t\t\t\tsubprocess.run(['git', '-C', str(Path('/home', getpass.getuser(), 'snipsLedControl')), 'stash'])\n-\t\t\t\tsubprocess.run(['git', '-C', str(Path('/home', getpass.getuser(), 'snipsLedControl')), 'pull'])\n-\t\t\t\tsubprocess.run(['git', '-C', str(Path('/home', getpass.getuser(), 'snipsLedControl')), 'stash', 'clear'])\n+\t\t\t\tsubprocess.run(['git', '-C', str(Path('/home', getpass.getuser(), 'hermesLedControl')), 'stash'])\n+\t\t\t\tsubprocess.run(['git', '-C', str(Path('/home', getpass.getuser(), 'hermesLedControl')), 'pull'])\n+\t\t\t\tsubprocess.run(['git', '-C', str(Path('/home', getpass.getuser(), 'hermesLedControl')), 'stash', 'clear'])\n \n-\t\t\tif not slcServiceFilePath.exists():\n-\t\t\t\tsubprocess.run(['sudo', 'cp', f'/home/{getpass.getuser()}/snipsLedControl/snipsledcontrol.service', str(slcServiceFilePath)])\n+\t\t\tif not hlcServiceFilePath.exists():\n+\t\t\t\tsubprocess.run(['sudo', 'cp', f'/home/{getpass.getuser()}/hermesLedControl/hermesledcontrol.service', str(hlcServiceFilePath)])\n \n-\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%WORKING_DIR%/\\/home\\/{getpass.getuser()}\\/snipsLedControl/', str(slcServiceFilePath)])\n-\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%EXECSTART%/\\/home\\/{getpass.getuser()}\\/snipsLedControl\\/venv\\/bin\\/python3 main.py --hardware=%HARDWARE% --pattern=projectalice/', str(slcServiceFilePath)])\n-\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%USER%/{getpass.getuser()}/', str(slcServiceFilePath)])\n+\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%WORKING_DIR%/\\/home\\/{getpass.getuser()}\\/hermesLedControl/', str(hlcServiceFilePath)])\n+\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%EXECSTART%/\\/home\\/{getpass.getuser()}\\/hermesLedControl\\/venv\\/bin\\/python3 main.py --hardware=%HARDWARE% --pattern=projectalice/', str(hlcServiceFilePath)])\n+\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%USER%/{getpass.getuser()}/', str(hlcServiceFilePath)])\n \n \t\tif audioHardware in {'respeaker2', 'respeaker4', 'respeaker6MicArray'}:\n \t\t\tsubprocess.run(['sudo', Path(self._rootDir, 'system/scripts/audioHardware/respeakers.sh')])\n-\t\t\tif initConfs['useSLC']:\n-\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%HARDWARE%/{audioHardware}/', str(slcServiceFilePath)])\n+\t\t\tif initConfs['useHLC']:\n+\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%HARDWARE%/{audioHardware}/', str(hlcServiceFilePath)])\n \n \t\t\tif audioHardware == 'respeaker6MicArray':\n \t\t\t\tsubprocess.run(['sudo', 'cp', Path(self._rootDir, 'system', 'asounds', 'respeaker6micarray.conf'), Path('/etc/asound.conf')])\n \n \t\telif audioHardware == 'respeaker7':\n \t\t\tsubprocess.run(['sudo', Path(self._rootDir, 'system/scripts/audioHardware/respeaker7.sh')])\n-\t\t\tif initConfs['useSLC']:\n-\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', 's/%HARDWARE%/respeaker7MicArray/', str(slcServiceFilePath)])\n+\t\t\tif initConfs['useHLC']:\n+\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', 's/%HARDWARE%/respeaker7MicArray/', str(hlcServiceFilePath)])\n \n \t\telif audioHardware == 'respeakerCoreV2':\n \t\t\tsubprocess.run(['sudo', Path(self._rootDir, 'system/scripts/audioHardware/respeakerCoreV2.sh')])\n-\t\t\tif initConfs['useSLC']:\n-\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%HARDWARE%/{audioHardware}/', str(slcServiceFilePath)])\n+\t\t\tif initConfs['useHLC']:\n+\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%HARDWARE%/{audioHardware}/', str(hlcServiceFilePath)])\n \n \t\telif audioHardware in {'matrixCreator', 'matrixVoice'}:\n \t\t\tsubprocess.run(['sudo', Path(self._rootDir, 'system/scripts/audioHardware/matrix.sh')])\n@@ -334,13 +362,13 @@ def initProjectAlice(self) -> bool:\n \n \t\t\tsnipsConf['snips-audio-server']['mike'] = 'MATRIXIO-SOUND: - (hw:2,0)'\n \n-\t\t\tif initConfs['useSLC']:\n-\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%HARDWARE%/{audioHardware.lower()}/', str(slcServiceFilePath)])\n+\t\t\tif initConfs['useHLC']:\n+\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', f's/%HARDWARE%/{audioHardware.lower()}/', str(hlcServiceFilePath)])\n \n \t\telif audioHardware == 'googleAIY':\n \t\t\tsubprocess.run(['sudo', Path(self._rootDir, 'system/scripts/audioHardware/aiy.sh')])\n-\t\t\tif initConfs['useSLC']:\n-\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', 's/%HARDWARE%/googleAIY/', str(slcServiceFilePath)])\n+\t\t\tif initConfs['useHLC']:\n+\t\t\t\tsubprocess.run(['sudo', 'sed', '-i', '-e', 's/%HARDWARE%/googleAIY/', str(hlcServiceFilePath)])\n \n \t\telif audioHardware == 'usbMic':\n \t\t\tsubprocess.run(['sudo', 'cp', Path(self._rootDir, 'system', 'asounds', 'usbmic.conf'), Path('/etc/asound.conf')])\n@@ -351,8 +379,8 @@ def initProjectAlice(self) -> bool:\n \t\tsort['skills'] = sort.pop('skills')\n \n \t\ttry:\n-\t\t\ts = json.dumps(sort, indent=4).replace('false', 'False').replace('true', 'True')\n-\t\t\tself._confsFile.write_text(f'settings = {s}')\n+\t\t\tconfString = json.dumps(sort, indent=4).replace('false', 'False').replace('true', 'True')\n+\t\t\tself._confsFile.write_text(f'settings = {confString}')\n \t\texcept Exception as e:\n \t\t\tself.fatal(f'An error occured while writting final configuration file: {e}')\n \t\telse:\n@@ -361,8 +389,6 @@ def initProjectAlice(self) -> bool:\n \t\tsnipsConf.dump()\n \n \t\tsubprocess.run(['sudo', 'rm', '-rf', Path(self._rootDir, 'assistant')])\n-\t\tsubprocess.run(['sudo', 'rm', '-rf', Path(self._rootDir, 'trained', 'assistants', f\"assistant_{confs['activeLanguage']}\")])\n-\t\tsubprocess.run(['sudo', 'rm', '-rf', Path(self._rootDir, 'var', 'assistants', confs['activeLanguage'])])\n \n \t\tif initConfs['keepYAMLBackup']:\n \t\t\tsubprocess.run(['sudo', 'mv', Path('/boot/ProjectAlice.yaml'), Path('/boot/ProjectAlice.yaml.bak')])\n@@ -377,7 +403,6 @@ def initProjectAlice(self) -> bool:\n \n \tdef fatal(self, text: str):\n \t\tself.logFatal(text)\n-\t\texit()\n \n \n \tdef warning(self, text: str):\n@@ -388,8 +413,10 @@ def loadSnipsConfigurations(self) -> TomlFile:\n \t\tself.logInfo('Loading Snips configuration file')\n \t\tsnipsConfig = Path('/etc/snips.toml')\n \n-\t\tif not snipsConfig.exists():\n-\t\t\tsubprocess.run(['sudo', 'cp', Path(self._rootDir, 'system/snips/snips.toml'), Path('/etc/snips.toml')])\n+\t\tif snipsConfig.exists():\n+\t\t\tsubprocess.run(['sudo', 'rm', '/etc/snips.toml'])\n+\n+\t\tsubprocess.run(['sudo', 'cp', Path(self._rootDir, 'system/snips/snips.toml'), Path('/etc/snips.toml')])\n \n \t\treturn TomlFile.loadToml(snipsConfig)\n \n@@ -402,26 +429,24 @@ def getUpdateSource(definedSource: str) -> str:\n \n \t\treq = requests.get('https://api.github.com/repos/project-alice-assistant/ProjectAlice/branches')\n \t\tresult = req.json()\n-\t\tif result:\n-\t\t\tuserUpdatePref = definedSource\n-\t\t\tversions = list()\n-\t\t\tfor branch in result:\n-\t\t\t\trepoVersion = Version(branch['name'])\n-\t\t\t\tif not repoVersion.isVersionNumber:\n-\t\t\t\t\tcontinue\n-\n-\t\t\t\tif userUpdatePref == 'alpha' and repoVersion.infos['releaseType'] in ('master', 'rc', 'b', 'a'):\n-\t\t\t\t\tversions.append(repoVersion)\n-\t\t\t\telif userUpdatePref == 'beta' and repoVersion.infos['releaseType'] in ('master', 'rc', 'b'):\n-\t\t\t\t\tversions.append(repoVersion)\n-\t\t\t\telif userUpdatePref == 'rc' and repoVersion.infos['releaseType'] in ('master', 'rc'):\n-\t\t\t\t\tversions.append(repoVersion)\n-\n-\t\t\tif len(versions) > 0:\n-\t\t\t\tversions.sort(reverse=True)\n-\t\t\t\tupdateSource = versions[0]\n-\n-\t\treturn updateSource\n+\n+\t\tversions = list()\n+\t\tfor branch in result:\n+\t\t\trepoVersion = Version.fromString(branch['name'])\n+\n+\t\t\treleaseType = repoVersion.releaseType\n+\t\t\tif not repoVersion.isVersionNumber \\\n+\t\t\t\t\tor definedSource == 'rc' and releaseType in {'b', 'a'} \\\n+\t\t\t\t\tor definedSource == 'beta' and releaseType == 'a':\n+\t\t\t\tcontinue\n+\n+\t\t\tversions.append(repoVersion)\n+\n+\t\tif versions:\n+\t\t\tversions.sort(reverse=True)\n+\t\t\tupdateSource = versions[0]\n+\n+\t\treturn str(updateSource)\n \n \n \t@staticmethod\ndiff --git a/core/ProjectAlice.py b/core/ProjectAlice.py\n--- a/core/ProjectAlice.py\n+++ b/core/ProjectAlice.py\n@@ -1,17 +1,23 @@\n-import subprocess\n+from pathlib import Path\n+\n+import requests\n \n from core.base.SuperManager import SuperManager\n+from core.base.model.Version import Version\n+from core.commons import constants\n from core.commons.model.Singleton import Singleton\n from core.util.Stopwatch import Stopwatch\n+from core.util.model.Logger import Logger\n \n \n class ProjectAlice(Singleton):\n-\n \tNAME = 'ProjectAlice'\n \n+\n \tdef __init__(self, restartHandler: callable):\n \t\tSingleton.__init__(self, self.NAME)\n-\t\tself.logInfo('Starting up Project Alice')\n+\t\tself._logger = Logger()\n+\t\tself._logger.logInfo('Starting up Project Alice')\n \t\tself._booted = False\n \t\twith Stopwatch() as stopWatch:\n \t\t\tself._restart = False\n@@ -21,11 +27,11 @@ def __init__(self, restartHandler: callable):\n \t\t\tself._superManager.initManagers()\n \t\t\tself._superManager.onStart()\n \n-\t\t\tif self._superManager.configManager.getAliceConfigByName('useSLC'):\n-\t\t\t\tsubprocess.run(['sudo', 'systemctl', 'start', 'snipsledcontrol'])\n+\t\t\tif self._superManager.configManager.getAliceConfigByName('useHLC'):\n+\t\t\t\tself._superManager.commons.runRootSystemCommand(['systemctl', 'start', 'hermesledcontrol'])\n \n \t\t\tself._superManager.onBooted()\n-\t\tself.logInfo(f'- Started Project Alice in {stopWatch} seconds')\n+\t\tself._logger.logInfo(f'- Started Project Alice in {stopWatch} seconds')\n \t\tself._booted = True\n \n \n@@ -55,10 +61,46 @@ def doRestart(self):\n \n \n \tdef onStop(self):\n-\t\tself.logInfo('Shutting down Project Alice')\n+\t\tself._logger.logInfo('Shutting down Project Alice')\n \t\tself._superManager.onStop()\n-\t\tif self._superManager.configManager.getAliceConfigByName('useSLC'):\n-\t\t\tsubprocess.run(['sudo', 'systemctl', 'stop', 'snipsledcontrol'])\n+\t\tif self._superManager.configManager.getAliceConfigByName('useHLC'):\n+\t\t\tself._superManager.commons.runRootSystemCommand(['systemctl', 'stop', 'hermesledcontrol'])\n \n \t\tself.INSTANCE = None\n \t\tself._restartHandler()\n+\n+\n+\tdef updateProjectAlice(self):\n+\t\tself._logger.logInfo('Checking Project Alice updates')\n+\t\treq = requests.get(url=f'{constants.GITHUB_URL}/ProjectAlice/branches', auth=SuperManager.getInstance().configManager.getGithubAuth())\n+\t\tif req.status_code != 200:\n+\t\t\tself._logger.logWarning('Failed checking for updates')\n+\t\t\treturn\n+\n+\t\tuserUpdatePref = SuperManager.getInstance().configManager.getAliceConfigByName('aliceUpdateChannel')\n+\n+\t\tif userUpdatePref == 'master':\n+\t\t\tcandidate = 'master'\n+\t\telse:\n+\t\t\tcandidate = Version.fromString(constants.VERSION)\n+\t\t\tfor branch in req.json():\n+\t\t\t\trepoVersion = Version.fromString(branch['name'])\n+\t\t\t\tif not repoVersion.isVersionNumber:\n+\t\t\t\t\tcontinue\n+\n+\t\t\t\treleaseType = repoVersion.releaseType\n+\t\t\t\tif userUpdatePref == 'rc' and releaseType in {'b', 'a'} or userUpdatePref == 'beta' and releaseType == 'a':\n+\t\t\t\t\tcontinue\n+\n+\t\t\t\tif repoVersion > candidate:\n+\t\t\t\t\tcandidate = repoVersion\n+\n+\t\tself._logger.logInfo(f'Checking on \"{str(candidate)}\" update channel')\n+\t\tcommons = SuperManager.getInstance().commons\n+\t\tcommons.runSystemCommand(['git', '-C', commons.rootDir(), 'stash'])\n+\t\tcommons.runSystemCommand(['git', '-C', commons.rootDir(), 'clean', '-df'])\n+\t\tcommons.runSystemCommand(['git', '-C', commons.rootDir(), 'checkout', str(candidate)])\n+\t\tcommons.runSystemCommand(['git', '-C', commons.rootDir(), 'pull'])\n+\n+\t\t# Remove install tickets\n+\t\t[file.unlink() for file in Path(commons.rootDir(), 'system/skillInstallTickets').glob('*') if file.is_file()]\ndiff --git a/core/asr/ASRManager.py b/core/asr/ASRManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/asr/ASRManager.py\n@@ -0,0 +1,146 @@\n+from importlib import import_module, reload\n+from pathlib import Path\n+from typing import Dict\n+\n+import paho.mqtt.client as mqtt\n+\n+from core.asr.model import ASR\n+from core.asr.model.ASRResult import ASRResult\n+from core.asr.model.Recorder import Recorder\n+from core.base.model.Manager import Manager\n+from core.commons import constants\n+from core.dialog.model.DialogSession import DialogSession\n+\n+\n+class ASRManager(Manager):\n+\tNAME = 'ASRManager'\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__(self.NAME)\n+\t\tself._asr = None\n+\t\tself._streams: Dict[str, Recorder] = dict()\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\t\tself._startASREngine()\n+\n+\n+\tdef onStop(self):\n+\t\tif self._asr:\n+\t\t\tself._asr.onStop()\n+\n+\n+\tdef _startASREngine(self):\n+\t\tuserASR = self.ConfigManager.getAliceConfigByName(configName='asr').lower()\n+\t\tkeepASROffline = self.ConfigManager.getAliceConfigByName('keepASROffline')\n+\t\tstayOffline = self.ConfigManager.getAliceConfigByName('stayCompletlyOffline')\n+\t\tonline = self.InternetManager.online\n+\n+\t\tself._asr = None\n+\n+\t\tif userASR == 'google':\n+\t\t\tpackage = 'core.asr.model.GoogleASR'\n+\t\telse:\n+\t\t\tpackage = 'core.asr.model.PocketSphinxASR'\n+\n+\t\tmodule = import_module(package)\n+\t\tasr = getattr(module, package.rsplit('.', 1)[-1])\n+\t\tself._asr = asr()\n+\n+\t\tif not self._asr.checkDependencies():\n+\t\t\tif not self._asr.install():\n+\t\t\t\tself._asr = None\n+\t\t\telse:\n+\t\t\t\tmodule = reload(module)\n+\t\t\t\tasr = getattr(module, package.rsplit('.', 1)[-1])\n+\t\t\t\tself._asr = asr()\n+\n+\t\tif self._asr is None:\n+\t\t\tself.logFatal(\"Couldn't install ASR, going down\")\n+\t\t\treturn\n+\n+\t\tif self._asr.isOnlineASR and (not online or keepASROffline or stayOffline):\n+\t\t\tself._asr = None\n+\n+\t\tif self._asr is None:\n+\t\t\tself.logWarning('ASR did not satisfy the user settings, falling back to pocketsphinx')\n+\t\t\tfrom core.asr.model.PocketSphinxASR import PocketSphinxASR\n+\n+\t\t\tself._asr = PocketSphinxASR()\n+\n+\t\tself._asr.onStart()\n+\n+\n+\t@property\n+\tdef asr(self) -> ASR:\n+\t\treturn self._asr\n+\n+\n+\tdef onInternetConnected(self):\n+\t\tif self.ConfigManager.getAliceConfigByName('stayCompletlyOffline') or self.ConfigManager.getAliceConfigByName('keepASROffline'):\n+\t\t\treturn\n+\n+\t\tif not self._asr.isOnlineASR:\n+\t\t\tself.logInfo('Connected to internet, switching ASR')\n+\t\t\tself._asr.onStop()\n+\t\t\tself._startASREngine()\n+\n+\n+\tdef onInternetLost(self):\n+\t\tif self._asr.isOnlineASR:\n+\t\t\tself.logInfo('Internet lost, switching to offline ASR')\n+\t\t\tself._asr.onStop()\n+\t\t\tself._startASREngine()\n+\n+\n+\tdef onStartListening(self, session: DialogSession):\n+\t\tself._asr.onStartListening(session)\n+\t\tself.ThreadManager.newThread(name=f'streamdecode_{session.siteId}', target=self.decodeStream, args=[session])\n+\n+\n+\tdef onAsrIntermediateResult(self, result: str):\n+\t\tself.logDebug(result)\n+\n+\n+\tdef decodeStream(self, session: DialogSession):\n+\t\tresult: ASRResult = self._asr.decodeStream(session)\n+\n+\t\tif result and result.text:\n+\t\t\tself.MqttManager.publish(topic=constants.TOPIC_ASR_STOP_LISTENING, payload={'sessionId': session.sessionId, 'siteId': session.siteId})\n+\t\t\tself.logDebug(f'ASR captured: {result.text}')\n+\t\t\ttext = self.LanguageManager.sanitizeNluQuery(result.text)\n+\n+\t\t\t# supportedIntents = result.session.intentFilter or self.SkillManager.supportedIntents\n+\t\t\t# intentFilter = [intent.justTopic if isinstance(intent, Intent) else intent for intent in supportedIntents]\n+\n+\t\t\tself.MqttManager.publish(topic=constants.TOPIC_TEXT_CAPTURED, payload={'sessionId': session.sessionId, 'text': text, 'siteId': session.siteId, 'likelihood': result.likelihood, 'seconds': result.processingTime})\n+\t\t# self.MqttManager.publish(topic=constants.TOPIC_NLU_QUERY, payload={'input': text, 'intentFilter': intentFilter, 'sessionId': session.sessionId})\n+\t\telse:\n+\t\t\tself.MqttManager.publish(topic=constants.TOPIC_INTENT_NOT_RECOGNIZED)\n+\t\t\tself.MqttManager.playSound(\n+\t\t\t\tsoundFilename='error',\n+\t\t\t\tlocation=Path('assistant/custom_dialogue/sound'),\n+\t\t\t\tsiteId=session.siteId\n+\t\t\t)\n+\n+\t\tself._streams.pop(session.siteId, None)\n+\n+\n+\tdef onAudioFrame(self, message: mqtt.MQTTMessage, siteId: str):\n+\t\tif siteId not in self._streams or not self._streams[siteId].isRecording:\n+\t\t\treturn\n+\n+\t\tself._streams[siteId].onAudioFrame(message)\n+\n+\n+\tdef onSessionError(self, session: DialogSession):\n+\t\tif session.siteId not in self._streams or not self._streams[session.siteId].isRecording:\n+\t\t\treturn\n+\n+\t\tself._streams[session.siteId].onSessionError(session)\n+\n+\n+\tdef addRecorder(self, siteId: str, recorder: Recorder):\n+\t\tself._streams[siteId] = recorder\ndiff --git a/core/snips/samkilla/__init__.py b/core/asr/__init__.py\nsimilarity index 100%\nrename from core/snips/samkilla/__init__.py\nrename to core/asr/__init__.py\ndiff --git a/core/asr/model/ASR.py b/core/asr/model/ASR.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/asr/model/ASR.py\n@@ -0,0 +1,104 @@\n+import threading\n+from pathlib import Path\n+from threading import Event\n+from typing import Optional\n+\n+import pkg_resources\n+\n+from core.asr.model.Recorder import Recorder\n+from core.base.model.ProjectAliceObject import ProjectAliceObject\n+from core.commons import constants\n+from core.dialog.model.DialogSession import DialogSession\n+\n+\n+class ASR(ProjectAliceObject):\n+\tNAME = 'Generic ASR'\n+\tDEPENDENCIES = dict()\n+\n+\n+\tdef __init__(self):\n+\t\tself._capableOfArbitraryCapture = False\n+\t\tself._isOnlineASR = False\n+\t\tself._timeout = Event()\n+\t\tself._timeoutTimer: Optional[threading.Timer] = None\n+\t\tsuper().__init__()\n+\n+\n+\t@property\n+\tdef capableOfArbitraryCapture(self) -> bool:\n+\t\treturn self._capableOfArbitraryCapture\n+\n+\n+\t@property\n+\tdef isOnlineASR(self) -> bool:\n+\t\treturn self._isOnlineASR\n+\n+\n+\tdef checkDependencies(self) -> bool:\n+\t\tself.logInfo('Checking dependencies')\n+\t\ttry:\n+\t\t\tpkg_resources.require(self.DEPENDENCIES['pip'])\n+\t\t\treturn True\n+\t\texcept:\n+\t\t\tself.logInfo('Found missing dependencies')\n+\t\t\treturn False\n+\n+\n+\tdef install(self) -> bool:\n+\t\tself.logInfo('Installing dependencies')\n+\n+\t\ttry:\n+\t\t\tfor dep in self.DEPENDENCIES['system']:\n+\t\t\t\tself.Commons.runRootSystemCommand(['apt-get', 'install', '-y', dep])\n+\t\t\t\tself.logInfo(f'Installed \"{dep}\"')\n+\n+\t\t\tfor dep in self.DEPENDENCIES['pip']:\n+\t\t\t\tself.Commons.runSystemCommand(['./venv/bin/pip', 'install', dep])\n+\t\t\t\tself.logInfo(f'Installed \"{dep}\"')\n+\n+\t\t\treturn True\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Installing dependencies failed: {e}')\n+\t\t\treturn False\n+\n+\n+\tdef onStart(self):\n+\t\tself.logInfo(f'Starting {self.NAME}')\n+\n+\n+\tdef onStop(self):\n+\t\tself.logInfo(f'Stopping {self.NAME}')\n+\t\tself._timeout.set()\n+\n+\n+\tdef onStartListening(self, session):\n+\t\tself.MqttManager.mqttClient.subscribe(constants.TOPIC_AUDIO_FRAME.format(session.siteId))\n+\n+\n+\tdef decodeFile(self, filepath: Path, session: DialogSession):\n+\t\tpass\n+\n+\n+\tdef decodeStream(self, session: DialogSession):\n+\t\tself._timeout.clear()\n+\t\tself._timeoutTimer = self.ThreadManager.newTimer(interval=int(self.ConfigManager.getSnipsConfiguration('snips-dialogue', 'session_timeout').value) or 30, func=self.timeout)\n+\n+\n+\tdef end(self, recorder: Recorder, session: DialogSession):\n+\t\tself.MqttManager.mqttClient.unsubscribe(constants.TOPIC_AUDIO_FRAME.format(session.siteId))\n+\t\trecorder.stopRecording()\n+\t\tif self._timeoutTimer and self._timeoutTimer.is_alive():\n+\t\t\tself._timeoutTimer.cancel()\n+\n+\n+\tdef timeout(self):\n+\t\tself._timeout.set()\n+\t\tself.logWarning('ASR timed out')\n+\n+\n+\tdef checkLanguage(self) -> bool:\n+\t\treturn True\n+\n+\n+\tdef downloadLanguage(self) -> bool:\n+\t\treturn False\ndiff --git a/core/asr/model/ASRResult.py b/core/asr/model/ASRResult.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/asr/model/ASRResult.py\n@@ -0,0 +1,11 @@\n+from dataclasses import dataclass\n+\n+from core.dialog.model.DialogSession import DialogSession\n+\n+\n+@dataclass\n+class ASRResult:\n+\ttext: str\n+\tsession: DialogSession\n+\tlikelihood: float\n+\tprocessingTime: float\ndiff --git a/core/asr/model/GoogleASR.py b/core/asr/model/GoogleASR.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/asr/model/GoogleASR.py\n@@ -0,0 +1,89 @@\n+from pathlib import Path\n+from typing import Optional\n+\n+import os\n+\n+from core.asr.model.ASR import ASR\n+from core.asr.model.ASRResult import ASRResult\n+from core.asr.model.Recorder import Recorder\n+from core.commons import constants\n+from core.dialog.model.DialogSession import DialogSession\n+\n+try:\n+\tfrom google.cloud.speech import SpeechClient, enums, types\n+except:\n+\tpass\n+\n+\n+class GoogleASR(ASR):\n+\tNAME = 'Google ASR'\n+\tDEPENDENCIES = {\n+\t\t'system': [],\n+\t\t'pip' : {\n+\t\t\t'google-cloud-speech==1.3.1'\n+\t\t}\n+\t}\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\t\tself._capableOfArbitraryCapture = True\n+\t\tself._isOnlineASR = True\n+\n+\t\tself._client: Optional[SpeechClient] = None\n+\t\tself._streamingConfig: Optional[types.StreamingRecognitionConfig] = None\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\t\tos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = str(Path(self.Commons.rootDir(), 'credentials/googlecredentials.json'))\n+\n+\t\tself._client = SpeechClient()\n+\t\t# noinspection PyUnresolvedReferences\n+\t\tconfig = types.RecognitionConfig(\n+\t\t\tencoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n+\t\t\tsample_rate_hertz=self.ConfigManager.getAliceConfigByName('micSampleRate'),\n+\t\t\tlanguage_code=self.LanguageManager.activeLanguageAndCountryCode\n+\t\t)\n+\n+\t\tself._streamingConfig = types.StreamingRecognitionConfig(config=config, interim_results=True)\n+\n+\n+\tdef decodeStream(self, session: DialogSession) -> Optional[ASRResult]:\n+\t\tsuper().decodeStream(session)\n+\t\trecorder = Recorder(self._timeout)\n+\t\tself.ASRManager.addRecorder(session.siteId, recorder)\n+\t\twith recorder as stream:\n+\t\t\taudioStream = stream.audioStream()\n+\t\t\trequests = (types.StreamingRecognizeRequest(audio_content=content) for content in audioStream)\n+\t\t\tresponses = self._client.streaming_recognize(self._streamingConfig, requests)\n+\t\t\tresult = self._checkResponses(responses)\n+\n+\t\tself.end(recorder, session)\n+\n+\t\treturn ASRResult(\n+\t\t\ttext=result[0],\n+\t\t\tsession=session,\n+\t\t\tlikelihood=result[1],\n+\t\t\tprocessingTime=10\n+\t\t) if result else None\n+\n+\n+\tdef _checkResponses(self, responses) -> Optional[tuple]:\n+\t\tif responses is None:\n+\t\t\treturn None\n+\n+\t\tfor response in responses:\n+\t\t\tif not response.results:\n+\t\t\t\tcontinue\n+\n+\t\t\tresult = response.results[0]\n+\t\t\tif not result.alternatives:\n+\t\t\t\tcontinue\n+\n+\t\t\tif result.is_final:\n+\t\t\t\treturn result.alternatives[0].transcript, result.alternatives[0].confidence\n+\t\t\telse:\n+\t\t\t\tself.broadcast(method=constants.EVENT_ASR_INTERMEDIATE_RESULT, exceptions=[constants.DUMMY], propagateToSkills=True, result=result.alternatives[0].transcript)\n+\n+\t\treturn None\ndiff --git a/core/asr/model/PocketSphinxASR.py b/core/asr/model/PocketSphinxASR.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/asr/model/PocketSphinxASR.py\n@@ -0,0 +1,127 @@\n+from pathlib import Path\n+from typing import Optional\n+\n+import shutil\n+import tarfile\n+\n+from core.asr.model.ASR import ASR\n+from core.asr.model.ASRResult import ASRResult\n+from core.asr.model.Recorder import Recorder\n+from core.dialog.model.DialogSession import DialogSession\n+from core.util.Stopwatch import Stopwatch\n+\n+try:\n+\tfrom pocketsphinx import Decoder\n+except:\n+\tpass\n+\n+\n+class PocketSphinxASR(ASR):\n+\tNAME = 'Pocketsphinx ASR'\n+\tDEPENDENCIES = {\n+\t\t'system': [\n+\t\t\t'swig',\n+\t\t\t'libpulse-dev'\n+\t\t],\n+\t\t'pip' : [\n+\t\t\t'pocketsphinx==0.1.15'\n+\t\t]\n+\t}\n+\n+\tLANGUAGE_PACKS = {\n+\t\t'fr': {\n+\t\t\t'cmusphinx-fr-ptm-8khz-5.2.tar.gz': 'https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/French/cmusphinx-fr-ptm-8khz-5.2.tar.gz/download',\n+\t\t\t'cmudict-fr-fr.dict' : 'https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/French/fr.dict/download',\n+\t\t\t'fr-fr.lm.bin' : 'https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/French/fr-small.lm.bin/download'\n+\t\t},\n+\t\t'de': {\n+\t\t\t'cmusphinx-de-voxforge-5.2.tar.gz': 'https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/German/cmusphinx-de-voxforge-5.2.tar.gz/download',\n+\t\t\t'cmudict-de-de.dict' : 'https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/German/cmusphinx-voxforge-de.dic/download',\n+\t\t\t'de-de.lm.bin' : 'https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/German/cmusphinx-voxforge-de.lm.bin/download',\n+\t\t}\n+\t}\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\t\tself._capableOfArbitraryCapture = True\n+\t\tself._isOnlineASR = False\n+\t\tself._decoder: Optional[Decoder] = None\n+\t\tself._config = None\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\n+\t\tif not self.checkLanguage():\n+\t\t\tself.downloadLanguage()\n+\n+\t\tself._config = Decoder.default_config()\n+\t\tself._config.set_string('-hmm', f'{self.Commons.rootDir()}/venv/lib/python3.7/site-packages/pocketsphinx/model/{self.LanguageManager.activeLanguageAndCountryCode.lower()}')\n+\t\tself._config.set_string('-lm', f'{self.Commons.rootDir()}/venv/lib/python3.7/site-packages/pocketsphinx/model/{self.LanguageManager.activeLanguageAndCountryCode.lower()}.lm.bin')\n+\t\tself._config.set_string('-dict', f'{self.Commons.rootDir()}/venv/lib/python3.7/site-packages/pocketsphinx/model/cmudict-{self.LanguageManager.activeLanguageAndCountryCode.lower()}.dict')\n+\t\tself._decoder = Decoder(self._config)\n+\n+\n+\tdef checkLanguage(self) -> bool:\n+\t\tif not Path(self.Commons.rootDir(), f'venv/lib/python3.7/site-packages/pocketsphinx/model/{self.LanguageManager.activeLanguageAndCountryCode.lower()}').exists():\n+\t\t\tself.logInfo('Missing language model')\n+\t\t\treturn False\n+\n+\t\treturn True\n+\n+\n+\tdef downloadLanguage(self) -> bool:\n+\t\tself.logInfo(f'Downloading language model for \"{self.LanguageManager.activeLanguage}\"')\n+\n+\t\tvenv = Path(self.Commons.rootDir(), 'venv/lib/python3.7/site-packages/pocketsphinx/')\n+\t\tfor filename, url in self.LANGUAGE_PACKS[self.LanguageManager.activeLanguage].items():\n+\t\t\tdownload = Path(venv, 'model', filename)\n+\t\t\tself.Commons.downloadFile(url=url, dest=str(download))\n+\n+\t\t\tif filename.endswith('.tar.gz'):\n+\t\t\t\tdest = Path(venv, 'model', self.LanguageManager.activeLanguageAndCountryCode.lower())\n+\n+\t\t\t\tif dest.exists():\n+\t\t\t\t\tshutil.rmtree(dest)\n+\n+\t\t\t\tdirName = filename.replace('.tar.gz', '')\n+\t\t\t\ttar = tarfile.open(str(download))\n+\t\t\t\ttar.extractall(str(download).replace('.tar.gz', ''))\n+\t\t\t\tPath(venv, 'model', dirName, dirName).rename(str(Path(venv, 'model', self.LanguageManager.activeLanguageAndCountryCode.lower())))\n+\t\t\t\tshutil.rmtree(Path(venv, 'model', dirName))\n+\t\t\t\tdownload.unlink()\n+\n+\t\tself.logInfo('Downloaded and installed')\n+\t\treturn True\n+\n+\n+\tdef decodeStream(self, session: DialogSession) -> Optional[ASRResult]:\n+\t\tsuper().decodeStream(session)\n+\n+\t\tresult = None\n+\t\twith Stopwatch() as processingTime:\n+\t\t\twith Recorder(self._timeout) as recorder:\n+\t\t\t\tself.ASRManager.addRecorder(session.siteId, recorder)\n+\t\t\t\tself._decoder.start_utt()\n+\t\t\t\tinSpeech = False\n+\t\t\t\tfor chunk in recorder:\n+\t\t\t\t\tif self._timeout.isSet():\n+\t\t\t\t\t\tbreak\n+\n+\t\t\t\t\tself._decoder.process_raw(chunk, False, False)\n+\t\t\t\t\tif self._decoder.get_in_speech() != inSpeech:\n+\t\t\t\t\t\tinSpeech = self._decoder.get_in_speech()\n+\t\t\t\t\t\tif not inSpeech:\n+\t\t\t\t\t\t\tself._decoder.end_utt()\n+\t\t\t\t\t\t\tresult = self._decoder.hyp() if self._decoder.hyp() else None\n+\t\t\t\t\t\t\tbreak\n+\n+\t\t\t\tself.end(recorder, session)\n+\n+\t\treturn ASRResult(\n+\t\t\ttext=result.hypstr.strip(),\n+\t\t\tsession=session,\n+\t\t\tlikelihood=self._decoder.hyp().prob,\n+\t\t\tprocessingTime=processingTime.time\n+\t\t) if result else None\ndiff --git a/core/asr/model/Recorder.py b/core/asr/model/Recorder.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/asr/model/Recorder.py\n@@ -0,0 +1,99 @@\n+import queue\n+import threading\n+from typing import Optional\n+\n+import paho.mqtt.client as mqtt\n+import struct\n+\n+from core.base.model.ProjectAliceObject import ProjectAliceObject\n+from core.dialog.model.DialogSession import DialogSession\n+\n+\n+class Recorder(ProjectAliceObject):\n+\n+\tdef __init__(self, timeoutFlag: threading.Event):\n+\t\tsuper().__init__()\n+\t\tself._recording = False\n+\t\tself._timeoutFlag = timeoutFlag\n+\t\tself._buffer = queue.Queue()\n+\n+\n+\tdef __enter__(self):\n+\t\tself.startRecording()\n+\t\treturn self\n+\n+\n+\tdef __exit__(self, exc_type, exc_val, exc_tb):\n+\t\tself.stopRecording()\n+\n+\n+\t@property\n+\tdef isRecording(self) -> bool:\n+\t\treturn self._recording\n+\n+\n+\tdef onSessionError(self, session: DialogSession):\n+\t\tself.stopRecording()\n+\n+\n+\tdef startRecording(self):\n+\t\tself._recording = True\n+\n+\n+\tdef stopRecording(self):\n+\t\tself._recording = False\n+\t\tself._buffer.put(None)\n+\n+\n+\tdef onAudioFrame(self, message: mqtt.MQTTMessage):\n+\t\ttry:\n+\t\t\triff, size, fformat = struct.unpack('<4sI4s', message.payload[:12])\n+\n+\t\t\tif riff != b'RIFF':\n+\t\t\t\tself.logError('Frame parse error')\n+\t\t\t\treturn\n+\n+\t\t\tif fformat != b'WAVE':\n+\t\t\t\tself.logError('Frame wrong format')\n+\t\t\t\treturn\n+\n+\t\t\tchunkOffset = 52\n+\t\t\twhile chunkOffset < size:\n+\t\t\t\tsubChunk2Id, subChunk2Size = struct.unpack('<4sI', message.payload[chunkOffset:chunkOffset + 8])\n+\t\t\t\tchunkOffset += 8\n+\t\t\t\tif subChunk2Id == b'data':\n+\t\t\t\t\tself._buffer.put(message.payload[chunkOffset:chunkOffset + subChunk2Size])\n+\n+\t\t\t\tchunkOffset = chunkOffset + subChunk2Size + 8\n+\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Error recording user speech: {e}')\n+\n+\n+\tdef __iter__(self):\n+\t\twhile self._recording:\n+\t\t\tyield self._buffer.get()\n+\n+\n+\tdef audioStream(self) -> Optional[bytes]:\n+\t\twhile self._recording:\n+\t\t\tif self._timeoutFlag.isSet():\n+\t\t\t\treturn\n+\n+\t\t\tchunk = self._buffer.get()\n+\t\t\tif not chunk:\n+\t\t\t\treturn\n+\n+\t\t\tdata = [chunk]\n+\n+\t\t\twhile True:\n+\t\t\t\ttry:\n+\t\t\t\t\tchunk = self._buffer.get(block=False)\n+\t\t\t\t\tif not chunk:\n+\t\t\t\t\t\treturn\n+\n+\t\t\t\t\tdata.append(chunk)\n+\t\t\t\texcept queue.Empty:\n+\t\t\t\t\tbreak\n+\n+\t\t\tyield b''.join(data)\ndiff --git a/core/snips/samkilla/gql/__init__.py b/core/asr/model/__init__.py\nsimilarity index 100%\nrename from core/snips/samkilla/gql/__init__.py\nrename to core/asr/model/__init__.py\ndiff --git a/core/base/ConfigManager.py b/core/base/ConfigManager.py\n--- a/core/base/ConfigManager.py\n+++ b/core/base/ConfigManager.py\n@@ -1,15 +1,12 @@\n import json\n-import subprocess\n+import logging\n from pathlib import Path\n \n-import requests\n import shutil\n \n import configTemplate\n from core.base.SkillManager import SkillManager\n-from core.base.model.GithubCloner import GithubCloner\n from core.base.model.TomlFile import TomlFile\n-from core.base.model.Version import Version\n \n try:\n \t# noinspection PyUnresolvedReferences,PyPackageRequirements\n@@ -28,10 +25,8 @@\n \n class ConfigManager(Manager):\n \n-\tNAME = 'ConfigManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n \t\tself._aliceSkillConfigurationKeys = [\n \t\t\t'active',\n@@ -40,11 +35,7 @@ def __init__(self):\n \t\t\t'conditions'\n \t\t]\n \n-\t\tself._vitalConfigs = [\n-\t\t\t'intentsOwner',\n-\t\t\t'snipsConsoleLogin',\n-\t\t\t'snipsConsolePassword'\n-\t\t]\n+\t\tself._vitalConfigs = list()\n \n \t\tself._aliceConfigurations: typing.Dict[str, typing.Any] = self._loadCheckAndUpdateAliceConfigFile()\n \t\tself._aliceTemplateConfigurations: typing.Dict[str, dict] = configTemplate.settings\n@@ -64,7 +55,8 @@ def onStart(self):\n \n \n \tdef _setDefaultSiteId(self):\n-\t\tconstants.DEFAULT_SITE_ID = self._snipsConfigurations['snips-audio-server']['bind'].replace('@mqtt', '')\n+\t\tif self._snipsConfigurations['snips-audio-server']['bind']:\n+\t\t\tconstants.DEFAULT_SITE_ID = self._snipsConfigurations['snips-audio-server']['bind'].replace('@mqtt', '')\n \n \n \tdef _loadCheckAndUpdateAliceConfigFile(self) -> dict:\n@@ -107,6 +99,10 @@ def _loadCheckAndUpdateAliceConfigFile(self) -> dict:\n \t\t\t\t\t\tself.logInfo(f'- Selected value \"{aliceConfigs[setting]}\" for setting \"{setting}\" doesn\\'t exist, reverted to default value \"{definition[\"defaultValue\"]}\"')\n \t\t\t\t\t\taliceConfigs[setting] = definition['defaultValue']\n \n+\t\t# Setting logger level immediately\n+\t\tif aliceConfigs['debug']:\n+\t\t\tlogging.getLogger('ProjectAlice').setLevel(logging.DEBUG)\n+\n \t\ttemp = aliceConfigs.copy()\n \n \t\tfor k, v in temp.items():\n@@ -131,7 +127,7 @@ def updateAliceConfiguration(self, key: str, value: typing.Any):\n \t\tif key not in self._aliceConfigurations:\n \t\t\tself.logWarning(f'Was asked to update {key} but key doesn\\'t exist')\n \t\t\traise ConfigurationUpdateFailed()\n-\t\t\n+\n \t\ttry:\n \t\t\t# Remove skill configurations\n \t\t\tif key == 'skills':\n@@ -141,7 +137,6 @@ def updateAliceConfiguration(self, key: str, value: typing.Any):\n \n \t\tself._aliceConfigurations[key] = value\n \t\tself.writeToAliceConfigurationFile(self.aliceConfigurations)\n-\t\t\n \n \n \tdef updateSkillConfigurationFile(self, skillName: str, key: str, value: typing.Any):\n@@ -156,9 +151,9 @@ def updateSkillConfigurationFile(self, skillName: str, key: str, value: typing.A\n \t\t# Cast value to template defined type\n \t\tvartype = self._skillsTemplateConfigurations[skillName][key]['dataType']\n \t\tif vartype == 'boolean':\n-\t\t\tif value in ('on', 'yes', 'true', 'active'):\n+\t\t\tif value.lower() in {'on', 'yes', 'true', 'active'}:\n \t\t\t\tvalue = True\n-\t\t\telif value in ('off', 'no', 'false', 'inactive'):\n+\t\t\telif value.lower() in {'off', 'no', 'false', 'inactive'}:\n \t\t\t\tvalue = False\n \t\telif vartype == 'integer':\n \t\t\ttry:\n@@ -172,7 +167,7 @@ def updateSkillConfigurationFile(self, skillName: str, key: str, value: typing.A\n \t\t\texcept:\n \t\t\t\tself.logWarning(f'Value missmatch for config {key} in skill {skillName}')\n \t\t\t\tvalue = 0.0\n-\t\telif vartype in ('string', 'email', 'password'):\n+\t\telif vartype in {'string', 'email', 'password'}:\n \t\t\ttry:\n \t\t\t\tvalue = str(value)\n \t\t\texcept:\n@@ -205,8 +200,8 @@ def writeToAliceConfigurationFile(self, confs: dict):\n \t\tself._aliceConfigurations = sort\n \n \t\ttry:\n-\t\t\ts = json.dumps(sort, indent=4).replace('false', 'False').replace('true', 'True')\n-\t\t\tPath('config.py').write_text(f'settings = {s}')\n+\t\t\tconfString = json.dumps(sort, indent=4).replace('false', 'False').replace('true', 'True')\n+\t\t\tPath('config.py').write_text(f'settings = {confString}')\n \t\t\timportlib.reload(config)\n \t\texcept Exception:\n \t\t\traise ConfigurationUpdateFailed()\n@@ -234,7 +229,7 @@ def loadSnipsConfigurations(self) -> TomlFile:\n \t\tsnipsConfigTemplatePath = Path(self.Commons.rootDir(), 'system/snips/snips.toml')\n \n \t\tif not snipsConfigPath.exists():\n-\t\t\tsubprocess.run(['sudo', 'cp', snipsConfigTemplatePath, '/etc/snips.toml'])\n+\t\t\tself.Commons.runRootSystemCommand(['cp', snipsConfigTemplatePath, '/etc/snips.toml'])\n \t\t\tsnipsConfigPath = snipsConfigTemplatePath\n \n \t\tsnipsConfig = TomlFile.loadToml(snipsConfigPath)\n@@ -270,7 +265,7 @@ def getSnipsConfiguration(self, parent: str, key: str, createIfNotExist: bool =\n \t\t:return: config value\n \t\t\"\"\"\n \t\tif createIfNotExist and key not in self._snipsConfigurations[parent]:\n-\t\t\tconf = self._snipsConfigurations[parent][key] # TomlFile does auto create missing keys\n+\t\t\tconf = self._snipsConfigurations[parent][key] # TomlFile does auto create missing keys\n \t\t\tself._snipsConfigurations.dump()\n \t\t\treturn conf\n \n@@ -400,9 +395,9 @@ def loadCheckAndUpdateSkillConfigurations(self, skill: str = None):\n \t\t\t\ttry:\n \t\t\t\t\tinstallFile = json.load(Path(skillsPath / skillDirectory / f'{skillName}.install').open())\n \t\t\t\t\tnode = {\n-\t\t\t\t\t\t'active' : True,\n-\t\t\t\t\t\t'version' : installFile['version'],\n-\t\t\t\t\t\t'author' : installFile['author'],\n+\t\t\t\t\t\t'active': True,\n+\t\t\t\t\t\t'version': installFile['version'],\n+\t\t\t\t\t\t'author': installFile['author'],\n \t\t\t\t\t\t'conditions': installFile['conditions']\n \t\t\t\t\t}\n \t\t\t\t\tconfig = {**config, **node}\n@@ -414,7 +409,7 @@ def loadCheckAndUpdateSkillConfigurations(self, skill: str = None):\n \t\t\t\t\t\tcontinue\n \t\t\t\t\telse:\n \t\t\t\t\t\tself.logError(f'- Failed generating default config, scheduling download for skill \"{skillName}\": {e}')\n-\t\t\t\t\t\tsubprocess.run(['wget', f'http://skills.projectalice.ch/{skillName}', '-O', Path(self.Commons.rootDir(), f'system/skillInstallTickets/{skillName}.install')])\n+\t\t\t\t\t\tself.Commons.downloadFile(f'https://skills.projectalice.ch/{skillName}', f'system/skillInstallTickets/{skillName}.install')\n \t\t\t\t\t\tif skillName in skillsConfigurations:\n \t\t\t\t\t\t\tskillsConfigurations.pop(skillName)\n \t\t\t\t\t\tcontinue\n@@ -422,7 +417,6 @@ def loadCheckAndUpdateSkillConfigurations(self, skill: str = None):\n \t\t\tif config:\n \t\t\t\tskillsConfigurations[skillName] = config\n \n-\n \t\tself._skillsConfigurations = {**self._skillsConfigurations, **skillsConfigurations}\n \n \n@@ -472,52 +466,50 @@ def changeActiveLanguage(self, toLang: str):\n \t\treturn False\n \n \n-\tdef changeActiveSnipsProjectIdForLanguage(self, projectId: str, forLang: str):\n-\t\tlangConfig = self.getAliceConfigByName('supportedLanguages').copy()\n-\n-\t\tif forLang in langConfig:\n-\t\t\tlangConfig[forLang]['snipsProjectId'] = projectId\n-\n-\t\tself.updateAliceConfiguration('supportedLanguages', langConfig)\n-\n-\n \tdef getAliceConfigType(self, confName: str) -> typing.Optional[str]:\n \t\t# noinspection PyTypeChecker\n-\t\treturn self._aliceConfigurations.get(confName['dataType'], None)\n+\t\treturn self._aliceConfigurations.get(confName['dataType'])\n \n \n \tdef isAliceConfHidden(self, confName: str) -> bool:\n \t\treturn confName in self._aliceTemplateConfigurations and \\\n-\t\t\tself._aliceTemplateConfigurations.get('display') == 'hidden'\n-\n-\n-\tdef getSkillsUpdateSource(self) -> str:\n-\t\tupdateSource = 'master'\n-\t\tif self.getAliceConfigByName('updateChannel') == 'master':\n-\t\t\treturn updateSource\n-\n-\t\treq = requests.get('https://api.github.com/repos/project-alice-assistant/ProjectAliceSkills/branches', auth=GithubCloner.getGithubAuth())\n-\t\tresult = req.json()\n-\t\tif result:\n-\t\t\tuserUpdatePref = self.getAliceConfigByName('updateChannel')\n-\t\t\tversions = list()\n-\t\t\tfor branch in result:\n-\t\t\t\trepoVersion = Version(branch['name'])\n-\t\t\t\tif not repoVersion.isVersionNumber:\n-\t\t\t\t\tcontinue\n+\t\t self._aliceTemplateConfigurations.get('display') == 'hidden'\n+\n+\n+\tdef getAliceConfUpdatePostProcessing(self, confName: str) -> typing.Optional[str]:\n+\t\t# Some config need some post processing if updated while Alice is running\n+\t\treturn self._aliceTemplateConfigurations.get(confName, dict()).get('onUpdate')\n+\n+\n+\tdef doConfigUpdatePostProcessing(self, functions: set):\n+\t\t# Call alice config post processing functions. This will call methods that are needed after a certain setting was\n+\t\t# updated while Project Alice was running\n+\t\tfor function in functions:\n+\t\t\ttry:\n+\t\t\t\tfunc = getattr(self, function)\n+\t\t\t\tfunc()\n+\t\t\texcept:\n+\t\t\t\tself.logWarning(f'Configuration post processing method \"{function}\" does not exist')\n+\t\t\t\tcontinue\n+\n+\n+\tdef reconnectMqtt(self):\n+\t\tself.MqttManager.reconnect()\n+\n+\n+\tdef reloadASR(self):\n+\t\tself.ASRManager.onStop()\n+\t\tself.ASRManager.onStart()\n+\n \n-\t\t\t\tif userUpdatePref == 'alpha' and repoVersion.infos['releaseType'] in ('master', 'rc', 'b', 'a'):\n-\t\t\t\t\tversions.append(repoVersion)\n-\t\t\t\telif userUpdatePref == 'beta' and repoVersion.infos['releaseType'] in ('master', 'rc', 'b'):\n-\t\t\t\t\tversions.append(repoVersion)\n-\t\t\t\telif userUpdatePref == 'rc' and repoVersion.infos['releaseType'] in ('master', 'rc'):\n-\t\t\t\t\tversions.append(repoVersion)\n+\tdef refreshStoreData(self):\n+\t\tself.SkillStoreManager.refreshStoreData()\n \n-\t\t\tif len(versions) > 0:\n-\t\t\t\tversions.sort(reverse=True)\n-\t\t\t\tupdateSource = versions[0]\n \n-\t\treturn updateSource\n+\tdef getGithubAuth(self) -> tuple:\n+\t\tusername = self.getAliceConfigByName('githubUsername')\n+\t\ttoken = self.getAliceConfigByName('githubToken')\n+\t\treturn (username, token) if (username and token) else None\n \n \n \t@property\ndiff --git a/core/base/SkillManager.py b/core/base/SkillManager.py\n--- a/core/base/SkillManager.py\n+++ b/core/base/SkillManager.py\n@@ -1,9 +1,9 @@\n import importlib\n import json\n-import subprocess\n from pathlib import Path\n-from typing import Optional\n+from typing import Dict, Optional\n \n+import os\n import requests\n import shutil\n \n@@ -15,21 +15,17 @@\n from core.base.model.Manager import Manager\n from core.base.model.Version import Version\n from core.commons import constants\n+from core.util.Decorators import IfSetting, Online\n \n \n class SkillManager(Manager):\n \n-\tNAME = 'SkillManager'\n-\n \tNEEDED_SKILLS = [\n \t\t'AliceCore',\n \t\t'ContextSensitive',\n \t\t'RedQueen'\n \t]\n \n-\tGITHUB_BARE_BASE_URL = 'https://raw.githubusercontent.com/project-alice-assistant/ProjectAliceSkills/master/PublishedSkills'\n-\tGITHUB_API_BASE_URL = 'repositories/193512918/contents/PublishedSkills'\n-\n \tDATABASE = {\n \t\t'widgets': [\n \t\t\t'parent TEXT NOT NULL UNIQUE',\n@@ -43,7 +39,7 @@ class SkillManager(Manager):\n \t}\n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME, self.DATABASE)\n+\t\tsuper().__init__(databaseSchema=self.DATABASE)\n \n \t\tself._busyInstalling = None\n \n@@ -60,13 +56,15 @@ def onStart(self):\n \t\tsuper().onStart()\n \n \t\tself._busyInstalling = self.ThreadManager.newEvent('skillInstallation')\n+\t\tself._skillInstallThread = self.ThreadManager.newThread(name='SkillInstallThread', target=self._checkForSkillInstall, autostart=False)\n \n \t\t# If it's the first time we start, don't delay skill install and do it on main thread\n \t\tif not self.ConfigManager.getAliceConfigByName('skills'):\n \t\t\tself.logInfo('Looks like a fresh install or skills were nuked. Let\\'s install the basic skills!')\n \t\t\tself._checkForSkillInstall()\n-\n-\t\tself._skillInstallThread = self.ThreadManager.newThread(name='SkillInstallThread', target=self._checkForSkillInstall, autostart=False)\n+\t\telse:\n+\t\t\tif self.checkForSkillUpdates():\n+\t\t\t\tself._checkForSkillInstall()\n \n \t\tself._activeSkills = self._loadSkillList()\n \t\tself._allSkills = {**self._activeSkills, **self._deactivatedSkills, **self._failedSkills}\n@@ -74,11 +72,12 @@ def onStart(self):\n \t\tfor skillName in self._deactivatedSkills:\n \t\t\tself.configureSkillIntents(skillName=skillName, state=False)\n \n-\t\tself.checkForSkillUpdates()\n \t\tself.startAllSkills()\n \n \n-\tdef onSnipsAssistantDownloaded(self, **kwargs):\n+\tdef onSnipsAssistantInstalled(self, **kwargs):\n+\t\tself.MqttManager.mqttBroadcast(topic='hermes/leds/clear')\n+\n \t\targv = kwargs.get('skillsInfos', dict())\n \t\tif not argv:\n \t\t\treturn\n@@ -95,16 +94,12 @@ def onSnipsAssistantDownloaded(self, **kwargs):\n \t\t\tself._activeSkills[skillName].onBooted()\n \n \t\t\tself.broadcast(\n-\t\t\t\tmethod='onSkillUpdated' if skill['update'] else 'onSkillInstalled',\n+\t\t\t\tmethod=constants.EVENT_SKILL_UPDATED if skill['update'] else constants.EVENT_SKILL_INSTALLED,\n \t\t\t\texceptions=[constants.DUMMY],\n \t\t\t\tskill=skillName\n \t\t\t)\n \n \n-\tdef onSkillInstalled(self):\n-\t\tpass\n-\n-\n \t@property\n \tdef widgets(self) -> dict:\n \t\treturn self._widgets\n@@ -141,7 +136,7 @@ def failedSkills(self) -> dict:\n \n \n \tdef onBooted(self):\n-\t\tself.skillBroadcast('onBooted')\n+\t\tself.skillBroadcast(constants.EVENT_BOOTED)\n \t\tself._skillInstallThread.start()\n \n \n@@ -188,7 +183,7 @@ def _loadSkillList(self, skillToLoad: str = '', isUpdate: bool = False) -> dict:\n \t\t\t\t\tskills[skillInstance.name] = skillInstance\n \t\t\t\telse:\n \t\t\t\t\tself._failedSkills[name] = None\n-\t\t\t\t\t\n+\n \t\t\texcept SkillStartingFailed as e:\n \t\t\t\tself.logWarning(f'Failed loading skill: {e}')\n \t\t\t\tcontinue\n@@ -231,7 +226,7 @@ def onStop(self):\n \n \t\tfor skillItem in self._activeSkills.values():\n \t\t\tskillItem.onStop()\n-\t\t\tself.logInfo(f\"- Stopped!\")\n+\t\t\tself.logInfo(f'- {skillItem.name} stopped!')\n \n \n \tdef onFullHour(self):\n@@ -260,7 +255,8 @@ def startAllSkills(self):\n \tdef _startSkill(self, skillInstance: AliceSkill) -> dict:\n \t\ttry:\n \t\t\tname = skillInstance.name\n-\t\t\tintents = skillInstance.onStart()\n+\t\t\tskillInstance.onStart()\n+\t\t\tintents = skillInstance.supportedIntents\n \n \t\t\tif skillInstance.widgets:\n \t\t\t\tself._widgets[name] = skillInstance.widgets\n@@ -282,10 +278,8 @@ def isSkillActive(self, skillName: str) -> bool:\n \n \n \tdef getSkillInstance(self, skillName: str, silent: bool = False) -> Optional[AliceSkill]:\n-\t\tif skillName in self._activeSkills:\n-\t\t\treturn self._activeSkills[skillName]\n-\t\telif skillName in self._deactivatedSkills:\n-\t\t\treturn self._deactivatedSkills[skillName]\n+\t\tif skillName in self._allSkills:\n+\t\t\treturn self._allSkills[skillName]\n \t\telse:\n \t\t\tif not silent:\n \t\t\t\tself.logWarning(f'Skill \"{skillName}\" is disabled or does not exist in skills manager')\n@@ -298,11 +292,12 @@ def skillBroadcast(self, method: str, filterOut: list = None, **kwargs):\n \t\tBroadcasts a call to the given method on every skill\n \t\t:param filterOut: array, skills not to broadcast to\n \t\t:param method: str, the method name to call on every skill\n-\t\t:param args: arguments that should be passed\n-\t\t:param silent\n \t\t:return:\n \t\t\"\"\"\n \n+\t\tif not method.startswith('on'):\n+\t\t\tmethod = f'on{method[0].capitalize() + method[1:]}'\n+\n \t\tfor skillItem in self._activeSkills.values():\n \n \t\t\tif filterOut and skillItem.name in filterOut:\n@@ -313,17 +308,20 @@ def skillBroadcast(self, method: str, filterOut: list = None, **kwargs):\n \t\t\t\tif func:\n \t\t\t\t\tfunc(**kwargs)\n \n-\t\t\texcept TypeError:\n-\t\t\t\t# Do nothing, it's most prolly kwargs\n-\t\t\t\tpass\n+\t\t\t\tfunc = getattr(skillItem, 'onEvent', None)\n+\t\t\t\tif func:\n+\t\t\t\t\tfunc(event=method, **kwargs)\n+\n+\t\t\texcept TypeError as e:\n+\t\t\t\tself.logWarning(f'- Failed to broadcast event {method} to {skillItem.name}: {e}')\n \n \n \tdef deactivateSkill(self, skillName: str, persistent: bool = False):\n \t\tif skillName in self._activeSkills:\n-\t\t\tself._activeSkills[skillName].active = False\n \t\t\tself.ConfigManager.deactivateSkill(skillName, persistent)\n \t\t\tself.configureSkillIntents(skillName=skillName, state=False)\n \t\t\tself._deactivatedSkills[skillName] = self._activeSkills.pop(skillName)\n+\t\t\tself._deactivatedSkills[skillName].active = False\n \n \n \tdef activateSkill(self, skillName: str, persistent: bool = False):\n@@ -335,36 +333,24 @@ def activateSkill(self, skillName: str, persistent: bool = False):\n \t\t\tself._activeSkills[skillName].onStart()\n \n \n+\t@Online(catchOnly=True)\n+\t@IfSetting(settingName='stayCompletlyOffline', settingValue=False)\n \tdef checkForSkillUpdates(self, skillToCheck: str = None) -> bool:\n-\t\tif self.ConfigManager.getAliceConfigByName('stayCompletlyOffline'):\n-\t\t\treturn False\n-\n \t\tself.logInfo('Checking for skill updates')\n-\t\tif not self.InternetManager.online:\n-\t\t\tself.logInfo('Not connected...')\n-\t\t\treturn False\n \n \t\tavailableSkills = self.ConfigManager.skillsConfigurations\n-\t\tupdateSource = self.ConfigManager.getSkillsUpdateSource()\n+\t\tupdateCount = 0\n \n-\t\ti = 0\n-\t\tfor skillName in self._allSkills:\n+\t\tfor skillName in availableSkills:\n \t\t\ttry:\n-\t\t\t\tif skillName not in availableSkills or (skillToCheck is not None and skillName != skillToCheck):\n+\t\t\t\tif skillToCheck and skillName != skillToCheck:\n \t\t\t\t\tcontinue\n-\t\n-\t\t\t\treq = requests.get(f'https://raw.githubusercontent.com/project-alice-assistant/ProjectAliceSkills/{updateSource}/PublishedSkills/{availableSkills[skillName][\"author\"]}/{skillName}/{skillName}.install')\n-\n-\t\t\t\tif req.status_code == 404:\n-\t\t\t\t\traise GithubNotFound\n \n-\t\t\t\tremoteFile = req.json()\n-\t\t\t\tif not remoteFile:\n-\t\t\t\t\traise Exception\n-\n-\t\t\t\tif Version(availableSkills[skillName]['version']) < Version(remoteFile['version']):\n-\t\t\t\t\ti += 1\n-\t\t\t\t\tself.logInfo(f'\u274c {skillName} - Version {availableSkills[skillName][\"version\"]} < {remoteFile[\"version\"]} in {self.ConfigManager.getAliceConfigByName(\"updateChannel\")}')\n+\t\t\t\tremoteVersion = self.SkillStoreManager.getSkillUpdateVersion(skillName)\n+\t\t\t\tlocalVersion = Version.fromString(availableSkills[skillName]['version'])\n+\t\t\t\tif localVersion < remoteVersion:\n+\t\t\t\t\tupdateCount += 1\n+\t\t\t\t\tself.logInfo(f'\u274c {skillName} - Version {availableSkills[skillName][\"version\"]} < {str(remoteVersion)} in {self.ConfigManager.getAliceConfigByName(\"skillsUpdateChannel\")}')\n \n \t\t\t\t\tif not self.ConfigManager.getAliceConfigByName('skillAutoUpdate'):\n \t\t\t\t\t\tif skillName in self._activeSkills:\n@@ -372,12 +358,20 @@ def checkForSkillUpdates(self, skillToCheck: str = None) -> bool:\n \t\t\t\t\t\telif skillName in self._deactivatedSkills:\n \t\t\t\t\t\t\tself._deactivatedSkills[skillName].updateAvailable = True\n \t\t\t\t\telse:\n-\t\t\t\t\t\tskillFile = Path(self.Commons.rootDir(), 'system/skillInstallTickets', skillName + '.install')\n+\t\t\t\t\t\treq = requests.get(f'{constants.GITHUB_RAW_URL}/skill_{skillName}/{self.SkillStoreManager.getSkillUpdateTag(skillName)}/{skillName}.install')\n+\t\t\t\t\t\tif req.status_code == 404:\n+\t\t\t\t\t\t\traise GithubNotFound\n+\n+\t\t\t\t\t\tremoteFile = req.json()\n+\t\t\t\t\t\tif not remoteFile:\n+\t\t\t\t\t\t\traise Exception\n+\n+\t\t\t\t\t\tskillFile = Path(self.Commons.rootDir(), constants.SKILL_INSTALL_TICKET_PATH, skillName + '.install')\n \t\t\t\t\t\tskillFile.write_text(json.dumps(remoteFile))\n \t\t\t\t\t\tif skillName in self._failedSkills:\n \t\t\t\t\t\t\tdel self._failedSkills[skillName]\n \t\t\t\telse:\n-\t\t\t\t\tself.logInfo(f'\u2714 {skillName} - Version {availableSkills[skillName][\"version\"]} in {self.ConfigManager.getAliceConfigByName(\"updateChannel\")}')\n+\t\t\t\t\tself.logInfo(f'\u2714 {skillName} - Version {availableSkills[skillName][\"version\"]} in {self.ConfigManager.getAliceConfigByName(\"skillsUpdateChannel\")}')\n \n \t\t\texcept GithubNotFound:\n \t\t\t\tself.logInfo(f'\u2753 Skill \"{skillName}\" is not available on Github. Deprecated or is it a dev skill?')\n@@ -385,57 +379,58 @@ def checkForSkillUpdates(self, skillToCheck: str = None) -> bool:\n \t\t\texcept Exception as e:\n \t\t\t\tself.logError(f'\u2757 Error checking updates for skill \"{skillName}\": {e}')\n \n-\t\tself.logInfo(f'Found {i} skill update(s)')\n-\t\treturn i > 0\n+\t\tself.logInfo(f'Found {updateCount} skill update(s)')\n+\t\treturn updateCount > 0\n \n \n+\t@Online(catchOnly=True)\n \tdef _checkForSkillInstall(self):\n \t\t# Don't start the install timer from the main thread in case it's the first start\n \t\tif self._skillInstallThread is not None:\n \t\t\tself.ThreadManager.newTimer(interval=10, func=self._checkForSkillInstall, autoStart=True)\n \n-\t\troot = Path(self.Commons.rootDir(), 'system/skillInstallTickets')\n+\t\troot = Path(self.Commons.rootDir(), constants.SKILL_INSTALL_TICKET_PATH)\n \t\tfiles = [f for f in root.iterdir() if f.suffix == '.install']\n \n-\t\tif self._busyInstalling.isSet() or \\\n-\t\t\tnot self.InternetManager.online or \\\n-\t\t\tnot files or \\\n-\t\t\tself.ThreadManager.getEvent('SnipsAssistantDownload').isSet():\n+\t\tif self._busyInstalling.isSet() or not files:\n \t\t\treturn\n \n-\t\tif files:\n-\t\t\tself.logInfo(f'Found {len(files)} install ticket(s)')\n-\t\t\tself._busyInstalling.set()\n+\t\tself.logInfo(f'Found {len(files)} install ticket(s)')\n+\t\tself._busyInstalling.set()\n+\n+\t\tskillsToBoot = dict()\n+\t\ttry:\n+\t\t\tskillsToBoot = self._installSkills(files)\n+\t\texcept Exception as e:\n+\t\t\tself._logger.error(f'Error installing skill: {e}')\n+\t\tfinally:\n+\t\t\tself.MqttManager.mqttBroadcast(topic='hermes/leds/clear')\n+\n+\t\t\tif skillsToBoot:\n+\t\t\t\tfor skillName, info in skillsToBoot.items():\n+\t\t\t\t\tself._activeSkills = self._loadSkillList(skillToLoad=skillName, isUpdate=info['update'])\n+\t\t\t\t\tself._allSkills = {**self._allSkills, **self._activeSkills}\n+\n+\t\t\t\t\tif info['update']:\n+\t\t\t\t\t\tself._allSkills[skillName].onSkillUpdated()\n+\t\t\t\t\telse:\n+\t\t\t\t\t\tself._allSkills[skillName].onSkillInstalled()\n \n-\t\t\tskillsToBoot = dict()\n-\t\t\ttry:\n-\t\t\t\tskillsToBoot = self._installSkills(files)\n-\t\t\texcept Exception as e:\n-\t\t\t\tself._logger.error(f'Error installing skill: {e}')\n-\t\t\tfinally:\n-\t\t\t\tself.MqttManager.mqttBroadcast(topic='hermes/leds/clear')\n-\n-\t\t\t\tif skillsToBoot:\n-\t\t\t\t\tfor skillName, info in skillsToBoot.items():\n-\t\t\t\t\t\tself._activeSkills = self._loadSkillList(skillToLoad=skillName, isUpdate=info['update'])\n-\t\t\t\t\t\tself._allSkills = {**self._allSkills, **self._activeSkills}\n-\n-\t\t\t\t\t\ttry:\n-\t\t\t\t\t\t\tself.LanguageManager.loadStrings(skillToLoad=skillName)\n-\t\t\t\t\t\t\tself.TalkManager.loadTalks(skillToLoad=skillName)\n-\t\t\t\t\t\texcept:\n-\t\t\t\t\t\t\tpass\n \t\t\t\t\ttry:\n-\t\t\t\t\t\tself.SamkillaManager.sync(skillFilter=skillsToBoot)\n-\t\t\t\t\texcept Exception as esamk:\n-\t\t\t\t\t\tself.logError(f'Failed syncing with remote snips console {esamk}')\n-\t\t\t\t\t\traise\n+\t\t\t\t\t\tself.LanguageManager.loadStrings(skillToLoad=skillName)\n+\t\t\t\t\t\tself.TalkManager.loadTalks(skillToLoad=skillName)\n+\t\t\t\t\texcept:\n+\t\t\t\t\t\tpass\n+\n+\t\t\t\tself.SnipsAssistantManager.train()\n+\t\t\t\tself.DialogTemplateManager.afterNewSkillInstall()\n+\t\t\t\tself.NluManager.afterNewSkillInstall()\n \n-\t\t\t\tself._busyInstalling.clear()\n+\t\t\tself._busyInstalling.clear()\n \n \n \tdef _installSkills(self, skills: list) -> dict:\n-\t\troot = Path(self.Commons.rootDir(), 'system/skillInstallTickets')\n+\t\troot = Path(self.Commons.rootDir(), constants.SKILL_INSTALL_TICKET_PATH)\n \t\tavailableSkills = self.ConfigManager.skillsConfigurations\n \t\tskillsToBoot = dict()\n \t\tself.MqttManager.mqttBroadcast(topic='hermes/leds/systemUpdate', payload={'sticky': True})\n@@ -467,14 +462,16 @@ def _installSkills(self, skills: list) -> dict:\n \t\t\t\tself.checkSkillConditions(skillName, conditions, availableSkills)\n \n \t\t\t\tif skillName in availableSkills:\n+\t\t\t\t\tinstalledVersion = Version.fromString(availableSkills[skillName]['version'])\n+\t\t\t\t\tremoteVersion = Version.fromString(installFile['version'])\n \t\t\t\t\tlocalVersionIsLatest: bool = \\\n \t\t\t\t\t\tdirectory.is_dir() and \\\n \t\t\t\t\t\t'version' in availableSkills[skillName] and \\\n-\t\t\t\t\t\tVersion(availableSkills[skillName]['version']) >= Version(installFile['version'])\n+\t\t\t\t\t\tinstalledVersion >= remoteVersion\n \n \t\t\t\t\tif localVersionIsLatest:\n \t\t\t\t\t\tself.logWarning(f'Skill \"{skillName}\" is already installed, skipping')\n-\t\t\t\t\t\tsubprocess.run(['sudo', 'rm', res])\n+\t\t\t\t\t\tself.Commons.runRootSystemCommand(['rm', res])\n \t\t\t\t\t\tcontinue\n \t\t\t\t\telse:\n \t\t\t\t\t\tself.logWarning(f'Skill \"{skillName}\" needs updating')\n@@ -487,10 +484,10 @@ def _installSkills(self, skills: list) -> dict:\n \t\t\t\t\t\tself.logError(f'Error stopping \"{skillName}\" for update: {e}')\n \t\t\t\t\t\traise\n \n-\t\t\t\tgitCloner = GithubCloner(baseUrl=self.GITHUB_API_BASE_URL, path=path, dest=directory)\n+\t\t\t\tgitCloner = GithubCloner(baseUrl=f'{constants.GITHUB_URL}/skill_{skillName}.git', path=path, dest=directory)\n \n \t\t\t\ttry:\n-\t\t\t\t\tgitCloner.clone()\n+\t\t\t\t\tgitCloner.clone(skillName=skillName)\n \t\t\t\t\tself.logInfo('Skill successfully downloaded')\n \t\t\t\t\tself._installSkill(res)\n \t\t\t\t\tskillsToBoot[skillName] = {\n@@ -515,8 +512,6 @@ def _installSkills(self, skills: list) -> dict:\n \t\t\t\t\telse:\n \t\t\t\t\t\tself.logWarning(f'Skill \"{skillName}\" is not available on Github, cannot install')\n \t\t\t\t\t\traise\n-\t\t\t\texcept Exception:\n-\t\t\t\t\traise\n \n \t\t\texcept SkillNotConditionCompliant as e:\n \t\t\t\tself.logInfo(f'Skill \"{skillName}\" does not comply to \"{e.condition}\" condition, required \"{e.conditionValue}\"')\n@@ -524,8 +519,8 @@ def _installSkills(self, skills: list) -> dict:\n \t\t\t\t\tres.unlink()\n \n \t\t\t\tself.broadcast(\n-\t\t\t\t\tmethod='onSkillInstallFailed',\n-\t\t\t\t\texceptions=self.name,\n+\t\t\t\t\tmethod=constants.EVENT_SKILL_INSTALL_FAILED,\n+\t\t\t\t\texceptions=self._name,\n \t\t\t\t\tskill=skillName\n \t\t\t\t)\n \n@@ -535,7 +530,7 @@ def _installSkills(self, skills: list) -> dict:\n \t\t\t\t\tres.unlink()\n \n \t\t\t\tself.broadcast(\n-\t\t\t\t\tmethod='onSkillInstallFailed',\n+\t\t\t\t\tmethod=constants.EVENT_SKILL_INSTALL_FAILED,\n \t\t\t\t\texceptions=self.name,\n \t\t\t\t\tskill=skillName\n \t\t\t\t)\n@@ -551,25 +546,30 @@ def _installSkill(self, res: Path):\n \t\t\tsysReqs = installFile.get('systemRequirements', list())\n \t\t\tscriptReq = installFile.get('script')\n \t\t\tdirectory = Path(self.Commons.rootDir()) / 'skills' / installFile['name']\n+\t\t\tinstalledInstallFile = Path(self.Commons.rootDir()) / 'skills' / installFile['name'] / f'{installFile[\"name\"]}.install'\n \n \t\t\tfor requirement in pipReqs:\n-\t\t\t\tsubprocess.run(['./venv/bin/pip3', 'install', requirement])\n+\t\t\t\tself.Commons.runSystemCommand(['./venv/bin/pip3', 'install', requirement])\n \n \t\t\tfor requirement in sysReqs:\n-\t\t\t\tsubprocess.run(['sudo', 'apt-get', 'install', '-y', requirement])\n+\t\t\t\tself.Commons.runRootSystemCommand(['apt-get', 'install', '-y', requirement])\n \n \t\t\tif scriptReq:\n-\t\t\t\tsubprocess.run(['sudo', 'chmod', '+x', str(directory / scriptReq)])\n-\t\t\t\tsubprocess.run(['sudo', str(directory / scriptReq)])\n-\n-\t\t\tnode = {\n-\t\t\t\t'active' : True,\n-\t\t\t\t'version' : installFile['version'],\n-\t\t\t\t'author' : installFile['author'],\n-\t\t\t\t'conditions': installFile['conditions']\n-\t\t\t}\n+\t\t\t\tself.Commons.runRootSystemCommand(['chmod', '+x', str(directory / scriptReq)])\n+\t\t\t\tself.Commons.runRootSystemCommand([str(directory / scriptReq)])\n+\n+\t\t\t# Grab the info of the skill we just installed, we can trust the installer file was up to date with the correct version number\n+\t\t\twith installedInstallFile.open() as fp:\n+\t\t\t\tdata = json.load(fp)\n+\n+\t\t\t\tnode = {\n+\t\t\t\t\t'active' : True,\n+\t\t\t\t\t'version' : data['version'],\n+\t\t\t\t\t'author' : data['author'],\n+\t\t\t\t\t'conditions': data['conditions']\n+\t\t\t\t}\n \n-\t\t\tshutil.move(str(res), str(directory))\n+\t\t\tos.unlink(str(res))\n \t\t\tself.ConfigManager.addSkillToAliceConfig(installFile['name'], node)\n \t\texcept Exception:\n \t\t\traise\n@@ -577,36 +577,39 @@ def _installSkill(self, res: Path):\n \n \tdef checkSkillConditions(self, skillName: str, conditions: dict, availableSkills: dict) -> bool:\n \n-\t\tif 'aliceMinVersion' in conditions and Version(conditions['aliceMinVersion']) > Version(constants.VERSION):\n-\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition='Alice minimum version', conditionValue=conditions['aliceMinVersion'])\n+\t\tnotCompliant = 'Skill is not compliant'\n+\n+\t\tif 'aliceMinVersion' in conditions and \\\n+\t\t\t\tVersion.fromString(conditions['aliceMinVersion']) > Version.fromString(constants.VERSION):\n+\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition='Alice minimum version', conditionValue=conditions['aliceMinVersion'])\n \n \t\tfor conditionName, conditionValue in conditions.items():\n \t\t\tif conditionName == 'lang' and self.LanguageManager.activeLanguage not in conditionValue:\n-\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n+\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \n \t\t\telif conditionName == 'online':\n-\t\t\t\tif conditionValue and self.ConfigManager.getAliceConfigByName('stayCompletlyOffline'):\n-\t\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n-\t\t\t\telif not conditionValue and not self.ConfigManager.getAliceConfigByName('stayCompletlyOffline'):\n-\t\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n+\t\t\t\tif conditionValue and self.ConfigManager.getAliceConfigByName('stayCompletlyOffline') \\\n+\t\t\t\t\t\tor not conditionValue and not self.ConfigManager.getAliceConfigByName('stayCompletlyOffline'):\n+\t\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \n \t\t\telif conditionName == 'skill':\n \t\t\t\tfor requiredSkill in conditionValue:\n \t\t\t\t\tif requiredSkill['name'] in availableSkills and not availableSkills[requiredSkill['name']]['active']:\n-\t\t\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n+\t\t\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \t\t\t\t\telif requiredSkill['name'] not in availableSkills:\n \t\t\t\t\t\tself.logInfo(f'Skill {skillName} has another skill as dependency, adding download')\n-\t\t\t\t\t\tsubprocess.run(['wget', requiredSkill['url'], '-O', Path(self.Commons.rootDir(), f\"system/skillInstallTickets/{requiredSkill['name']}.install\")])\n+\t\t\t\t\t\tif not self.Commons.downloadFile(requiredSkill['url'], Path(self.Commons.rootDir(), f\"system/skillInstallTickets/{requiredSkill['name']}.install\")):\n+\t\t\t\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \n \t\t\telif conditionName == 'notSkill':\n \t\t\t\tfor excludedSkill in conditionValue:\n \t\t\t\t\tauthor, name = excludedSkill.split('/')\n \t\t\t\t\tif name in availableSkills and availableSkills[name]['author'] == author and availableSkills[name]['active']:\n-\t\t\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n+\t\t\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \n \t\t\telif conditionName == 'asrArbitraryCapture':\n \t\t\t\tif conditionValue and not self.ASRManager.asr.capableOfArbitraryCapture:\n-\t\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n+\t\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \n \t\t\telif conditionName == 'activeManager':\n \t\t\t\tfor manager in conditionValue:\n@@ -614,7 +617,7 @@ def checkSkillConditions(self, skillName: str, conditions: dict, availableSkills\n \n \t\t\t\t\tman = SuperManager.getInstance().getManager(manager)\n \t\t\t\t\tif not man or not man.isActive:\n-\t\t\t\t\t\traise SkillNotConditionCompliant(message='Skill is not compliant', skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n+\t\t\t\t\t\traise SkillNotConditionCompliant(message=notCompliant, skillName=skillName, condition=conditionName, conditionValue=conditionValue)\n \n \t\treturn True\n \n@@ -624,7 +627,7 @@ def configureSkillIntents(self, skillName: str, state: bool):\n \t\t\tskill = self._activeSkills.get(skillName, self._deactivatedSkills.get(skillName))\n \t\t\tconfs = [{\n \t\t\t\t'intentId': intent.justTopic if hasattr(intent, 'justTopic') else intent,\n-\t\t\t\t'enable' : state\n+\t\t\t\t'enable': state\n \t\t\t} for intent in skill.supportedIntents if not self.isIntentInUse(intent=intent, filtered=[skillName])]\n \n \t\t\tself.MqttManager.configureIntents(confs)\n@@ -638,17 +641,202 @@ def isIntentInUse(self, intent: Intent, filtered: list) -> bool:\n \n \n \tdef removeSkill(self, skillName: str):\n-\t\tif skillName not in {**self._activeSkills, **self._deactivatedSkills, **self._failedSkills}:\n+\t\tif skillName not in self._allSkills:\n \t\t\treturn\n \n \t\tself.configureSkillIntents(skillName, False)\n \t\tself.ConfigManager.removeSkill(skillName)\n \n-\t\ttry:\n-\t\t\tdel self._activeSkills[skillName]\n-\t\texcept KeyError:\n-\t\t\tdel self._deactivatedSkills[skillName]\n+\t\tself._activeSkills.pop(skillName, None)\n+\t\tself._deactivatedSkills.pop(skillName, None)\n+\t\tself._allSkills.pop(skillName, None)\n \n \t\tshutil.rmtree(Path(self.Commons.rootDir(), 'skills', skillName))\n-\t\t# TODO Samkilla cleaning\n-\t\tself.SnipsConsoleManager.doDownload()\n+\n+\t\tself.SnipsAssistantManager.checkAssistant()\n+\t\tself.DialogTemplateManager.afterNewSkillInstall()\n+\t\tself.NluManager.afterNewSkillInstall()\n+\n+\n+\tdef reloadSkill(self, skillName: str):\n+\t\tif skillName not in self._allSkills:\n+\t\t\treturn\n+\n+\t\ttry:\n+\t\t\tself._allSkills[skillName].onStop()\n+\t\texcept:\n+\t\t\t# Do nothing, it's maybe because the skill crashed while running\n+\t\t\tpass\n+\n+\t\tself._loadSkillList(skillToLoad=skillName, isUpdate=True)\n+\t\tself._startSkill(self._allSkills[skillName])\n+\n+\n+\tdef allScenarioNodes(self, includeInactive: bool = False) -> Dict[str, tuple]:\n+\t\tskills = self._activeSkills if not includeInactive else self._allSkills\n+\n+\t\tret = dict()\n+\t\tfor skill in skills.values():\n+\t\t\tif not skill.hasScenarioNodes():\n+\t\t\t\tcontinue\n+\n+\t\t\tret[skill.name] = (skill.scenarioNodeName, skill.scenarioNodeVersion, Path(skill.getCurrentDir(), 'scenarioNodes'))\n+\n+\t\treturn ret\n+\n+\n+\tdef createNewSkill(self, skillDefinition: dict) -> bool:\n+\t\ttry:\n+\t\t\tself.logInfo(f'Creating new skill \"{skillDefinition[\"name\"]}\"')\n+\n+\t\t\trootDir = Path(self.Commons.rootDir()) / 'skills'\n+\t\t\tskillTemplateDir = rootDir / 'skill_DefaultTemplate'\n+\n+\t\t\tif skillTemplateDir.exists():\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(rootDir), 'stash'])\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(rootDir), 'clear', '-dfx'])\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(rootDir), 'pull'])\n+\t\t\telse:\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(rootDir), 'clone', f'{constants.GITHUB_URL}/skill_DefaultTemplate.git'])\n+\n+\t\t\tskillName = skillDefinition['name'][0].upper() + skillDefinition['name'][1:]\n+\t\t\tskillDir = rootDir / skillName\n+\n+\t\t\tskillTemplateDir.rename(skillDir)\n+\n+\t\t\tinstallFile = skillDir / f'{skillDefinition[\"name\"]}.install'\n+\t\t\tPath(skillDir, 'DefaultTemplate.install').rename(installFile)\n+\t\t\tsupportedLanguages = [\n+\t\t\t\t'en'\n+\t\t\t]\n+\t\t\tif skillDefinition['fr'] == 'yes':\n+\t\t\t\tsupportedLanguages.append('fr')\n+\t\t\tif skillDefinition['de'] == 'yes':\n+\t\t\t\tsupportedLanguages.append('de')\n+\n+\t\t\tconditions = {\n+\t\t\t\t'lang': supportedLanguages\n+\t\t\t}\n+\n+\t\t\treadmeConditions = ''\n+\t\t\treadmeReqs = ''\n+\t\t\treadmeWidgets = ''\n+\n+\t\t\tif skillDefinition['conditionOnline']:\n+\t\t\t\tconditions['online'] = True\n+\t\t\t\treadmeConditions += ' Online\\n'\n+\n+\t\t\tif skillDefinition['conditionASRArbitrary']:\n+\t\t\t\tconditions['asrArbitraryCapture'] = True\n+\t\t\t\treadmeConditions += ' Arbitrary capture\\n'\n+\n+\t\t\tif skillDefinition['conditionSkill']:\n+\t\t\t\tconditions['skill'] = [skill.strip() for skill in skillDefinition['conditionSkill'].split(',')]\n+\t\t\t\treadmeConditions += f' Required skills: {str(conditions[\"skill\"])}\\n'\n+\n+\t\t\tif skillDefinition['conditionNotSkill']:\n+\t\t\t\tconditions['notSkill'] = [skill.strip() for skill in skillDefinition['conditionNotSkill'].split(',')]\n+\t\t\t\treadmeConditions += f' Conflicting skills: {str(conditions[\"notSkill\"])}\\n'\n+\n+\t\t\tif skillDefinition['conditionActiveManager']:\n+\t\t\t\tconditions['activeManager'] = [manager.strip() for manager in skillDefinition['conditionActiveManager'].split(',')]\n+\t\t\t\treadmeConditions += f' Active managers: {str(conditions[\"activeManager\"])}\\n'\n+\n+\t\t\tinstallContent = {\n+\t\t\t\t'name' : skillName,\n+\t\t\t\t'version' : '0.0.1',\n+\t\t\t\t'author' : self.ConfigManager.getAliceConfigByName('githubUsername'),\n+\t\t\t\t'maintainers' : [],\n+\t\t\t\t'desc' : skillDefinition['description'].capitalize(),\n+\t\t\t\t'aliceMinVersion' : constants.VERSION,\n+\t\t\t\t'systemRequirements': [req.strip() for req in skillDefinition['sysreq'].split(',')],\n+\t\t\t\t'pipRequirements' : [req.strip() for req in skillDefinition['pipreq'].split(',')],\n+\t\t\t\t'conditions' : conditions\n+\t\t\t}\n+\n+\t\t\treadmeReqs += f' PIP: {str(installContent[\"pipRequirements\"])}\\n'\n+\t\t\treadmeReqs += f' System: {str(installContent[\"systemRequirements\"])}\\n'\n+\n+\t\t\t# Install file\n+\t\t\twith installFile.open('w') as fp:\n+\t\t\t\tfp.write(json.dumps(installContent, indent=4))\n+\n+\t\t\t# Dialog templates and talks\n+\t\t\tdialogTemplateTemplate = skillDir / 'dialogTemplate/default.json'\n+\t\t\twith dialogTemplateTemplate.open() as fp:\n+\t\t\t\tdialogTemplate = json.load(fp)\n+\t\t\t\tdialogTemplate['skill'] = skillName\n+\t\t\t\tdialogTemplate['description'] = skillDefinition['description'].capitalize()\n+\n+\t\t\tfor lang in supportedLanguages:\n+\t\t\t\twith Path(skillDir, f'dialogTemplate/{lang}.json').open('w+') as fp:\n+\t\t\t\t\tfp.write(json.dumps(dialogTemplate, indent=4))\n+\n+\t\t\t\twith Path(skillDir, f'talks/{lang}.json').open('w+') as fp:\n+\t\t\t\t\tfp.write(json.dumps(dict()))\n+\n+\t\t\tdialogTemplateTemplate.unlink()\n+\n+\t\t\t# Widgets\n+\t\t\tif skillDefinition['widgets']:\n+\t\t\t\twidgetRootDir = skillDir / 'widgets'\n+\t\t\t\tcss = widgetRootDir / 'css/widget.css'\n+\t\t\t\tjs = widgetRootDir / 'js/widget.js'\n+\t\t\t\tlang = widgetRootDir / 'lang/widget.json'\n+\t\t\t\thtml = widgetRootDir / 'templates/widget.html'\n+\t\t\t\tpython = widgetRootDir / 'widget.py'\n+\n+\t\t\t\tfor widget in skillDefinition['widgets'].split(','):\n+\t\t\t\t\twidgetName = widget.strip()\n+\t\t\t\t\twidgetName = widgetName[0].upper() + widgetName[1:]\n+\t\t\t\t\treadmeWidgets += f' {widgetName}\\n'\n+\n+\t\t\t\t\twith css.open() as fp:\n+\t\t\t\t\t\tcontent = fp.read().replace('%widgetname%', widgetName)\n+\n+\t\t\t\t\twith Path(widgetRootDir, f'css/{widgetName}.css').open('w+') as fp:\n+\t\t\t\t\t\tfp.write(content)\n+\n+\t\t\t\t\tshutil.copy(str(js), str(js).replace('widget.js', f'{widgetName}.js'))\n+\t\t\t\t\tshutil.copy(str(lang), str(lang).replace('widget.json', f'{widgetName}.json'))\n+\n+\t\t\t\t\twith html.open() as fp:\n+\t\t\t\t\t\tcontent = fp.read().replace('%widgetname%', widgetName)\n+\n+\t\t\t\t\twith Path(widgetRootDir, f'templates/{widgetName}.html').open('w+') as fp:\n+\t\t\t\t\t\tfp.write(content)\n+\n+\t\t\t\t\twith python.open() as fp:\n+\t\t\t\t\t\tcontent = fp.read().replace('Template(Widget)', f'{widgetName}(Widget)')\n+\n+\t\t\t\t\twith Path(widgetRootDir, f'{widgetName}.py').open('w+') as fp:\n+\t\t\t\t\t\tfp.write(content)\n+\n+\t\t\t\tcss.unlink()\n+\t\t\t\tjs.unlink()\n+\t\t\t\tlang.unlink()\n+\t\t\t\thtml.unlink()\n+\t\t\t\tpython.unlink()\n+\n+\t\t\telse:\n+\t\t\t\tshutil.rmtree(str(Path(skillDir, 'widgets')))\n+\n+\t\t\t# Readme file\n+\t\t\t# For some reason r+ mode appends at the end instead of overwritting\n+\t\t\twith Path(skillDir, 'README.md').open() as fp:\n+\t\t\t\tcontent = fp.read().replace('%skillname%', skillName) \\\n+\t\t\t\t\t.replace('%author%', self.ConfigManager.getAliceConfigByName('githubUsername')) \\\n+\t\t\t\t\t.replace('%description%', skillDefinition['description'].capitalize()) \\\n+\t\t\t\t\t.replace('%conditions%', readmeConditions) \\\n+\t\t\t\t\t.replace('%requirements%', readmeReqs) \\\n+\t\t\t\t\t.replace('%widgets%', readmeWidgets)\n+\n+\t\t\twith Path(skillDir, 'README.md').open('w') as fp:\n+\t\t\t\tfp.write(content)\n+\n+\t\t\tself.logInfo(f'Created \"{skillDefinition[\"name\"]}\" skill')\n+\n+\t\t\treturn True\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Error creating new skill: {e}')\n+\t\t\treturn False\ndiff --git a/core/base/SkillStoreManager.py b/core/base/SkillStoreManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/base/SkillStoreManager.py\n@@ -0,0 +1,84 @@\n+from typing import Optional\n+\n+import requests\n+\n+from core.ProjectAliceExceptions import GithubNotFound\n+from core.base.model.Manager import Manager\n+from core.base.model.Version import Version\n+from core.commons import constants\n+from core.util.Decorators import Online\n+\n+\n+class SkillStoreManager(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\t\tself._skillStoreData = dict()\n+\n+\n+\t@property\n+\tdef skillStoreData(self) -> dict:\n+\t\treturn self._skillStoreData\n+\n+\n+\tdef onStart(self):\n+\t\tself.refreshStoreData()\n+\n+\n+\t@Online(catchOnly=True)\n+\tdef onQuarterHour(self):\n+\t\tself.refreshStoreData()\n+\n+\n+\tdef refreshStoreData(self):\n+\t\tupdateChannel = self.ConfigManager.getAliceConfigByName('skillsUpdateChannel')\n+\t\treq = requests.get(url=f'https://skills.projectalice.io/assets/store/{updateChannel}.json')\n+\t\tif req.status_code not in {200, 304}:\n+\t\t\treturn\n+\n+\t\tself._skillStoreData = req.json()\n+\n+\n+\tdef _getSkillUpdateVersion(self, skillName: str) -> Optional[tuple]:\n+\t\tversionMapping = self._skillStoreData.get(skillName, dict()).get('versionMapping', dict())\n+\n+\t\tuserUpdatePref = self.ConfigManager.getAliceConfigByName('skillsUpdateChannel')\n+\t\tskillUpdateVersion = (Version(), 'master')\n+\n+\t\taliceVersion = Version.fromString(constants.VERSION)\n+\t\tfor aliceMinVersion, repoVersion in versionMapping.items():\n+\t\t\taliceMinVersion = Version.fromString(aliceMinVersion)\n+\t\t\trepoVersion = Version.fromString(repoVersion)\n+\n+\t\t\tif not repoVersion.isVersionNumber or not aliceMinVersion.isVersionNumber or aliceMinVersion > aliceVersion:\n+\t\t\t\tcontinue\n+\n+\t\t\treleaseType = repoVersion.releaseType\n+\t\t\tif userUpdatePref == 'master' and releaseType in {'rc', 'b', 'a'} \\\n+\t\t\t\t\tor userUpdatePref == 'rc' and releaseType in {'b', 'a'} \\\n+\t\t\t\t\tor userUpdatePref == 'beta' and releaseType == 'a':\n+\t\t\t\tcontinue\n+\n+\t\t\tif repoVersion > skillUpdateVersion[0]:\n+\t\t\t\tskillUpdateVersion = (repoVersion, f'{str(repoVersion)}_{str(aliceMinVersion)}')\n+\n+\t\tif not skillUpdateVersion[0].isVersionNumber:\n+\t\t\traise GithubNotFound\n+\n+\t\treturn skillUpdateVersion\n+\n+\n+\tdef getSkillUpdateTag(self, skillName: str) -> str:\n+\t\treturn self._getSkillUpdateVersion(skillName)[1]\n+\n+\n+\tdef getSkillUpdateVersion(self, skillName: str) -> Version:\n+\t\treturn self._getSkillUpdateVersion(skillName)[0]\n+\n+\n+\tdef getSkillData(self, skillName: str) -> dict:\n+\t\treturn self._skillStoreData.get(skillName, dict())\n+\n+\n+\tdef skillExists(self, skillName: str) -> bool:\n+\t\treturn skillName in self._skillStoreData\ndiff --git a/core/base/SuperManager.py b/core/base/SuperManager.py\n--- a/core/base/SuperManager.py\n+++ b/core/base/SuperManager.py\n@@ -4,10 +4,9 @@\n from core.util.model.Logger import Logger\n \n \n-class SuperManager(Logger):\n-\n-\tNAME = 'SuperManager'\n-\t_INSTANCE = None\n+class SuperManager:\n+\tNAME = 'SuperManager'\n+\t_INSTANCE = None\n \n \n \tdef __new__(cls, *args, **kwargs):\n@@ -18,37 +17,38 @@ def __new__(cls, *args, **kwargs):\n \n \n \tdef __init__(self, mainClass):\n-\t\tsuper().__init__(depth=3)\n-\n-\t\tSuperManager._INSTANCE = self\n-\t\tself._managers = dict()\n-\n-\t\tself.projectAlice = mainClass\n-\t\tself.commons = None\n-\t\tself.commonsManager = None\n-\t\tself.configManager = None\n-\t\tself.databaseManager = None\n-\t\tself.languageManager = None\n-\t\tself.snipsServicesManager = None\n-\t\tself.asrManager = None\n-\t\tself.ttsManager = None\n-\t\tself.protectedIntentManager = None\n-\t\tself.threadManager = None\n-\t\tself.mqttManager = None\n-\t\tself.timeManager = None\n-\t\tself.dialogSessionManager = None\n-\t\tself.multiIntentManager = None\n-\t\tself.telemetryManager = None\n-\t\tself.skillManager = None\n-\t\tself.deviceManager = None\n-\t\tself.internetManager = None\n-\t\tself.snipsConsoleManager = None\n-\t\tself.samkillaManager = None\n-\t\tself.wakewordManager = None\n-\t\tself.userManager = None\n-\t\tself.talkManager = None\n-\t\tself.webInterfaceManager = None\n-\t\tself.snipsWatchManager = None\n+\t\tSuperManager._INSTANCE = self\n+\t\tself._managers = dict()\n+\n+\t\tself.projectAlice = mainClass\n+\t\tself.commons = None\n+\t\tself.commonsManager = None\n+\t\tself.configManager = None\n+\t\tself.databaseManager = None\n+\t\tself.languageManager = None\n+\t\tself.snipsServicesManager = None\n+\t\tself.asrManager = None\n+\t\tself.ttsManager = None\n+\t\tself.protectedIntentManager = None\n+\t\tself.threadManager = None\n+\t\tself.mqttManager = None\n+\t\tself.timeManager = None\n+\t\tself.dialogSessionManager = None\n+\t\tself.multiIntentManager = None\n+\t\tself.telemetryManager = None\n+\t\tself.skillManager = None\n+\t\tself.deviceManager = None\n+\t\tself.internetManager = None\n+\t\tself.wakewordManager = None\n+\t\tself.userManager = None\n+\t\tself.talkManager = None\n+\t\tself.webInterfaceManager = None\n+\t\tself.snipsWatchManager = None\n+\t\tself.nodeRedManager = None\n+\t\tself.skillStoreManager = None\n+\t\tself.nluManager = None\n+\t\tself.snipsAssistantManager = None\n+\t\tself.dialogTemplateManager = None\n \n \n \tdef onStart(self):\n@@ -58,6 +58,12 @@ def onStart(self):\n \t\tconfigManager = self._managers.pop('ConfigManager')\n \t\tconfigManager.onStart()\n \n+\t\tlanguageManager = self._managers.pop('LanguageManager')\n+\t\tlanguageManager.onStart()\n+\n+\t\tinternetManager = self._managers.pop('InternetManager')\n+\t\tinternetManager.onStart()\n+\n \t\tsnipsServicesManager = self._managers.pop('SnipsServicesManager')\n \t\tsnipsServicesManager.onStart()\n \n@@ -70,13 +76,12 @@ def onStart(self):\n \t\tmqttManager = self._managers.pop('MqttManager')\n \t\tmqttManager.onStart()\n \n-\t\tlanguageManager = self._managers.pop('LanguageManager')\n-\t\tlanguageManager.onStart()\n-\n \t\ttalkManager = self._managers.pop('TalkManager')\n \t\tskillManager = self._managers.pop('SkillManager')\n-\n-\t\tsamkillaManager = self._managers.pop('SamkillaManager')\n+\t\tdialogTemplateManager = self._managers.pop('DialogTemplateManager')\n+\t\tsnipsAssistantManager = self._managers.pop('SnipsAssistantManager')\n+\t\tnluManager = self._managers.pop('NluManager')\n+\t\tnodeRedManager = self._managers.pop('NodeRedManager')\n \n \t\tfor manager in self._managers.values():\n \t\t\tif manager:\n@@ -84,7 +89,10 @@ def onStart(self):\n \n \t\ttalkManager.onStart()\n \t\tskillManager.onStart()\n-\t\tsamkillaManager.onStart()\n+\t\tdialogTemplateManager.onStart()\n+\t\tsnipsAssistantManager.onStart()\n+\t\tnluManager.onStart()\n+\t\tnodeRedManager.onStart()\n \n \t\tself._managers[configManager.name] = configManager\n \t\tself._managers[languageManager.name] = languageManager\n@@ -94,7 +102,11 @@ def onStart(self):\n \t\tself._managers[userManager.name] = userManager\n \t\tself._managers[mqttManager.name] = mqttManager\n \t\tself._managers[skillManager.name] = skillManager\n-\t\tself._managers[samkillaManager.name] = samkillaManager\n+\t\tself._managers[dialogTemplateManager.name] = dialogTemplateManager\n+\t\tself._managers[snipsAssistantManager.name] = snipsAssistantManager\n+\t\tself._managers[nluManager.name] = nluManager\n+\t\tself._managers[internetManager.name] = internetManager\n+\t\tself._managers[nodeRedManager.name] = nodeRedManager\n \n \n \tdef onBooted(self):\n@@ -102,6 +114,8 @@ def onBooted(self):\n \t\t\tif manager:\n \t\t\t\tmanager.onBooted()\n \n+\t\tself.mqttManager.playSound(soundFilename='boot')\n+\n \n \t@staticmethod\n \tdef getInstance() -> SuperManager:\n@@ -109,56 +123,62 @@ def getInstance() -> SuperManager:\n \n \n \tdef initManagers(self):\n-\t\tfrom core.commons.CommonsManager import CommonsManager\n-\t\tfrom core.base.ConfigManager import ConfigManager\n-\t\tfrom core.base.SkillManager import SkillManager\n-\t\tfrom core.device.DeviceManager import DeviceManager\n-\t\tfrom core.dialog.DialogSessionManager import DialogSessionManager\n-\t\tfrom core.dialog.MultiIntentManager import MultiIntentManager\n+\t\tfrom core.commons.CommonsManager import CommonsManager\n+\t\tfrom core.base.ConfigManager import ConfigManager\n+\t\tfrom core.base.SkillManager import SkillManager\n+\t\tfrom core.device.DeviceManager import DeviceManager\n+\t\tfrom core.dialog.DialogSessionManager import DialogSessionManager\n+\t\tfrom core.dialog.MultiIntentManager import MultiIntentManager\n \t\tfrom core.dialog.ProtectedIntentManager import ProtectedIntentManager\n-\t\tfrom core.server.MqttManager import MqttManager\n-\t\tfrom core.snips.SamkillaManager import SamkillaManager\n-\t\tfrom core.snips.SnipsConsoleManager import SnipsConsoleManager\n-\t\tfrom core.snips.SnipsServicesManager import SnipsServicesManager\n-\t\tfrom core.user.UserManager import UserManager\n-\t\tfrom core.util.DatabaseManager import DatabaseManager\n-\t\tfrom core.util.InternetManager import InternetManager\n-\t\tfrom core.util.TelemetryManager import TelemetryManager\n-\t\tfrom core.util.ThreadManager import ThreadManager\n-\t\tfrom core.util.TimeManager import TimeManager\n-\t\tfrom core.voice.ASRManager import ASRManager\n-\t\tfrom core.voice.LanguageManager import LanguageManager\n-\t\tfrom core.voice.TalkManager import TalkManager\n-\t\tfrom core.voice.TTSManager import TTSManager\n-\t\tfrom core.voice.WakewordManager import WakewordManager\n+\t\tfrom core.server.MqttManager import MqttManager\n+\t\tfrom core.snips.SnipsServicesManager import SnipsServicesManager\n+\t\tfrom core.user.UserManager import UserManager\n+\t\tfrom core.util.DatabaseManager import DatabaseManager\n+\t\tfrom core.util.InternetManager import InternetManager\n+\t\tfrom core.util.TelemetryManager import TelemetryManager\n+\t\tfrom core.util.ThreadManager import ThreadManager\n+\t\tfrom core.util.TimeManager import TimeManager\n+\t\tfrom core.asr.ASRManager import ASRManager\n+\t\tfrom core.voice.LanguageManager import LanguageManager\n+\t\tfrom core.voice.TalkManager import TalkManager\n+\t\tfrom core.voice.TTSManager import TTSManager\n+\t\tfrom core.voice.WakewordManager import WakewordManager\n \t\tfrom core.interface.WebInterfaceManager import WebInterfaceManager\n-\t\tfrom core.snips.SnipsWatchManager import SnipsWatchManager\n-\n-\t\tself.commonsManager = CommonsManager()\n-\t\tself.commons = self.commonsManager\n-\t\tself.configManager = ConfigManager()\n-\t\tself.databaseManager = DatabaseManager()\n-\t\tself.languageManager = LanguageManager()\n-\t\tself.snipsServicesManager = SnipsServicesManager()\n-\t\tself.asrManager = ASRManager()\n-\t\tself.ttsManager = TTSManager()\n-\t\tself.threadManager = ThreadManager()\n-\t\tself.protectedIntentManager = ProtectedIntentManager()\n-\t\tself.mqttManager = MqttManager()\n-\t\tself.timeManager = TimeManager()\n-\t\tself.userManager = UserManager()\n-\t\tself.dialogSessionManager = DialogSessionManager()\n-\t\tself.multiIntentManager = MultiIntentManager()\n-\t\tself.telemetryManager = TelemetryManager()\n-\t\tself.skillManager = SkillManager()\n-\t\tself.deviceManager = DeviceManager()\n-\t\tself.internetManager = InternetManager()\n-\t\tself.snipsConsoleManager = SnipsConsoleManager()\n-\t\tself.samkillaManager = SamkillaManager()\n-\t\tself.wakewordManager = WakewordManager()\n-\t\tself.talkManager = TalkManager()\n-\t\tself.webInterfaceManager = WebInterfaceManager()\n-\t\tself.snipsWatchManager = SnipsWatchManager()\n+\t\tfrom core.snips.SnipsWatchManager import SnipsWatchManager\n+\t\tfrom core.interface.NodeRedManager import NodeRedManager\n+\t\tfrom core.base.SkillStoreManager import SkillStoreManager\n+\t\tfrom core.dialog.DialogTemplateManager import DialogTemplateManager\n+\t\tfrom core.snips.SnipsAssistantManager import SnipsAssistantManager\n+\t\tfrom core.nlu.NluManager import NluManager\n+\n+\t\tself.commonsManager = CommonsManager()\n+\t\tself.commons = self.commonsManager\n+\t\tself.configManager = ConfigManager()\n+\t\tself.databaseManager = DatabaseManager()\n+\t\tself.languageManager = LanguageManager()\n+\t\tself.snipsServicesManager = SnipsServicesManager()\n+\t\tself.asrManager = ASRManager()\n+\t\tself.ttsManager = TTSManager()\n+\t\tself.threadManager = ThreadManager()\n+\t\tself.protectedIntentManager = ProtectedIntentManager()\n+\t\tself.mqttManager = MqttManager()\n+\t\tself.timeManager = TimeManager()\n+\t\tself.userManager = UserManager()\n+\t\tself.dialogSessionManager = DialogSessionManager()\n+\t\tself.multiIntentManager = MultiIntentManager()\n+\t\tself.telemetryManager = TelemetryManager()\n+\t\tself.skillManager = SkillManager()\n+\t\tself.deviceManager = DeviceManager()\n+\t\tself.internetManager = InternetManager()\n+\t\tself.wakewordManager = WakewordManager()\n+\t\tself.talkManager = TalkManager()\n+\t\tself.webInterfaceManager = WebInterfaceManager()\n+\t\tself.snipsWatchManager = SnipsWatchManager()\n+\t\tself.nodeRedManager = NodeRedManager()\n+\t\tself.skillStoreManager = SkillStoreManager()\n+\t\tself.dialogTemplateManager = DialogTemplateManager()\n+\t\tself.snipsAssistantManager = SnipsAssistantManager()\n+\t\tself.nluManager = NluManager()\n \n \t\tself._managers = {name[0].upper() + name[1:]: manager for name, manager in self.__dict__.items() if name.endswith('Manager')}\n \n@@ -169,7 +189,7 @@ def onStop(self):\n \t\t\tfor managerName, manager in self._managers.items():\n \t\t\t\tmanager.onStop()\n \t\texcept Exception as e:\n-\t\t\tself.logError(f'Error while shutting down manager \"{managerName}\": {e}')\n+\t\t\tLogger().logError(f'Error while shutting down manager \"{managerName}\": {e}')\n \n \n \tdef getManager(self, managerName: str):\ndiff --git a/core/base/model/AliceSkill.py b/core/base/model/AliceSkill.py\n--- a/core/base/model/AliceSkill.py\n+++ b/core/base/model/AliceSkill.py\n@@ -14,8 +14,10 @@\n from core.base.model import Widget\n from core.base.model.Intent import Intent\n from core.base.model.ProjectAliceObject import ProjectAliceObject\n+from core.base.model.Version import Version\n from core.commons import constants\n from core.dialog.model.DialogSession import DialogSession\n+from core.user.model.AccessLevels import AccessLevel\n \n \n class AliceSkill(ProjectAliceObject):\n@@ -41,12 +43,29 @@ def __init__(self, supportedIntents: Iterable = None, databaseSchema: dict = Non\n \t\tself._databaseSchema = databaseSchema\n \t\tself._widgets = dict()\n \t\tself._intentsDefinitions = dict()\n+\t\tself._scenarioNodeName = ''\n+\t\tself._scenarioNodeVersion = Version(mainVersion=0, updateVersion=0, hotfix=0)\n \n \t\tself._supportedIntents: Dict[str, Intent] = self.buildIntentList(supportedIntents)\n \t\tself.loadIntentsDefinition()\n \n \t\tself._utteranceSlotCleaner = re.compile('{(.+?):=>.+?}')\n \t\tself.loadWidgets()\n+\t\tself.loadScenarioNodes()\n+\n+\n+\tdef loadScenarioNodes(self):\n+\t\tpath = Path(self.getCurrentDir() / 'scenarioNodes/package.json')\n+\t\tif not path.exists():\n+\t\t\treturn\n+\n+\t\ttry:\n+\t\t\twith path.open('r') as fp:\n+\t\t\t\tdata = json.load(fp)\n+\t\t\t\tself._scenarioNodeName = data['name']\n+\t\t\t\tself._scenarioNodeVersion = Version.fromString(data['version'])\n+\t\texcept Exception as e:\n+\t\t\tself.logWarning(f'Failed to load scenario nodes: {e}')\n \n \n \tdef loadIntentsDefinition(self):\n@@ -61,7 +80,7 @@ def loadIntentsDefinition(self):\n \t\t\t\twith path.open('r') as fp:\n \t\t\t\t\tdata = json.load(fp)\n \n-\t\t\t\t\tif not 'intents' in data:\n+\t\t\t\t\tif 'intents' not in data:\n \t\t\t\t\t\tcontinue\n \n \t\t\t\t\tself._intentsDefinitions[lang] = dict()\n@@ -86,13 +105,13 @@ def buildIntentList(self, supportedIntents) -> dict:\n \t\t\t\titem = Intent(item, userIntent=False)\n \n \t\t\tif str(item) in intents:\n-\t\t\t\tintents[str(item)].addDialogMapping(item.dialogMapping)\n+\t\t\t\tintents[str(item)].addDialogMapping(item.dialogMapping, skillName=self.name)\n \n \t\t\t\tif item.fallbackFunction:\n \t\t\t\t\tintents[str(item)].fallbackFunction = item.fallbackFunction\n-\t\t\t\t# always use the highes auth level specified\n-\t\t\t\tif item.authOnly > intents[str(item)].authOnly:\n-\t\t\t\t\tintents[str(item)].authOnly = item.authOnly\n+\t\t\t\t# always use the highest auth level specified (low values mean a higher auth level)\n+\t\t\t\tif item.authLevel < intents[str(item)].authLevel:\n+\t\t\t\t\tintents[str(item)].authLevel = item.authLevel\n \t\t\telse:\n \t\t\t\tintents[str(item)] = item\n \n@@ -112,13 +131,13 @@ def findDecoratedIntents(self) -> dict:\n \t\t\t\t\tintentMappings[str(intent)] = intent\n \n \t\t\t\tif requiredState:\n-\t\t\t\t\tintentMappings[str(intent)].addDialogMapping({requiredState: function})\n+\t\t\t\t\tintentMappings[str(intent)].addDialogMapping({requiredState: function}, skillName=self.name)\n \t\t\t\telse:\n \t\t\t\t\tintentMappings[str(intent)].fallbackFunction = function\n \n-\t\t\t\t# always use the highes auth level specified\n-\t\t\t\tif intent.authOnly > intentMappings[str(intent)].authOnly:\n-\t\t\t\t\tintentMappings[str(intent)].authOnly = intent.authOnly\n+\t\t\t\t# always use the highest auth level specified (low values mean a higher auth level)\n+\t\t\t\tif intent.authLevel < intentMappings[str(intent)].authLevel:\n+\t\t\t\t\tintentMappings[str(intent)].authLevel = intent.authLevel\n \n \t\treturn intentMappings\n \n@@ -147,14 +166,14 @@ def loadWidgets(self):\n \t\t\t\twidgetImport = importlib.import_module(f'skills.{self.name}.widgets.{widgetName}')\n \t\t\t\tklass = getattr(widgetImport, widgetName)\n \n-\t\t\t\tif widgetName in data: # widget already exists in DB\n+\t\t\t\tif widgetName in data: # widget already exists in DB\n \t\t\t\t\twidget = klass(data[widgetName])\n \t\t\t\t\tself._widgets[widgetName] = widget\n \t\t\t\t\twidget.setParentSkillInstance(self)\n \t\t\t\t\tdel data[widgetName]\n \t\t\t\t\tself.logInfo(f'Loaded widget \"{widgetName}\"')\n \n-\t\t\t\telse: # widget is new\n+\t\t\t\telse: # widget is new\n \t\t\t\t\tself.logInfo(f'Adding widget \"{widgetName}\"')\n \t\t\t\t\twidget = klass({\n \t\t\t\t\t\t'name': widgetName,\n@@ -164,7 +183,7 @@ def loadWidgets(self):\n \t\t\t\t\twidget.setParentSkillInstance(self)\n \t\t\t\t\twidget.saveToDB()\n \n-\t\t\tfor widgetName in data: # deprecated widgets\n+\t\t\tfor widgetName in data: # deprecated widgets\n \t\t\t\tself.logInfo(f'Widget \"{widgetName}\" is deprecated, removing')\n \t\t\t\tself.DatabaseManager.delete(\n \t\t\t\t\ttableName='widgets',\n@@ -183,20 +202,25 @@ def getWidgetInstance(self, widgetName: str) -> Optional[Widget]:\n \n \tdef getUtterancesByIntent(self, intent: Intent, forceLowerCase: bool = True, cleanSlots: bool = False) -> list:\n \t\tlang = self.LanguageManager.activeLanguage\n-\t\tif not lang in self._intentsDefinitions:\n+\t\tif lang not in self._intentsDefinitions:\n \t\t\treturn list()\n \n+\t\t#TODO: either typing in function definition is wrong, or it is always a Intent\n \t\tif isinstance(intent, tuple):\n-\t\t\tcheck = intent[0].justAction\n+\t\t\tcheck = intent[0].action\n \t\telif isinstance(intent, Intent):\n-\t\t\tcheck = intent.justAction\n+\t\t\tcheck = intent.action\n \t\telse:\n \t\t\tcheck = str(intent).split('/')[-1].split(':')[-1]\n \n-\t\tif not check in self._intentsDefinitions[lang]:\n+\t\tif check not in self._intentsDefinitions[lang]:\n \t\t\treturn list()\n \n-\t\treturn [re.sub(self._utteranceSlotCleaner, '\\\\1', utterance.lower() if forceLowerCase else utterance) if cleanSlots else utterance for utterance in self._intentsDefinitions[lang][check]]\n+\t\tif not cleanSlots:\n+\t\t\treturn list(self._intentsDefinitions[lang][check])\n+\n+\t\treturn [re.sub(self._utteranceSlotCleaner, '\\\\1', utterance.lower() if forceLowerCase else utterance)\n+\t\t\tfor utterance in self._intentsDefinitions[lang][check]]\n \n \n \tdef getCurrentDir(self):\n@@ -288,6 +312,20 @@ def delayed(self, value: bool):\n \t\tself._delayed = value\n \n \n+\t@property\n+\tdef scenarioNodeName(self) -> str:\n+\t\treturn self._scenarioNodeName\n+\n+\n+\t@property\n+\tdef scenarioNodeVersion(self) -> Version:\n+\t\treturn self._scenarioNodeVersion\n+\n+\n+\tdef hasScenarioNodes(self) -> bool:\n+\t\treturn self._scenarioNodeName != ''\n+\n+\n \tdef subscribe(self, mqttClient: MQTTClient):\n \t\tfor intent in self._supportedIntents:\n \t\t\ttry:\n@@ -306,7 +344,7 @@ def notifyDevice(self, topic: str, uid: str = '', siteId: str = ''):\n \n \n \tdef authenticateIntent(self, session: DialogSession):\n-\t\tintent = self._supportedIntents[session.intentName]\n+\t\tintent = self._supportedIntents[session.message.topic]\n \t\t# Return if intent is for auth users only but the user is unknown\n \t\tif session.user == constants.UNKNOWN_USER:\n \t\t\tself.endDialog(\n@@ -315,7 +353,7 @@ def authenticateIntent(self, session: DialogSession):\n \t\t\t)\n \t\t\traise AccessLevelTooLow()\n \t\t# Return if intent is for auth users only and the user doesn't have the accesslevel for it\n-\t\tif not self.UserManager.hasAccessLevel(session.user, intent.authOnly):\n+\t\tif not self.UserManager.hasAccessLevel(session.user, intent.authLevel):\n \t\t\tself.endDialog(\n \t\t\t\tsessionId=session.sessionId,\n \t\t\t\ttext=self.TalkManager.randomTalk(talk='noAccess', skill='system')\n@@ -323,10 +361,11 @@ def authenticateIntent(self, session: DialogSession):\n \t\t\traise AccessLevelTooLow()\n \n \n+\t@staticmethod\n \tdef intentNameMoreSpecific(intentName: str, oldIntentName: str) -> bool:\n \t\tcleanedIntentName = intentName.rstrip('#').split('+')[0]\n \t\tcleanedOldIntentName = oldIntentName.rstrip('#').split('+')[0]\n-\t\treturn len(cleanedIntentName) > len(cleanedOldIntentName)\n+\t\treturn cleanedIntentName > cleanedOldIntentName\n \n \n \tdef filterIntent(self, session: DialogSession) -> Optional[Intent]:\n@@ -338,20 +377,20 @@ def filterIntent(self, session: DialogSession) -> Optional[Intent]:\n \t\tmatchingIntent = None\n \t\toldIntentName = None\n \t\tfor intentName, intent in self._supportedIntents.items():\n-\t\t\tif MQTTClient.topic_matches_sub(intentName, session.intentName):\n-\t\t\t\tif not matchingIntent or self.intentNameMoreSpecific(intentName, oldIntentName):\n-\t\t\t\t\tmatchingIntent = intent\n-\t\t\t\t\toldIntentName = intentName\n+\t\t\tif MQTTClient.topic_matches_sub(intentName, session.message.topic) \\\n+\t\t\t\t\tand (not matchingIntent or self.intentNameMoreSpecific(intentName, oldIntentName)):\n+\t\t\t\tmatchingIntent = intent\n+\t\t\t\toldIntentName = intentName\n \n \t\treturn matchingIntent\n \n \n-\tdef dispatchMessage(self, session: DialogSession) -> bool:\n+\tdef onDispatchMessage(self, session: DialogSession) -> bool:\n \t\tintent = self.filterIntent(session)\n \t\tif not intent:\n \t\t\treturn False\n \n-\t\tif intent.authOnly:\n+\t\tif intent.authLevel != AccessLevel.ZERO:\n \t\t\tself.authenticateIntent(session)\n \n \t\tfunction = intent.getMapping(session) or self.onMessage\n@@ -368,7 +407,7 @@ def _initDB(self) -> bool:\n \t\treturn True\n \n \n-\tdef onStart(self) -> dict:\n+\tdef onStart(self):\n \t\tif not self._active:\n \t\t\tself.logInfo(f'Skill {self.name} is not active')\n \t\telse:\n@@ -376,29 +415,28 @@ def onStart(self) -> dict:\n \n \t\tself._initDB()\n \t\tself.MqttManager.subscribeSkillIntents(self.name)\n-\t\treturn self._supportedIntents\n+\n+\n+\tdef onStop(self):\n+\t\tself.SkillManager.configureSkillIntents(self._name, False)\n \n \n \tdef onBooted(self) -> bool:\n \t\tif self.delayed:\n-\t\t\tif self.ThreadManager.getEvent('SnipsAssistantDownload').isSet():\n-\t\t\t\tself.ThreadManager.doLater(interval=5, func=self.onBooted)\n-\t\t\t\treturn False\n-\n \t\t\tself.logInfo('Delayed start')\n \t\t\tself.ThreadManager.doLater(interval=5, func=self.onStart)\n \n \t\treturn True\n \n \n-\tdef onSkillInstalled(self):\n+\tdef onSkillInstalled(self, **kwargs):\n \t\tself._updateAvailable = False\n-\t\t#self.MqttManager.subscribeSkillIntents(self.name)\n+\t\tself.MqttManager.subscribeSkillIntents(self.name)\n \n \n-\tdef onSkillUpdated(self):\n+\tdef onSkillUpdated(self, **kwargs):\n \t\tself._updateAvailable = False\n-\t\t#self.MqttManager.subscribeSkillIntents(self.name)\n+\t\tself.MqttManager.subscribeSkillIntents(self.name)\n \n \n \t# HELPERS\n@@ -447,8 +485,8 @@ def databaseInsert(self, tableName: str, query: str = None, values: dict = None)\n \t\treturn self.DatabaseManager.insert(tableName=tableName, query=query, values=values, callerName=self.name)\n \n \n-\tdef randomTalk(self, text: str, replace: list = None) -> str:\n-\t\ttalk = self.TalkManager.randomTalk(talk=text, skill=self.name)\n+\tdef randomTalk(self, text: str, replace: list = None, skill: str = None) -> str:\n+\t\ttalk = self.TalkManager.randomTalk(talk=text, skill=skill or self.name)\n \n \t\tif replace:\n \t\t\ttalk = talk.format(*replace)\n@@ -464,10 +502,14 @@ def say(self, text: str, siteId: str = constants.DEFAULT_SITE_ID, customData: di\n \n \n \tdef ask(self, text: str, siteId: str = constants.DEFAULT_SITE_ID, intentFilter: list = None, customData: dict = None, previousIntent: str = '', canBeEnqueued: bool = True, currentDialogState: str = ''):\n+\t\tif currentDialogState:\n+\t\t\tcurrentDialogState = f'{self.name}:{currentDialogState}'\n \t\tself.MqttManager.ask(text=text, client=siteId, intentFilter=intentFilter, customData=customData, previousIntent=previousIntent, canBeEnqueued=canBeEnqueued, currentDialogState=currentDialogState)\n \n \n \tdef continueDialog(self, sessionId: str, text: str, customData: dict = None, intentFilter: list = None, previousIntent: str = '', slot: str = '', currentDialogState: str = ''):\n+\t\tif currentDialogState:\n+\t\t\tcurrentDialogState = f'{self.name}:{currentDialogState}'\n \t\tself.MqttManager.continueDialog(sessionId=sessionId, text=text, customData=customData, intentFilter=intentFilter, previousIntent=str(previousIntent), slot=slot, currentDialogState=currentDialogState)\n \n \ndiff --git a/core/base/model/GithubCloner.py b/core/base/model/GithubCloner.py\n--- a/core/base/model/GithubCloner.py\n+++ b/core/base/model/GithubCloner.py\n@@ -1,17 +1,15 @@\n from pathlib import Path\n \n-import requests\n import shutil\n \n-from core.ProjectAliceExceptions import GithubNotFound, GithubRateLimit, GithubTokenFailed\n from core.base.SuperManager import SuperManager\n from core.base.model.ProjectAliceObject import ProjectAliceObject\n \n \n class GithubCloner(ProjectAliceObject):\n-\n \tNAME = 'GithubCloner'\n \n+\n \tdef __init__(self, baseUrl: str, path: Path, dest: Path):\n \t\tsuper().__init__(logDepth=3)\n \t\tself._baseUrl = baseUrl\n@@ -26,76 +24,29 @@ def getGithubAuth(cls) -> tuple:\n \t\treturn (username, token) if (username and token) else None\n \n \n-\tdef clone(self) -> bool:\n-\t\tif self._dest.exists():\n-\t\t\tself._cleanDestDir()\n-\t\telse:\n+\tdef clone(self, skillName: str) -> bool:\n+\t\tif not self._dest.exists():\n \t\t\tself._dest.mkdir(parents=True)\n+\t\telse:\n+\t\t\tif Path(self._dest / '.git').exists():\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(self._dest), 'stash'])\n+\t\t\telse:\n+\t\t\t\tshutil.rmtree(str(self._dest))\n+\t\t\t\tself._dest.mkdir(parents=True)\n \n-\t\ttry:\n-\t\t\treturn self._doClone(f'https://api.github.com/{self._baseUrl}/{self._path}?ref={self.ConfigManager.getSkillsUpdateSource()}')\n-\t\texcept Exception:\n-\t\t\treturn False\n+\t\treturn self._doClone(skillName)\n \n \n-\tdef _doClone(self, url: str):\n+\tdef _doClone(self, skillName: str) -> bool:\n \t\ttry:\n-\t\t\treq = requests.get(url, auth=self.getGithubAuth())\n-\t\t\tif req.status_code == 401:\n-\t\t\t\traise GithubTokenFailed\n-\t\t\telif req.status_code == 403:\n-\t\t\t\traise GithubRateLimit\n-\t\t\telif req.status_code == 404:\n-\t\t\t\traise GithubNotFound\n-\t\t\telif req.status_code != 200:\n-\t\t\t\traise Exception\n-\n-\t\t\tdata = req.json()\n-\t\t\tfor item in data:\n-\t\t\t\tpath = Path(*Path(item['path']).parts[3:])\n-\t\t\t\tif item['type'] == 'file':\n-\t\t\t\t\tif path.suffix == '.install':\n-\t\t\t\t\t\tcontinue\n-\n-\t\t\t\t\tfileStream = requests.get(url=item['download_url'], auth=self.getGithubAuth())\n-\t\t\t\t\tPath(self._dest / path).write_bytes(fileStream.content)\n-\t\t\t\telse:\n-\t\t\t\t\tPath(self._dest / path).mkdir(parents=True)\n-\t\t\t\t\tself._doClone(url=item['url'])\n-\n-\t\texcept GithubTokenFailed:\n-\t\t\tself.logError('Provided Github username / token invalid')\n-\t\t\traise\n+\t\t\tif not Path(self._dest / '.git').exists():\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(self._dest), 'init'])\n+\t\t\t\tself.Commons.runSystemCommand(['git', '-C', str(self._dest), 'remote', 'add', 'origin', self._baseUrl])\n \n-\t\texcept GithubRateLimit:\n-\t\t\tself.logError('Github rate limit reached, cannot access updates for now. You should consider creating a token to avoid this problem')\n-\t\t\traise\n-\n-\t\texcept GithubNotFound:\n-\t\t\tself.logError('Requested skill not found on servers')\n-\t\t\traise\n+\t\t\tself.Commons.runSystemCommand(['git', '-C', str(self._dest), 'pull'])\n+\t\t\tself.Commons.runSystemCommand(['git', '-C', str(self._dest), 'checkout', self.SkillStoreManager.getSkillUpdateTag(skillName)])\n \n+\t\t\treturn True\n \t\texcept Exception as e:\n-\t\t\tself.logError(f'Error downloading skill: {e}')\n-\t\t\traise\n-\n-\n-\tdef _cleanDestDir(self):\n-\t\tfilesToDelete = list()\n-\t\tdirectoriesToDelete = list()\n-\t\tfor file in self._dest.iterdir():\n-\t\t\tif file.with_suffix(file.suffix + '.template').exists() or file.with_suffix(file.suffix + '.dist').exists() or file.suffix == '.conf':\n-\t\t\t\tcontinue\n-\n-\t\t\tif (file.is_dir() and not file.name.startswith('_')) or file.name == '__pycache__':\n-\t\t\t\tdirectoriesToDelete.append(file)\n-\n-\t\t\telif file.is_file():\n-\t\t\t\tfilesToDelete.append(file)\n-\n-\t\t# Not deleting directories and files directly because they are needed for the .dist check\n-\t\tfor directory in directoriesToDelete:\n-\t\t\tshutil.rmtree(directory)\n-\n-\t\tfor file in filesToDelete:\n-\t\t\tfile.unlink()\n+\t\t\tself.logWarning(f'Something went wrong cloning github repo: {e}')\n+\t\t\treturn False\ndiff --git a/core/base/model/Intent.py b/core/base/model/Intent.py\n--- a/core/base/model/Intent.py\n+++ b/core/base/model/Intent.py\n@@ -1,66 +1,45 @@\n-from pathlib import Path\n-from typing import Dict, Callable, Optional\n+from dataclasses import dataclass, field\n+from typing import Callable, Dict, Optional, Union\n \n-from core.base.model.ProjectAliceObject import ProjectAliceObject\n+import core.base.SuperManager as SM\n+from core.user.model.AccessLevels import AccessLevel\n \n-class Intent(ProjectAliceObject):\n \n-\tdef __init__(self, _value: str, isProtected: bool = False, userIntent: bool = True, authOnly = 0):\n-\t\tself._owner = self.ConfigManager.getAliceConfigByName('intentsOwner')\n-\t\tself._topic = f'hermes/intent/{self._owner}:{_value}' if userIntent else _value\n-\t\tself._protected = isProtected\n-\t\tself._authOnly = int(authOnly)\n-\t\tself._dialogMapping = dict()\n-\t\tself._fallbackFunction = None\n+@dataclass\n+class Intent:\n+\ttopic: str = field(init=False)\n+\taction: str = field(repr=False)\n+\tisProtected: bool = False\n+\tuserIntent: bool = True\n+\tauthLevel: AccessLevel = AccessLevel.ZERO\n+\tfallbackFunction: Optional[Callable] = None\n+\t_dialogMapping: dict = field(default_factory=dict)\n \n-\t\tif isProtected:\n-\t\t\tself.ProtectedIntentManager.protectIntent(self._topic)\n \n-\t\tsuper().__init__()\n+\tdef __post_init__(self):\n+\t\tself.topic = f'hermes/intent/{self.action}' if self.userIntent else self.action\n+\t\tif self.isProtected:\n+\t\t\tSM.SuperManager.getInstance().protectedIntentManager.protectIntent(self.topic)\n \n \n \tdef __str__(self) -> str:\n-\t\treturn self._topic\n+\t\treturn self.topic\n \n \n \tdef __repr__(self) -> str:\n-\t\treturn self._topic\n-\n-\n-\tdef __eq__(self, other) -> bool:\n-\t\treturn self._topic == other\n+\t\treturn self.topic\n \n \n \tdef __hash__(self) -> int:\n-\t\treturn hash(self._topic)\n-\n-\n-\tdef decoratedSelf(self) -> str:\n-\t\treturn self._topic.format(owner=self._owner)\n-\n-\n-\tdef hasDialogMapping(self) -> bool:\n-\t\treturn bool(self.dialogMapping)\n+\t\treturn hash(self.topic)\n \n \n-\t@property\n-\tdef protected(self) -> bool:\n-\t\treturn self._protected\n-\n-\n-\t@property\n-\tdef owner(self) -> str:\n-\t\treturn self._owner\n+\tdef __eq__(self, other: str) -> bool:\n+\t\treturn self.topic == other\n \n \n-\t@property\n-\tdef justTopic(self) -> str:\n-\t\treturn Path(self._topic).name\n-\n-\n-\t@property\n-\tdef justAction(self) -> str:\n-\t\treturn self.justTopic.split(':')[-1]\n+\tdef __ne__(self, other) -> bool:\n+\t\treturn self.topic != other\n \n \n \t@property\n@@ -69,33 +48,25 @@ def dialogMapping(self) -> dict:\n \n \n \t@dialogMapping.setter\n-\tdef dialogMapping(self, value: Dict[str, Callable]):\n-\t\tself._dialogMapping = value\n+\tdef dialogMapping(self, value: Union[Dict[str, Callable], property]):\n+\t\tskillName = SM.SuperManager.getInstance().commonsManager.getFunctionCaller(depth=2)\n+\t\tif isinstance(value, property):\n+\t\t\tself._dialogMapping = dict()\n+\t\telse:\n+\t\t\tself._dialogMapping = {\n+\t\t\t\tf'{skillName}:{dialogState}': func for dialogState, func in value.items()\n+\t\t\t}\n \n \n \t@property\n-\tdef fallbackFunction(self) -> Callable:\n-\t\treturn self._fallbackFunction\n-\n-\n-\t@fallbackFunction.setter\n-\tdef fallbackFunction(self, value: Callable):\n-\t\tself._fallbackFunction = value\n-\n-\n-\t@property\n-\tdef authOnly(self):\n-\t\treturn self._authOnly\n-\n-\n-\t@authOnly.setter\n-\tdef authOnly(self, value):\n-\t\tself._authOnly = int(value)\n+\tdef justTopic(self) -> str:\n+\t\treturn self.action\n \n \n-\tdef addDialogMapping(self, value: Dict[str, Callable]):\n-\t\tself._dialogMapping.update(value)\n+\tdef addDialogMapping(self, value: Dict[str, Callable], skillName: str):\n+\t\tfor dialogState, func in value.items():\n+\t\t\tself.dialogMapping[f'{skillName}:{dialogState}'] = func\n \n \n \tdef getMapping(self, session) -> Optional[Callable]:\n-\t\treturn self._dialogMapping.get(session.currentState, self._fallbackFunction)\n+\t\treturn self.dialogMapping.get(session.currentState, self.fallbackFunction)\ndiff --git a/core/base/model/Manager.py b/core/base/model/Manager.py\n--- a/core/base/model/Manager.py\n+++ b/core/base/model/Manager.py\n@@ -6,14 +6,14 @@\n \n class Manager(ProjectAliceObject):\n \n-\tdef __init__(self, name: str, databaseSchema: dict = None):\n+\tdef __init__(self, name: str = '', databaseSchema: dict = None):\n \t\tsuper().__init__(logDepth=3)\n \n-\t\tself._name = name\n-\t\tself._databaseSchema = databaseSchema\n-\t\tself._isActive = True\n+\t\tself._name = self.Commons.getFunctionCaller(depth=2) if not name else name\n+\t\tself._databaseSchema = databaseSchema\n+\t\tself._isActive = True\n \n-\t\tself.logInfo(f'Initializing {name}')\n+\t\tself.logInfo(f'Initializing {self._name}')\n \n \n \t@property\ndiff --git a/core/base/model/ProjectAliceObject.py b/core/base/model/ProjectAliceObject.py\n--- a/core/base/model/ProjectAliceObject.py\n+++ b/core/base/model/ProjectAliceObject.py\n@@ -5,11 +5,11 @@\n from core.util.model.Logger import Logger\n \n \n-class ProjectAliceObject(Logger):\n+class ProjectAliceObject:\n \n \tdef __init__(self, logDepth: int = 3, *args, **kwargs):\n \t\tself._depth = logDepth\n-\t\tsuper().__init__(depth=self._depth)\n+\t\tself._logger = Logger(logDepth)\n \n \n \tdef __repr__(self):\n@@ -35,6 +35,9 @@ def broadcast(self, method: str, exceptions: list = None, manager = None, propag\n \t\tif 'ProjectAlice' not in exceptions:\n \t\t\texceptions.append('ProjectAlice')\n \n+\t\tif not method.startswith('on'):\n+\t\t\tmethod = f'on{method[0].capitalize() + method[1:]}'\n+\n \t\tdeadManagers = list()\n \t\tfor name, man in SM.SuperManager.getInstance().managers.items():\n \t\t\tif not man:\n@@ -49,9 +52,8 @@ def broadcast(self, method: str, exceptions: list = None, manager = None, propag\n \t\t\t\tif func:\n \t\t\t\t\tfunc(**kwargs)\n \n-\t\t\texcept TypeError:\n-\t\t\t\t# Do nothing, it's most prolly kwargs\n-\t\t\t\tpass\n+\t\t\texcept TypeError as e:\n+\t\t\t\tself.logWarning(f'- Failed to broadcast event {method} to {man.name}: {e}')\n \n \t\tif propagateToSkills:\n \t\t\tself.SkillManager.skillBroadcast(method=method, **kwargs)\n@@ -60,79 +62,309 @@ def broadcast(self, method: str, exceptions: list = None, manager = None, propag\n \t\t\tdel SM.SuperManager.getInstance().managers[name]\n \n \n-\tdef onStart(self): pass\n-\tdef onStop(self): pass\n-\tdef onBooted(self): pass\n-\tdef onSkillInstalled(self): pass\n-\tdef onSkillUpdated(self): pass\n-\tdef onInternetConnected(self): pass\n-\tdef onInternetLost(self): pass\n-\tdef onHotword(self, siteId: str, user: str = constants.UNKNOWN_USER): pass\n-\tdef onHotwordToggleOn(self, siteId: str): pass\n-\tdef onSessionStarted(self, session): pass\n-\tdef onStartListening(self, session): pass\n-\tdef onCaptured(self, session): pass\n-\tdef onIntentParsed(self, session): pass\n-\tdef onUserCancel(self, session): pass\n-\tdef onSessionTimeout(self, session): pass\n-\tdef onIntentNotRecognized(self, session): pass\n-\tdef onSessionError(self, session): pass\n-\tdef onSessionEnded(self, session): pass\n-\tdef onSay(self, session): pass\n-\tdef onSayFinished(self, session): pass\n-\tdef onSessionQueued(self, session): pass\n+\tdef logInfo(self, msg: str):\n+\t\tself._logger.doLog(function='info', msg=msg, printStack=False)\n+\n+\n+\tdef logError(self, msg: str):\n+\t\tself._logger.doLog(function='error', msg=msg)\n+\n+\n+\tdef logDebug(self, msg: str):\n+\t\tself._logger.doLog(function='debug', msg=msg, printStack=False)\n+\n+\n+\tdef logFatal(self, msg: str):\n+\t\tself._logger.doLog(function='fatal', msg=msg)\n+\t\ttry:\n+\t\t\tself.ProjectAlice.onStop()\n+\t\texcept:\n+\t\t\texit()\n+\n+\n+\tdef logWarning(self, msg: str, printStack: bool = False):\n+\t\tself._logger.doLog(function='warning', msg=msg, printStack=printStack)\n+\n+\n+\tdef logCritical(self, msg: str):\n+\t\tself._logger.doLog(function='critical', msg=msg)\n+\n+\n+\tdef onStart(self):\n+\t\tpass\n+\n+\n+\tdef onStop(self):\n+\t\tpass\n+\n+\n+\tdef onBooted(self):\n+\t\tpass\n+\n+\n+\tdef onSkillInstalled(self, skill: str):\n+\t\tpass\n+\n+\n+\tdef onSkillUpdated(self, skill: str):\n+\t\tpass\n+\n+\n+\tdef onInternetConnected(self):\n+\t\tpass\n+\n+\n+\tdef onInternetLost(self):\n+\t\tpass\n+\n+\n+\tdef onHotword(self, siteId: str, user: str = constants.UNKNOWN_USER):\n+\t\tpass\n+\n+\n+\tdef onHotwordToggleOn(self, siteId: str):\n+\t\tpass\n+\n+\n+\tdef onSessionStarted(self, session):\n+\t\tpass\n+\n+\n+\tdef onStartListening(self, session):\n+\t\tpass\n+\n+\n+\tdef onStopListening(self, session):\n+\t\tpass\n+\n+\n+\tdef onCaptured(self, session):\n+\t\tpass\n+\n+\n+\tdef onNluQuery(self, session):\n+\t\tpass\n+\n+\n+\tdef onIntentParsed(self, session):\n+\t\tpass\n+\n+\n+\tdef onUserCancel(self, session):\n+\t\tpass\n+\n+\n+\tdef onSessionTimeout(self, session):\n+\t\tpass\n+\n+\n+\tdef onIntentNotRecognized(self, session):\n+\t\tpass\n+\n+\n+\tdef onSessionError(self, session):\n+\t\tpass\n+\n+\n+\tdef onSessionEnded(self, session):\n+\t\tpass\n+\n+\n+\tdef onSay(self, session):\n+\t\tpass\n+\n+\n+\tdef onSayFinished(self, session):\n+\t\tpass\n+\n+\n+\tdef onSessionQueued(self, session):\n+\t\tpass\n+\n \n \tdef onMessage(self, session) -> bool:\n \t\t\"\"\" Do not consume the intent by default \"\"\"\n \t\treturn False\n \n-\tdef onSleep(self): pass\n-\tdef onWakeup(self): pass\n-\tdef onGoingBed(self): pass\n-\tdef onLeavingHome(self): pass\n-\tdef onReturningHome(self): pass\n-\tdef onEating(self): pass\n-\tdef onWatchingTV(self): pass\n-\tdef onCooking(self): pass\n-\tdef onMakeup(self): pass\n-\tdef onContextSensitiveDelete(self, sessionId: str): pass\n-\tdef onContextSensitiveEdit(self, sessionId: str): pass\n-\tdef onFullMinute(self): pass\n-\tdef onFiveMinute(self): pass\n-\tdef onQuarterHour(self): pass\n-\tdef onFullHour(self): pass\n-\tdef onCancel(self): pass\n-\tdef onASRCaptured(self): pass\n-\tdef onWakeword(self, siteId: str, user: str = constants.UNKNOWN_USER): pass\n-\tdef onMotionDetected(self): pass\n-\tdef onMotionStopped(self): pass\n-\tdef onButtonPressed(self): pass\n-\tdef onButtonReleased(self): pass\n-\tdef onDeviceConnecting(self): pass\n-\tdef onDeviceDisconnecting(self): pass\n-\tdef onUVIndexAlert(self, deviceList: list): pass\n-\tdef onRaining(self, deviceList: list): pass\n-\tdef onTooMuchRain(self, deviceList: list): pass\n-\tdef onWindy(self, deviceList: list): pass\n-\tdef onFreezing(self, deviceList: list): pass\n-\tdef onTemperatureHighAlert(self, deviceList: list): pass\n-\tdef onTemperatureLowAlert(self, deviceList: list): pass\n-\tdef onCO2Alert(self, deviceList: list): pass\n-\tdef onHumidityHighAlert(self, deviceList: list): pass\n-\tdef onHumidityLowAlert(self, deviceList: list): pass\n-\tdef onNoiseAlert(self, deviceList: list): pass\n-\tdef onPressureHighAlert(self, deviceList: list): pass\n-\tdef onPressureLowAlert(self, deviceList: list): pass\n-\tdef onBroadcastingForNewDeviceStart(self, session): pass\n-\tdef onBroadcastingForNewDeviceStop(self): pass\n-\tdef onSnipsAssistantDownloaded(self, **kwargs): pass\n-\tdef onSnipsAssistantDownloadFailed(self, **kwargs): pass\n-\tdef onAuthenticated(self, session): pass\n-\tdef onAuthenticationFailed(self, session): pass\n-\tdef onAudioFrame(self, message): pass\n-\tdef onSnipsAssistantInstalled(self, **kwargs): pass\n-\tdef onSnipsAssistantFailedInstalling(self, **kwargs): pass\n-\tdef onSkillInstallFailed(self, **kwargs): pass\n+\n+\tdef onSleep(self):\n+\t\tpass\n+\n+\n+\tdef onWakeup(self):\n+\t\tpass\n+\n+\n+\tdef onGoingBed(self):\n+\t\tpass\n+\n+\n+\tdef onLeavingHome(self):\n+\t\tpass\n+\n+\n+\tdef onReturningHome(self):\n+\t\tpass\n+\n+\n+\tdef onEating(self):\n+\t\tpass\n+\n+\n+\tdef onWatchingTV(self):\n+\t\tpass\n+\n+\n+\tdef onCooking(self):\n+\t\tpass\n+\n+\n+\tdef onMakeup(self):\n+\t\tpass\n+\n+\n+\tdef onContextSensitiveDelete(self, sessionId: str):\n+\t\tpass\n+\n+\n+\tdef onContextSensitiveEdit(self, sessionId: str):\n+\t\tpass\n+\n+\n+\tdef onFullMinute(self):\n+\t\tpass\n+\n+\n+\tdef onFiveMinute(self):\n+\t\tpass\n+\n+\n+\tdef onQuarterHour(self):\n+\t\tpass\n+\n+\n+\tdef onFullHour(self):\n+\t\tpass\n+\n+\n+\tdef onWakeword(self, siteId: str, user: str = constants.UNKNOWN_USER):\n+\t\tpass\n+\n+\n+\tdef onMotionDetected(self):\n+\t\tpass\n+\n+\n+\tdef onMotionStopped(self):\n+\t\tpass\n+\n+\n+\tdef onButtonPressed(self):\n+\t\tpass\n+\n+\n+\tdef onButtonReleased(self):\n+\t\tpass\n+\n+\n+\tdef onDeviceConnecting(self):\n+\t\tpass\n+\n+\n+\tdef onDeviceDisconnecting(self):\n+\t\tpass\n+\n+\n+\tdef onUVIndexAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onRaining(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onTooMuchRain(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onWindy(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onFreezing(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onTemperatureHighAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onTemperatureLowAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onCO2Alert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onHumidityHighAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onHumidityLowAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onNoiseAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onPressureHighAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onPressureLowAlert(self, *args, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onBroadcastingForNewDeviceStart(self, session):\n+\t\tpass\n+\n+\n+\tdef onBroadcastingForNewDeviceStop(self):\n+\t\tpass\n+\n+\n+\tdef onAuthenticated(self, session):\n+\t\tpass\n+\n+\n+\tdef onAuthenticationFailed(self, session):\n+\t\tpass\n+\n+\n+\tdef onAudioFrame(self, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onSnipsAssistantInstalled(self, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onSnipsAssistantFailedTraining(self, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onSkillInstallFailed(self, skill: str):\n+\t\tpass\n+\n+\n+\tdef onNluTrained(self, **kwargs):\n+\t\tpass\n+\n+\n+\tdef onAsrIntermediateResult(self, result: str):\n+\t\tpass\n \n \n \t@property\n@@ -175,16 +407,6 @@ def MqttManager(self):\n \t\treturn SM.SuperManager.getInstance().mqttManager\n \n \n-\t@property\n-\tdef SamkillaManager(self):\n-\t\treturn SM.SuperManager.getInstance().samkillaManager\n-\n-\n-\t@property\n-\tdef SnipsConsoleManager(self):\n-\t\treturn SM.SuperManager.getInstance().snipsConsoleManager\n-\n-\n \t@property\n \tdef SnipsServicesManager(self):\n \t\treturn SM.SuperManager.getInstance().snipsServicesManager\n@@ -258,3 +480,23 @@ def Commons(self):\n \t@property\n \tdef SnipsWatchManager(self):\n \t\treturn SM.SuperManager.getInstance().snipsWatchManager\n+\n+\n+\t@property\n+\tdef SkillStoreManager(self):\n+\t\treturn SM.SuperManager.getInstance().skillStoreManager\n+\n+\n+\t@property\n+\tdef NluManager(self):\n+\t\treturn SM.SuperManager.getInstance().nluManager\n+\n+\n+\t@property\n+\tdef DialogTemplateManager(self):\n+\t\treturn SM.SuperManager.getInstance().dialogTemplateManager\n+\n+\n+\t@property\n+\tdef SnipsAssistantManager(self):\n+\t\treturn SM.SuperManager.getInstance().snipsAssistantManager\ndiff --git a/core/base/model/TomlFile.py b/core/base/model/TomlFile.py\n--- a/core/base/model/TomlFile.py\n+++ b/core/base/model/TomlFile.py\n@@ -7,6 +7,7 @@\n from typing import Any, Dict, ItemsView, Optional, Union, ValuesView\n \n import re\n+import tempfile\n \n from core.base.model.ProjectAliceObject import ProjectAliceObject\n \n@@ -66,8 +67,8 @@ def dump(self, withComments: bool = True, otherPath: Path = None, keepOtherPath:\n \t\twritePath = self._path\n \n \t\ttry:\n-\t\t\tif not self.Commons.isWritable(self._path):\n-\t\t\t\traise Exception\n+\t\t\ttest = tempfile.TemporaryFile(dir=path)\n+\t\t\ttest.close()\n \t\texcept Exception:\n \t\t\twritePath = Path(writePath.stem).with_suffix('.toml')\n \n@@ -145,7 +146,7 @@ def addEmptinessIfNeeded(self):\n \t\t\"\"\"\n \t\tif self._loaded:\n \t\t\ttry:\n-\t\t\t\tself._data[list(self._data.keys())[-1]].addEmptiness()\n+\t\t\t\tself._data[list(self._data)[-1]].addEmptiness()\n \t\t\texcept Exception:\n \t\t\t\t# No need to add new emptiness\n \t\t\t\tpass\ndiff --git a/core/base/model/Version.py b/core/base/model/Version.py\n--- a/core/base/model/Version.py\n+++ b/core/base/model/Version.py\n@@ -1,134 +1,45 @@\n from __future__ import annotations\n \n-import re\n-\n-from core.base.model.ProjectAliceObject import ProjectAliceObject\n-\n-\n-class Version(str, ProjectAliceObject):\n-\n-\tVERSION_PARSER_REGEX = re.compile('(?P\\d+)\\.(?P\\d+)(\\.(?P\\d+))?(-(?Pa|b|rc)(?P\\d+)?)?')\n-\n-\tdef __new__(cls, value, *args, **kwargs):\n-\t\treturn super().__new__(cls, value)\n-\n-\n-\tdef __init__(self, versionString: str):\n-\t\tsuper().__init__()\n-\t\tself._string = versionString\n-\n-\t\ttry:\n-\t\t\tmatches = self.VERSION_PARSER_REGEX.search(str(versionString))\n-\n-\t\t\tif not matches:\n-\t\t\t\traise TypeError\n-\t\t\telse:\n-\t\t\t\tself._isVersionNumber = True\n-\t\t\t\tself._infos = {\n-\t\t\t\t\t'mainVersion' : int(matches.group('mainVersion')),\n-\t\t\t\t\t'updateVersion': int(matches.group('updateVersion')),\n-\t\t\t\t\t'hotfix' : -1 if not matches.group('hotfix') else int(matches.group('hotfix')),\n-\t\t\t\t\t'releaseType' : matches.group('releaseType') or 'master',\n-\t\t\t\t\t'releaseNumber': 1 if not matches.group('releaseNumber') else int(matches.group('releaseNumber'))\n-\t\t\t\t}\n-\t\t\t\tself.isOldVersioning()\n-\t\texcept TypeError:\n-\t\t\tself._isVersionNumber = False\n-\t\t\tself._infos = {\n-\t\t\t\t'mainVersion' : 0,\n-\t\t\t\t'updateVersion': 0,\n-\t\t\t\t'hotfix' : 0,\n-\t\t\t\t'releaseType' : '',\n-\t\t\t\t'releaseNumber': 0\n-\t\t\t}\n+from dataclasses import dataclass\n \n+import re\n \n-\tdef __gt__(self, other: Version) -> bool:\n-\t\tif self.__eq__(other) or self.isOldVersioning():\n-\t\t\treturn False\n \n-\t\tif other.isOldVersioning():\n-\t\t\treturn True\n+@dataclass(order=True)\n+class Version:\n+\tmainVersion: int = 0\n+\tupdateVersion: int = 0\n+\thotfix: int = 0\n+\t# use of release instead of master since release > rc > b > a\n+\treleaseType: str = 'release'\n+\treleaseNumber: int = 1\n \n-\t\tif self._infos['mainVersion'] > other.infos['mainVersion']:\n-\t\t\t# 2.0.0 > 1.0.0\n-\t\t\treturn True\n \n-\t\telif self._infos['mainVersion'] == other.infos['mainVersion'] and \\\n-\t\t\t\tself._infos['updateVersion'] > other.infos['updateVersion']:\n-\t\t\t# 2.1.0 > 2.0.0\n-\t\t\treturn True\n+\t@property\n+\tdef isVersionNumber(self):\n+\t\treturn self > Version(0, 0, 0, '', 0)\n \n-\t\telif self._infos['mainVersion'] == other.infos['mainVersion'] and \\\n-\t\t\t\tself._infos['updateVersion'] == other.infos['updateVersion'] and \\\n-\t\t\t\tself._infos['hotfix'] > other.infos['hotfix']:\n-\t\t\t# 2.1.1 > 2.1.0\n-\t\t\treturn True\n \n+\tdef __str__(self):\n+\t\tif self.releaseType == 'release':\n+\t\t\treturn f'{self.mainVersion}.{self.updateVersion}.{self.hotfix}'\n \t\telse:\n-\t\t\tif self._infos['releaseType'] in ('a', 'b', 'rc') and other.infos['releaseType'] == 'master':\n-\t\t\t\t# 2.1.1-a < 2.1.1\n-\t\t\t\treturn False\n-\t\t\telif self._infos['releaseType'] == 'b' and other.infos['releaseType'] == 'a':\n-\t\t\t\t# 2.1.1-b > 2.1.1-a\n-\t\t\t\treturn True\n-\t\t\telif self._infos['releaseType'] == 'rc' and other.infos['releaseType'] in ('a', 'b'):\n-\t\t\t\t# 2.1.1-rc > 2.1.1-b\n-\t\t\t\treturn True\n-\t\t\telif self._infos['releaseType'] == 'master' and other.infos['releaseType'] in ('a', 'b', 'rc'):\n-\t\t\t\t# 2.1.1 > 2.1.1-b\n-\t\t\t\treturn True\n-\t\t\telif self._infos['releaseType'] == other.infos['releaseType']:\n-\t\t\t\t# 2.1.1-b2 > 2.1.1-b1\n-\t\t\t\treturn self._infos['releaseNumber'] > other.infos['releaseNumber']\n-\n-\t\treturn False\n-\n-\n-\tdef __lt__(self, other: Version) -> bool:\n-\t\tif self.__eq__(other):\n-\t\t\treturn False\n-\n-\t\treturn not self.__gt__(other)\n-\n+\t\t\treturn f'{self.mainVersion}.{self.updateVersion}.{self.hotfix}-{self.releaseType}{self.releaseNumber}'\n \n-\tdef __eq__(self, other: Version) -> bool:\n-\t\treturn self._infos == other.infos\n \n+\t@classmethod\n+\tdef fromString(cls, versionString: str) -> Version:\n+\t\tversionMatch = re.search(\n+\t\t\t'(?P\\d+)\\.(?P\\d+)(?:\\.(?P\\d+))?(?:-(?Pa|b|rc)(?P\\d+)?)?',\n+\t\t\tstr(versionString))\n \n-\tdef __ne__(self, other: Version) -> bool:\n-\t\treturn not self.__eq__(other)\n+\t\t# when the string is no version set the version to the lowest possible value\n+\t\tif not versionMatch:\n+\t\t\treturn cls(0, 0, 0, '', 0)\n \n-\n-\tdef __ge__(self, other: Version) -> bool:\n-\t\treturn self.__eq__(other) or self.__gt__(other)\n-\n-\n-\tdef __le__(self, other: Version) -> bool:\n-\t\treturn self.__eq__(other) or not self.__gt__(other)\n-\n-\n-\tdef __repr__(self):\n-\t\treturn self._string\n-\n-\n-\tdef isOldVersioning(self) -> bool:\n-\t\tif self._infos['hotfix'] == -1:\n-\t\t\tself.logWarning(f'Use of deprecated version number: {self._string}. Please use 3 digits format: x.x.x(-[a/b/rc]x)')\n-\t\t\treturn True\n-\t\treturn False\n-\n-\n-\t@property\n-\tdef string(self) -> str:\n-\t\treturn self._string\n-\n-\n-\t@property\n-\tdef infos(self) -> dict:\n-\t\treturn self._infos\n-\n-\n-\t@property\n-\tdef isVersionNumber(self) -> bool:\n-\t\treturn self._isVersionNumber\n+\t\treturn cls(\n+\t\t\tint(versionMatch.group('mainVersion')),\n+\t\t\tint(versionMatch.group('updateVersion')),\n+\t\t\tint(versionMatch.group('hotfix') or 0),\n+\t\t\tversionMatch.group('releaseType') or 'release',\n+\t\t\tint(versionMatch.group('releaseNumber') or 1))\ndiff --git a/core/base/model/Widget.py b/core/base/model/Widget.py\n--- a/core/base/model/Widget.py\n+++ b/core/base/model/Widget.py\n@@ -3,14 +3,17 @@\n import sqlite3\n from pathlib import Path\n from textwrap import dedent\n-from typing import Dict, Optional\n+from typing import Dict, Match, Optional\n+\n+import re\n \n from core.base.model.ProjectAliceObject import ProjectAliceObject\n+from core.base.model.widgetSizes import WidgetSizes\n \n \n class Widget(ProjectAliceObject):\n+\tSIZE = WidgetSizes.w\n \n-\tSIZE = 'w'\n \tOPTIONS = dict()\n \n \tdef __init__(self, data: sqlite3.Row):\n@@ -23,12 +26,11 @@ def __init__(self, data: sqlite3.Row):\n \t\tself._state = data['state'] if 'state' in data.keys() else 0\n \t\tself._x = data['posx'] if 'posx' in data.keys() else 0\n \t\tself._y = data['posy'] if 'posy' in data.keys() else 0\n-\t\tself._size = data['size'] if 'size' in data.keys() else self.SIZE\n-\t\toptions = json.loads(data['options']) if 'options' in data.keys() else self.OPTIONS\n-\t\tif options:\n-\t\t\tself._options = {**self.OPTIONS, **options}\n-\t\telse:\n-\t\t\tself._options = self.OPTIONS\n+\t\tself._size = self.SIZE.value\n+\n+\t\tself._options = self.OPTIONS\n+\t\tif 'options' in data.keys():\n+\t\t\tself._options.update(json.loads(data['options']))\n \n \t\tself._zindex = data['zindex'] if 'zindex' in data.keys() else 9999\n \t\tself._language = self.loadLanguage()\n@@ -76,14 +78,26 @@ def getCurrentDir(self) -> Path:\n \tdef html(self) -> str:\n \t\ttry:\n \t\t\tfile = self.getCurrentDir() / f'templates/{self.name}.html'\n-\t\t\treturn file.open().read()\n+\t\t\tfp = file.open()\n+\t\t\tcontent = fp.read()\n+\t\t\t# noinspection PyTypeChecker\n+\t\t\tcontent = re.sub(r'{{ lang\\.([\\w]*) }}', self.langReplace, content)\n+\n+\t\t\treturn content\n \t\texcept:\n \t\t\tself.logWarning(f\"Widget doesn't have html file\")\n \t\t\treturn ''\n \n \n+\tdef langReplace(self, match: Match):\n+\t\treturn self.getLanguageString(match.group(1))\n+\n+\n \tdef getLanguageString(self, key: str) -> str:\n-\t\treturn self._language.get(key, 'Missing string')\n+\t\ttry:\n+\t\t\treturn self._language[self.LanguageManager.activeLanguage][key]\n+\t\texcept KeyError:\n+\t\t\treturn 'Missing string'\n \n \n \t@property\n@@ -137,7 +151,7 @@ def state(self, value: int):\n \n \n \t@property\n-\tdef size(self) -> str:\n+\tdef size(self) -> WidgetSizes:\n \t\treturn self._size\n \n \ndiff --git a/core/base/model/widgetSizes.py b/core/base/model/widgetSizes.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/base/model/widgetSizes.py\n@@ -0,0 +1,19 @@\n+from enum import Enum\n+\n+\n+class WidgetSizes(Enum):\n+\tw_tiny = 'w_tiny'\n+\tw_tiny_wide = 'w_tiny_wide'\n+\tw_tiny_tall = 'w_tiny_tall'\n+\tw_small = 'w_small'\n+\tw_small_wide = 'w_small_wide'\n+\tw_small_tall = 'w_small_tall'\n+\tw = 'w'\n+\tw_wide = 'w_wide'\n+\tw_tall = 'w_tall'\n+\tw_large = 'w_large'\n+\tw_large_wide = 'w_large_wide'\n+\tw_large_tall = 'w_large_tall'\n+\tw_extralarge = 'w_extralarge'\n+\tw_extralarge_wide = 'w_extralarge_wide'\n+\tw_extralarge_tall = 'w_extralarge_tall'\ndiff --git a/core/commons/CommonsManager.py b/core/commons/CommonsManager.py\n--- a/core/commons/CommonsManager.py\n+++ b/core/commons/CommonsManager.py\n@@ -1,15 +1,19 @@\n import inspect\n import json\n import socket\n+import string\n+import subprocess\n import time\n from collections import defaultdict\n-from contextlib import contextmanager\n+from contextlib import contextmanager, suppress\n from ctypes import *\n from datetime import datetime\n from pathlib import Path\n-from typing import Union\n-from contextlib import suppress\n+from typing import Any, Union\n \n+import hashlib\n+import random\n+import requests\n import tempfile\n from googletrans import Translator\n from paho.mqtt.client import MQTTMessage\n@@ -24,9 +28,9 @@\n class CommonsManager(Manager):\n \n \tERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)\n-\t\n+\n \tdef __init__(self):\n-\t\tsuper().__init__('Commons')\n+\t\tsuper().__init__(name='Commons')\n \n \n \t@staticmethod\n@@ -59,7 +63,7 @@ def isEqualTranslated(self, baseString: str, compareTo: str, skill: str = 'syste\n \n \n \t@staticmethod\n-\tdef dictMaxValue(d: dict) -> str:\n+\tdef dictMaxValue(d: dict) -> Any:\n \t\treturn max(d, key=d.get)\n \n \n@@ -74,12 +78,12 @@ def payload(message: MQTTMessage) -> dict:\n \t\t\tpayload = json.loads(message.payload)\n \t\texcept (ValueError, TypeError):\n \t\t\tpayload = dict()\n-\t\t\n+\n \t\tif payload is True:\n \t\t\tpayload = {'true': True}\n \t\telif payload is False:\n \t\t\tpayload = {'false': False}\n-\t\t\n+\n \t\treturn payload\n \n \n@@ -88,7 +92,7 @@ def parseSlotsToObjects(cls, message: MQTTMessage) -> dict:\n \t\tslots = defaultdict(list)\n \t\tdata = cls.payload(message)\n \t\tfor slotData in data.get('slots', dict()):\n-\t\t\tslot = slotModel.Slot(slotData)\n+\t\t\tslot = slotModel.Slot(**slotData)\n \t\t\tslots[slot.slotName].append(slot)\n \t\treturn slots\n \n@@ -287,8 +291,42 @@ def translate(self, text: Union[str, list], destLang: str = None, srcLang: str =\n \t\treturn [result.text for result in Translator().translate(**kwargs)]\n \n \n+\tdef runRootSystemCommand(self, commands: list, shell: bool = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE):\n+\t\tif commands[0] != 'sudo':\n+\t\t\tcommands.insert(0, 'sudo')\n+\t\treturn self.runSystemCommand(commands, shell=shell, stdout=stdout, stderr=stderr)\n+\n+\n+\t@staticmethod\n+\tdef runSystemCommand(commands: list, shell: bool = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE):\n+\t\treturn subprocess.run(commands, shell=shell, stdout=stdout, stderr=stderr)\n+\n+\n+\tdef downloadFile(self, url: str, dest: str) -> bool:\n+\t\ttry:\n+\t\t\twith Path(self.Commons.rootDir(), dest).open('wb') as fp:\n+\t\t\t\tfp.write(requests.get(url).content)\n+\n+\t\t\treturn True\n+\t\texcept Exception as e:\n+\t\t\tself.logWarning(f'Failed downloading file: {e}')\n+\t\t\treturn False\n+\n+\n+\t@staticmethod\n+\tdef fileChecksum(file: Path) -> str:\n+\t\treturn hashlib.blake2b(file.read_bytes()).hexdigest()\n+\n+\n+\t@staticmethod\n+\tdef randomString(length: int) -> str:\n+\t\tchars = string.ascii_letters + string.digits\n+\t\treturn ''.join(random.choice(chars) for i in range(length))\n+\n+\n # noinspection PyUnusedLocal\n def py_error_handler(filename, line, function, err, fmt):\n \tpass\n \n+\n c_error_handler = CommonsManager.ERROR_HANDLER_FUNC(py_error_handler)\ndiff --git a/core/commons/constants.py b/core/commons/constants.py\n--- a/core/commons/constants.py\n+++ b/core/commons/constants.py\n@@ -1,4 +1,4 @@\n-VERSION = '1.0.0-a4'\n+VERSION = '1.0.0-a5'\n DEFAULT_SITE_ID = 'default'\n DEFAULT = 'default'\n UNKNOWN_WORD = 'unknownword'\n@@ -7,13 +7,20 @@\n UNKNOWN = 'unknown'\n EVERYWHERE = 'everywhere'\n ALL = 'all'\n+RANDOM = 'random'\n DUMMY = 'dummy'\n DATABASE_FILE = 'system/database/data.db'\n+SKILL_INSTALL_TICKET_PATH = 'system/skillInstallTickets'\n+GITHUB_URL = 'https://github.com/project-alice-assistant'\n+GITHUB_RAW_URL = 'https://raw.githubusercontent.com/project-alice-assistant'\n+GITHUB_API_URL = 'https://api.github.com/repos/project-alice-assistant'\n+GITHUB_REPOSITORY_ID = 193512918\n \n TOPIC_AUDIO_FRAME = 'hermes/audioServer/{}/audioFrame'\n TOPIC_HOTWORD_DETECTED = 'hermes/hotword/default/detected'\n TOPIC_WAKEWORD_DETECTED = 'hermes/hotword/{}/detected'\n TOPIC_ASR_START_LISTENING = 'hermes/asr/startListening'\n+TOPIC_ASR_STOP_LISTENING = 'hermes/asr/stopListening'\n TOPIC_SESSION_STARTED = 'hermes/dialogueManager/sessionStarted'\n TOPIC_SESSION_QUEUED = 'hermes/dialogueManager/sessionQueued'\n TOPIC_SESSION_ENDED = 'hermes/dialogueManager/sessionEnded'\n@@ -31,7 +38,47 @@\n TOPIC_TOGGLE_FEEDBACK_ON = 'hermes/feedback/sound/toggleOn'\n TOPIC_TOGGLE_FEEDBACK_OFF = 'hermes/feedback/sound/toggleOff'\n TOPIC_TOGGLE_FEEDBACK = 'hermes/feedback/sound/toggle{}'\n-TOPIC_STOP_LISTENING = 'hermes/asr/stopListening'\n TOPIC_NLU_QUERY = 'hermes/nlu/query'\n TOPIC_VAD_UP = 'hermes/voiceActivity/{}/vadUp'\n TOPIC_VAD_DOWN = 'hermes/voiceActivity/{}/vadDown'\n+\n+EVENT_FULL_MINUTE = 'fullMinute'\n+EVENT_FIVE_MINUTE = 'fiveMinute'\n+EVENT_QUARTER_HOUR = 'quarterHour'\n+EVENT_FULL_HOUR = 'fullHour'\n+EVENT_SKILL_UPDATED = 'skillUpdated'\n+EVENT_SKILL_INSTALLED = 'skillInstalled'\n+EVENT_BOOTED = 'booted'\n+EVENT_SKILL_INSTALL_FAILED = 'skillInstallFailed'\n+EVENT_DEVICE_CONNECTING = 'deviceConnecting'\n+EVENT_DEVICE_DISCONNECTING = 'deviceDisconnecting'\n+EVENT_AUDIO_FRAME = 'audioFrame'\n+EVENT_HOTWORD_TOGGLE_ON = 'hotwordToggleOn'\n+EVENT_MESSAGE = 'message'\n+EVENT_HOTWORD = 'hotword'\n+EVENT_WAKEWORD = 'wakeword'\n+EVENT_SESSION_STARTED = 'sessionStarted'\n+EVENT_SESSION_QUEUED = 'sessionQueued'\n+EVENT_START_LISTENING = 'startListening'\n+EVENT_STOP_LISTENING = 'stopListening'\n+EVENT_CAPTURED = 'captured'\n+EVENT_NLU_QUERY = 'nluQuery'\n+EVENT_INTENT_PARSED = 'intentParsed'\n+EVENT_SESSION_ENDED = 'sessionEnded'\n+EVENT_USER_CANCEL = 'userCancel'\n+EVENT_SESSION_TIMEOUT = 'sessionTimeout'\n+EVENT_SESSION_ERROR = 'sessionError'\n+EVENT_SAY = 'say'\n+EVENT_SAY_FINISHED = 'sayFinished'\n+EVENT_INTENT_NOT_RECOGNIZED = 'intentNotRecognized'\n+EVENT_SNIPS_ASSISTANT_DOWNLOAD_FAILED = 'snipsAssistantDownloadFailed'\n+EVENT_SNIPS_ASSISTANT_INSTALLED = 'snipsAssistantInstalled'\n+EVENT_SNIPS_ASSISTANT_INSTALL_FAILED = 'snipsAssistantFailedInstalling'\n+EVENT_INTERNET_LOST = 'internetLost'\n+EVENT_INTERNET_CONNECTED = 'internetConnected'\n+EVENT_BROADCASTING_FOR_NEW_DEVICE = 'broadcastingForNewDeviceStart'\n+EVENT_STOP_BROADCASTING_FOR_NEW_DEVICE = 'broadcastingForNewDeviceStop'\n+EVENT_WAKEUP = 'wakeup'\n+EVENT_SLEEP = 'sleep'\n+EVENT_NLU_TRAINED = 'nluTrained'\n+EVENT_ASR_INTERMEDIATE_RESULT = 'asrIntermediateResult'\ndiff --git a/core/commons/model/PartOfDay.py b/core/commons/model/PartOfDay.py\n--- a/core/commons/model/PartOfDay.py\n+++ b/core/commons/model/PartOfDay.py\n@@ -1,9 +1,9 @@\n from enum import Enum\n \n class PartOfDay(Enum):\n-\tEARLY_MORNING \t= 'Early morning'\n-\tMORNING \t\t= 'Morning'\n-\tAFTERNOON \t\t= 'Afternoon'\n-\tEVENING \t\t= 'Evening'\n-\tNIGHT \t\t\t= 'Night'\n-\tSLEEPING \t\t= 'Sleeping'\n+\tEARLY_MORNING = 'Early morning'\n+\tMORNING = 'Morning'\n+\tAFTERNOON = 'Afternoon'\n+\tEVENING = 'Evening'\n+\tNIGHT = 'Night'\n+\tSLEEPING = 'Sleeping'\ndiff --git a/core/commons/model/Singleton.py b/core/commons/model/Singleton.py\n--- a/core/commons/model/Singleton.py\n+++ b/core/commons/model/Singleton.py\n@@ -1,15 +1,15 @@\n from core.util.model.Logger import Logger\n \n \n-class Singleton(Logger):\n-\n+class Singleton:\n \tINSTANCE = None\n \n+\n \tdef __init__(self, name):\n \t\tsuper().__init__()\n \n \t\tif self.INSTANCE:\n-\t\t\tself.logError(f'Trying to instanciate {name} but instance already exists')\n+\t\t\tLogger().logFatal(f'Trying to instanciate {name} but instance already exists')\n \t\t\traise KeyboardInterrupt\n \t\telse:\n \t\t\tself.INSTANCE = self\ndiff --git a/core/commons/model/Slot.py b/core/commons/model/Slot.py\n--- a/core/commons/model/Slot.py\n+++ b/core/commons/model/Slot.py\n@@ -1,27 +1,12 @@\n-class Slot:\n-\tdef __init__(self, data):\n-\t\tself._slotName = data['slotName']\n-\t\tself._entity = data['entity']\n-\t\tself._rawValue = data['rawValue']\n-\t\tself._value = data['value']\n-\t\tself._range = data['range']\n-\n-\t@property\n-\tdef slotName(self):\n-\t\treturn self._slotName\n-\n-\t@property\n-\tdef entity(self):\n-\t\treturn self._entity\n+from dataclasses import dataclass, field\n+from typing import Dict, Union, Optional\n \n-\t@property\n-\tdef rawValue(self):\n-\t\treturn self._rawValue\n-\n-\t@property\n-\tdef value(self):\n-\t\treturn self._value\n-\n-\t@property\n-\tdef range(self):\n-\t\treturn self._range\n\\ No newline at end of file\n+@dataclass\n+class Slot:\n+\tslotName: str\n+\tentity: str\n+\trawValue: str\n+\tvalue: Dict[str, Union[str, int]]\n+\trange: Dict[str, int]\n+\talternatives: list = field(default_factory=list)\n+\tconfidenceScore: Optional[float] = None\ndiff --git a/core/console/AddCommand.py b/core/console/AddCommand.py\n--- a/core/console/AddCommand.py\n+++ b/core/console/AddCommand.py\n@@ -2,7 +2,7 @@\n import click\n import urllib.request\n import requests\n-from terminaltables import DoubleTable # type: ignore\n+from terminaltables import DoubleTable # type: ignore\n from core.base.SkillManager import SkillManager\n \n @click.group()\ndiff --git a/core/console/ListCommand.py b/core/console/ListCommand.py\n--- a/core/console/ListCommand.py\n+++ b/core/console/ListCommand.py\n@@ -1,7 +1,7 @@\n import random\n import click\n import requests\n-from terminaltables import SingleTable # type: ignore\n+from terminaltables import SingleTable # type: ignore\n from core.base.SkillManager import SkillManager\n from core.console.Helpers import OptionEatAll\n from core.base.SuperManager import SuperManager\ndiff --git a/core/console/UpdateCommand.py b/core/console/UpdateCommand.py\n--- a/core/console/UpdateCommand.py\n+++ b/core/console/UpdateCommand.py\n@@ -1,5 +1,5 @@\n import click\n-from terminaltables import DoubleTable # type: ignore\n+from terminaltables import DoubleTable # type: ignore\n from core.base.SuperManager import SuperManager\n import logging.handlers\n \ndiff --git a/core/device/DeviceManager.py b/core/device/DeviceManager.py\n--- a/core/device/DeviceManager.py\n+++ b/core/device/DeviceManager.py\n@@ -15,6 +15,7 @@\n from serial.tools import list_ports # type: ignore\n \n from core.base.model.Manager import Manager\n+from core.commons import constants\n from core.device.model.Device import Device\n from core.device.model.TasmotaConfigs import TasmotaConfigs\n from core.dialog.model.DialogSession import DialogSession\n@@ -22,8 +23,6 @@\n \n class DeviceManager(Manager):\n \n-\tNAME = 'DeviceManager'\n-\n \tDATABASE = {\n \t\t'devices': [\n \t\t\t'id INTEGER PRIMARY KEY',\n@@ -36,24 +35,24 @@ class DeviceManager(Manager):\n \n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME, self.DATABASE)\n+\t\tsuper().__init__(databaseSchema=self.DATABASE)\n \n-\t\tself._devices = dict()\n-\t\tself._broadcastRoom = ''\n-\t\tself._broadcastFlag = threading.Event()\n+\t\tself._devices = dict()\n+\t\tself._broadcastRoom = ''\n+\t\tself._broadcastFlag = threading.Event()\n \n-\t\tself._broadcastPort = None\n-\t\tself._broadcastTimer = None\n+\t\tself._broadcastPort = None\n+\t\tself._broadcastTimer = None\n \n-\t\tself._flashThread = None\n+\t\tself._flashThread = None\n \n-\t\tself._listenPort = None\n+\t\tself._listenPort = None\n \n-\t\tself._broadcastSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n+\t\tself._broadcastSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n \t\tself._broadcastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n \t\tself._broadcastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n \n-\t\tself._listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n+\t\tself._listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \t\tself._listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n \t\tself._listenSocket.settimeout(2)\n \n@@ -208,7 +207,7 @@ def doFlashTasmota(self, room: str, espType: str, siteId: str):\n \t\t\tmac = ':'.join([f'{x:02x}' for x in mac])\n \t\t\tcmd = [\n \t\t\t\t'--port', port,\n-\t\t\t\t'--baud','115200',\n+\t\t\t\t'--baud', '115200',\n \t\t\t\t'--after', 'no_reset', 'write_flash',\n \t\t\t\t'--flash_mode', 'dout', '0x00000', 'sonoff.bin',\n \t\t\t\t'--erase-all'\n@@ -223,7 +222,7 @@ def doFlashTasmota(self, room: str, espType: str, siteId: str):\n \n \t\tself.logInfo('Tasmota flash done')\n \t\tself.MqttManager.say(text=self.TalkManager.randomTalk('espFlashedUnplugReplug', skill='AliceCore'), client=siteId)\n-\t\tfound = self.findUSBPort(timeout = 60)\n+\t\tfound = self.findUSBPort(timeout=60)\n \t\tif found:\n \t\t\tself.MqttManager.say(text=self.TalkManager.randomTalk('espFoundReadyForConf', skill='AliceCore'), client=siteId)\n \t\t\ttime.sleep(10)\n@@ -315,7 +314,7 @@ def startBroadcastingForNewDevice(self, room: str, siteId: str, uid: str = '') -\n \n \t\tself._broadcastTimer = self.ThreadManager.newTimer(interval=300, func=self.stopBroadcasting)\n \n-\t\tself.SkillManager.skillBroadcast(method='onBroadcastingForNewDeviceStart')\n+\t\tself.broadcast(method=constants.EVENT_BROADCASTING_FOR_NEW_DEVICE, exceptions=[self.name], propagateToSkills=True)\n \t\treturn True\n \n \n@@ -327,7 +326,7 @@ def stopBroadcasting(self):\n \t\t\tself._broadcastTimer.cancel()\n \n \t\tself._broadcastRoom = ''\n-\t\tself.SkillManager.skillBroadcast(method='onBroadcastingForNewDeviceStop')\n+\t\tself.broadcast(method=constants.EVENT_STOP_BROADCASTING_FOR_NEW_DEVICE, exceptions=[self.name], propagateToSkills=True)\n \n \n \tdef startBroadcast(self, room: str, uid: str, replyOnSiteId: str):\n@@ -346,18 +345,18 @@ def startBroadcast(self, room: str, uid: str, replyOnSiteId: str):\n \t\t\t\t\tfor satellite in self.getDevicesByRoom(room):\n \t\t\t\t\t\tif satellite.deviceType.lower() == 'alicesatellite':\n \t\t\t\t\t\t\tself.logWarning('Cannot have more than one Alice skill per room, aborting')\n-\t\t\t\t\t\t\tself.MqttManager.say(text = self.TalkManager.randomTalk('maxOneAlicePerRoom', skill='system'), client=replyOnSiteId)\n+\t\t\t\t\t\t\tself.MqttManager.say(text=self.TalkManager.randomTalk('maxOneAlicePerRoom', skill='system'), client=replyOnSiteId)\n \t\t\t\t\t\t\tanswer = 'nok'\n \t\t\t\t\t\t\tbreak\n \n \t\t\t\tif answer != 'nok':\n \t\t\t\t\tif self.addNewDevice(deviceType, room, uid):\n \t\t\t\t\t\tself.logInfo(f'New device with uid {uid} successfully added')\n-\t\t\t\t\t\tself.MqttManager.say(text = self.TalkManager.randomTalk('newDeviceAdditionSuccess', skill='system'), client=replyOnSiteId)\n+\t\t\t\t\t\tself.MqttManager.say(text=self.TalkManager.randomTalk('newDeviceAdditionSuccess', skill='system'), client=replyOnSiteId)\n \t\t\t\t\t\tanswer = 'ok'\n \t\t\t\t\telse:\n \t\t\t\t\t\tself.logInfo('Failed adding new device')\n-\t\t\t\t\t\tself.MqttManager.say(text = self.TalkManager.randomTalk('newDeviceAdditionFailed', skill='system'), client=replyOnSiteId)\n+\t\t\t\t\t\tself.MqttManager.say(text=self.TalkManager.randomTalk('newDeviceAdditionFailed', skill='system'), client=replyOnSiteId)\n \t\t\t\t\t\tanswer = 'nok'\n \n \t\t\t\t\tif deviceType.lower() == 'alicesatellite':\n@@ -376,7 +375,7 @@ def deviceConnecting(self, uid: str) -> Optional[Device]:\n \n \t\tif not self._devices[uid].connected:\n \t\t\tself._devices[uid].connected = True\n-\t\t\tself.broadcast(method='onDeviceConnecting', exceptions=[self.name], propagateToSkills=True)\n+\t\t\tself.broadcast(method=constants.EVENT_DEVICE_CONNECTING, exceptions=[self.name], propagateToSkills=True)\n \n \t\treturn self._devices[uid]\n \n@@ -387,7 +386,7 @@ def deviceDisconnecting(self, uid: str):\n \n \t\tif self._devices[uid].connected:\n \t\t\tself._devices[uid].connected = False\n-\t\t\tself.broadcast(method='onDeviceDisconnecting', exceptions=[self.name], propagateToSkills=True)\n+\t\t\tself.broadcast(method=constants.EVENT_DEVICE_DISCONNECTING, exceptions=[self.name], propagateToSkills=True)\n \n \n \tdef getDevicesByRoom(self, room: str, connectedOnly: bool = False) -> List[Device]:\ndiff --git a/core/device/model/Device.py b/core/device/model/Device.py\n--- a/core/device/model/Device.py\n+++ b/core/device/model/Device.py\n@@ -1,49 +1,19 @@\n-class Device:\n-\tdef __init__(self, data: dict, connected: bool = False):\n-\t\tself._id \t\t\t= data['id']\n-\t\tself._deviceType\t= data['type']\n-\t\tself._uid \t\t\t= data['uid']\n-\t\tself._room \t\t\t= data['room']\n-\t\tself._name \t\t\t= ''\n-\t\tself._connected \t= connected\n-\t\tself._lastContact \t= 0\n-\n-\n-\t@property\n-\tdef id(self) -> int:\n-\t\treturn self._id\n-\n-\n-\t@property\n-\tdef deviceType(self) -> str:\n-\t\treturn self._deviceType\n-\n-\n-\t@property\n-\tdef uid(self) -> str:\n-\t\treturn self._uid\n-\n-\n-\t@property\n-\tdef room(self) -> str:\n-\t\treturn self._room\n+from dataclasses import dataclass, field\n \n-\n-\t@property\n-\tdef name(self) -> str:\n-\t\treturn self._name\n-\n-\n-\t@name.setter\n-\tdef name(self, value: str):\n-\t\tself._name = value\n-\n-\n-\t@property\n-\tdef connected(self) -> bool:\n-\t\treturn self._connected\n-\n-\n-\t@connected.setter\n-\tdef connected(self, value: bool):\n-\t\tself._connected = value\n+@dataclass\n+class Device:\n+\tdata: dict\n+\tconnected: bool = False\n+\tname: str = ''\n+\tlastContact: int = 0\n+\n+\tid: int = field(init=False)\n+\tdeviceType: str = field(init=False)\n+\tuid: str = field(init=False)\n+\troom: str = field(init=False)\n+\n+\tdef __post_init__(self):\n+\t\tself.id = self.data['id']\n+\t\tself.deviceType = self.data['type']\n+\t\tself.uid = self.data['uid']\n+\t\tself.room = self.data['room']\ndiff --git a/core/device/model/TasmotaConfigs.py b/core/device/model/TasmotaConfigs.py\n--- a/core/device/model/TasmotaConfigs.py\n+++ b/core/device/model/TasmotaConfigs.py\n@@ -3,17 +3,35 @@\n \n class TasmotaConfigs(ProjectAliceObject):\n \n+\tdef __init__(self, deviceType: str, uid: str):\n+\t\tsuper().__init__()\n+\t\tself._name = 'TasmotaConfigs'\n+\n+\t\tself._deviceType = deviceType\n+\t\tself._uid = uid\n+\n+\n+\t@property\n+\tdef deviceType(self) -> str:\n+\t\treturn self._deviceType\n+\n+\n+\t@property\n+\tdef uid(self) -> str:\n+\t\treturn self._uid\n+\n+\n \tdef getConfigs(self, deviceBrand: str, room: str) -> list:\n-\t\tif deviceBrand not in self._configs:\n+\t\tif deviceBrand not in self.CONFIGS:\n \t\t\tself.logError(f'[{self._name}] Devices brand \"{deviceBrand}\" unknown')\n \t\t\treturn list()\n \n-\t\telif self._deviceType not in self._configs[deviceBrand]:\n+\t\telif self._deviceType not in self.CONFIGS[deviceBrand]:\n \t\t\tself.logError(f'[{self._name}] Devices type \"{self._deviceType}\" unknown')\n \t\t\treturn list()\n \n \t\telse:\n-\t\t\tconfs = self._configs[deviceBrand][self._deviceType].copy()\n+\t\t\tconfs = self.CONFIGS[deviceBrand][self._deviceType].copy()\n \t\t\tfor deviceConfs in confs:\n \t\t\t\tfor conf in deviceConfs:\n \t\t\t\t\tconf['topic'] = conf['topic'].format(identifier=self._uid)\n@@ -23,7 +41,7 @@ def getConfigs(self, deviceBrand: str, room: str) -> list:\n \n \tdef getBacklogConfigs(self, room: str) -> list:\n \t\tcmds = list()\n-\t\tfor cmdGroup in self._backlogConfigs:\n+\t\tfor cmdGroup in self.BACKLOG_CONFIGS:\n \t\t\tgroup = dict()\n \t\t\tgroup['cmds'] = [cmd.format(\n \t\t\t\t\tmqtthost=self.Commons.getLocalIp(),\n@@ -40,201 +58,184 @@ def getBacklogConfigs(self, room: str) -> list:\n \t\treturn cmds\n \n \n-\tdef __init__(self, deviceType: str, uid: str):\n-\t\tsuper().__init__()\n-\t\tself._name = 'TasmotaConfigs'\n-\n-\t\tself._deviceType = deviceType\n-\t\tself._uid = uid\n-\n-\t\tself._backlogConfigs = [\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'ssid1 {ssid}',\n-\t\t\t\t\t'password1 {wifipass}'\n-\t\t\t\t],\n-\t\t\t\t'waitAfter': 15\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'MqttHost {mqtthost}',\n-\t\t\t\t\t'MqttClient {type}_{room}',\n-\t\t\t\t\t'TelePeriod 0',\n-\t\t\t\t\t#TODO should this be renamed?\n-\t\t\t\t\t'module 18'\n-\t\t\t\t],\n-\t\t\t\t'waitAfter': 8\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'gpio0 9',\n-\t\t\t\t\t'gpio12 21'\n-\t\t\t\t],\n-\t\t\t\t'waitAfter': 8\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'friendlyname {type} - {room}'\n-\t\t\t\t],\n-\t\t\t\t'waitAfter': 8\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'switchmode 2',\n-\t\t\t\t\t'switchtopic 0'\n-\t\t\t\t],\n-\t\t\t\t'waitAfter': 8\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'topic {identifier}',\n-\t\t\t\t\t'grouptopic all',\n-\t\t\t\t\t'fulltopic projectalice/devices/tasmota/%prefix%/%topic%/',\n-\t\t\t\t\t'prefix1 cmd',\n-\t\t\t\t\t'prefix2 feedback',\n-\t\t\t\t\t'prefix3 feedback'\n-\t\t\t\t],\n-\t\t\t\t'waitAfter': 8\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\t'cmds' : [\n-\t\t\t\t\t'rule1 on System#Boot do publish projectalice/devices/tasmota/feedback/hello/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"uid\":\"{identifier}\"}} endon',\n-\t\t\t\t\t'rule1 1',\n-\t\t\t\t\t'rule2 on switch1#state do publish projectalice/devices/tasmota/feedback/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"feedback\":%value%,\"uid\":\"{identifier}\"}} endon',\n-\t\t\t\t\t'rule2 1',\n-\t\t\t\t\t'restart 1'\n+\tBACKLOG_CONFIGS = [\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'ssid1 {ssid}',\n+\t\t\t\t'password1 {wifipass}'\n+\t\t\t],\n+\t\t\t'waitAfter': 15\n+\t\t},\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'MqttHost {mqtthost}',\n+\t\t\t\t'MqttClient {type}_{room}',\n+\t\t\t\t'TelePeriod 0',\n+\t\t\t\t#TODO should this be renamed?\n+\t\t\t\t'module 18'\n+\t\t\t],\n+\t\t\t'waitAfter': 8\n+\t\t},\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'gpio0 9',\n+\t\t\t\t'gpio12 21'\n+\t\t\t],\n+\t\t\t'waitAfter': 8\n+\t\t},\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'friendlyname {type} - {room}'\n+\t\t\t],\n+\t\t\t'waitAfter': 8\n+\t\t},\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'switchmode 2',\n+\t\t\t\t'switchtopic 0'\n+\t\t\t],\n+\t\t\t'waitAfter': 8\n+\t\t},\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'topic {identifier}',\n+\t\t\t\t'grouptopic all',\n+\t\t\t\t'fulltopic projectalice/devices/tasmota/%prefix%/%topic%/',\n+\t\t\t\t'prefix1 cmd',\n+\t\t\t\t'prefix2 feedback',\n+\t\t\t\t'prefix3 feedback'\n+\t\t\t],\n+\t\t\t'waitAfter': 8\n+\t\t},\n+\t\t{\n+\t\t\t'cmds': [\n+\t\t\t\t'rule1 on System#Boot do publish projectalice/devices/tasmota/feedback/hello/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"uid\":\"{identifier}\"}} endon',\n+\t\t\t\t'rule1 1',\n+\t\t\t\t'rule2 on switch1#state do publish projectalice/devices/tasmota/feedback/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"feedback\":%value%,\"uid\":\"{identifier}\"}} endon',\n+\t\t\t\t'rule2 1',\n+\t\t\t\t'restart 1'\n+\t\t\t],\n+\t\t\t'waitAfter': 5\n+\t\t}\n+\t]\n+\n+\tCONFIGS = {\n+\t\t'wemos': {\n+\t\t\t'switch': [\n+\t\t\t\t[\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Module',\n+\t\t\t\t\t\t'payload': '18'\n+\t\t\t\t\t}\n \t\t\t\t],\n-\t\t\t\t'waitAfter': 5\n-\t\t\t}\n-\t\t]\n-\n-\t\tself._configs = {\n-\t\t\t'wemos': {\n-\t\t\t\t'switch': [\n-\t\t\t\t\t[\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Module',\n-\t\t\t\t\t\t\t'payload': '18'\n-\t\t\t\t\t\t}\n-\t\t\t\t\t],\n-\t\t\t\t\t[\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/MqttClient',\n-\t\t\t\t\t\t\t'payload': 'switch_{room}'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Gpio0',\n-\t\t\t\t\t\t\t'payload': '9'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Gpio12',\n-\t\t\t\t\t\t\t'payload': '21'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Prefix1',\n-\t\t\t\t\t\t\t'payload': 'cmd'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Prefix2',\n-\t\t\t\t\t\t\t'payload': 'feedback'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Prefix3',\n-\t\t\t\t\t\t\t'payload': 'feedback'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/GroupTopic',\n-\t\t\t\t\t\t\t'payload': 'all'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/TelePeriod',\n-\t\t\t\t\t\t\t'payload': '0'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/FriendlyName',\n-\t\t\t\t\t\t\t'payload': 'Switch - {room}'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/SwitchMode',\n-\t\t\t\t\t\t\t'payload': '2'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/SwitchTopic',\n-\t\t\t\t\t\t\t'payload': '0'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Topic',\n-\t\t\t\t\t\t\t'payload': '0'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n-\t\t\t\t\t\t\t'payload': 'on switch1#state do publish projectalice/devices/tasmota/feedback/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"feedback\":%value%,\"uid\":\"{identifier}\"}} endon'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n-\t\t\t\t\t\t\t'payload': '1'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Restart',\n-\t\t\t\t\t\t\t'payload': '1'\n-\t\t\t\t\t\t}\n-\t\t\t\t\t]\n+\t\t\t\t[\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/MqttClient',\n+\t\t\t\t\t\t'payload': 'switch_{room}'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Gpio0',\n+\t\t\t\t\t\t'payload': '9'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Gpio12',\n+\t\t\t\t\t\t'payload': '21'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Prefix1',\n+\t\t\t\t\t\t'payload': 'cmd'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Prefix2',\n+\t\t\t\t\t\t'payload': 'feedback'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Prefix3',\n+\t\t\t\t\t\t'payload': 'feedback'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/GroupTopic',\n+\t\t\t\t\t\t'payload': 'all'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/TelePeriod',\n+\t\t\t\t\t\t'payload': '0'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/FriendlyName',\n+\t\t\t\t\t\t'payload': 'Switch - {room}'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/SwitchMode',\n+\t\t\t\t\t\t'payload': '2'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/SwitchTopic',\n+\t\t\t\t\t\t'payload': '0'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Topic',\n+\t\t\t\t\t\t'payload': '0'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n+\t\t\t\t\t\t'payload': 'on switch1#state do publish projectalice/devices/tasmota/feedback/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"feedback\":%value%,\"uid\":\"{identifier}\"}} endon'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n+\t\t\t\t\t\t'payload': '1'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Restart',\n+\t\t\t\t\t\t'payload': '1'\n+\t\t\t\t\t}\n+\t\t\t\t]\n+\t\t\t],\n+\t\t\t'pir': [\n+\t\t\t\t[\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Module',\n+\t\t\t\t\t\t'payload': '18'\n+\t\t\t\t\t}\n \t\t\t\t],\n-\t\t\t\t'pir' : [\n-\t\t\t\t\t[\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Module',\n-\t\t\t\t\t\t\t'payload': '18'\n-\t\t\t\t\t\t}\n-\t\t\t\t\t],\n-\t\t\t\t\t[\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/MqttClient',\n-\t\t\t\t\t\t\t'payload': 'PIR_{room}'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Gpio0',\n-\t\t\t\t\t\t\t'payload': '9'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Gpio12',\n-\t\t\t\t\t\t\t'payload': '21'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/FriendlyName',\n-\t\t\t\t\t\t\t'payload': 'PIR - {room}'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/SwitchMode',\n-\t\t\t\t\t\t\t'payload': '1'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/SwitchTopic',\n-\t\t\t\t\t\t\t'payload': '0'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n-\t\t\t\t\t\t\t'payload': 'on switch1#state do publish projectalice/devices/tasmota/feedback/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"feedback\":%value%,\"uid\":\"{identifier}\"}} endon'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n-\t\t\t\t\t\t\t'payload': '1'\n-\t\t\t\t\t\t},\n-\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t'topic' : 'projectalice/devices/tasmota/cmd/{identifier}/Restart',\n-\t\t\t\t\t\t\t'payload': '1'\n-\t\t\t\t\t\t}\n-\t\t\t\t\t]\n+\t\t\t\t[\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/MqttClient',\n+\t\t\t\t\t\t'payload': 'PIR_{room}'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Gpio0',\n+\t\t\t\t\t\t'payload': '9'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Gpio12',\n+\t\t\t\t\t\t'payload': '21'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/FriendlyName',\n+\t\t\t\t\t\t'payload': 'PIR - {room}'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/SwitchMode',\n+\t\t\t\t\t\t'payload': '1'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/SwitchTopic',\n+\t\t\t\t\t\t'payload': '0'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n+\t\t\t\t\t\t'payload': 'on switch1#state do publish projectalice/devices/tasmota/feedback/{identifier} {{\"siteId\":\"{room}\",\"deviceType\":\"{type}\",\"feedback\":%value%,\"uid\":\"{identifier}\"}} endon'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/rule1',\n+\t\t\t\t\t\t'payload': '1'\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t'topic': 'projectalice/devices/tasmota/cmd/{identifier}/Restart',\n+\t\t\t\t\t\t'payload': '1'\n+\t\t\t\t\t}\n \t\t\t\t]\n-\t\t\t}\n+\t\t\t]\n \t\t}\n-\n-\n-\t@property\n-\tdef deviceType(self) -> str:\n-\t\treturn self._deviceType\n-\n-\n-\t@property\n-\tdef uid(self) -> str:\n-\t\treturn self._uid\n+\t}\ndiff --git a/core/dialog/DialogManager.py b/core/dialog/DialogManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/dialog/DialogManager.py\n@@ -0,0 +1,6 @@\n+from core.base.model.Manager import Manager\n+\n+\n+class DialogManager(Manager):\n+\tdef __init__(self):\n+\t\tsuper().__init__()\ndiff --git a/core/dialog/DialogSessionManager.py b/core/dialog/DialogSessionManager.py\n--- a/core/dialog/DialogSessionManager.py\n+++ b/core/dialog/DialogSessionManager.py\n@@ -16,15 +16,13 @@ class DialogSessionManager(Manager):\n \tevery skill calls\n \t\"\"\"\n \n-\tNAME = 'DialogSessionManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n-\t\tself._preSessions: Dict[str, DialogSession] = dict()\n-\t\tself._sessions: Dict[str, DialogSession] = dict()\n-\t\tself._terminatedSessions: Dict[str, DialogSession] = dict()\n-\t\tself._revivePendingSessions: Dict[str, DialogSession] = dict()\n+\t\tself._preSessions: Dict[str, DialogSession] = dict()\n+\t\tself._sessions: Dict[str, DialogSession] = dict()\n+\t\tself._terminatedSessions: Dict[str, DialogSession] = dict()\n+\t\tself._revivePendingSessions: Dict[str, DialogSession] = dict()\n \n \n \t@property\n@@ -39,8 +37,7 @@ def preSession(self, siteId: str, user: str) -> DialogSession:\n \t\t:param siteId: int\n \t\t:param user: string\n \t\t\"\"\"\n-\t\tsession = DialogSession(siteId)\n-\t\tsession.user = user\n+\t\tsession = DialogSession(siteId=siteId, user=user)\n \t\tself._preSessions[siteId] = session\n \t\treturn session\n \ndiff --git a/core/dialog/DialogTemplateManager.py b/core/dialog/DialogTemplateManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/dialog/DialogTemplateManager.py\n@@ -0,0 +1,149 @@\n+import json\n+from pathlib import Path\n+from typing import Dict\n+\n+from core.base.model.Manager import Manager\n+\n+\n+class DialogTemplateManager(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\t\tself._pathToCache = Path(self.Commons.rootDir(), 'var/cache/dialogTemplates/')\n+\t\tself._pathToChecksums = self._pathToCache / 'checksums.json'\n+\t\tself._hasChanges = False\n+\t\tself._updatedData: Dict[str, list] = dict()\n+\n+\n+\t@property\n+\tdef hasChanges(self) -> bool:\n+\t\treturn self._hasChanges\n+\n+\n+\t@property\n+\tdef updatedData(self) -> Dict[str, list]:\n+\t\treturn self._updatedData\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\n+\t\tchanges = self.checkCache()\n+\t\tif not changes:\n+\t\t\tself.logInfo('Cache uptodate')\n+\t\telse:\n+\t\t\tself.buildCache()\n+\n+\n+\tdef afterNewSkillInstall(self):\n+\t\tif self.checkCache():\n+\t\t\tself.buildCache()\n+\n+\n+\tdef checkCache(self) -> Dict[str, list]:\n+\t\tself._hasChanges = False\n+\n+\t\twith self._pathToChecksums.open() as fp:\n+\t\t\tchecksums = json.load(fp)\n+\n+\t\t# First check upon the skills that are installed\n+\t\tchanges = dict()\n+\t\tlanguage = self.LanguageManager.activeLanguage\n+\t\tfor skill in Path(self.Commons.rootDir(), 'skills/').glob('*/'):\n+\t\t\tif skill.is_file() or skill.stem.startswith('_'):\n+\t\t\t\tcontinue\n+\n+\t\t\tskillName = skill.stem\n+\t\t\tself.logInfo(f'Checking data for skill \"{skillName}\"')\n+\t\t\tif skillName not in checksums:\n+\t\t\t\tself.logInfo(f'Skill \"{skillName}\" is new')\n+\t\t\t\tchecksums[skillName] = list()\n+\t\t\t\tchanges[skillName] = list()\n+\n+\t\t\tpathToResources = skill / 'dialogTemplate'\n+\t\t\tif not pathToResources.exists():\n+\t\t\t\tself.logWarning(f'{skillName} has no dialog template defined')\n+\t\t\t\tcontinue\n+\n+\t\t\tfor file in pathToResources.glob('*.json'):\n+\t\t\t\tfilename = file.stem\n+\t\t\t\tif filename not in checksums[skillName]:\n+\t\t\t\t\t# Trigger a change only if the change concerns the language in use\n+\t\t\t\t\tif filename == language:\n+\t\t\t\t\t\tself.logInfo(f'Skill \"{skillName}\" has new language support \"{filename}\"')\n+\t\t\t\t\t\tchanges.setdefault(skillName, list()).append(filename)\n+\t\t\t\t\tcontinue\n+\n+\t\t\t\tif self.Commons.fileChecksum(file) != checksums[skillName][filename]:\n+\t\t\t\t\t# Trigger a change only if the change concerns the language in use\n+\t\t\t\t\tif filename == language:\n+\t\t\t\t\t\tself.logInfo(f'Skill \"{skillName}\" has changes in language \"{filename}\"')\n+\t\t\t\t\t\tchanges.setdefault(skillName, list()).append(filename)\n+\t\t\t\t\tcontinue\n+\n+\t\t# Now check that what we have in cache in actually existing and wasn't manually deleted\n+\t\tfor skillName, languages in checksums.items():\n+\t\t\tif not Path(self.Commons.rootDir(), f'skills/{skillName}/').exists():\n+\t\t\t\tself.logInfo(f'Skill \"{skillName}\" was removed')\n+\t\t\t\tchanges[f'--{skillName}'] = list()\n+\t\t\t\tcontinue\n+\n+\t\t\tfor lang in languages:\n+\t\t\t\tif not Path(self.Commons.rootDir(), f'skills/{skillName}/dialogTemplate/{lang}.json').exists() and lang == language:\n+\t\t\t\t\tself.logInfo(f'Skill \"{skillName}\" has dropped language \"{lang}\"')\n+\t\t\t\t\tchanges.setdefault(f'--{skillName}', list()).append(lang)\n+\n+\t\tif changes:\n+\t\t\tself._hasChanges = True\n+\t\t\tself._updatedData = changes\n+\n+\t\treturn changes\n+\n+\n+\tdef buildCache(self):\n+\t\tself.logInfo('Building dialog templates cache')\n+\n+\t\tcached = dict()\n+\n+\t\tfor skill in Path(self.Commons.rootDir(), 'skills/').glob('*'):\n+\t\t\tif skill.is_file() or skill.stem.startswith('_'):\n+\t\t\t\tcontinue\n+\n+\t\t\tskillName = skill.stem\n+\t\t\tpathToResources = skill / 'dialogTemplate'\n+\t\t\tif not pathToResources.exists():\n+\t\t\t\tself.logWarning(f'{skillName} has no dialog template defined to build cache')\n+\t\t\t\tcontinue\n+\n+\t\t\tcached[skillName] = dict()\n+\t\t\tfor file in pathToResources.glob('*.json'):\n+\t\t\t\tcached[skillName][file.stem] = self.Commons.fileChecksum(file)\n+\n+\t\twith self._pathToChecksums.open('w') as fp:\n+\t\t\tfp.write(json.dumps(cached, indent=4, sort_keys=True))\n+\n+\n+\tdef cleanCache(self, skillName: str):\n+\t\tfor file in Path(self._pathToCache, 'trainingData').glob('*.json'):\n+\t\t\tif file.stem.startswith(f'{skillName}_'):\n+\t\t\t\tfile.unlink()\n+\n+\t\twith self._pathToChecksums.open() as fp:\n+\t\t\tchecksums = json.load(fp)\n+\t\t\tchecksums.pop(skillName, None)\n+\n+\t\twith self._pathToChecksums.open('w') as fp:\n+\t\t\tfp.write(json.dumps(checksums, indent=4, sort_keys=True))\n+\n+\n+\tdef skillResource(self) -> Path:\n+\t\tfor skillPath in Path(self.Commons.rootDir(), 'skills/').glob('*/'):\n+\t\t\tif skillPath.is_file() or skillPath.stem.startswith('_'):\n+\t\t\t\tcontinue\n+\n+\t\t\tresource = skillPath / f'dialogTemplate/{self.LanguageManager.activeLanguage}.json'\n+\t\t\tif not resource.exists():\n+\t\t\t\tcontinue\n+\n+\t\t\tyield resource\ndiff --git a/core/dialog/MultiIntentManager.py b/core/dialog/MultiIntentManager.py\n--- a/core/dialog/MultiIntentManager.py\n+++ b/core/dialog/MultiIntentManager.py\n@@ -1,4 +1,5 @@\n from paho.mqtt.client import MQTTMessage\n+from collections import deque\n \n from core.base.model.Manager import Manager\n from core.commons import constants\n@@ -8,10 +9,8 @@\n \n class MultiIntentManager(Manager):\n \n-\tNAME = 'MultiIntentManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \t\tself._multiIntents = dict()\n \n \n@@ -36,17 +35,14 @@ def processMessage(self, message: MQTTMessage) -> bool:\n \t\t\t\tuserInput.replace(separator, GLUE_SPLITTER)\n \n \t\t\tif GLUE_SPLITTER in userInput:\n-\t\t\t\tmultiIntent = MultiIntent(session, userInput)\n-\n-\t\t\t\tfor string in userInput.split(GLUE_SPLITTER):\n-\t\t\t\t\tmultiIntent.addIntent(string)\n+\t\t\t\tself._multiIntents[session.sessionId] = MultiIntent(\n+\t\t\t\t\tsession=session,\n+\t\t\t\t\tprocessedString=userInput,\n+\t\t\t\t\tintents=deque(userInput.split(GLUE_SPLITTER)))\n \n-\t\t\t\tself._multiIntents[session.sessionId] = multiIntent\n \t\t\t\treturn self.processNextIntent(session.sessionId)\n-\t\t\telse:\n-\t\t\t\treturn False\n-\t\telse:\n-\t\t\treturn False\n+\n+\t\treturn False\n \n \n \tdef processNextIntent(self, sessionId: str) -> bool:\n@@ -55,14 +51,14 @@ def processNextIntent(self, sessionId: str) -> bool:\n \t\tif not intent:\n \t\t\treturn False\n \n-\t\tself._queryNLU(multiIntent.session, string=intent)\n+\t\tself.queryNLU(multiIntent.session, string=intent)\n \t\treturn True\n \n \n-\tdef _queryNLU(self, session: DialogSession, string: str):\n+\tdef queryNLU(self, session: DialogSession, string: str):\n \t\tself.MqttManager.publish(topic=constants.TOPIC_NLU_QUERY, payload={\n-\t\t\t'input': string,\n-\t\t\t'sessionId': session.sessionId,\n+\t\t\t'input' : string,\n+\t\t\t'sessionId' : session.sessionId,\n \t\t\t'intentFilter': session.intentFilter\n \t\t})\n \ndiff --git a/core/dialog/ProtectedIntentManager.py b/core/dialog/ProtectedIntentManager.py\n--- a/core/dialog/ProtectedIntentManager.py\n+++ b/core/dialog/ProtectedIntentManager.py\n@@ -1,22 +1,17 @@\n-import os\n-\n from core.base.model.Manager import Manager\n \n \n class ProtectedIntentManager(Manager):\n \n-\tNAME = 'ProtectedIntentManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n \t\t# Protected intents cannot be randomly rejected by Alice\n-\t\tself._protectedIntents = list()\n+\t\tself._protectedIntents = set()\n \n \n \tdef protectIntent(self, intentName: str):\n-\t\tif intentName not in self._protectedIntents:\n-\t\t\tself._protectedIntents.append(intentName)\n+\t\tself._protectedIntents.add(intentName)\n \n \n \tdef isProtectedIntent(self, intentName: str) -> bool:\n@@ -24,5 +19,5 @@ def isProtectedIntent(self, intentName: str) -> bool:\n \n \n \t@property\n-\tdef protectedIntents(self) -> list:\n+\tdef protectedIntents(self) -> set:\n \t\treturn self._protectedIntents\ndiff --git a/core/dialog/model/DialogSession.py b/core/dialog/model/DialogSession.py\n--- a/core/dialog/model/DialogSession.py\n+++ b/core/dialog/model/DialogSession.py\n@@ -1,225 +1,95 @@\n from __future__ import annotations\n \n-from textwrap import dedent\n-from typing import Any\n+from dataclasses import dataclass, field\n+from typing import Any, Optional\n \n from paho.mqtt.client import MQTTMessage\n \n from core.base.model import Intent\n-from core.base.model.ProjectAliceObject import ProjectAliceObject\n from core.commons import constants\n \n \n-class DialogSession(ProjectAliceObject):\n-\tdef __init__(self, siteId):\n-\t\tsuper().__init__(logDepth=5)\n-\t\tself._siteId = siteId\n-\t\tself._sessionId = ''\n-\t\tself._user = constants.UNKNOWN_USER\n-\t\tself._message = None\n-\t\tself._slots = dict()\n-\t\tself._slotsAsObjects = dict()\n-\t\tself._customData = dict()\n-\t\tself._payload = dict()\n-\t\tself._intentName = ''\n-\t\tself._intentHistory = list()\n-\t\tself._intentFilter = list()\n-\t\tself._notUnderstood = 0\n-\t\tself._currentState = constants.DEFAULT\n+@dataclass\n+class DialogSession:\n+\tsiteId: str\n+\tsessionId: str = ''\n+\tuser: str = constants.UNKNOWN_USER\n+\tmessage: MQTTMessage = None\n+\tintentName: str = ''\n+\tnotUnderstood: int = 0\n+\tcurrentState: str = constants.DEFAULT\n+\tisAPIGenerated: bool = False\n+\tslots: dict = field(default_factory=dict)\n+\tslotsAsObjects: dict = field(default_factory=dict)\n+\tcustomData: dict = field(default_factory=dict)\n+\tpayload: dict = field(default_factory=dict)\n+\tintentHistory: list = field(default_factory=list)\n+\tintentFilter: list = field(default_factory=list)\n \n \n \tdef extend(self, message: MQTTMessage, sessionId: str = None):\n \t\tif sessionId:\n-\t\t\tself._sessionId = sessionId\n+\t\t\tself.sessionId = sessionId\n \n-\t\tself._message = message\n-\t\tself._intentName = message.topic\n-\t\tself._parseMessage()\n+\t\tfrom core.commons.CommonsManager import CommonsManager\n+\t\tself.message = message\n+\t\tself.intentName = message.topic\n+\t\tself.payload = CommonsManager.payload(message)\n+\t\tself.slots = CommonsManager.parseSlots(message)\n+\t\tself.slotsAsObjects = CommonsManager.parseSlotsToObjects(message)\n+\t\tself.customData = CommonsManager.parseCustomData(message)\n \n \n \tdef update(self, message: MQTTMessage):\n-\t\tself._message = message\n-\t\tself._intentName = message.topic\n-\t\tself._updateSessionData()\n+\t\tfrom core.commons.CommonsManager import CommonsManager\n+\t\tself.message = message\n+\t\tself.intentName = message.topic\n+\t\tself.payload = CommonsManager.payload(message)\n+\t\tself.slots.update(CommonsManager.parseSlots(message))\n+\t\tself.slotsAsObjects.update(CommonsManager.parseSlotsToObjects(message))\n+\t\tself.customData.update(CommonsManager.parseCustomData(message))\n \n \n \tdef reviveOldSession(self, session: DialogSession):\n-\t\tself._payload = session.payload\n-\t\tself._slots = session.slots\n-\t\tself._slotsAsObjects = session.slotsAsObjects\n-\t\tself._customData = session.customData\n-\t\tself._user = session.user\n-\t\tself._message = session.message\n-\t\tself._intentName = session.intentName\n-\t\tself._intentHistory = session.intentHistory\n-\t\tself._intentFilter = session.intentFilter\n-\t\tself._notUnderstood = session.notUnderstood\n-\t\tself._currentState = session.currentState\n-\n-\n-\tdef _parseMessage(self):\n-\t\tself._payload = self.Commons.payload(self._message)\n-\t\tself._slots = self.Commons.parseSlots(self._message)\n-\t\tself._slotsAsObjects = self.Commons.parseSlotsToObjects(self._message)\n-\t\tself._customData = self.Commons.parseCustomData(self._message)\n-\n-\n-\tdef _updateSessionData(self):\n-\t\tself._payload = self.Commons.payload(self._message)\n-\t\tself._slots = {**self._slots, **self.Commons.parseSlots(self._message)}\n-\t\tself._slotsAsObjects = {**self._slotsAsObjects, **self.Commons.parseSlotsToObjects(self._message)}\n-\t\tself._customData = {**self._customData, **self.Commons.parseCustomData(self._message)}\n-\n-\n-\tdef addToHistory(self, intent: Intent):\n-\t\tself._intentHistory.append(intent)\n-\n-\n-\t@property\n-\tdef slots(self) -> dict:\n-\t\treturn self._slots\n-\n-\n-\t@property\n-\tdef slotsAsObjects(self) -> dict:\n-\t\treturn self._slotsAsObjects\n+\t\t\"\"\"\n+\t\tRevives old session keeping siteId, sessionId and isAPIGenerated from the\n+\t\tnew session\n+\t\t\"\"\"\n+\t\tself.payload = session.payload\n+\t\tself.slots = session.slots\n+\t\tself.slotsAsObjects = session.slotsAsObjects\n+\t\tself.customData = session.customData\n+\t\tself.user = session.user\n+\t\tself.message = session.message\n+\t\tself.intentName = session.intentName\n+\t\tself.intentHistory = session.intentHistory\n+\t\tself.intentFilter = session.intentFilter\n+\t\tself.notUnderstood = session.notUnderstood\n+\t\tself.currentState = session.currentState\n+\t\tself.isAPIGenerated = session.isAPIGenerated\n \n \n \tdef slotValue(self, slotName: str, index: int = 0, defaultValue: Any = None) -> Any:\n \t\t\"\"\"\n \t\tThis returns the slot master value, not what was heard / captured\n \t\t\"\"\"\n-\t\tif slotName in self._slotsAsObjects:\n+\t\ttry:\n \t\t\treturn self.slotsAsObjects[slotName][index].value['value']\n-\t\telse:\n+\t\texcept (KeyError, IndexError):\n \t\t\treturn defaultValue\n \n \n \tdef slotRawValue(self, slotName: str) -> str:\n \t\t\"\"\"\n-\t\tThis returns the slot raw value, what whas really heard / captured, so it can be a synonym per exemple\n+\t\tThis returns the slot raw value, what whas really heard / captured, so it can be a synonym for example\n \t\t\"\"\"\n-\t\treturn self._slots.get(slotName, '')\n-\n-\n-\t@property\n-\tdef customData(self) -> dict:\n-\t\treturn self._customData\n-\n-\n-\t@property\n-\tdef payload(self) -> dict:\n-\t\treturn self._payload\n-\n-\n-\t@payload.setter\n-\tdef payload(self, value: dict):\n-\t\tself._payload = value\n-\n-\n-\t@property\n-\tdef siteId(self) -> str:\n-\t\treturn self._siteId\n-\n-\n-\t@property\n-\tdef sessionId(self) -> str:\n-\t\treturn self._sessionId\n-\n-\n-\t@property\n-\tdef user(self) -> str:\n-\t\treturn self._user\n-\n-\n-\t@user.setter\n-\tdef user(self, user: str):\n-\t\tself._user = user\n-\n-\n-\t@sessionId.setter\n-\tdef sessionId(self, sessionId: str):\n-\t\tself._sessionId = sessionId\n-\n-\n-\t@property\n-\tdef message(self) -> MQTTMessage:\n-\t\treturn self._message\n-\n-\n-\t@message.setter\n-\tdef message(self, message: MQTTMessage):\n-\t\tself._message = message\n-\n-\t@property\n-\tdef intentName(self) -> str:\n-\t\treturn self._intentName\n-\n-\n-\t@property\n-\tdef intentHistory(self) -> list:\n-\t\treturn self._intentHistory\n-\n+\t\treturn self.slots.get(slotName, '')\n \n-\t@intentHistory.setter\n-\tdef intentHistory(self, value: list):\n-\t\tself._intentHistory = value.copy()\n \n-\n-\t@property\n-\tdef previousIntent(self) -> Intent:\n-\t\treturn self._intentHistory[-1] if self._intentHistory else None\n-\n-\n-\t@property\n-\tdef intentFilter(self) -> list:\n-\t\treturn self._intentFilter\n-\n-\n-\t@intentFilter.setter\n-\tdef intentFilter(self, value: list):\n-\t\tself._intentFilter = value\n-\n-\n-\t@property\n-\tdef notUnderstood(self) -> int:\n-\t\treturn self._notUnderstood\n-\n-\n-\t@notUnderstood.setter\n-\tdef notUnderstood(self, value: int):\n-\t\tself._notUnderstood = value\n-\n-\n-\t@notUnderstood.deleter\n-\tdef notUnderstood(self):\n-\t\tself._notUnderstood = 0\n+\tdef addToHistory(self, intent: Intent):\n+\t\tself.intentHistory.append(intent)\n \n \n \t@property\n-\tdef currentState(self) -> str:\n-\t\treturn self._currentState\n-\n-\n-\t@currentState.setter\n-\tdef currentState(self, value: str):\n-\t\tself._currentState = value\n-\n-\n-\tdef __repr__(self) -> str:\n-\t\treturn dedent(f'''\\\n-\t\t\t[{self.__class__.__name__}] -> [\n-\t\t\t\tsiteId: \"{self.siteId}\",\n-\t\t\t\tsessionId: \"{self._sessionId}\",\n-\t\t\t\tuser: \"{self._user}\",\n-\t\t\t\tmessage: \"{self._message.topic}\",\n-\t\t\t\tslots: \"{self._slots}\",\n-\t\t\t\tslotsAsObject: \"{self._slotsAsObjects}\",\n-\t\t\t\tcustomData: \"{self._customData}\",\n-\t\t\t\tpayload: \"{self._payload}\",\n-\t\t\t\tpreviousIntent: \"{self.previousIntent}\",\n-\t\t\t\tintentHistory: \"{self._intentHistory}\",\n-\t\t\t\tintentFilter: \"{self._intentFilter}\",\n-\t\t\t\tnotUnderstood: \"{self._notUnderstood}\"\n-\t\t\t]\n-\t\t''')\n+\tdef previousIntent(self) -> Optional[Intent]:\n+\t\treturn self.intentHistory[-1] if self.intentHistory else None\ndiff --git a/core/dialog/model/DialogState.py b/core/dialog/model/DialogState.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/dialog/model/DialogState.py\n@@ -0,0 +1,31 @@\n+from core.base.SuperManager import SuperManager\n+\n+\n+class DialogState:\n+\n+\tdef __init__(self, state: str):\n+\t\tif ':' not in state:\n+\t\t\tcaller = SuperManager.getInstance().commons.getFunctionCaller(depth=2)\n+\t\t\tstate = f'{caller}:{state}'\n+\n+\t\tself._state = state\n+\n+\n+\tdef __eq__(self, other) -> bool:\n+\t\tif ':' not in other:\n+\t\t\tcaller = SuperManager.getInstance().commons.getFunctionCaller()\n+\t\t\tother = f'{caller}:{other}'\n+\n+\t\treturn self._state == other\n+\n+\n+\tdef __ne__(self, other) -> bool:\n+\t\treturn not self.__eq__(other)\n+\n+\n+\tdef __repr__(self) -> str:\n+\t\treturn self._state\n+\n+\n+\tdef __str__(self) -> str:\n+\t\treturn self._state\ndiff --git a/core/dialog/model/MultiIntent.py b/core/dialog/model/MultiIntent.py\n--- a/core/dialog/model/MultiIntent.py\n+++ b/core/dialog/model/MultiIntent.py\n@@ -1,23 +1,23 @@\n-from core.dialog.model import DialogSession\n+from dataclasses import dataclass, field\n+from typing import Deque\n+from collections import deque\n \n+from core.dialog.model import DialogSession\n \n+@dataclass\n class MultiIntent:\n-\tdef __init__(self, session: DialogSession, string: str):\n-\t\tself._originalString = session['payload']['input']\n-\t\tself._processedString = string\n-\t\tself._session = session\n+\tsession: DialogSession\n+\tprocessedString: str\n+\tintents: Deque[str] = field(default_factory=deque)\n \n-\t\tself._intents = list()\n+\t@property\n+\tdef originalString(self) -> str:\n+\t\treturn self.session['payload']['input']\n \n \n \tdef addIntent(self, string: str):\n-\t\tself._intents.append(string)\n+\t\tself.intents.append(string)\n \n \n \tdef getNextIntent(self) -> str:\n-\t\treturn self._intents.pop(0) if self._intents else ''\n-\n-\n-\t@property\n-\tdef session(self) -> DialogSession:\n-\t\treturn self._session\n+\t\treturn self.intents.popleft() if self.intents else ''\ndiff --git a/core/hotword/HotwordManager.py b/core/hotword/HotwordManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/hotword/HotwordManager.py\n@@ -0,0 +1,7 @@\n+from core.base.model.Manager import Manager\n+\n+\n+class HotwordManager(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\ndiff --git a/core/snips/samkilla/gql/assistants/__init__.py b/core/hotword/__init__.py\nsimilarity index 100%\nrename from core/snips/samkilla/gql/assistants/__init__.py\nrename to core/hotword/__init__.py\ndiff --git a/core/interface/NodeRedManager.py b/core/interface/NodeRedManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/interface/NodeRedManager.py\n@@ -0,0 +1,54 @@\n+import json\n+from pathlib import Path\n+\n+from core.base.model.Manager import Manager\n+from core.base.model.Version import Version\n+\n+\n+class NodeRedManager(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\t\tself.injectSkillNodes()\n+\t\tself.Commons.runRootSystemCommand(['systemctl', 'start', 'nodered'])\n+\n+\n+\tdef onStop(self):\n+\t\tsuper().onStop()\n+\t\tself.Commons.runRootSystemCommand(['systemctl', 'stop', 'nodered'])\n+\n+\n+\tdef reloadServer(self):\n+\t\tself.Commons.runRootSystemCommand(['systemctl', 'restart', 'nodered'])\n+\n+\n+\tdef injectSkillNodes(self):\n+\t\tpackage = Path('../.node-red/package.json')\n+\t\tif not package.exists():\n+\t\t\tself.logWarning('Package json file for Node Red is missing. Is Node Red even installed?')\n+\t\t\treturn\n+\n+\t\tfor skillName, tup in self.SkillManager.allScenarioNodes().items():\n+\t\t\tscenarioNodeName, scenarioNodeVersion, scenarioNodePath = tup\n+\t\t\tpath = Path('../.node-red/node_modules', scenarioNodeName, 'package.json')\n+\t\t\tif not path.exists():\n+\t\t\t\tself.logInfo('New scenario node found')\n+\t\t\t\tinstall = self.Commons.runSystemCommand(f'cd ~/.node-red && npm install {scenarioNodePath}', shell=True)\n+\t\t\t\tif install.returncode == 1:\n+\t\t\t\t\tself.logWarning(f'Something went wrong installing new node: {install.stderr}')\n+\n+\t\t\t\tcontinue\n+\n+\t\t\twith path.open('r') as fp:\n+\t\t\t\tdata = json.load(fp)\n+\t\t\t\tversion = Version.fromString(data['version'])\n+\n+\t\t\t\tif version < scenarioNodeVersion:\n+\t\t\t\t\tself.logInfo('New scenario node update found')\n+\t\t\t\t\tinstall = self.Commons.runSystemCommand(f'cd ~/.node-red && npm install {scenarioNodePath}', shell=True)\n+\t\t\t\t\tif install.returncode == 1:\n+\t\t\t\t\t\tself.logWarning(f'Something went wrong updating node: {install.stderr}')\ndiff --git a/core/interface/WebInterfaceManager.py b/core/interface/WebInterfaceManager.py\n--- a/core/interface/WebInterfaceManager.py\n+++ b/core/interface/WebInterfaceManager.py\n@@ -9,29 +9,32 @@\n from flask_login import LoginManager\n \n from core.base.model.Manager import Manager\n+from core.interface.api.DialogApi import DialogApi\n+from core.interface.api.LoginApi import LoginApi\n from core.interface.api.SkillsApi import SkillsApi\n+from core.interface.api.TelemetryApi import TelemetryApi\n from core.interface.api.UsersApi import UsersApi\n-from core.interface.views import ScenarioView\n+from core.interface.api.UtilsApi import UtilsApi\n from core.interface.views.AdminAuth import AdminAuth\n from core.interface.views.AdminView import AdminView\n+from core.interface.views.AliceWatchView import AliceWatchView\n from core.interface.views.DevModeView import DevModeView\n from core.interface.views.IndexView import IndexView\n+from core.interface.views.ScenarioView import ScenarioView\n from core.interface.views.SkillsView import SkillsView\n-from core.interface.views.SnipswatchView import SnipswatchView\n from core.interface.views.SyslogView import SyslogView\n \n \n class WebInterfaceManager(Manager):\n-\n-\tNAME = 'WebInterfaceManager'\n \tapp = Flask(__name__)\n \tapp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n \n-\t_VIEWS = [AdminView, AdminAuth, IndexView, SkillsView, SnipswatchView, SyslogView, DevModeView, ScenarioView]\n-\t_APIS = [UsersApi, SkillsApi]\n+\t_VIEWS = [AdminView, AdminAuth, IndexView, SkillsView, AliceWatchView, SyslogView, DevModeView, ScenarioView]\n+\t_APIS = [UtilsApi, LoginApi, UsersApi, SkillsApi, DialogApi, TelemetryApi]\n+\n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \t\tlog = logging.getLogger('werkzeug')\n \t\tlog.setLevel(logging.ERROR)\n \t\tself._langData = dict()\n@@ -42,7 +45,7 @@ def __init__(self):\n \t# noinspection PyMethodParameters\n \t@app.route('/favicon.ico')\n \tdef favicon():\n-\t\treturn send_from_directory('static/','favicon.ico', mimetype='image/vnd.microsoft.icon')\n+\t\treturn send_from_directory('static/', 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n \n \t@app.route('/base/')\n \tdef base_static(self, filename):\n@@ -110,7 +113,7 @@ def onStop(self):\n \tdef newSkillInstallProcess(self, skill):\n \t\tself._skillInstallProcesses[skill] = {\n \t\t\t'startedAt': time.time(),\n-\t\t\t'status' : 'installing'\n+\t\t\t'status': 'installing'\n \t\t}\n \n \n@@ -124,20 +127,16 @@ def onSkillUpdated(self, **kwargs):\n \t\t\tself.logError(f'Failed setting skill \"{skill}\" status to \"updated\": {e}')\n \n \n-\tdef onSkillInstalled(self, **kwargs):\n-\t\tskill = ''\n+\tdef onSkillInstalled(self, skill: str):\n \t\ttry:\n-\t\t\tskill = kwargs['skill']\n \t\t\tif skill in self.skillInstallProcesses:\n \t\t\t\tself.skillInstallProcesses[skill]['status'] = 'installed'\n \t\texcept KeyError as e:\n \t\t\tself.logError(f'Failed setting skill \"{skill}\" status to \"installed\": {e}')\n \n \n-\tdef onSkillInstallFailed(self, **kwargs):\n-\t\tskill = ''\n+\tdef onSkillInstallFailed(self, skill: str):\n \t\ttry:\n-\t\t\tskill = kwargs['skill']\n \t\t\tif skill in self.skillInstallProcesses:\n \t\t\t\tself.skillInstallProcesses[skill]['status'] = 'failed'\n \t\texcept KeyError as e:\ndiff --git a/core/interface/api/DialogApi.py b/core/interface/api/DialogApi.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/interface/api/DialogApi.py\n@@ -0,0 +1,70 @@\n+import json\n+import uuid\n+\n+from flask import jsonify, request\n+from flask_classful import route\n+from paho.mqtt.client import MQTTMessage\n+\n+from core.commons import constants\n+from core.interface.model.Api import Api\n+from core.util.Decorators import ApiAuthenticated\n+\n+\n+class DialogApi(Api):\n+\troute_base = f'/api/{Api.version()}/dialog/'\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\n+\t@route('/say/', methods=['POST'])\n+\t@ApiAuthenticated\n+\tdef say(self):\n+\t\ttry:\n+\t\t\tsiteId = request.form.get('siteId') if request.form.get('siteId', None) is not None else constants.DEFAULT_SITE_ID\n+\t\t\tself.MqttManager.say(\n+\t\t\t\ttext=request.form.get('text'),\n+\t\t\t\tclient=siteId\n+\t\t\t)\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed speaking: {e}')\n+\t\t\treturn jsonify(success=False)\n+\n+\n+\t@route('/ask/', methods=['POST'])\n+\t@ApiAuthenticated\n+\tdef ask(self):\n+\t\ttry:\n+\t\t\tsiteId = request.form.get('siteId') if request.form.get('siteId', None) is not None else constants.DEFAULT_SITE_ID\n+\t\t\tself.MqttManager.ask(\n+\t\t\t\ttext=request.form.get('text'),\n+\t\t\t\tclient=siteId\n+\t\t\t)\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed asking: {e}')\n+\t\t\treturn jsonify(success=False)\n+\n+\n+\t@route('/process/', methods=['POST'])\n+\t@ApiAuthenticated\n+\tdef process(self):\n+\t\ttry:\n+\t\t\tsiteId = request.form.get('siteId') if request.form.get('siteId', None) is not None else constants.DEFAULT_SITE_ID\n+\n+\t\t\tsessionId = str(uuid.uuid4())\n+\t\t\tmessage = MQTTMessage()\n+\t\t\tmessage.payload = json.dumps({'sessionId': sessionId, 'siteId': siteId})\n+\n+\t\t\tsession = self.DialogSessionManager.addSession(sessionId=sessionId, message=message)\n+\t\t\tsession.isAPIGenerated = True\n+\t\t\tself.MqttManager.publish(topic=constants.TOPIC_NLU_QUERY, payload={\n+\t\t\t\t'input' : request.form.get('query'),\n+\t\t\t\t'sessionId': session.sessionId\n+\t\t\t})\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed processing: {e}')\n+\t\t\treturn jsonify(success=False)\ndiff --git a/core/interface/api/LoginApi.py b/core/interface/api/LoginApi.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/interface/api/LoginApi.py\n@@ -0,0 +1,24 @@\n+from flask import jsonify, request\n+\n+from core.interface.model.Api import Api\n+\n+\n+class LoginApi(Api):\n+\troute_base = f'/api/{Api.version()}/login/'\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\n+\tdef post(self):\n+\t\ttry:\n+\t\t\tusername = request.form.get('username')\n+\t\t\tif not self.UserManager.checkPinCode(self.UserManager.getUser(username), request.form.get('pin')):\n+\t\t\t\traise Exception\n+\n+\t\t\ttoken = self.UserManager.getUser(username).apiToken or self.UserManager.createApiToken(self.UserManager.getUser(username))\n+\n+\t\t\treturn jsonify({'apiToken': token})\n+\t\texcept:\n+\t\t\treturn jsonify(message='ERROR: Unauthorized')\ndiff --git a/core/interface/api/SkillsApi.py b/core/interface/api/SkillsApi.py\n--- a/core/interface/api/SkillsApi.py\n+++ b/core/interface/api/SkillsApi.py\n@@ -1,13 +1,19 @@\n+import json\n+from pathlib import Path\n+\n+import requests\n from flask import jsonify, request\n from flask_classful import route\n \n+from core.commons import constants\n from core.interface.model.Api import Api\n+from core.util.Decorators import ApiAuthenticated\n \n \n class SkillsApi(Api):\n-\n \troute_base = f'/api/{Api.version()}/skills/'\n \n+\n \tdef __init__(self):\n \t\tsuper().__init__()\n \n@@ -16,6 +22,7 @@ def index(self):\n \t\treturn jsonify(data=[skill.toJson() for skill in self.SkillManager.allSkills.values()])\n \n \n+\t@ApiAuthenticated\n \tdef delete(self, skillName: str):\n \t\tif skillName in self.SkillManager.neededSkills:\n \t\t\treturn jsonify(success=False, reason='skill cannot be deleted')\n@@ -35,6 +42,7 @@ def get(self, skillName: str):\n \n \n \t@route('//toggleActiveState/')\n+\t@ApiAuthenticated\n \tdef toggleActiveState(self, skillName: str):\n \t\tif skillName not in self.SkillManager.allSkills:\n \t\t\treturn jsonify(success=False, reason='skill not found')\n@@ -51,6 +59,7 @@ def toggleActiveState(self, skillName: str):\n \n \n \t@route('//activate/', methods=['GET', 'POST'])\n+\t@ApiAuthenticated\n \tdef activate(self, skillName: str):\n \t\tif skillName not in self.SkillManager.allSkills:\n \t\t\treturn jsonify(success=False, reason='skill not found')\n@@ -64,6 +73,7 @@ def activate(self, skillName: str):\n \n \n \t@route('//deactivate/', methods=['GET', 'POST'])\n+\t@ApiAuthenticated\n \tdef deactivate(self, skillName: str):\n \t\tif skillName not in self.SkillManager.allSkills:\n \t\t\treturn jsonify(success=False, reason='skill not found')\n@@ -79,6 +89,44 @@ def deactivate(self, skillName: str):\n \t\t\treturn jsonify(success=False, reason='not active')\n \n \n+\t@route('//reload/', methods=['GET', 'POST'])\n+\t@ApiAuthenticated\n+\tdef reload(self, skillName: str):\n+\t\tif skillName not in self.SkillManager.allSkills:\n+\t\t\treturn jsonify(success=False, reason='skill not found')\n+\n+\t\ttry:\n+\t\t\tself.logInfo(f'Reloading skill \"{skillName}\"')\n+\t\t\tself.SkillManager.reloadSkill(skillName)\n+\t\texcept Exception as e:\n+\t\t\tself.logWarning(f'Failed reloading skill: {e}', printStack=True)\n+\t\t\treturn jsonify(success=False)\n+\n+\t\treturn jsonify(success=True)\n+\n+\n+\t@ApiAuthenticated\n+\tdef put(self, skillName: str):\n+\t\tif not self.SkillStoreManager.skillExists(skillName):\n+\t\t\treturn jsonify(success=False, reason='skill not found')\n+\t\telif self.SkillManager.getSkillInstance(skillName, True) is not None:\n+\t\t\treturn jsonify(success=False, reason='skill already installed')\n+\n+\t\ttry:\n+\t\t\treq = requests.get(f'{constants.GITHUB_RAW_URL}/skill_{skillName}/{self.SkillStoreManager.getSkillUpdateTag(skillName)}/{skillName}.install')\n+\t\t\tremoteFile = req.json()\n+\t\t\tif not remoteFile:\n+\t\t\t\treturn jsonify(success=False, reason='skill not found')\n+\n+\t\t\tskillFile = Path(self.Commons.rootDir(), f'system/skillInstallTickets/{skillName}.install')\n+\t\t\tskillFile.write_text(json.dumps(remoteFile))\n+\t\texcept Exception as e:\n+\t\t\tself.logWarning(f'Failed installing skill: {e}', printStack=True)\n+\t\t\treturn jsonify(success=False)\n+\n+\t\treturn jsonify(success=True)\n+\n+\n \t@route('//checkUpdate/')\n \tdef checkUpdate(self, skillName: str):\n \t\tif skillName not in self.SkillManager.allSkills:\ndiff --git a/core/interface/api/TelemetryApi.py b/core/interface/api/TelemetryApi.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/interface/api/TelemetryApi.py\n@@ -0,0 +1,24 @@\n+from flask import jsonify, request\n+\n+from core.interface.model.Api import Api\n+from core.util.Decorators import ApiAuthenticated\n+\n+\n+class TelemetryApi(Api):\n+\troute_base = f'/api/{Api.version()}/telemetry/'\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\n+\t@ApiAuthenticated\n+\tdef post(self):\n+\t\ttry:\n+\t\t\tfromTimestamp = request.form.get('from', '')\n+\t\t\ttoTimestamp = request.form.get('to', '')\n+\n+\t\t\treturn jsonify(message='Not implemented')\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed getting telemetry data: {e}')\n+\t\t\treturn jsonify(success=False)\ndiff --git a/core/interface/api/UsersApi.py b/core/interface/api/UsersApi.py\n--- a/core/interface/api/UsersApi.py\n+++ b/core/interface/api/UsersApi.py\n@@ -1,19 +1,66 @@\n-from flask import jsonify\n+from flask import jsonify, request\n \n from core.interface.model.Api import Api\n+from core.user.model.AccessLevels import AccessLevel\n+from core.util.Decorators import ApiAuthenticated\n \n \n class UsersApi(Api):\n-\n \troute_base = f'/api/{Api.version()}/users/'\n \n+\n \tdef __init__(self):\n \t\tsuper().__init__()\n \n \n+\t@ApiAuthenticated\n \tdef index(self):\n \t\treturn jsonify(data=[user.toJson() for user in self.UserManager.users.values()])\n \n \n+\t@ApiAuthenticated\n \tdef get(self, userId: int):\n \t\treturn jsonify(data=self.UserManager.getUserById(userId).toJson())\n+\n+\n+\t@ApiAuthenticated\n+\tdef put(self):\n+\t\ttry:\n+\t\t\tusername = request.form.get('username', '').lower()\n+\t\t\tpin = int(request.form.get('pin'))\n+\t\t\taccess = request.form.get('access')\n+\n+\t\t\tif not username or not pin or not access:\n+\t\t\t\treturn jsonify(message='ERROR: Make sure to specify username, pin and access level (admin, default, kid, worker, guest)')\n+\n+\t\t\tif self.UserManager.getUser(username):\n+\t\t\t\treturn jsonify(message=f\"ERROR: User '{username}' is already existing\")\n+\n+\t\t\tif not self.UserManager.hasAccessLevel(self.UserManager.getUserByAPIToken(request.headers.get('auth')).name, AccessLevel[access.upper()].value):\n+\t\t\t\treturn jsonify(message='ERROR: You cannot create a user with a higher access level than yours')\n+\n+\t\t\tself.UserManager.addNewUser(name=username, access=access, pinCode=pin)\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed adding new user: {e}')\n+\t\t\treturn jsonify(success=False)\n+\n+\n+\t@ApiAuthenticated\n+\tdef delete(self):\n+\t\ttry:\n+\t\t\tif not self.UserManager.hasAccessLevel(self.UserManager.getUserByAPIToken(request.headers.get('auth')).name, AccessLevel.ADMIN):\n+\t\t\t\treturn jsonify(message='ERROR: You need admin access to delete a user')\n+\n+\t\t\tusername = request.form.get('username', '').lower()\n+\t\t\tkeepWakeword = request.form.get('keepWakeword', False)\n+\t\t\tkeepWakeword = False if keepWakeword in {False, 'no', '0', 'false', 'False'} else True\n+\n+\t\t\tif not self.UserManager.getUser(username):\n+\t\t\t\treturn jsonify(message=f\"ERROR: User '{username}' does not exist\")\n+\n+\t\t\tself.UserManager.deleteUser(username=username, keepWakeword=keepWakeword)\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed deleting user: {e}')\n+\t\t\treturn jsonify(success=False)\ndiff --git a/core/interface/api/UtilsApi.py b/core/interface/api/UtilsApi.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/interface/api/UtilsApi.py\n@@ -0,0 +1,35 @@\n+from flask import jsonify\n+from flask_classful import route\n+\n+from core.interface.model.Api import Api\n+from core.util.Decorators import ApiAuthenticated\n+\n+\n+class UtilsApi(Api):\n+\troute_base = f'/api/{Api.version()}/utils/'\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\n+\t@route('/restart/')\n+\t@ApiAuthenticated\n+\tdef restart(self):\n+\t\ttry:\n+\t\t\tself.ThreadManager.doLater(interval=2, func=self.ProjectAlice.doRestart)\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed restarting Alice: {e}')\n+\t\t\treturn jsonify(success=False)\n+\n+\n+\t@route('/reboot/')\n+\t@ApiAuthenticated\n+\tdef reboot(self):\n+\t\ttry:\n+\t\t\tself.ThreadManager.doLater(interval=2, func=self.Commons.runRootSystemCommand, args=[['shutdown', '-r', 'now']])\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed rebooting device: {e}')\n+\t\t\treturn jsonify(success=False)\ndiff --git a/core/interface/model/Api.py b/core/interface/model/Api.py\n--- a/core/interface/model/Api.py\n+++ b/core/interface/model/Api.py\n@@ -4,9 +4,9 @@\n \n \n class Api(FlaskView, ProjectAliceObject):\n+\tdefault_methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']\n+\t_version = '1.0.1'\n \n-\tdefault_methods = ['GET', 'POST', 'PUT', 'DELETE']\n-\t_version = '1.0.0'\n \n \tdef __init__(self):\n \t\tsuper().__init__(logDepth=6)\ndiff --git a/core/interface/views/AdminAuth.py b/core/interface/views/AdminAuth.py\n--- a/core/interface/views/AdminAuth.py\n+++ b/core/interface/views/AdminAuth.py\n@@ -51,7 +51,7 @@ def authenticate(self):\n \n \t\texcept Exception as e:\n \t\t\tself.logError(f'Failed auth trial: {e}')\n-\t\t\n+\n \t\treturn jsonify(success=False)\n \n \ndiff --git a/core/interface/views/AdminView.py b/core/interface/views/AdminView.py\n--- a/core/interface/views/AdminView.py\n+++ b/core/interface/views/AdminView.py\n@@ -1,5 +1,5 @@\n-import subprocess\n from pathlib import Path\n+from typing import Any\n \n import shutil\n from flask import jsonify, render_template, request\n@@ -35,13 +35,23 @@ def getWaitType(cls) -> str:\n \tdef saveAliceSettings(self):\n \t\ttry:\n \t\t\t# Create the conf dict. on and off values are translated to True and False and we try to cast to int\n-\t\t\t# because HTTP data is type less.\n-\t\t\tconfs = {key: False if value == 'off' else True if value == 'on' else int(value) if value.isdigit() else float(value) if self.isfloat(value) else value for key, value in request.form.items()}\n+\t\t\t# or float because HTTP data is type less.\n+\t\t\tconfs = {key: self.retrieveValue(value) for key, value in request.form.items()}\n+\n+\t\t\tpostProcessing = set()\n+\t\t\tfor conf, value in confs.items():\n+\t\t\t\tif value == self.ConfigManager.getAliceConfigByName(conf):\n+\t\t\t\t\tcontinue\n+\n+\t\t\t\tpp = self.ConfigManager.getAliceConfUpdatePostProcessing(conf)\n+\t\t\t\tif pp:\n+\t\t\t\t\tpostProcessing.add(pp)\n \n \t\t\tconfs['skills'] = self.ConfigManager.getAliceConfigByName('skills')\n \t\t\tconfs['supportedLanguages'] = self.ConfigManager.getAliceConfigByName('supportedLanguages')\n \n \t\t\tself.ConfigManager.writeToAliceConfigurationFile(confs=confs)\n+\t\t\tself.ConfigManager.doConfigUpdatePostProcessing(postProcessing)\n \t\t\treturn self.index()\n \t\texcept Exception as e:\n \t\t\tself.logError(f'Failed saving Alice config: {e}')\n@@ -62,7 +72,7 @@ def reboot(self) -> dict:\n \t\ttry:\n \t\t\tself.__class__.setWaitType('reboot')\n \t\t\tself.ProjectAlice.onStop()\n-\t\t\tself.ThreadManager.doLater(interval=2, func=subprocess.run, args=[['sudo', 'shutdown', '-r', 'now']])\n+\t\t\tself.ThreadManager.doLater(interval=2, func=self.Commons.runRootSystemCommand, args=[['shutdown', '-r', 'now']])\n \t\t\treturn jsonify(success=True)\n \t\texcept Exception as e:\n \t\t\tself.logError(f'Failed rebooting device: {e}')\n@@ -79,13 +89,28 @@ def assistantDownload(self) -> dict:\n \t\t\treturn jsonify(success=False)\n \n \n+\tdef updatee(self) -> dict:\n+\t\ttry:\n+\t\t\tself.__class__.setWaitType('update')\n+\t\t\tself.ProjectAlice.updateProjectAlice()\n+\t\t\treturn jsonify(success=True)\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed updating Project Alice: {e}')\n+\t\t\treturn jsonify(success=False)\n+\n+\n \tdef wipeAll(self) -> dict:\n \t\ttry:\n-\t\t\tsubprocess.run(['wget', 'http://skills.projectalice.ch/AliceCore', '-O', Path(self.Commons.rootDir(), 'system/skillInstallTickets/AliceCore.install')])\n-\t\t\tsubprocess.run(['wget', 'http://skills.projectalice.ch/ContextSensitive', '-O', Path(self.Commons.rootDir(), 'system/skillInstallTickets/ContextSensitive.install')])\n-\t\t\tsubprocess.run(['wget', 'http://skills.projectalice.ch/RedQueen', '-O', Path(self.Commons.rootDir(), 'system/skillInstallTickets/RedQueen.install')])\n-\t\t\tsubprocess.run(['wget', 'http://skills.projectalice.ch/Telemetry', '-O', Path(self.Commons.rootDir(), 'system/skillInstallTickets/Telemetry.install')])\n-\t\t\tsubprocess.run(['wget', 'http://skills.projectalice.ch/DateDayTimeYear', '-O', Path(self.Commons.rootDir(), 'system/skillInstallTickets/DateDayTimeYear.install')])\n+\t\t\ttickets = [\n+\t\t\t\t'http://skills.projectalice.ch/AliceCore',\n+\t\t\t\t'http://skills.projectalice.ch/ContextSensitive',\n+\t\t\t\t'http://skills.projectalice.ch/RedQueen',\n+\t\t\t\t'http://skills.projectalice.ch/Telemetry',\n+\t\t\t\t'http://skills.projectalice.ch/DateDayTimeYear'\n+\t\t\t]\n+\n+\t\t\tfor link in tickets:\n+\t\t\t\tself.Commons.downloadFile(link, f'system/skillInstallTickets/{link.rsplit(\"/\")[-1]}.install')\n \n \t\t\tshutil.rmtree(Path(self.Commons.rootDir(), 'var/assistants'))\n \t\t\tshutil.rmtree(Path(self.Commons.rootDir(), 'trained/assistants'))\n@@ -110,10 +135,23 @@ def areYouReady(self) -> bool:\n \t\t\treturn False\n \n \n-\t# noinspection PyMethodMayBeStatic,PyUnusedLocal\n-\tdef isfloat(self, value: str) -> bool:\n+\t@classmethod\n+\tdef retrieveValue(cls, value: str) -> Any:\n+\t\tif value == 'off':\n+\t\t\treturn False\n+\t\tif value == 'on':\n+\t\t\treturn True\n+\t\tif value.isdigit():\n+\t\t\treturn int(value)\n+\t\tif cls.isfloat(value):\n+\t\t\treturn float(value)\n+\t\treturn value\n+\n+\n+\t@staticmethod\n+\tdef isfloat(value: str) -> bool:\n \t\ttry:\n-\t\t\tvalue = float(value)\n+\t\t\t_ = float(value)\n \t\t\treturn True\n \t\texcept:\n \t\t\treturn False\ndiff --git a/core/interface/views/SnipswatchView.py b/core/interface/views/AliceWatchView.py\nsimilarity index 88%\nrename from core/interface/views/SnipswatchView.py\nrename to core/interface/views/AliceWatchView.py\n--- a/core/interface/views/SnipswatchView.py\n+++ b/core/interface/views/AliceWatchView.py\n@@ -1,14 +1,13 @@\n from pathlib import Path\n \n import tempfile\n-\n from flask import jsonify, render_template, request\n \n from core.interface.model.View import View\n \n \n-class SnipswatchView(View):\n-\troute_base = '/snipswatch/'\n+class AliceWatchView(View):\n+\troute_base = '/alicewatch/'\n \n \n \tdef __init__(self):\n@@ -21,7 +20,7 @@ def __init__(self):\n \n \tdef index(self):\n \t\tself.SnipsWatchManager.startWatching()\n-\t\treturn render_template(template_name_or_list='snipswatch.html',\n+\t\treturn render_template(template_name_or_list='alicewatch.html',\n \t\t langData=self._langData,\n \t\t aliceSettings=self.ConfigManager.aliceConfigurations)\n \ndiff --git a/core/interface/views/DevModeView.py b/core/interface/views/DevModeView.py\n--- a/core/interface/views/DevModeView.py\n+++ b/core/interface/views/DevModeView.py\n@@ -1,11 +1,16 @@\n-from flask import render_template\n+import json\n \n+import requests as requests\n+from flask import jsonify, render_template, request\n+\n+from core.base.model.GithubCloner import GithubCloner\n from core.interface.model.View import View\n \n \n class DevModeView(View):\n \troute_base = '/devmode/'\n \n+\n \tdef __init__(self):\n \t\tsuper().__init__()\n \n@@ -14,3 +19,63 @@ def index(self):\n \t\treturn render_template(template_name_or_list='devmode.html',\n \t\t langData=self._langData,\n \t\t aliceSettings=self.ConfigManager.aliceConfigurations)\n+\n+\n+\tdef uploadToGithub(self):\n+\t\ttry:\n+\t\t\tskillName = request.form.get('skillName', '')\n+\t\t\tskillDesc = request.form.get('skillDesc', '')\n+\n+\t\t\tif not skillName:\n+\t\t\t\traise Exception\n+\n+\t\t\tskillName = skillName[0].upper() + skillName[1:]\n+\t\t\tdata = {\n+\t\t\t\t'name' : skillName,\n+\t\t\t\t'description': skillDesc,\n+\t\t\t\t'has-issues' : True,\n+\t\t\t\t'has-wiki' : False\n+\t\t\t}\n+\t\t\treq = requests.post('https://api.github.com/user/repos', data=json.dumps(data), auth=GithubCloner.getGithubAuth())\n+\n+\t\t\tif req.status_code == 201:\n+\t\t\t\treturn jsonify(success=True)\n+\t\t\telse:\n+\t\t\t\traise Exception\n+\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Failed uploading to github: {e}')\n+\t\t\treturn jsonify(success=False)\n+\n+\n+\tdef get(self, skillName: str):\n+\t\tif self.SkillStoreManager.skillExists(skillName):\n+\t\t\treturn jsonify(success=False)\n+\t\telse:\n+\t\t\treturn jsonify(success=True)\n+\n+\n+\tdef put(self, skillName: str):\n+\t\ttry:\n+\t\t\tnewSkill = {\n+\t\t\t\t'name' : skillName,\n+\t\t\t\t'description' : request.form.get('description', 'Missing description'),\n+\t\t\t\t'fr' : request.form.get('fr', False),\n+\t\t\t\t'de' : request.form.get('de', False),\n+\t\t\t\t'pipreq' : request.form.get('pipreq', list()),\n+\t\t\t\t'sysreq' : request.form.get('sysreq', list()),\n+\t\t\t\t'conditionOnline' : request.form.get('sysreq', False),\n+\t\t\t\t'conditionASRArbitrary' : request.form.get('conditionASRArbitrary', False),\n+\t\t\t\t'conditionSkill' : request.form.get('conditionSkill', list()),\n+\t\t\t\t'conditionNotSkill' : request.form.get('conditionNotSkill', list()),\n+\t\t\t\t'conditionActiveManager': request.form.get('conditionActiveManager', list()),\n+\t\t\t\t'widgets' : request.form.get('widgets', list())\n+\t\t\t}\n+\t\t\tif not self.SkillManager.createNewSkill(newSkill):\n+\t\t\t\traise Exception('Unhandled skill creation exception')\n+\n+\t\t\treturn jsonify(success=True)\n+\n+\t\texcept Exception as e:\n+\t\t\tself.logError(f'Something went wrong creating a new skill: {e}')\n+\t\t\treturn jsonify(success=False)\ndiff --git a/core/interface/views/ScenarioView.py b/core/interface/views/ScenarioView.py\n--- a/core/interface/views/ScenarioView.py\n+++ b/core/interface/views/ScenarioView.py\n@@ -8,5 +8,6 @@ class ScenarioView(View):\n \n \tdef index(self):\n \t\treturn render_template(template_name_or_list='scenarios.html',\n+\t\t myIp=self.Commons.getLocalIp(),\n \t\t langData=self._langData,\n \t\t aliceSettings=self.ConfigManager.aliceConfigurations)\ndiff --git a/core/interface/views/SkillsView.py b/core/interface/views/SkillsView.py\n--- a/core/interface/views/SkillsView.py\n+++ b/core/interface/views/SkillsView.py\n@@ -46,6 +46,17 @@ def deleteSkill(self):\n \t\treturn self.index()\n \n \n+\tdef reloadSkill(self):\n+\t\ttry:\n+\t\t\t_, skill = request.form.get('id').split('_')\n+\t\t\tself.logInfo(f'Reloading skill \"{skill}\"')\n+\t\t\tself.SkillManager.reloadSkill(skill)\n+\t\texcept Exception as e:\n+\t\t\tself.logWarning(f'Failed reloading skill: {e}', printStack=True)\n+\n+\t\treturn self.index()\n+\n+\n \tdef saveSkillSettings(self):\n \t\tskillName = request.form['skillName']\n \t\tfor confName, confValue in request.form.items():\n@@ -66,7 +77,7 @@ def updateSkill(self):\n \t\t\t_, author, skill = request.form.get('id').split('_')\n \n \t\t\tself.WebInterfaceManager.newSkillInstallProcess(skill)\n-\t\t\treq = requests.get(f'https://raw.githubusercontent.com/project-alice-assistant/ProjectAliceSkills/{self.ConfigManager.getSkillsUpdateSource()}/PublishedSkills/{author}/{skill}/{skill}.install')\n+\t\t\treq = requests.get(f'{constants.GITHUB_RAW_URL}/skill_{skill[\"skill\"]}/{self.SkillStoreManager.getSkillUpdateTag(skill[\"skill\"])}/{skill[\"skill\"]}.install')\n \t\t\tremoteFile = req.json()\n \t\t\tif not remoteFile:\n \t\t\t\tself.WebInterfaceManager.skillInstallProcesses[skill['skill']]['status'] = 'failed'\n@@ -86,7 +97,8 @@ def installSkills(self):\n \n \t\t\tfor skill in skills:\n \t\t\t\tself.WebInterfaceManager.newSkillInstallProcess(skill['skill'])\n-\t\t\t\treq = requests.get(f'https://raw.githubusercontent.com/project-alice-assistant/ProjectAliceSkills/{self.ConfigManager.getSkillsUpdateSource()}/PublishedSkills/{skill[\"author\"]}/{skill[\"skill\"]}/{skill[\"skill\"]}.install')\n+\n+\t\t\t\treq = requests.get(f'{constants.GITHUB_RAW_URL}/skill_{skill[\"skill\"]}/{self.SkillStoreManager.getSkillUpdateTag(skill[\"skill\"])}/{skill[\"skill\"]}.install')\n \t\t\t\tremoteFile = req.json()\n \t\t\t\tif not remoteFile:\n \t\t\t\t\tself.WebInterfaceManager.skillInstallProcesses[skill['skill']]['status'] = 'failed'\n@@ -108,24 +120,28 @@ def checkInstallStatus(self):\n \n \n \tdef loadStoreData(self):\n-\t\tinstallers = dict()\n-\t\tupdateSource = self.ConfigManager.getSkillsUpdateSource()\n-\t\treq = requests.get(url=f'https://alice.maxbachmann.de/assets/{updateSource}/store/store.json')\n-\t\tresults = req.json()\n+\t\tself.SkillStoreManager.refreshStoreData()\n+\t\tskillStoreData = self.SkillStoreManager.skillStoreData\n+\t\tactiveLanguage = self.LanguageManager.activeLanguage.lower()\n+\t\taliceVersion = Version.fromString(constants.VERSION)\n+\t\tsupportedSkillStoreData = dict()\n \n-\t\tif not results:\n-\t\t\treturn dict()\n+\t\tfor skillName, skillInfo in skillStoreData.items():\n+\t\t\tif self.SkillManager.getSkillInstance(skillName=skillName, silent=True) \\\n+\t\t\t\t\tor ('lang' in skillInfo['conditions'] and activeLanguage not in skillInfo['conditions']['lang']):\n+\t\t\t\tcontinue\n \n-\t\tfor skill in results:\n-\t\t\tif 'lang' not in skill['conditions']:\n-\t\t\t\tskill['conditions']['lang'] = constants.ALL\n-\t\t\tinstallers[skill['name']] = skill\n+\t\t\tversion = Version()\n+\t\t\tfor aliceMinVersion, skillVersion in skillInfo['versionMapping'].items():\n+\t\t\t\tif Version.fromString(aliceMinVersion) > aliceVersion:\n+\t\t\t\t\tcontinue\n \n-\t\taliceVersion = Version(constants.VERSION)\n-\t\tactiveLanguage = self.LanguageManager.activeLanguage.lower()\n-\t\treturn {\n-\t\t\tskillName: skillInfo for skillName, skillInfo in installers.items()\n-\t\t\tif self.SkillManager.getSkillInstance(skillName=skillName, silent=True) is None\n-\t\t\t\tand aliceVersion >= Version(skillInfo['aliceMinVersion'])\n-\t\t\t\tand (activeLanguage in skillInfo['conditions']['lang'] or skillInfo['conditions']['lang'] == constants.ALL)\n-\t\t}\n+\t\t\t\tskillRepoVersion = Version.fromString(skillVersion)\n+\n+\t\t\t\tif skillRepoVersion > version:\n+\t\t\t\t\tversion = skillRepoVersion\n+\n+\t\t\tskillInfo['version'] = str(version)\n+\t\t\tsupportedSkillStoreData[skillName] = skillInfo\n+\n+\t\treturn supportedSkillStoreData\ndiff --git a/core/nlu/NluManager.py b/core/nlu/NluManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/nlu/NluManager.py\n@@ -0,0 +1,74 @@\n+from pathlib import Path\n+\n+from core.base.model.Manager import Manager\n+\n+\n+class NluManager(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\t\tself._nluEngine = None\n+\t\tself._pathToCache = Path(self.Commons.rootDir(), 'var/cache/nlu/')\n+\t\tself.selectNluEngine()\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\t\tself.isTrainingNeeded()\n+\n+\n+\tdef onStop(self):\n+\t\tsuper().onStop()\n+\n+\t\tif self._nluEngine:\n+\t\t\tself._nluEngine.stop()\n+\n+\n+\tdef afterNewSkillInstall(self):\n+\t\tself.isTrainingNeeded()\n+\n+\n+\tdef isTrainingNeeded(self):\n+\t\tif self.DialogTemplateManager.hasChanges:\n+\t\t\tself.buildTrainingData(self.DialogTemplateManager.updatedData)\n+\t\t\tself.trainNLU()\n+\n+\n+\tdef selectNluEngine(self):\n+\t\tif self._nluEngine:\n+\t\t\tself._nluEngine.stop()\n+\n+\t\tif self.ConfigManager.getAliceConfigByName('nluEngine') == 'snips':\n+\t\t\tfrom core.nlu.model.SnipsNlu import SnipsNlu\n+\n+\t\t\tself._nluEngine = SnipsNlu()\n+\t\telse:\n+\t\t\tself.logFatal(f'Unsupported NLU engine: {self.ConfigManager.getAliceConfigByName(\"nluEngine\")}')\n+\t\t\tself.ProjectAlice.onStop()\n+\t\t\treturn\n+\n+\t\tself._nluEngine.start()\n+\n+\n+\tdef buildTrainingData(self, changes: dict):\n+\t\tfor changedSkill, changedLanguages in changes.items():\n+\t\t\tif not changedSkill.startswith('--'):\n+\t\t\t\tpathToSkillResources = Path(self.Commons.rootDir(), f'skills/{changedSkill}/dialogTemplate')\n+\n+\t\t\t\tfor lang in changedLanguages:\n+\t\t\t\t\tself._nluEngine.convertDialogTemplate(pathToSkillResources / f'{lang}.json')\n+\t\t\telse:\n+\t\t\t\tskillName = changedSkill.replace('--', '')\n+\n+\t\t\t\tif not changedLanguages:\n+\t\t\t\t\tfor file in Path(self.Commons.rootDir(), '/var/cache/nlu/trainingData/').glob(f'{skillName}_'):\n+\t\t\t\t\t\tfile.unlink()\n+\t\t\t\telse:\n+\t\t\t\t\tfor lang in changedLanguages:\n+\t\t\t\t\t\tlangFile = Path(self.Commons.rootDir(), f'/var/cache/nlu/trainingData/{skillName}_{lang}.json')\n+\t\t\t\t\t\tif langFile.exists():\n+\t\t\t\t\t\t\tlangFile.unlink()\n+\n+\n+\tdef trainNLU(self):\n+\t\tself._nluEngine.train()\ndiff --git a/core/snips/samkilla/gql/entities/__init__.py b/core/nlu/__init__.py\nsimilarity index 100%\nrename from core/snips/samkilla/gql/entities/__init__.py\nrename to core/nlu/__init__.py\ndiff --git a/core/nlu/model/NluEngine.py b/core/nlu/model/NluEngine.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/nlu/model/NluEngine.py\n@@ -0,0 +1,27 @@\n+from pathlib import Path\n+\n+from core.base.model.ProjectAliceObject import ProjectAliceObject\n+\n+\n+class NluEngine(ProjectAliceObject):\n+\tNAME = ''\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\n+\n+\tdef start(self):\n+\t\tself.logInfo(f'Starting {self.NAME}')\n+\n+\n+\tdef stop(self):\n+\t\tself.logInfo(f'Stopping {self.NAME}')\n+\n+\n+\tdef train(self):\n+\t\tself.logInfo(f'Training {self.NAME}')\n+\n+\n+\tdef convertDialogTemplate(self, file: Path):\n+\t\tself.logFatal(f'NLU Engine {self.NAME} is missing implementation of \"convertDialogTemplate\"')\ndiff --git a/core/nlu/model/SnipsNlu.py b/core/nlu/model/SnipsNlu.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/nlu/model/SnipsNlu.py\n@@ -0,0 +1,162 @@\n+import json\n+from pathlib import Path\n+\n+import re\n+import shutil\n+\n+from core.base.SuperManager import SuperManager\n+from core.commons import constants\n+from core.nlu.model.NluEngine import NluEngine\n+from core.util.Stopwatch import Stopwatch\n+\n+\n+class SnipsNlu(NluEngine):\n+\tNAME = 'Snips NLU'\n+\tUTTERANCE_REGEX = re.compile('(.*?){(.+?:=>.+?)}(.*?)')\n+\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\t\tself._cachePath = Path(self.Commons.rootDir(), f'var/cache/nlu/trainingData')\n+\n+\n+\tdef start(self):\n+\t\tsuper().start()\n+\t\tSuperManager.getInstance().snipsServicesManager.runCmd(cmd='start', services=['snips-nlu'])\n+\n+\n+\tdef stop(self):\n+\t\tsuper().stop()\n+\t\tSuperManager.getInstance().snipsServicesManager.runCmd(cmd='stop', services=['snips-nlu'])\n+\n+\n+\tdef convertDialogTemplate(self, file: Path):\n+\t\tself.logInfo(f'Preparing NLU training file for {file}')\n+\t\twith file.open() as fp:\n+\t\t\tdialogTemplate = json.load(fp)\n+\n+\t\tnluTrainingSample = dict()\n+\t\tnluTrainingSample['language'] = file.stem\n+\t\tnluTrainingSample['entities'] = dict()\n+\n+\t\tfor entity in dialogTemplate['slotTypes']:\n+\t\t\tnluTrainingSampleEntity = nluTrainingSample['entities'].setdefault(entity['name'], dict())\n+\n+\t\t\tnluTrainingSampleEntity['automatically_extensible'] = entity['automaticallyExtensible']\n+\t\t\tnluTrainingSampleEntity['matching_strictness'] = entity['matchingStrictness'] or 1.0\n+\t\t\tnluTrainingSampleEntity['use_synonyms'] = entity['useSynonyms']\n+\n+\t\t\tnluTrainingSampleEntity['data'] = [{\n+\t\t\t\t\t'value' : value['value'],\n+\t\t\t\t\t'synonyms': value.get('synonyms', list())\n+\t\t\t\t} for value in entity['values']\n+\t\t\t]\n+\n+\t\tnluTrainingSample['intents'] = dict()\n+\t\tfor intent in dialogTemplate['intents']:\n+\t\t\tintentName = intent['name']\n+\t\t\tslots = self.loadSlots(intent)\n+\t\t\tnluTrainingSample['intents'].setdefault(intentName, {'utterances': list()})\n+\n+\t\t\tfor utterance in intent['utterances']:\n+\t\t\t\tdata = list()\n+\t\t\t\tresult = re.findall(self.UTTERANCE_REGEX, utterance)\n+\t\t\t\tif not result:\n+\t\t\t\t\tdata.append({\n+\t\t\t\t\t\t'text': utterance\n+\t\t\t\t\t})\n+\t\t\t\telse:\n+\t\t\t\t\tfor dataset in result:\n+\t\t\t\t\t\tfor match in dataset:\n+\t\t\t\t\t\t\tif not match:\n+\t\t\t\t\t\t\t\tcontinue\n+\n+\t\t\t\t\t\t\tif ':=>' not in match:\n+\t\t\t\t\t\t\t\tdata.append({\n+\t\t\t\t\t\t\t\t\t'text': match\n+\t\t\t\t\t\t\t\t})\n+\t\t\t\t\t\t\t\tcontinue\n+\t\t\t\t\t\t\t\n+\t\t\t\t\t\t\ttext, slotName = match.split(':=>')\n+\t\t\t\t\t\t\tentity = slots.get(slotName, 'Unknown')\n+\n+\t\t\t\t\t\t\tif entity.startswith('snips/'):\n+\t\t\t\t\t\t\t\tnluTrainingSample['entities'][entity] = dict()\n+\n+\t\t\t\t\t\t\tdata.append({\n+\t\t\t\t\t\t\t\t'entity' : entity,\n+\t\t\t\t\t\t\t\t'slot_name': slotName,\n+\t\t\t\t\t\t\t\t'text' : text\n+\t\t\t\t\t\t\t})\n+\n+\t\t\t\t# noinspection PyTypeChecker\n+\t\t\t\tnluTrainingSample['intents'][intentName]['utterances'].append({'data': data})\n+\n+\t\t\twith Path(self._cachePath, f'{dialogTemplate[\"skill\"]}_{file.stem}.json').open('w') as fp:\n+\t\t\t\tjson.dump(nluTrainingSample, fp, ensure_ascii=False, indent=4)\n+\n+\n+\tdef train(self):\n+\t\tself.logInfo('Training Snips NLU')\n+\t\tdataset = {\n+\t\t\t'entities': dict(),\n+\t\t\t'intents' : dict(),\n+\t\t\t'language': self.LanguageManager.activeLanguage,\n+\t\t}\n+\n+\t\tfor file in self._cachePath.glob(f'*_{self.LanguageManager.activeLanguage}.json'):\n+\t\t\twith file.open() as fp:\n+\t\t\t\ttrainingData = json.load(fp)\n+\t\t\t\tdataset['entities'].update(trainingData['entities'])\n+\t\t\t\tdataset['intents'].update(trainingData['intents'])\n+\n+\t\tdatasetFile = Path('/tmp/snipsNluDataset.json')\n+\n+\t\twith datasetFile.open('w') as fp:\n+\t\t\tjson.dump(dataset, fp, ensure_ascii=False, indent=4)\n+\n+\t\tself.logInfo('Generated dataset for training')\n+\n+\t\t# Now that we have generated the dataset, let's train in the background if we are already booted, else do it directly\n+\t\tif self.ProjectAlice.isBooted:\n+\t\t\tself.ThreadManager.newThread(name='NLUTraining', target=self.nluTrainingThread, args=[datasetFile])\n+\t\telse:\n+\t\t\tself.nluTrainingThread(datasetFile)\n+\n+\n+\tdef nluTrainingThread(self, datasetFile: Path):\n+\t\twith Stopwatch() as stopWatch:\n+\t\t\tself.logInfo('Begin training...')\n+\n+\t\t\ttempTrainingData = Path('/tmp/snipsNLU')\n+\n+\t\t\tif tempTrainingData.exists():\n+\t\t\t\tshutil.rmtree(tempTrainingData)\n+\n+\t\t\tself.Commons.runSystemCommand([f'./venv/bin/snips-nlu', 'train', str(datasetFile), str(tempTrainingData)])\n+\n+\t\t\tassistantPath = Path(self.Commons.rootDir(), f'trained/assistants/assistant_{self.LanguageManager.activeLanguage}/nlu_engine')\n+\n+\t\t\tif not tempTrainingData.exists():\n+\t\t\t\tself.logError('Snips NLU training failed')\n+\t\t\t\tif not assistantPath.exists():\n+\t\t\t\t\tself.logFatal('No NLU engine found, cannot start')\n+\t\t\t\treturn\n+\n+\t\t\tif assistantPath.exists():\n+\t\t\t\tshutil.rmtree(assistantPath)\n+\n+\t\t\ttempTrainingData.rename(assistantPath)\n+\n+\t\t\tself.broadcast(method=constants.EVENT_NLU_TRAINED, exceptions=[constants.DUMMY], propagateToSkills=True)\n+\t\t\tself.SnipsServicesManager.runCmd(cmd='restart', services=['snips-nlu'])\n+\n+\t\tself.logInfo(f'Snips NLU trained in {stopWatch} seconds')\n+\n+\n+\t@staticmethod\n+\tdef loadSlots(intent: dict) -> dict:\n+\t\treturn dict() if 'slots' not in intent else {\n+\t\t\tslot['name']: slot['type']\n+\t\t\tfor slot in intent['slots']\n+\t\t}\ndiff --git a/core/scenario/model/ScenarioTile.py b/core/scenario/model/ScenarioTile.py\n--- a/core/scenario/model/ScenarioTile.py\n+++ b/core/scenario/model/ScenarioTile.py\n@@ -8,7 +8,7 @@ class ScenarioTile(ProjectAliceObject):\n \n \tdef __init__(self):\n \t\tsuper().__init__()\n-\t\tself.tileType: ScenarioTileType = ScenarioTileType.ACTION_TILE\n+\t\tself.tileType: ScenarioTileType = ScenarioTileType.ACTION\n \t\tself.name: str = ''\n \t\tself.description: str = ''\n \t\tself.value: Any = ''\ndiff --git a/core/server/AudioServer.py b/core/server/AudioServer.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/server/AudioServer.py\n@@ -0,0 +1,7 @@\n+from core.base.model.Manager import Manager\n+\n+\n+class AudioServer(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\ndiff --git a/core/server/MqttManager.py b/core/server/MqttManager.py\n--- a/core/server/MqttManager.py\n+++ b/core/server/MqttManager.py\n@@ -1,10 +1,10 @@\n import json\n-import subprocess\n import uuid\n from pathlib import Path\n \n import paho.mqtt.client as mqtt\n import paho.mqtt.publish as publish\n+import random\n import re\n \n from core.ProjectAliceExceptions import AccessLevelTooLow\n@@ -16,14 +16,13 @@\n \n \n class MqttManager(Manager):\n-\tNAME = 'MqttManager'\n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n-\t\tself._mqttClient = mqtt.Client()\n-\t\tself._thanked = False\n-\t\tself._wideAskingSessions = list()\n+\t\tself._mqttClient = mqtt.Client()\n+\t\tself._thanked = False\n+\t\tself._wideAskingSessions = list()\n \t\tself._multiDetectionsHolder = list()\n \n \t\tself._audioFrameRegex = re.compile(constants.TOPIC_AUDIO_FRAME.replace('{}', '(.*)'))\n@@ -45,7 +44,6 @@ def onStart(self):\n \t\tself._mqttClient.on_connect = self.onConnect\n \t\tself._mqttClient.on_log = self.onLog\n \n-\n \t\tself._mqttClient.message_callback_add(constants.TOPIC_HOTWORD_DETECTED, self.onHotwordDetected)\n \t\tfor username in self.UserManager.getAllUserNames():\n \t\t\tself._mqttClient.message_callback_add(constants.TOPIC_WAKEWORD_DETECTED.replace('{user}', username), self.onHotwordDetected)\n@@ -54,6 +52,8 @@ def onStart(self):\n \n \t\tself._mqttClient.message_callback_add(constants.TOPIC_ASR_START_LISTENING, self.onSnipsStartListening)\n \n+\t\tself._mqttClient.message_callback_add(constants.TOPIC_ASR_STOP_LISTENING, self.onSnipsStopListening)\n+\n \t\tself._mqttClient.message_callback_add(constants.TOPIC_INTENT_PARSED, self.onSnipsIntentParsed)\n \n \t\tself._mqttClient.message_callback_add(constants.TOPIC_TEXT_CAPTURED, self.onSnipsCaptured)\n@@ -68,27 +68,14 @@ def onStart(self):\n \n \t\tself._mqttClient.message_callback_add(constants.TOPIC_SESSION_QUEUED, self.onSnipsSessionQueued)\n \n-\t\tif self.ConfigManager.getAliceConfigByName('mqttUser') and self.ConfigManager.getAliceConfigByName('mqttPassword'):\n-\t\t\tself._mqttClient.username_pw_set(self.ConfigManager.getAliceConfigByName('mqttUser'), self.ConfigManager.getAliceConfigByName('mqttPassword'))\n+\t\tself._mqttClient.message_callback_add(constants.TOPIC_NLU_QUERY, self.onTopicNluQuery)\n \n-\t\tif self.ConfigManager.getAliceConfigByName('mqttTLSFile'):\n-\t\t\tself._mqttClient.tls_set(certfile=self.ConfigManager.getAliceConfigByName('mqttTLSFile'))\n-\t\t\tself._mqttClient.tls_insecure_set(False)\n-\n-\t\tself._mqttClient.connect(self.ConfigManager.getAliceConfigByName('mqttHost'), int(self.ConfigManager.getAliceConfigByName('mqttPort')))\n-\n-\t\tself._mqttClient.loop_start()\n-\t\tself.logInfo(f'Started {self.NAME}')\n-\n-\n-\tdef onBooted(self):\n-\t\tself.playSound(soundFilename='boot')\n+\t\tself.connect()\n \n \n \tdef onStop(self):\n \t\tsuper().onStop()\n-\t\tself._mqttClient.loop_stop()\n-\t\tself._mqttClient.disconnect()\n+\t\tself.disconnect()\n \n \n \t# noinspection PyUnusedLocal\n@@ -104,7 +91,8 @@ def onConnect(self, client, userdata, flags, rc):\n \t\t\t(constants.TOPIC_ASR_START_LISTENING, 0),\n \t\t\t(constants.TOPIC_TTS_SAY, 0),\n \t\t\t(constants.TOPIC_TEXT_CAPTURED, 0),\n-\t\t\t(constants.TOPIC_HOTWORD_TOGGLE_ON, 0)\n+\t\t\t(constants.TOPIC_HOTWORD_TOGGLE_ON, 0),\n+\t\t\t(constants.TOPIC_NLU_QUERY, 0)\n \t\t]\n \n \t\tfor username in self.UserManager.getAllUserNames():\n@@ -121,6 +109,29 @@ def onConnect(self, client, userdata, flags, rc):\n \t\tself.toggleFeedbackSounds()\n \n \n+\tdef connect(self):\n+\t\tif self.ConfigManager.getAliceConfigByName('mqttUser') and self.ConfigManager.getAliceConfigByName('mqttPassword'):\n+\t\t\tself._mqttClient.username_pw_set(self.ConfigManager.getAliceConfigByName('mqttUser'), self.ConfigManager.getAliceConfigByName('mqttPassword'))\n+\n+\t\tif self.ConfigManager.getAliceConfigByName('mqttTLSFile'):\n+\t\t\tself._mqttClient.tls_set(certfile=self.ConfigManager.getAliceConfigByName('mqttTLSFile'))\n+\t\t\tself._mqttClient.tls_insecure_set(False)\n+\n+\t\tself._mqttClient.connect(self.ConfigManager.getAliceConfigByName('mqttHost'), int(self.ConfigManager.getAliceConfigByName('mqttPort')))\n+\n+\t\tself._mqttClient.loop_start()\n+\n+\n+\tdef disconnect(self):\n+\t\tself._mqttClient.loop_stop()\n+\t\tself._mqttClient.disconnect()\n+\n+\n+\tdef reconnect(self):\n+\t\tself.disconnect()\n+\t\tself.connect()\n+\n+\n \tdef subscribeSkillIntents(self, skillName: str = None):\n \t\tif skillName:\n \t\t\tself.SkillManager.getSkillInstance(skillName).subscribe(self._mqttClient)\n@@ -135,10 +146,11 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\ttry:\n \t\t\tif self._audioFrameRegex.match(message.topic):\n \t\t\t\tself.broadcast(\n-\t\t\t\t\tmethod='onAudioFrame',\n+\t\t\t\t\tmethod=constants.EVENT_AUDIO_FRAME,\n \t\t\t\t\texceptions=[self.name],\n \t\t\t\t\tpropagateToSkills=True,\n-\t\t\t\t\tmessage=message\n+\t\t\t\t\tmessage=message,\n+\t\t\t\t\tsiteId=message.topic.replace('hermes/audioServer/', '').replace('/audioFrame', '')\n \t\t\t\t)\n \t\t\t\treturn\n \n@@ -159,12 +171,12 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\t\t\treturn\n \n \t\t\telif message.topic == constants.TOPIC_HOTWORD_TOGGLE_ON:\n-\t\t\t\tself.broadcast(method='onHotwordToggleOn', exceptions=[constants.DUMMY], siteId=siteId)\n+\t\t\t\tself.broadcast(method=constants.EVENT_HOTWORD_TOGGLE_ON, exceptions=[constants.DUMMY], siteId=siteId)\n \t\t\t\treturn\n \n-\t\t\tif not session: # It is a device trying to communicate with Alice\n+\t\t\tif not session: # It is a device trying to communicate with Alice\n \t\t\t\tsession = self.DeviceManager.deviceMessage(message)\n-\t\t\t\tself.broadcast(method='onMessage', exceptions=[self.name], session=session)\n+\t\t\t\tself.broadcast(method=constants.EVENT_MESSAGE, exceptions=[self.name], session=session)\n \t\t\t\tself.SkillManager.skillBroadcast(method='dispatchMessage', session=session)\n \t\t\t\treturn\n \n@@ -172,7 +184,6 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\t\tif redQueen and not redQueen.inTheMood(session):\n \t\t\t\treturn\n \n-\t\t\tcustomData = session.customData\n \t\t\tif 'intent' in payload and payload['intent']['confidenceScore'] < self.ConfigManager.getAliceConfigByName('probabilityThreshold'):\n \t\t\t\tif session.notUnderstood < self.ConfigManager.getAliceConfigByName('notUnderstoodRetries'):\n \t\t\t\t\tsession.notUnderstood = session.notUnderstood + 1\n@@ -182,7 +193,7 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\t\t\t\t\ttext=self.TalkManager.randomTalk('notUnderstood', skill='system')\n \t\t\t\t\t)\n \t\t\t\telse:\n-\t\t\t\t\tdel session.notUnderstood\n+\t\t\t\t\tsession.notUnderstood = 0\n \t\t\t\t\tself.endDialog(\n \t\t\t\t\t\tsessionId=sessionId,\n \t\t\t\t\t\ttext=self.TalkManager.randomTalk('notUnderstoodEnd', skill='system')\n@@ -193,9 +204,9 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\t\tif skill:\n \t\t\t\tskill.addToMessageHistory(session)\n \n-\t\t\tfor modul in self.SkillManager.activeSkills.values():\n+\t\t\tfor skill in self.SkillManager.activeSkills.values():\n \t\t\t\ttry:\n-\t\t\t\t\tconsumed = modul.dispatchMessage(session)\n+\t\t\t\t\tconsumed = skill.onDispatchMessage(session)\n \t\t\t\texcept AccessLevelTooLow:\n \t\t\t\t\t# The command was recognized but required higher access level\n \t\t\t\t\treturn\n@@ -209,7 +220,7 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\t\t\t\treturn\n \n \t\t\t\telif consumed or consumed is None:\n-\t\t\t\t\tself.logInfo(f\"The intent {message.topic.replace('hermes/intent/', '')} was consumed by {modul.__class__.__name__}\")\n+\t\t\t\t\tself.logInfo(f\"The intent {message.topic.replace('hermes/intent/', '')} was consumed by {skill.__class__.__name__}\")\n \t\t\t\t\treturn\n \n \t\t\tself.logWarning(f\"Intent \\\"{message.topic}\\\" wasn't consumed by any skill\")\n@@ -222,7 +233,7 @@ def onMqttMessage(self, client, userdata, message: mqtt.MQTTMessage):\n \t\t\t\t)\n \t\t\t\treturn\n \t\t\telse:\n-\t\t\t\tdel session.notUnderstood\n+\t\t\t\tsession.notUnderstood = 0\n \t\t\t\tself.endDialog(\n \t\t\t\t\tsessionId=sessionId,\n \t\t\t\t\ttext=self.TalkManager.randomTalk('notUnderstoodEnd', skill='system')\n@@ -253,9 +264,9 @@ def onHotwordDetected(self, client, data, msg):\n \t\tself.DialogSessionManager.preSession(siteId, user)\n \n \t\tif user == constants.UNKNOWN_USER:\n-\t\t\tself.broadcast(method='onHotword', exceptions=[self.name], propagateToSkills=True, siteId=siteId, user=user)\n+\t\t\tself.broadcast(method=constants.EVENT_HOTWORD, exceptions=[self.name], propagateToSkills=True, siteId=siteId, user=user)\n \t\telse:\n-\t\t\tself.broadcast(method='onWakeword', exceptions=[self.name], propagateToSkills=True, siteId=siteId, user=user)\n+\t\t\tself.broadcast(method=constants.EVENT_WAKEWORD, exceptions=[self.name], propagateToSkills=True, siteId=siteId, user=user)\n \n \n \tdef handleMultiDetection(self):\n@@ -278,7 +289,7 @@ def onSnipsSessionStarted(self, client, data, msg: mqtt.MQTTMessage):\n \t\tsession = self.DialogSessionManager.addSession(sessionId=sessionId, message=msg)\n \n \t\tif session:\n-\t\t\tself.broadcast(method='onSessionStarted', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\tself.broadcast(method=constants.EVENT_SESSION_STARTED, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \t# noinspection PyUnusedLocal\n@@ -287,7 +298,18 @@ def onSnipsSessionQueued(self, client, data, msg: mqtt.MQTTMessage):\n \t\tsession = self.DialogSessionManager.addSession(sessionId=sessionId, message=msg)\n \n \t\tif session:\n-\t\t\tself.broadcast(method='onSessionQueued', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\tself.broadcast(method=constants.EVENT_SESSION_QUEUED, exceptions=[self.name], propagateToSkills=True, session=session)\n+\n+\n+\t# noinspection PyUnusedLocal\n+\tdef onTopicNluQuery(self, client, data, msg: mqtt.MQTTMessage):\n+\t\tsessionId = self.Commons.parseSessionId(msg)\n+\n+\t\tsession = self.DialogSessionManager.getSession(sessionId)\n+\t\tif not session:\n+\t\t\tsession = self.DialogSessionManager.addSession(sessionId=sessionId, message=msg)\n+\n+\t\tself.broadcast(method=constants.EVENT_NLU_QUERY, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \t# noinspection PyUnusedLocal\n@@ -296,7 +318,16 @@ def onSnipsStartListening(self, client, data, msg: mqtt.MQTTMessage):\n \t\tsession = self.DialogSessionManager.getSession(sessionId=sessionId)\n \n \t\tif session:\n-\t\t\tself.broadcast(method='onStartListening', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\tself.broadcast(method=constants.EVENT_START_LISTENING, exceptions=[self.name], propagateToSkills=True, session=session)\n+\n+\n+\t# noinspection PyUnusedLocal\n+\tdef onSnipsStopListening(self, client, data, msg: mqtt.MQTTMessage):\n+\t\tsessionId = self.Commons.parseSessionId(msg)\n+\t\tsession = self.DialogSessionManager.getSession(sessionId=sessionId)\n+\n+\t\tif session:\n+\t\t\tself.broadcast(method=constants.EVENT_STOP_LISTENING, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \t# noinspection PyUnusedLocal\n@@ -305,7 +336,7 @@ def onSnipsCaptured(self, client, data, msg: mqtt.MQTTMessage):\n \t\tsession = self.DialogSessionManager.getSession(sessionId=sessionId)\n \n \t\tif session:\n-\t\t\tself.broadcast(method='onCaptured', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\tself.broadcast(method=constants.EVENT_CAPTURED, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \tdef onSnipsIntentParsed(self, client, data, msg: mqtt.MQTTMessage):\n@@ -314,9 +345,9 @@ def onSnipsIntentParsed(self, client, data, msg: mqtt.MQTTMessage):\n \n \t\tif session:\n \t\t\tsession.update(msg)\n-\t\t\tself.broadcast(method='onIntentParsed', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\tself.broadcast(method=constants.EVENT_INTENT_PARSED, exceptions=[self.name], propagateToSkills=True, session=session)\n \n-\t\t\tif self.ConfigManager.getAliceConfigByName('asr').lower() != 'snips':\n+\t\t\tif session.isAPIGenerated:\n \t\t\t\tintent = Intent(session.payload['intent']['intentName'].split(':')[1])\n \t\t\t\tmessage = mqtt.MQTTMessage(topic=str.encode(str(intent)))\n \t\t\t\tmessage.payload = json.dumps(session.payload)\n@@ -331,24 +362,24 @@ def onSnipsSessionEnded(self, client, data, msg: mqtt.MQTTMessage):\n \t\tif session:\n \t\t\tsession.update(msg)\n \t\telse:\n-\t\t\tself.broadcast(method='onSessionEnded', exceptions=[self.name])\n+\t\t\tself.broadcast(method=constants.EVENT_SESSION_ENDED, exceptions=[self.name])\n \t\t\treturn\n \n \t\treason = session.payload['termination']['reason']\n \t\tif reason:\n \t\t\tif reason == 'abortedByUser':\n-\t\t\t\tself.broadcast(method='onUserCancel', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\t\tself.broadcast(method=constants.EVENT_USER_CANCEL, exceptions=[self.name], propagateToSkills=True, session=session)\n \t\t\telif reason == 'timeout':\n-\t\t\t\tself.broadcast(method='onSessionTimeout', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\t\tself.broadcast(method=constants.EVENT_SESSION_TIMEOUT, exceptions=[self.name], propagateToSkills=True, session=session)\n \t\t\telif reason == 'intentNotRecognized':\n \t\t\t\t# This should never trigger, as \"sendIntentNotRecognized\" is always set to True, but we never know\n \t\t\t\tself.onSnipsIntentNotRecognized(None, data, msg)\n \t\t\telif reason == 'error':\n-\t\t\t\tself.broadcast(method='onSessionError', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\t\tself.broadcast(method=constants.EVENT_SESSION_ERROR, exceptions=[self.name], propagateToSkills=True, session=session)\n \t\t\telse:\n-\t\t\t\tself.broadcast(method='onSessionEnded', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\t\t\tself.broadcast(method=constants.EVENT_SESSION_ENDED, exceptions=[self.name], propagateToSkills=True, session=session)\n \n-\t\tself.broadcast(method='onSessionEnded', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\tself.broadcast(method=constants.EVENT_SESSION_ENDED, exceptions=[self.name], propagateToSkills=True, session=session)\n \t\tself.DialogSessionManager.removeSession(sessionId=sessionId)\n \n \n@@ -369,7 +400,7 @@ def onSnipsSay(self, client, data, msg: mqtt.MQTTMessage):\n \t\t\tif skill:\n \t\t\t\tskill.addChat(text=payload['text'], siteId=siteId)\n \n-\t\tself.broadcast(method='onSay', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\tself.broadcast(method=constants.EVENT_SAY, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \t# noinspection PyUnusedLocal\n@@ -381,7 +412,7 @@ def onSnipsSayFinished(self, client, data, msg: mqtt.MQTTMessage):\n \t\tif session:\n \t\t\tsession.payload = payload\n \n-\t\tself.broadcast(method='onSayFinished', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\tself.broadcast(method=constants.EVENT_SAY_FINISHED, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \t# noinspection PyUnusedLocal\n@@ -390,7 +421,7 @@ def onSnipsIntentNotRecognized(self, client, data, msg: mqtt.MQTTMessage):\n \t\tsession = self.DialogSessionManager.getSession(sessionId)\n \n \t\tif not session:\n-\t\t\tself.ask(text=self.TalkManager.randomTalk('notUnderstood', skill='system'), client=session.siteId)\n+\t\t\tself.ask(text=self.TalkManager.randomTalk('notUnderstood', skill='system'), client='default')\n \t\telse:\n \t\t\tif msg.topic == Intent('UserRandomAnswer'):\n \t\t\t\treturn\n@@ -405,10 +436,10 @@ def onSnipsIntentNotRecognized(self, client, data, msg: mqtt.MQTTMessage):\n \t\t\t\tsession.notUnderstood = session.notUnderstood + 1\n \t\t\t\tself.reviveSession(session, self.TalkManager.randomTalk('notUnderstood', skill='system'))\n \t\t\telse:\n-\t\t\t\tdel session.notUnderstood\n+\t\t\t\tsession.notUnderstood = 0\n \t\t\t\tself.endDialog(sessionId=sessionId, text=self.TalkManager.randomTalk('notUnderstoodEnd', skill='system'))\n \n-\t\tself.broadcast(method='onIntentNotRecognized', exceptions=[self.name], propagateToSkills=True, session=session)\n+\t\tself.broadcast(method=constants.EVENT_INTENT_NOT_RECOGNIZED, exceptions=[self.name], propagateToSkills=True, session=session)\n \n \n \tdef reviveSession(self, session: DialogSession, text: str):\n@@ -427,13 +458,19 @@ def say(self, text, client: str = constants.DEFAULT_SITE_ID, customData: dict =\n \t\t:param customData: json object\n \t\t\"\"\"\n \n-\t\tif client == constants.ALL:\n-\t\t\tdeviceList = self.DeviceManager.getDevicesByType('AliceSatellite', connectedOnly=True)\n+\t\tif client == constants.ALL or client == constants.RANDOM:\n+\t\t\tdeviceList = [device.room for device in self.DeviceManager.getDevicesByType('AliceSatellite', connectedOnly=True) if device]\n \t\t\tdeviceList.append(constants.DEFAULT_SITE_ID)\n \n-\t\t\tfor device in deviceList:\n-\t\t\t\tdevice = device.replace('@mqtt', '')\n-\t\t\t\tself.say(text=text, client=device, customData=customData)\n+\t\t\tif client == constants.ALL:\n+\t\t\t\tfor device in deviceList:\n+\t\t\t\t\tdevice = device.replace('@mqtt', '')\n+\t\t\t\t\tif not device:\n+\t\t\t\t\t\tcontinue\n+\n+\t\t\t\t\tself.say(text=text, client=device, customData=customData)\n+\t\t\telse:\n+\t\t\t\tself.say(text=text, client=random.choice(deviceList), customData=customData)\n \t\telse:\n \t\t\tif customData is not None:\n \t\t\t\tif isinstance(customData, dict):\n@@ -449,21 +486,21 @@ def say(self, text, client: str = constants.DEFAULT_SITE_ID, customData: dict =\n \n \t\t\tif self.ConfigManager.getAliceConfigByName('outputOnSonos') != '1' or (self.ConfigManager.getAliceConfigByName('outputOnSonos') == '1' and self.SkillManager.getSkillInstance('Sonos') is None or not self.SkillManager.getSkillInstance('Sonos').anySkillHere(client)) or not self.SkillManager.getSkillInstance('Sonos').active:\n \t\t\t\tself._mqttClient.publish(constants.TOPIC_START_SESSION, json.dumps({\n-\t\t\t\t\t'siteId' : client,\n-\t\t\t\t\t'init' : {\n-\t\t\t\t\t\t'type' : 'notification',\n-\t\t\t\t\t\t'text' : text,\n+\t\t\t\t\t'siteId': client,\n+\t\t\t\t\t'init': {\n+\t\t\t\t\t\t'type': 'notification',\n+\t\t\t\t\t\t'text': text,\n \t\t\t\t\t\t'sendIntentNotRecognized': True,\n-\t\t\t\t\t\t'canBeEnqueued' \t\t : canBeEnqueued\n+\t\t\t\t\t\t'canBeEnqueued': canBeEnqueued\n \t\t\t\t\t},\n \t\t\t\t\t'customData': customData\n \t\t\t\t}))\n \t\t\telse:\n \t\t\t\tself._speakOnSonos(text, client)\n \t\t\t\tself._mqttClient.publish(constants.TOPIC_START_SESSION, json.dumps({\n-\t\t\t\t\t'siteId' : client,\n-\t\t\t\t\t'init' : {\n-\t\t\t\t\t\t'type' : 'notification',\n+\t\t\t\t\t'siteId': client,\n+\t\t\t\t\t'init': {\n+\t\t\t\t\t\t'type': 'notification',\n \t\t\t\t\t\t'sendIntentNotRecognized': True\n \t\t\t\t\t},\n \t\t\t\t\t'customData': customData\n@@ -515,16 +552,15 @@ def ask(self, text: str, client: str = constants.DEFAULT_SITE_ID, intentFilter:\n \t\t\tjsonDict['customData'] = json.dumps(customData)\n \n \t\tinitDict = {\n-\t\t\t'type' : 'action',\n-\t\t\t'text' : text,\n-\t\t\t'canBeEnqueued' : canBeEnqueued,\n+\t\t\t'type': 'action',\n+\t\t\t'text': text,\n+\t\t\t'canBeEnqueued': canBeEnqueued,\n \t\t\t'sendIntentNotRecognized': True\n \t\t}\n \n \t\tif intentFilter:\n \t\t\tintentList = [str(x).replace('hermes/intent/', '') for x in intentFilter]\n \t\t\tinitDict['intentFilter'] = intentList\n-\t\t\tinitDict['intentFilter'].append(Intent('GlobalStop').justTopic)\n \n \t\tjsonDict['init'] = initDict\n \n@@ -561,8 +597,8 @@ def continueDialog(self, sessionId: str, text: str, customData: dict = None, int\n \t\t\tself.DialogSessionManager.addPreviousIntent(sessionId=sessionId, previousIntent=previousIntent)\n \n \t\tjsonDict = {\n-\t\t\t'sessionId' : sessionId,\n-\t\t\t'text' : text,\n+\t\t\t'sessionId': sessionId,\n+\t\t\t'text': text,\n \t\t\t'sendIntentNotRecognized': True,\n \t\t}\n \n@@ -578,8 +614,6 @@ def continueDialog(self, sessionId: str, text: str, customData: dict = None, int\n \t\tif intentFilter:\n \t\t\tintentList = [str(x).replace('hermes/intent/', '') for x in intentFilter]\n \t\t\tjsonDict['intentFilter'] = intentList\n-\t\t\tif not slot:\n-\t\t\t\tjsonDict['intentFilter'].append(Intent('GlobalStop').justTopic)\n \n \t\tif slot:\n \t\t\tif intentFilter and len(intentList) > 1:\n@@ -618,6 +652,10 @@ def endDialog(self, sessionId: str = '', text: str = '', client: str = ''):\n \t\tif not sessionId:\n \t\t\treturn\n \n+\t\tsession = self.DialogSessionManager.getSession(sessionId)\n+\t\tif session and session.isAPIGenerated:\n+\t\t\treturn self.say(text=text, client=session.siteId)\n+\n \t\tclient = client.replace(' ', '_')\n \n \t\tif self.ConfigManager.getAliceConfigByName('outputOnSonos') != '1' or (self.ConfigManager.getAliceConfigByName('outputOnSonos') == '1' and self.SkillManager.getSkillInstance('Sonos') is None or not self.SkillManager.getSkillInstance('Sonos').anySkillHere(client)) or not self.SkillManager.getSkillInstance('Sonos').active:\n@@ -678,7 +716,7 @@ def playSound(self, soundFilename: str, location: Path = None, sessionId: str =\n \n \n \tdef publish(self, topic: str, payload: (dict, str) = None, qos: int = 0, retain: bool = False):\n-\t\tif payload and isinstance(payload, dict):\n+\t\tif isinstance(payload, dict):\n \t\t\tpayload = json.dumps(payload)\n \n \t\tself._mqttClient.publish(topic, payload, qos, retain)\n@@ -715,9 +753,10 @@ def _speakOnSonos(self, text, client):\n \t\tif text == '':\n \t\t\treturn\n \n-\t\tsubprocess.call(['sudo',\n+\t\tself.Commons.runRootSystemCommand([\n \t\t\tPath(self.Commons.rootDir(), '/system/scripts/snipsSuperTTS.sh'),\n-\t\t\tPath('/share/tmp.wav'), 'amazon', self.LanguageManager.activeLanguage, 'US', 'Joanna', 'FEMALE', text, '22050'])\n+\t\t\tPath('/share/tmp.wav'), 'amazon', self.LanguageManager.activeLanguage, 'US', 'Joanna', 'FEMALE', text, '22050'\n+\t\t])\n \n \t\tsonosSkill = self.SkillManager.getSkillInstance('Sonos')\n \t\tif sonosSkill:\ndiff --git a/core/snips/SamkillaManager.py b/core/snips/SamkillaManager.py\ndeleted file mode 100755\n--- a/core/snips/SamkillaManager.py\n+++ /dev/null\n@@ -1,390 +0,0 @@\n-import json\n-import time\n-from datetime import datetime\n-from pathlib import Path\n-\n-import requests\n-from selenium import webdriver\n-from selenium.webdriver.chrome.options import Options\n-from selenium.webdriver.chrome.webdriver import WebDriver\n-from selenium.webdriver.support import expected_conditions as EC\n-from selenium.webdriver.support.ui import WebDriverWait\n-\n-from core.ProjectAliceExceptions import AssistantNotFoundError, HttpError, IntentWithUnknownSlotError\n-from core.snips.samkilla.Assistant import Assistant\n-from core.snips.samkilla.Entity import Entity\n-from core.snips.samkilla.Intent import Intent\n-from core.snips.samkilla.Skill import Skill\n-from core.snips.samkilla.models.EnumSkillImageUrl import EnumSkillImageUrl as EnumSkillImageUrlClass\n-from core.snips.samkilla.processors.MainProcessor import MainProcessor\n-\n-EnumSkillImageUrl = EnumSkillImageUrlClass()\n-\n-from core.base.model.Manager import Manager\n-\n-class SamkillaManager(Manager):\n-\n-\tNAME = 'SamkillaManager'\n-\tROOT_URL = \"https://console.snips.ai\"\n-\n-\tdef __init__(self, devMode: bool = True):\n-\t\tsuper().__init__(self.NAME)\n-\n-\t\tself._currentUrl = ''\n-\t\tself._browser = None\n-\t\tself._devMode = devMode\n-\t\tself._cookie = ''\n-\t\tself._userId = ''\n-\t\tself._userEmail = ''\n-\t\tself._userPassword = ''\n-\t\tself._assistant = None\n-\t\tself._skill = None\n-\t\tself._intent = None\n-\t\tself._entity = None\n-\n-\t\tself._dtSlotTypesSkillsValues \t\t= dict()\n-\t\tself._dtIntentsSkillsValues\t\t= dict()\n-\t\tself._dtIntentNameSkillMatching \t= dict()\n-\n-\t\tself._mainProcessor = None\n-\n-\n-\tdef onStart(self):\n-\t\tsuper().onStart()\n-\n-\t\tself._userEmail = self.ConfigManager.getAliceConfigByName('snipsConsoleLogin')\n-\t\tself._userPassword = self.ConfigManager.getAliceConfigByName('snipsConsolePassword')\n-\n-\t\tself._mainProcessor = MainProcessor(self)\n-\t\tself.initActions()\n-\t\tself._loadDialogTemplateMapsInConfigManager()\n-\n-\t\tif not Path(self.Commons.rootDir(), f'trained/assistants/assistant_{self.LanguageManager.activeLanguage}').exists():\n-\t\t\tself.sync()\n-\n-\n-\tdef _loadDialogTemplateMapsInConfigManager(self):\n-\t\tself._dtSlotTypesSkillsValues, self._dtIntentsSkillsValues, self._dtIntentNameSkillMatching = self.getDialogTemplatesMaps(\n-\t\t\trunOnAssistantId=self.LanguageManager.activeSnipsProjectId,\n-\t\t\tlanguageFilter=self.LanguageManager.activeLanguage\n-\t\t)\n-\n-\n-\t@property\n-\tdef entity(self) -> Entity:\n-\t\treturn self._entity\n-\n-\n-\t@property\n-\tdef intent(self) -> Intent:\n-\t\treturn self._intent\n-\n-\n-\t@property\n-\tdef skill(self) -> Skill:\n-\t\treturn self._skill\n-\n-\n-\t@property\n-\tdef assistant(self) -> Assistant:\n-\t\treturn self._assistant\n-\n-\n-\t@property\n-\tdef userEmail(self) -> str:\n-\t\treturn self._userEmail\n-\n-\n-\t@property\n-\tdef userId(self) -> str:\n-\t\treturn self._userId\n-\n-\n-\tdef sync(self, skillFilter: dict = None, download: bool = True) -> bool:\n-\t\tif skillFilter is None:\n-\t\t\tskillFilter = dict()\n-\n-\t\tself.log(f\"Sync for skill/s [{', '.join(skillFilter) or '*'}]\")\n-\n-\t\tif not self.start():\n-\t\t\tself.log('No credentials. Unable to synchronize assistant with remote console')\n-\t\t\treturn False\n-\n-\t\tactiveLang: str = self.LanguageManager.activeLanguage\n-\t\tactiveProjectId: str = self.LanguageManager.activeSnipsProjectId\n-\t\tchanges: bool = False\n-\n-\t\ttry:\n-\t\t\tchanges = self.syncLocalToRemote(\n-\t\t\t\tbaseAssistantId=activeProjectId,\n-\t\t\t\tbaseLanguageFilter=activeLang,\n-\t\t\t\tbaseSkillFilter=list(skillFilter),\n-\t\t\t\tnewAssistantTitle=f\"ProjectAlice_{datetime.today().strftime('%Y-%m-%d')}_{self.LanguageManager.activeLanguage}\"\n-\t\t\t)\n-\n-\t\t\tif changes:\n-\t\t\t\tif download:\n-\t\t\t\t\tself.log('Changes detected during sync, let\\'s update the assistant...')\n-\t\t\t\t\tself.SnipsConsoleManager.doDownload(skillFilter)\n-\t\t\t\telse:\n-\t\t\t\t\tself.log('Changes detected during sync but not downloading yet')\n-\t\t\telse:\n-\t\t\t\tself.log('No changes detected during sync')\n-\n-\t\t\t\tif not Path(self.Commons.rootDir(), f'trained/assistants/assistant_{self.LanguageManager.activeLanguage}').exists():\n-\t\t\t\t\tself.SnipsConsoleManager.doDownload()\n-\t\t\t\telse:\n-\t\t\t\t\tself.SkillManager.onSnipsAssistantDownloaded(skillsInfos=skillFilter)\n-\n-\t\t\tself.stop()\n-\n-\t\texcept AssistantNotFoundError:\n-\t\t\tself.log(f'Assistant project id \\'{activeProjectId}\\' for lang \\'{activeLang}\\' doesn\\'t exist. Check your config.py')\n-\n-\t\treturn changes\n-\n-\n-\tdef log(self, msg: str):\n-\t\tif self._devMode:\n-\t\t\tself.logInfo(msg)\n-\n-\n-\tdef start(self):\n-\t\tif self.SnipsConsoleManager.loginCredentialsAreConfigured():\n-\t\t\tself.initBrowser()\n-\t\t\tself.login(self.ROOT_URL + '/home/apps')\n-\t\t\treturn True\n-\n-\t\treturn False\n-\n-\n-\tdef stop(self):\n-\t\tself._browser.quit()\n-\n-\n-\tdef initActions(self):\n-\t\tself._assistant = Assistant(self)\n-\t\tself._skill = Skill(self)\n-\t\tself._intent = Intent(self)\n-\t\tself._entity = Entity(self)\n-\n-\n-\tdef initBrowser(self):\n-\t\toptions = Options()\n-\t\toptions.headless = True\n-\t\toptions.add_argument('--no-sandbox')\n-\t\toptions.add_argument('--disable-dev-shm-usage')\n-\t\t# self._browser = webdriver.Firefox('geckodriver', options=options)\n-\t\tself._browser = webdriver.Chrome('chromedriver', options=options)\n-\n-\n-\tdef getBrowser(self) -> WebDriver:\n-\t\treturn self._browser\n-\n-\n-\tdef reloadBrowserPage(self):\n-\t\tself._browser.execute_script('location.reload()')\n-\n-\n-\tdef visitUrl(self, url):\n-\t\tself._currentUrl = url\n-\t\tself._browser.get(url)\n-\t\ttime.sleep(0.1)\n-\t\t# self.log(\"[Browser] \" + self._browser.title +' - ' + self._browser.current_url)\n-\n-\n-\tdef login(self, url: str):\n-\t\tself.visitUrl(url)\n-\t\tself._browser.find_element_by_class_name('cookies-analytics-info__ok-button').click()\n-\t\tself._browser.find_element_by_name('email').send_keys(self._userEmail)\n-\t\tself._browser.find_element_by_name('password').send_keys(self._userPassword)\n-\t\tself._browser.find_element_by_css_selector('.login-page__section-public__form .button[type=submit]').click()\n-\t\tself._cookie = self._browser.execute_script('return document.cookie')\n-\t\tself._userId = self._browser.execute_script(\"return window._loggedInUser['id']\")\n-\n-\n-\t# TODO batch gql requests\n-\t# payload appears to be typed wrong can be string or dict\n-\tdef postGQLBrowserly(self, payload: dict, jsonRequest: bool = True, dataReadyResponse: bool = True, rawResponse: bool = False) -> dict:\n-\t\tinjectedPayload = payload\n-\n-\t\tif jsonRequest:\n-\t\t\tinjectedPayload = json.dumps(payload)\n-\n-\t\tinjectedPayload = injectedPayload.replace(\"'\", \"__SINGLE_QUOTES__\").replace(\"\\\\n\", ' ')\n-\n-\t\t# self.log(injectedPayload)\n-\t\t# self._browser.execute_script('console.log(\\'' + injectedPayload + '\\')')\n-\t\t# self._browser.execute_script('console.log(\\'' + injectedPayload + '\\'.replace(/__SINGLE_QUOTES__/g,\"\\'\").replace(/__QUOTES__/g,\\'\\\\\\\\\"\\'))')\n-\n-\t\tself._browser.execute_script(\"document.title = 'loading'\")\n-\t\tself._browser.execute_script('fetch(\"/gql\", {method: \"POST\", headers:{\"accept\":\"*/*\",\"content-type\":\"application/json\"}, credentials: \"same-origin\", body:\\'' + injectedPayload + '\\'.replace(/__SINGLE_QUOTES__/g,\"\\'\").replace(/__QUOTES__/g,\\'\\\\\\\\\"\\')}).then((data) => { data.text().then((text) => { document.title = text; }); })')\n-\t\twait = WebDriverWait(self._browser, 10)\n-\t\twait.until(EC.title_contains('{'))\n-\t\tresponse = self._browser.execute_script('return document.title')\n-\t\tself._browser.execute_script(\"document.title = 'idle'\")\n-\n-\t\t# self.log(response)\n-\n-\t\tjsonResponse = json.loads(response)\n-\n-\t\tif 'errors' in jsonResponse[0]:\n-\t\t\tfirstError = jsonResponse[0]['errors'][0]\n-\t\t\tcomplexMessage = firstError['message']\n-\t\t\tpath = firstError.get('path', '')\n-\n-\t\t\ttry:\n-\t\t\t\terrorDetails = json.loads(complexMessage)\n-\t\t\texcept:\n-\t\t\t\terrorDetails = {'status': 0}\n-\n-\t\t\terrorResponse = {\n-\t\t\t\t'code': errorDetails['status'],\n-\t\t\t\t'message': complexMessage,\n-\t\t\t\t'context': path\n-\t\t\t}\n-\n-\t\t\tif 'non-nullable field IntentSlot.name' in complexMessage:\n-\t\t\t\traise IntentWithUnknownSlotError(errorResponse['code'], payload[0]['variables']['input']['config']['displayName'], ['intent'])\n-\n-\t\t\traise HttpError(errorResponse['code'], errorResponse['message'], errorResponse['context'])\n-\n-\t\tif rawResponse:\n-\t\t\treturn response\n-\n-\t\tif not dataReadyResponse:\n-\t\t\treturn jsonResponse\n-\n-\t\treturn jsonResponse[0]['data']\n-\n-\n-\tdef postGQLNatively(self, payload: dict) -> requests.Response:\n-\t\t\"\"\"\n-\t\tDo not use for authenticated function like MUTATIONS (and maybe certain QUERY)\n-\t\tconsole-session is randomly present from browser (document.cookie) so we can't authenticated him automatically\n-\t\tconsole-session cookie must be present\n-\t\t\"\"\"\n-\t\turl = self.ROOT_URL + '/gql'\n-\t\theaders = {\n-\t\t\t'Pragma': 'no-cache',\n-\t\t\t'Origin': self.ROOT_URL,\n-\t\t\t'Accept-Encoding': 'gzip, deflate, br',\n-\t\t\t'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',\n-\t\t\t'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36',\n-\t\t\t'content-type': 'application/json',\n-\t\t\t'accept': '*/*',\n-\t\t\t'Cache-Control': 'no-cache',\n-\t\t\t'Referer': self.ROOT_URL + '/home/assistants',\n-\t\t\t'Cookie': self._cookie,\n-\t\t\t'Connection': 'keep-alive'\n-\t\t}\n-\t\treturn requests.post(url=url, data=payload, headers=headers)\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef findRunnableAssistant(self, assistantId: str, assistantLanguage: str, newAssistantTitle: str = '', persistLocal: bool = False) -> str:\n-\t\tif not newAssistantTitle: newAssistantTitle = f\"ProjectAlice_{datetime.today().strftime('%Y-%m-%d')}_{self.LanguageManager.activeLanguage}\"\n-\n-\t\trunOnAssistantId = None\n-\n-\t\t# AssistantId provided\n-\t\tif assistantId:\n-\t\t\tif not self._assistant.exists(assistantId):\n-\t\t\t\t# If not found remotely, stop everything\n-\t\t\t\traise AssistantNotFoundError(4001, f'Assistant with id {assistantId} not found', ['assistant'])\n-\t\t\t# If found remotely, just use it\n-\t\t\trunOnAssistantId = assistantId\n-\t\t\tself.log(f'Using provided assistantId: {runOnAssistantId}')\n-\n-\n-\t\tif not runOnAssistantId:\n-\t\t\t# Try to find the first local assistant for the targeted language\n-\t\t\tlocalFirstAssistantId = self._mainProcessor.getLocalFirstAssistantByLanguage(assistantLanguage=assistantLanguage, returnId=True)\n-\n-\t\t\tif not localFirstAssistantId or not self._assistant.exists(localFirstAssistantId):\n-\t\t\t\t# If not found remotely, create a new one\n-\t\t\t\trunOnAssistantId = self._assistant.create(title=newAssistantTitle, language=assistantLanguage)\n-\t\t\t\tself.log(f'Using new assistantId: {runOnAssistantId}')\n-\t\t\telse:\n-\t\t\t\t# If found remotely, just use it\n-\t\t\t\trunOnAssistantId = localFirstAssistantId\n-\t\t\t\tself.log(f'Using first local assistantId: {runOnAssistantId}')\n-\n-\t\t# Add assistant in cache locally if it isn't the case\n-\t\tself._mainProcessor.syncRemoteToLocalAssistant(\n-\t\t\tassistantId=runOnAssistantId,\n-\t\t\tassistantLanguage=assistantLanguage,\n-\t\t\tassistantTitle=self._assistant.getTitleById(runOnAssistantId)\n-\t\t)\n-\n-\t\treturn runOnAssistantId\n-\n-\n-\tdef syncLocalToRemote(self, baseAssistantId: str, baseSkillFilter: list, newAssistantTitle: str = '', baseLanguageFilter: str = 'en') -> bool:\n-\t\t# RemoteFetch/LocalCheck/CreateIfNeeded: assistant\n-\n-\t\trunOnAssistantId = self.findRunnableAssistant(\n-\t\t\tassistantId=baseAssistantId,\n-\t\t\tassistantLanguage=baseLanguageFilter,\n-\t\t\tnewAssistantTitle=newAssistantTitle,\n-\t\t\tpersistLocal=True\n-\t\t)\n-\n-\t\tif self.LanguageManager.activeSnipsProjectId != runOnAssistantId:\n-\t\t\tself.LanguageManager.changeActiveSnipsProjectIdForLanguage(runOnAssistantId, baseLanguageFilter)\n-\n-\t\t# From skill intents files to dict then push to SnipsConsole\n-\t\treturn self._mainProcessor.syncLocalToRemote(runOnAssistantId, skillFilter=baseSkillFilter, languageFilter=baseLanguageFilter)\n-\n-\n-\tdef syncRemoteToLocal(self, baseAssistantId: str, baseSkillFilter: str, baseLanguageFilter: str = 'en'):\n-\t\t# RemoteFetch/LocalCheck/CreateIfNeeded: assistant\n-\t\trunOnAssistantId = self.findRunnableAssistant(\n-\t\t\tassistantId=baseAssistantId,\n-\t\t\tassistantLanguage=baseLanguageFilter,\n-\t\t\tpersistLocal=False\n-\t\t)\n-\n-\t\t# From SnipsConsole objects to skill intents files\n-\t\tself._mainProcessor.syncRemoteToLocal(runOnAssistantId, languageFilter=baseLanguageFilter, skillFilter=baseSkillFilter)\n-\n-\n-\tdef getDialogTemplatesMaps(self, runOnAssistantId: str, languageFilter: str, skillFilter: str = None) -> tuple:\n-\t\treturn self._mainProcessor.buildMapsFromDialogTemplates(runOnAssistantId, languageFilter=languageFilter, skillFilter=skillFilter)\n-\n-\n-\tdef getIntentsBySkillName(self, runOnAssistantId: str, languageFilter: str, skillFilter: str = None) -> list:\n-\t\t_, intentsSkillsValues, intentNameSkillMatching = self.getDialogTemplatesMaps(\n-\t\t\trunOnAssistantId=runOnAssistantId,\n-\t\t\tlanguageFilter=languageFilter\n-\t\t)\n-\n-\t\treturn [{\n-\t\t\t'name': intentName,\n-\t\t\t'description': intentsSkillsValues[intentName]['__otherattributes__']['description']\n-\t\t} for intentName, skillName in intentNameSkillMatching.items() if skillName == skillFilter]\n-\n-\n-\tdef getUtterancesByIntentName(self, runOnAssistantId: str, languageFilter: str, intentFilter: str = None) -> list:\n-\t\t_, intentsSkillsValues, intentNameSkillMatching = self.getDialogTemplatesMaps(\n-\t\t\trunOnAssistantId=runOnAssistantId,\n-\t\t\tlanguageFilter=languageFilter\n-\t\t)\n-\n-\t\treturn [{'sentence': utterance} for intent in intentNameSkillMatching if intent == intentFilter\n-\t\t\tfor utterance in intentsSkillsValues[intent]['utterances'].items()]\n-\n-\n-\t@property\n-\tdef dtSlotTypesSkillsValues(self) -> dict:\n-\t\treturn self._dtSlotTypesSkillsValues\n-\n-\n-\t@property\n-\tdef dtIntentsSkillsValues(self) -> dict:\n-\t\treturn self._dtIntentsSkillsValues\n-\n-\n-\t@property\n-\tdef dtIntentNameSkillMatching(self) -> dict:\n-\t\treturn self._dtIntentNameSkillMatching\ndiff --git a/core/snips/SnipsAssistantManager.py b/core/snips/SnipsAssistantManager.py\nnew file mode 100644\n--- /dev/null\n+++ b/core/snips/SnipsAssistantManager.py\n@@ -0,0 +1,185 @@\n+import json\n+from datetime import datetime\n+from pathlib import Path\n+\n+from core.base.model.Manager import Manager\n+\n+\n+class SnipsAssistantManager(Manager):\n+\n+\tdef __init__(self):\n+\t\tsuper().__init__()\n+\t\tself._assistantPath = Path(self.Commons.rootDir(), f'assistant/assistant.json')\n+\n+\n+\tdef onStart(self):\n+\t\tsuper().onStart()\n+\t\tself.checkAssistant()\n+\n+\n+\tdef checkAssistant(self):\n+\t\tself.logInfo('Checking assistant')\n+\t\tif not self._assistantPath.exists():\n+\t\t\tself.logInfo('Assistant not found, generating')\n+\t\t\tself.train()\n+\t\telse:\n+\t\t\tself.logInfo('Assistant existing, check consistency')\n+\t\t\tif not self.checkConsistency():\n+\t\t\t\tself.logInfo('Assistant is not consistent, needs training')\n+\t\t\t\tself.train()\n+\n+\n+\tdef checkConsistency(self) -> bool:\n+\t\tif not self._assistantPath.exists():\n+\t\t\treturn False\n+\n+\t\texistingIntents = set()\n+\t\texistingSlots = set()\n+\n+\t\tfor skillResource in self.DialogTemplateManager.skillResource():\n+\n+\t\t\twith skillResource.open() as resource:\n+\t\t\t\tdata = json.load(resource)\n+\n+\t\t\tif 'intents' not in data:\n+\t\t\t\tcontinue\n+\n+\t\t\tfor intent in data['intents']:\n+\t\t\t\texistingIntents.add(intent['name'])\n+\n+\t\t\t\tif not intent['slots']:\n+\t\t\t\t\tcontinue\n+\n+\t\t\t\tfor slot in intent['slots']:\n+\t\t\t\t\texistingSlots.add(slot['name'])\n+\n+\t\twith self._assistantPath.open() as fp:\n+\t\t\tdata = json.load(fp)\n+\t\t\tfor intent in data['intents']:\n+\t\t\t\tif intent['name'] not in existingIntents:\n+\t\t\t\t\treturn False\n+\n+\t\t\t\tfor slot in intent['slots']:\n+\t\t\t\t\tif slot['name'] not in existingSlots:\n+\t\t\t\t\t\treturn False\n+\n+\t\tself.logInfo('Assistant seems consistent')\n+\t\treturn True\n+\n+\n+\tdef train(self):\n+\t\tself.logInfo('Training assistant')\n+\n+\t\ttry:\n+\t\t\tassistant = self.generateAssistant()\n+\t\t\tintents = dict()\n+\t\t\tslots = dict()\n+\t\t\trandoms = set()\n+\n+\t\t\t# When slots of the same entity id (type) wear the same name, their id is identical, so we need to\n+\t\t\t# keep a track about entity ids, names and type\n+\t\t\tentityVSType = dict()\n+\n+\t\t\tfor skillResource in self.DialogTemplateManager.skillResource():\n+\n+\t\t\t\twith skillResource.open() as fp:\n+\t\t\t\t\tdata = json.load(fp)\n+\n+\t\t\t\tif 'intents' not in data:\n+\t\t\t\t\tself.logDebug(f'Skill \"{skillResource[\"skill\"]}\" has no intent')\n+\t\t\t\t\tcontinue\n+\n+\t\t\t\tfor intent in data['intents']:\n+\t\t\t\t\tif intent['name'] in intents:\n+\t\t\t\t\t\tself.logWarning(f'Intent \"{intent[\"name\"]}\" is duplicated')\n+\t\t\t\t\t\tcontinue\n+\n+\t\t\t\t\tintents[intent['name']] = {\n+\t\t\t\t\t\t'id' : intent['name'],\n+\t\t\t\t\t\t'type' : 'registry',\n+\t\t\t\t\t\t'version' : '0.1.0',\n+\t\t\t\t\t\t'language' : self.LanguageManager.activeLanguage,\n+\t\t\t\t\t\t'slots' : list(),\n+\t\t\t\t\t\t'name' : intent['name'],\n+\t\t\t\t\t\t'enabledByDefault': intent['enabledByDefault']\n+\t\t\t\t\t}\n+\n+\t\t\t\t\tif not intent['slots']:\n+\t\t\t\t\t\tcontinue\n+\n+\t\t\t\t\tfor slot in intent['slots']:\n+\t\t\t\t\t\trand9 = self.Commons.randomString(9)\n+\t\t\t\t\t\twhile rand9 in randoms:\n+\t\t\t\t\t\t\trand9 = self.Commons.randomString(9)\n+\t\t\t\t\t\trandoms.add(rand9)\n+\n+\t\t\t\t\t\trand11 = self.Commons.randomString(11)\n+\t\t\t\t\t\twhile rand11 in randoms:\n+\t\t\t\t\t\t\trand11 = self.Commons.randomString(11)\n+\t\t\t\t\t\trandoms.add(rand11)\n+\n+\t\t\t\t\t\tif slot['type'] not in slots:\n+\t\t\t\t\t\t\tintentSlot = {\n+\t\t\t\t\t\t\t\t'name' : slot['name'],\n+\t\t\t\t\t\t\t\t'id' : rand9,\n+\t\t\t\t\t\t\t\t'entityId' : f'entity_{rand11}',\n+\t\t\t\t\t\t\t\t'missingQuestion': slot['missingQuestion'],\n+\t\t\t\t\t\t\t\t'required' : slot['required']\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\tslots[slot['type']] = intentSlot\n+\t\t\t\t\t\t\tentityVSType[f'{slot[\"type\"]}_{slot[\"name\"]}'] = f'{rand9}'\n+\t\t\t\t\t\telse:\n+\n+\t\t\t\t\t\t\t# Check if a slot with same type and name already exist and use it's id, else use the new random\n+\t\t\t\t\t\t\tslotId = entityVSType.get(f'{slot[\"type\"]}_{slot[\"name\"]}', rand9)\n+\n+\t\t\t\t\t\t\tintentSlot = {\n+\t\t\t\t\t\t\t\t'name' : slot['name'],\n+\t\t\t\t\t\t\t\t'id' : slotId,\n+\t\t\t\t\t\t\t\t'entityId' : slots[slot['type']]['entityId'],\n+\t\t\t\t\t\t\t\t'missingQuestion': slot['missingQuestion'],\n+\t\t\t\t\t\t\t\t'required' : slot['required']\n+\t\t\t\t\t\t\t}\n+\n+\t\t\t\t\t\tintents[intent['name']]['slots'].append(intentSlot)\n+\n+\t\t\tassistant['intents'] = [intent for intent in intents.values()]\n+\n+\t\t\tself.Commons.runRootSystemCommand(['ln', '-sfn', self.Commons.rootDir() + f'/trained/assistants/assistant_{self.LanguageManager.activeLanguage}', self.Commons.rootDir() + '/assistant'])\n+\n+\t\t\twith self._assistantPath.open('w') as fp:\n+\t\t\t\tfp.write(json.dumps(assistant, ensure_ascii=False, indent=4, sort_keys=True))\n+\n+\t\t\tself.Commons.runRootSystemCommand(['ln', '-sfn', self.Commons.rootDir() + f'/system/sounds/{self.LanguageManager.activeLanguage}/start_of_input.wav', self.Commons.rootDir() + '/assistant/custom_dialogue/sound/start_of_input.wav'])\n+\t\t\tself.Commons.runRootSystemCommand(['ln', '-sfn', self.Commons.rootDir() + f'/system/sounds/{self.LanguageManager.activeLanguage}/end_of_input.wav', self.Commons.rootDir() + '/assistant/custom_dialogue/sound/end_of_input.wav'])\n+\t\t\tself.Commons.runRootSystemCommand(['ln', '-sfn', self.Commons.rootDir() + f'/system/sounds/{self.LanguageManager.activeLanguage}/error.wav', self.Commons.rootDir() + '/assistant/custom_dialogue/sound/error.wav'])\n+\n+\t\t\tself.SnipsServicesManager.runCmd('restart')\n+\n+\t\t\tself.broadcast(method='snipsAssistantInstalled', exceptions=[self.name], propagateToSkills=True)\n+\t\t\tself.logInfo(f'Assistant trained with {len(intents)} intents with a total of {len(slots)} slots')\n+\t\texcept Exception as e:\n+\t\t\tself.broadcast(method='snipsAssistantFailedTraining', exceptions=[self.name], propagateToSkills=True)\n+\t\t\tif not self._assistantPath.exists():\n+\t\t\t\tself.logFatal('Assistant failed training and no assistant existing, stopping here, sorry....')\n+\n+\n+\tdef generateAssistant(self) -> dict:\n+\t\tassistant = {\n+\t\t\t'id' : f'proj_{self.Commons.randomString(11)}',\n+\t\t\t'name' : f'ProjectAlice_{self.LanguageManager.activeLanguage}',\n+\t\t\t'analyticsEnabled': False,\n+\t\t\t'heartbeatEnabled': False,\n+\t\t\t'language' : self.LanguageManager.activeLanguage,\n+\n+\t\t\t# Declare as google so snips doesn't try to find the snips-asr service\n+\t\t\t'asr' : {'type': 'google'},\n+\n+\t\t\t'platform' : {'type': 'raspberrypi'},\n+\t\t\t'createdAt' : datetime.utcnow().isoformat() + 'Z',\n+\t\t\t'hotword' : 'hey_snips',\n+\t\t\t'version' : {'nluModel': '0.20.1'},\n+\t\t\t'intents' : list()\n+\t\t}\n+\n+\t\treturn assistant\ndiff --git a/core/snips/SnipsConsoleManager.py b/core/snips/SnipsConsoleManager.py\ndeleted file mode 100644\n--- a/core/snips/SnipsConsoleManager.py\n+++ /dev/null\n@@ -1,235 +0,0 @@\n-import time\n-import uuid\n-from pathlib import Path\n-\n-import requests\n-import tempfile\n-\n-from core.base.model.Manager import Manager\n-from core.snips.model.SnipsConsoleUser import SnipsConsoleUser\n-from core.snips.model.SnipsTrainingStatus import SnipsTrainingType, TrainingStatusResponse\n-\n-\n-class SnipsConsoleManager(Manager):\n-\n-\tNAME = 'SnipsConsoleManager'\n-\n-\tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n-\n-\t\tself._connected = False\n-\t\tself._tries = 0\n-\t\tself._user = None\n-\n-\t\tself._headers = {\n-\t\t\t'Accept' \t: 'application/json',\n-\t\t\t'Content-Type' \t: 'application/json'\n-\t\t}\n-\n-\n-\tdef onStart(self):\n-\t\tsuper().onStart()\n-\n-\t\tif self.ConfigManager.getSnipsConfiguration('project-alice', 'console_token'):\n-\t\t\tself.logInfo('Snips console authorized')\n-\t\t\tself._headers['Authorization'] = f\"JWT {self.ConfigManager.getSnipsConfiguration('project-alice', 'console_token')}\"\n-\n-\t\t\tself._user = SnipsConsoleUser({\n-\t\t\t\t'id': self.ConfigManager.getSnipsConfiguration('project-alice', 'console_user_id'),\n-\t\t\t\t'email': self.ConfigManager.getSnipsConfiguration('project-alice', 'console_user_email')\n-\t\t\t})\n-\n-\t\t\tself._connected = True\n-\n-\t\telif self.loginCredentialsAreConfigured():\n-\t\t\tself.logInfo('Snips console not authorized')\n-\t\t\tself._login()\n-\t\telse:\n-\t\t\tself.logWarning('Snips console credentials not found')\n-\t\t\tif not Path(self.Commons.rootDir(), '/assistant').exists():\n-\t\t\t\tself.logError('No assistant found, cannot start')\n-\t\t\t\tself.ProjectAlice.onStop()\n-\t\t\telse:\n-\t\t\t\tself.logWarning('Assistant is existing, allowing to boot but functions will be restricted!')\n-\t\t\t\tself.isActive = False\n-\n-\n-\tdef doDownload(self, skillsInfos: dict = None):\n-\t\tself.logInfo('Starting Snips assistant training and download procedure')\n-\t\tself.ThreadManager.newEvent('SnipsAssistantDownload', onClearCallback='onSnipsAssistantDownloaded').set(skillsInfos=skillsInfos)\n-\n-\t\tprojectId = self.LanguageManager.activeSnipsProjectId\n-\t\tself.ThreadManager.newThread(name='SnipsAssistantDownload', target=self.download, args=[projectId])\n-\n-\n-\tdef loginCredentialsAreConfigured(self):\n-\t\treturn self.ConfigManager.getAliceConfigByName('snipsConsoleLogin') and \\\n-\t\t\t self.ConfigManager.getAliceConfigByName('snipsConsolePassword')\n-\n-\n-\tdef _login(self):\n-\t\tself._tries += 1\n-\t\tif self._tries > 3:\n-\t\t\tself.logInfo(f'Tried to login {self._tries} times, giving up now')\n-\t\t\tself._tries = 0\n-\t\t\treturn\n-\n-\t\tself.logInfo(f\"Connecting to Snips console using account {self.ConfigManager.getAliceConfigByName('snipsConsoleLogin')}\")\n-\t\tpayload = {\n-\t\t\t'email' : self.ConfigManager.getAliceConfigByName('snipsConsoleLogin'),\n-\t\t\t'password': self.ConfigManager.getAliceConfigByName('snipsConsolePassword')\n-\t\t}\n-\n-\t\treq = self._req(url='/v1/user/auth', data=payload)\n-\t\tif req.status_code == 200:\n-\t\t\tself.logInfo('Connected to Snips console. Fetching and saving access token')\n-\t\t\ttry:\n-\t\t\t\ttoken = req.headers['authorization']\n-\t\t\t\tself._user = SnipsConsoleUser(req.json()['user'])\n-\n-\t\t\t\taccessToken = self._getAccessToken(token)\n-\t\t\t\tif accessToken:\n-\t\t\t\t\tself.logInfo('Saving console access token')\n-\t\t\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_token', value=accessToken['token'])\n-\t\t\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_alias', value=accessToken['alias'])\n-\t\t\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_user_id', value=self._user.userId)\n-\t\t\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_user_email', value=self._user.userEmail)\n-\n-\t\t\t\t\tself._headers['Authorization'] = f\"JWT {accessToken['token']}\"\n-\n-\t\t\t\t\tself._connected = True\n-\t\t\t\t\tself._tries = 0\n-\t\t\t\telse:\n-\t\t\t\t\traise Exception('Error fetching JWT console token')\n-\t\t\texcept Exception as e:\n-\t\t\t\tself.logError(f\"Couldn't retrieve snips console token: {e}\")\n-\t\t\t\tself._connected = False\n-\t\t\t\treturn\n-\t\telse:\n-\t\t\tself.logError(f\"Couldn't connect to Snips console: {req.status_code}\")\n-\t\t\tself._connected = False\n-\n-\n-\tdef _getAccessToken(self, token: str) -> dict:\n-\t\talias = f'projectalice{uuid.uuid4()}'.replace('-', '')[:29]\n-\t\tself._headers['Authorization'] = token\n-\t\treq = self._req(url=f'/v1/user/{self._user.userId}/accesstoken', data={'alias': alias})\n-\t\tif req.status_code == 201:\n-\t\t\treturn req.json()['token']\n-\t\treturn dict()\n-\n-\n-\tdef _listAssistants(self) -> dict:\n-\t\treq = self._req(url='/v3/assistant', method='get', data={'userId': self._user.userId})\n-\t\treturn req.json()['assistants']\n-\n-\n-\tdef _trainAssistant(self, assistantId: str, trainingType: SnipsTrainingType):\n-\t\treturn self._req(url=f'/v2/training/assistant/{assistantId}', data={'trainingType': trainingType.value}, method='post')\n-\n-\n-\tdef _trainingStatus(self, assistantId: str) -> TrainingStatusResponse:\n-\t\treq = self._req(url=f'/v2/training/assistant/{assistantId}', method='get')\n-\t\tif req.status_code // 100 == 4:\n-\t\t\traise Exception(f'Snips API returned an error: {req.status_code}')\n-\t\treturn TrainingStatusResponse(req.json())\n-\n-\n-\tdef _handleTraining(self, assistantId: str):\n-\t\ttrainingLock = self.ThreadManager.newEvent('TrainingAssistantLock')\n-\t\ttrainingLock.set()\n-\t\twhile trainingLock.isSet():\n-\t\t\ttrainingStatus = self._trainingStatus(assistantId)\n-\n-\t\t\tif not trainingStatus.nluStatus.needTraining and not trainingStatus.nluStatus.inProgress and \\\n-\t\t\t not trainingStatus.asrStatus.needTraining and not trainingStatus.asrStatus.inProgress:\n-\t\t\t\ttrainingLock.clear()\n-\n-\t\t\telif trainingStatus.nluStatus.inProgress or trainingStatus.asrStatus.inProgress:\n-\t\t\t\tpass\n-\n-\t\t\telif trainingStatus.nluStatus.needTraining and \\\n-\t\t\t\t not trainingStatus.nluStatus.inProgress and \\\n-\t\t\t\t not trainingStatus.asrStatus.inProgress:\n-\t\t\t\tself.logInfo('Training NLU')\n-\t\t\t\treq = self._trainAssistant(assistantId, SnipsTrainingType.NLU)\n-\t\t\t\tif req.status_code == 400:\n-\t\t\t\t\tself.logInfo('There are no intents, so the assistant could not be trained')\n-\t\t\t\t\ttrainingLock.clear()\n-\n-\t\t\telif not trainingStatus.nluStatus.inProgress and \\\n-\t\t\t\t trainingStatus.asrStatus.needTraining and \\\n-\t\t\t\t not trainingStatus.asrStatus.inProgress:\n-\t\t\t\tself.logInfo('Training ASR')\n-\t\t\t\treq = self._trainAssistant(assistantId, SnipsTrainingType.ASR)\n-\t\t\t\tif req.status_code == 400:\n-\t\t\t\t\tself.logInfo('There are no intents, so the assistant could not be trained')\n-\t\t\t\t\ttrainingLock.clear()\n-\n-\t\t\telse:\n-\t\t\t\traise Exception('Something went wrong while training the assistant')\n-\n-\t\t\ttime.sleep(5)\n-\n-\n-\tdef download(self, assistantId: str) -> bool:\n-\t\ttry:\n-\t\t\tself._handleTraining(assistantId)\n-\t\t\tself.logInfo('Downloading assistant...')\n-\t\t\treq = self._req(url=f'/v3/assistant/{assistantId}/download', method='get')\n-\n-\t\t\tPath(tempfile.gettempdir(), 'assistant.zip').write_bytes(req.content)\n-\n-\t\t\tself.logInfo(f'Assistant {assistantId} trained and downloaded')\n-\t\t\tself.ThreadManager.getEvent('SnipsAssistantDownload').clear()\n-\t\t\treturn True\n-\t\texcept Exception as e:\n-\t\t\tself.logError(f'Assistant download failed: {e}')\n-\t\t\tself.broadcast(method='onSnipsAssistantDownloadFailed', exceptions=[self.name], propagateToSkills=True)\n-\t\t\tself.ThreadManager.getEvent('SnipsAssistantDownload').cancel()\n-\t\t\treturn False\n-\n-\n-\tdef _logout(self):\n-\t\tself._req(url=f\"/v1/user/{self._user.userId}/accesstoken/{self.ConfigManager.getSnipsConfiguration('project-alice', 'console_alias')}\", method='get')\n-\t\tif 'Authorization' in self._headers:\n-\t\t\tdel self._headers['Authorization']\n-\t\tself._connected = False\n-\n-\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_token', value='')\n-\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_alias', value='')\n-\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_user_id', value='')\n-\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_user_email', value='')\n-\n-\n-\tdef login(self):\n-\t\tif self._connected:\n-\t\t\tself.logError('SnipsConsole: cannot login, already logged in')\n-\t\telse:\n-\t\t\tself._login()\n-\n-\n-\tdef _req(self, url: str = '', method: str = 'post', params: dict = None, data: dict = None, **kwargs) -> requests.Response:\n-\t\t\"\"\"\n-\t\tSends a http request\n-\t\t:param url: the url path\n-\t\t:param method: get or post\n-\t\t:param params: used for method get\n-\t\t:param data: used for method post\n-\t\t:param kwargs:\n-\t\t:return: requests.Response\n-\t\t\"\"\"\n-\t\treq = requests.request(method=method, url=f'https://external-gateway.snips.ai{url}', params=params, json=data, headers=self._headers, **kwargs)\n-\t\tif req.status_code == 401:\n-\t\t\tself.logWarning('Console token has expired, need to login')\n-\t\t\tif 'Authorization' in self._headers:\n-\t\t\t\tdel self._headers['Authorization']\n-\t\t\tself._connected = False\n-\n-\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_token', value='')\n-\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_alias', value='')\n-\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_user_id', value='')\n-\t\t\tself.ConfigManager.updateSnipsConfiguration(parent='project-alice', key='console_user_email', value='')\n-\n-\t\t\tself._login()\n-\t\treturn req\ndiff --git a/core/snips/SnipsServicesManager.py b/core/snips/SnipsServicesManager.py\n--- a/core/snips/SnipsServicesManager.py\n+++ b/core/snips/SnipsServicesManager.py\n@@ -1,92 +1,38 @@\n-import getpass\n-import subprocess\n-import time\n from pathlib import Path\n-from zipfile import ZipFile\n-\n-import tempfile\n \n from core.base.model.Manager import Manager\n from core.commons import constants\n-from core.voice.model.SnipsASR import SnipsASR\n from core.voice.model.SnipsTTS import SnipsTTS\n \n \n class SnipsServicesManager(Manager):\n \n-\tNAME = 'SnipsServicesManager'\n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n \t\tself._snipsServices = [\n \t\t\t'snips-hotword',\n-\t\t\t'snips-nlu',\n \t\t\t'snips-dialogue',\n-\t\t\t'snips-injection',\n \t\t\t'snips-audio-server',\n-\t\t\t'snips-asr',\n \t\t\t'snips-tts'\n \t\t]\n \n \n-\tdef snipsServices(self, withASR: bool = True) -> list:\n-\t\tif withASR:\n-\t\t\treturn self._snipsServices\n-\t\telse:\n-\t\t\treturn [x for x in self._snipsServices if not 'asr' in x]\n+\tdef snipsServices(self) -> list:\n+\t\treturn self._snipsServices\n \n \n \tdef onStart(self):\n-\t\tself.runCmd(cmd='start', services=self.snipsServices(withASR=False))\n+\t\tsuper().onStart()\n+\t\tself.runCmd(cmd='start', services=self.snipsServices())\n \n \n \tdef onStop(self):\n+\t\tsuper().onStop()\n \t\tself.runCmd(cmd='stop', services=self.snipsServices())\n \n \n-\tdef onSnipsAssistantInstalled(self, **kwargs):\n-\t\tself.runCmd(cmd='restart')\n-\t\ttime.sleep(1)\n-\n-\n-\tdef onSnipsAssistantDownloaded(self, **kwargs):\n-\t\ttry:\n-\t\t\tfilepath = Path(tempfile.gettempdir(), 'assistant.zip')\n-\t\t\twith ZipFile(filepath) as zipfile:\n-\t\t\t\tzipfile.extractall(tempfile.gettempdir())\n-\n-\t\t\tsubprocess.run(['sudo', 'rm', '-rf', self.Commons.rootDir() + f'/trained/assistants/assistant_{self.LanguageManager.activeLanguage}'])\n-\t\t\tsubprocess.run(['sudo', 'rm', '-rf', self.Commons.rootDir() + '/assistant'])\n-\t\t\tsubprocess.run(['sudo', 'cp', '-R', str(filepath).replace('.zip', ''), self.Commons.rootDir() + f'/trained/assistants/assistant_{self.LanguageManager.activeLanguage}'])\n-\n-\t\t\ttime.sleep(0.5)\n-\n-\t\t\tsubprocess.run(['sudo', 'chown', '-R', getpass.getuser(), self.Commons.rootDir() + f'/trained/assistants/assistant_{self.LanguageManager.activeLanguage}'])\n-\t\t\tsubprocess.run(['sudo', 'ln', '-sfn', self.Commons.rootDir() + f'/trained/assistants/assistant_{self.LanguageManager.activeLanguage}', self.Commons.rootDir() + '/assistant'])\n-\t\t\tsubprocess.run(['sudo', 'ln', '-sfn', self.Commons.rootDir() + f'/system/sounds/{self.LanguageManager.activeLanguage}/start_of_input.wav', self.Commons.rootDir() + '/assistant/custom_dialogue/sound/start_of_input.wav'])\n-\t\t\tsubprocess.run(['sudo', 'ln', '-sfn', self.Commons.rootDir() + f'/system/sounds/{self.LanguageManager.activeLanguage}/end_of_input.wav', self.Commons.rootDir() + '/assistant/custom_dialogue/sound/end_of_input.wav'])\n-\t\t\tsubprocess.run(['sudo', 'ln', '-sfn', self.Commons.rootDir() + f'/system/sounds/{self.LanguageManager.activeLanguage}/error.wav', self.Commons.rootDir() + '/assistant/custom_dialogue/sound/error.wav'])\n-\n-\t\t\ttime.sleep(0.5)\n-\t\t\tself.onSnipsAssistantInstalled()\n-\n-\t\t\tself.broadcast(\n-\t\t\t\tmethod='onSnipsAssistantInstalled',\n-\t\t\t\texceptions=[self.name],\n-\t\t\t\tpropagateToSkills=True,\n-\t\t\t\t**kwargs\n-\t\t\t)\n-\t\texcept Exception as e:\n-\t\t\tself.logError(f'Failed installing Snips Assistant: {e}')\n-\t\t\tself.broadcast(\n-\t\t\t\tmethod='onSnipsAssistantFailedInstalling',\n-\t\t\t\texceptions=[constants.DUMMY],\n-\t\t\t\tpropagateToSkills=True,\n-\t\t\t\t**kwargs\n-\t\t\t)\n-\n-\n \tdef runCmd(self, cmd: str, services: list = None):\n \t\tif not Path(self.Commons.rootDir() + '/assistant').exists():\n \t\t\tself.logWarning('Assistant not yet existing, shouldn\\'t handle Snips for now')\n@@ -96,10 +42,10 @@ def runCmd(self, cmd: str, services: list = None):\n \t\t\tservices = self._snipsServices\n \n \t\tfor service in services:\n-\t\t\tif (service == 'snips-asr' and not isinstance(self.ASRManager.asr, SnipsASR)) or (service == 'snips-tts' and not isinstance(self.TTSManager.tts, SnipsTTS)):\n+\t\t\tif service == 'snips-tts' and not isinstance(self.TTSManager.tts, SnipsTTS):\n \t\t\t\tcontinue\n \n-\t\t\tresult = subprocess.run(['sudo', 'systemctl', cmd, service], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n+\t\t\tresult = self.Commons.runRootSystemCommand(['systemctl', cmd, service])\n \t\t\tif result.returncode == 0:\n \t\t\t\tself.logInfo(f\"Service {service} {cmd}'ed\")\n \t\t\telif result.returncode == 5:\ndiff --git a/core/snips/SnipsWatchManager.py b/core/snips/SnipsWatchManager.py\n--- a/core/snips/SnipsWatchManager.py\n+++ b/core/snips/SnipsWatchManager.py\n@@ -1,11 +1,11 @@\n-import re\n import subprocess\n-import tempfile\n import time\n from pathlib import Path\n \n+import re\n+import tempfile\n # noinspection PyUnresolvedReferences\n-from fcntl import fcntl, F_GETFL, F_SETFL\n+from fcntl import F_GETFL, F_SETFL, fcntl\n # noinspection PyUnresolvedReferences\n from os import O_NONBLOCK\n \n@@ -14,10 +14,8 @@\n \n class SnipsWatchManager(Manager):\n \n-\tNAME = 'SnipsWatchManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \t\tself._counter = 0\n \t\tself._thread = None\n \t\tself._file = Path(tempfile.gettempdir(), 'snipswatch')\ndiff --git a/core/snips/model/SnipsTrainingStatus.py b/core/snips/model/SnipsTrainingStatus.py\n--- a/core/snips/model/SnipsTrainingStatus.py\n+++ b/core/snips/model/SnipsTrainingStatus.py\n@@ -4,7 +4,7 @@\n class NLUTrainingStatus:\n \n \tdef __init__(self, data: dict):\n-\t\tif not 'nluStatus' in data:\n+\t\tif 'nluStatus' not in data:\n \t\t\traise Exception('NLU status missing in Snips answer')\n \n \t\tdata = data['nluStatus']\n@@ -32,7 +32,7 @@ def trainingResult(self) -> str:\n class ASRTrainingStatus:\n \n \tdef __init__(self, data: dict):\n-\t\tif not 'nluStatus' in data:\n+\t\tif 'nluStatus' not in data:\n \t\t\traise Exception('ASR status missing in Snips answer')\n \n \t\tdata = data['asrStatus']\ndiff --git a/core/snips/samkilla/Assistant.py b/core/snips/samkilla/Assistant.py\ndeleted file mode 100755\n--- a/core/snips/samkilla/Assistant.py\n+++ /dev/null\n@@ -1,140 +0,0 @@\n-import requests\n-\n-from core.snips import SamkillaManager\n-from core.snips.samkilla.gql.assistants.createAssistant import createAssistant\n-from core.snips.samkilla.gql.assistants.deleteAssistant import deleteAssistant\n-from core.snips.samkilla.gql.assistants.forkAssistantSkill import forkAssistantSkill\n-from core.snips.samkilla.gql.assistants.patchAssistant import patchAssistant\n-from core.snips.samkilla.gql.assistants.queries import allAssistantsQuery, assistantWithSkillsQuery, assistantTrainingStatusQuery\n-\n-\n-class Assistant:\n-\n-\tdef __init__(self, ctx: SamkillaManager):\n-\t\tself._ctx = ctx\n-\n-\n-\tdef create(self, title: str, language: str, platformType: str = 'raspberrypi', asrType: str = 'snips', hotwordId: str = 'hey_snips', rawResponse: bool = False) -> str:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'CreateAssistant',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': {\n-\t\t\t\t\t'title' : title,\n-\t\t\t\t\t'platform' : {'type': platformType},\n-\t\t\t\t\t'asr' : {'type': asrType},\n-\t\t\t\t\t'language' : language,\n-\t\t\t\t\t'hotwordId': hotwordId\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : createAssistant\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\t# Mandatory after a create action to update APOLLO_STATE, @TODO maybe update the state manually to improve performances ?\n-\t\tself._ctx.reloadBrowserPage()\n-\n-\t\treturn response if rawResponse else response['createAssistant']['id']\n-\n-\n-\tdef edit(self, assistantId: str, title: str = None):\n-\t\tinputt = dict()\n-\n-\t\tif title: inputt['title'] = title\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'PatchAssistant',\n-\t\t\t'variables' : {\n-\t\t\t\t'assistantId': assistantId,\n-\t\t\t\t'input' : inputt\n-\t\t\t},\n-\t\t\t'query' : patchAssistant\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest)\n-\n-\n-\tdef delete(self, assistantId: str) -> requests.Response:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'DeleteAssistant',\n-\t\t\t'variables' : {'assistantId': assistantId},\n-\t\t\t'query' : deleteAssistant\n-\t\t}]\n-\t\treturn self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\n-\tdef list(self, rawResponse: bool = False, parseWithAttribute: str = 'id') -> list:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'AssistantsQuery',\n-\t\t\t'variables' : dict(),\n-\t\t\t'query' : allAssistantsQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\t\tif rawResponse: return response\n-\n-\t\tif parseWithAttribute and parseWithAttribute != '':\n-\t\t\treturn [assistantItem[parseWithAttribute] for assistantItem in response['assistants']]\n-\n-\t\treturn response['assistants']\n-\n-\n-\tdef getTitleById(self, assistantId: str) -> str:\n-\t\treturn next((item['title'] for item in self.list(parseWithAttribute='') if item['id'] == assistantId), '')\n-\n-\n-\tdef exists(self, assistantId: str) -> bool:\n-\t\treturn any(itemId == assistantId for itemId in self.list())\n-\n-\n-\tdef extractSkillIdentifiersLegacy(self, assistantId: str) -> list:\n-\t\tskills = self._ctx.getBrowser().execute_script(f\"return window.__APOLLO_STATE__['Assistant:{assistantId}']['skills']\")\n-\n-\t\treturn [skill['id'].replace('Skill:', '') for skill in skills]\n-\n-\n-\tdef extractSkillIdentifiers(self, assistantId: str) -> list:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'AssistantWithSkillsQuery',\n-\t\t\t'variables': {'assistantId': assistantId},\n-\t\t\t'query': assistantWithSkillsQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\treturn [skill['id'] for skill in response['assistant']['skills']]\n-\n-\n-\tdef forkAssistantSkill(self, assistantId: str, sourceSkillId: str) -> str:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'forkAssistantSkill',\n-\t\t\t'variables' : {'assistantId': assistantId, 'skillId': sourceSkillId},\n-\t\t\t'query' : forkAssistantSkill\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\treturn response['forkAssistantSkill']['copiedBundleId']\n-\n-\t@staticmethod\n-\tdef trainAssistant(_assistantId: str) -> bool:\n-\t\t# gqlRequest = [{\n-\t\t# \t'operationName': 'TrainAssistantV2',\n-\t\t# \t'variables': {'assistantId': assistantId},\n-\t\t# \t'query': trainAssistant\n-\t\t# }]\n-\t\treturn True\n-\n-\tdef trainingStatusAssistantReady(self, assistantId: str) -> bool:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'AssistantTrainingStatusQuery',\n-\t\t\t'variables': {'assistantId': assistantId},\n-\t\t\t'query': assistantTrainingStatusQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\tasrProgress = response['assistant']['training']['asrStatus']['inProgress']\n-\t\tasrResult = response['assistant']['training']['asrStatus']['trainingResult']\n-\t\tasrNeedTraining = response['assistant']['training']['asrStatus']['needTraining']\n-\n-\t\tnluProgress = response['assistant']['training']['nluStatus']['inProgress']\n-\t\tnluResult = response['assistant']['training']['nluStatus']['trainingResult']\n-\t\tnluNeedTraining = response['assistant']['training']['nluStatus']['needTraining']\n-\n-\t\treturn not asrProgress and not asrNeedTraining and asrResult == 'ok' \\\n-\t\t\tand not nluProgress and not nluNeedTraining and nluResult == 'ok'\ndiff --git a/core/snips/samkilla/Entity.py b/core/snips/samkilla/Entity.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/Entity.py\n+++ /dev/null\n@@ -1,169 +0,0 @@\n-import typing\n-\n-from core.snips import SamkillaManager\n-from core.snips.samkilla.gql.entities.createIntentEntity import createIntentEntity\n-from core.snips.samkilla.gql.entities.deleteIntentEntity import deleteIntentEntity\n-from core.snips.samkilla.gql.entities.patchIntentEntity import patchIntentEntity\n-from core.snips.samkilla.gql.entities.queries import customEntitiesWithUsageQuery, fullCustomEntityQuery\n-\n-\n-class Entity:\n-\n-\tdef __init__(self, ctx: SamkillaManager):\n-\t\tself._ctx = ctx\n-\t\tself._cacheInit = False\n-\t\tself._entitiesCache = {'cacheId': dict(), 'cacheName': dict()}\n-\n-\n-\tdef getEntityByUserEmailAndEntityName(self, userEmail: str, entityName: str) -> str:\n-\t\treturn self._entitiesCache['cacheName'].get(entityName, self.listEntitiesByUserEmail(userEmail, entityFilter=entityName, entityFilterAttribute='name'))\n-\n-\n-\tdef getEntityByUserEmailAndEntityId(self, userEmail: str, entityId: str) -> str:\n-\t\treturn self._entitiesCache['cacheId'].get(entityId, self.listEntitiesByUserEmail(userEmail, entityFilter=entityId))\n-\n-\n-\tdef listEntitiesByUserEmail(self, userEmail: str, entityFilter: str = None, languageFilter: str = None, entityFilterAttribute: str = 'id', returnAllCacheIndexedBy: list = None) -> dict:\n-\t\tvariables = {'email': userEmail}\n-\n-\t\tif languageFilter:\n-\t\t\tvariables['lang'] = languageFilter\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'customEntitiesWithUsageQuery',\n-\t\t\t'variables' : variables,\n-\t\t\t'query' : customEntitiesWithUsageQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\tfor entity in response['entities']:\n-\t\t\tself._entitiesCache['cacheId'][entity['id']] = entity\n-\t\t\tself._entitiesCache['cacheName'][entity['name']] = entity\n-\n-\t\tself._cacheInit = True\n-\n-\t\tif returnAllCacheIndexedBy:\n-\t\t\tkey = returnAllCacheIndexedBy[0].upper() + returnAllCacheIndexedBy[1:]\n-\t\t\treturn self._entitiesCache['cache' + key]\n-\n-\t\tif entityFilter:\n-\t\t\tif entityFilterAttribute == 'id':\n-\t\t\t\treturn self._entitiesCache['cacheId'][entityFilter]\n-\t\t\telif entityFilterAttribute == 'name':\n-\t\t\t\treturn self._entitiesCache['cacheName'][entityFilter]\n-\n-\t\treturn response['entities']\n-\n-\n-\tdef listEntitiesByUserEmailAndIntentId(self, userEmail: str, intentId: str, languageFilter: str = None, indexedBy: str = None, fromCache: bool = False) -> typing.Iterable:\n-\t\tif fromCache and self._cacheInit:\n-\t\t\tentities = self._entitiesCache['cacheId'].values()\n-\t\telse:\n-\t\t\tentities = self.listEntitiesByUserEmail(userEmail=userEmail, languageFilter=languageFilter)\n-\n-\t\tintentEntities = list()\n-\t\tindexedIntentEntities = dict()\n-\n-\t\tfor entity in entities:\n-\t\t\tfor intentMeta in entity['usedIn'] or list():\n-\t\t\t\tif intentMeta['intentId'] == intentId:\n-\t\t\t\t\tif indexedBy:\n-\t\t\t\t\t\tindexedIntentEntities[entity[indexedBy]] = entity\n-\t\t\t\t\telse:\n-\t\t\t\t\t\tintentEntities.append(entity)\n-\n-\t\treturn indexedIntentEntities if indexedBy else intentEntities\n-\n-\n-\tdef listEntityValuesByEntityId(self, entityId: str) -> str:\n-\t\tvariables = {'entityId': entityId}\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'FullCustomEntityQuery',\n-\t\t\t'variables' : variables,\n-\t\t\t'query' : fullCustomEntityQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\treturn response['entity']['data']\n-\n-\n-\t@staticmethod\n-\tdef formatSlotValues(slotValues: list) -> list:\n-\t\treturn [{\n-\t\t\t'value' : slotValue['value'],\n-\t\t\t'synonyms' : slotValue.get('synonyms', list()),\n-\t\t\t'fromWikilists': None\n-\t\t} for slotValue in slotValues]\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef create(self, name: str, language: str, matchingStrictness: int = 1, automaticallyExtensible: bool = False, useSynonyms: bool = True, slotValues: list = None) -> str:\n-\t\t\"\"\"\n-\t\tWarning: mind the language parameter if the assistant language is EN, entity must set language to EN\n-\t\tno error will be shown and the entity won't be created\n-\t\t\"\"\"\n-\n-\t\t# Slot values exemple:\n-\t\t# [ {'value': 'room'}, {'value': 'house', 'synonyms': ['entire house']} ]\n-\t\tformattedSlotValues = self.formatSlotValues(slotValues) if slotValues else list()\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'createIntentEntity',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': {\n-\t\t\t\t\t'author' : self._ctx.userEmail,\n-\t\t\t\t\t'automaticallyExtensible': automaticallyExtensible,\n-\t\t\t\t\t'data' : formattedSlotValues,\n-\t\t\t\t\t'language' : language,\n-\t\t\t\t\t'name' : name,\n-\t\t\t\t\t'private' : True,\n-\t\t\t\t\t'useSynonyms' : useSynonyms\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : createIntentEntity\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\t\tcreatedEntityId = response['createIntentEntity']['id']\n-\n-\t\treturn createdEntityId\n-\n-\n-\tdef edit(self, entityId: str, name: str = None, automaticallyExtensible: bool = False, matchingStrictness: int = None, useSynonyms: bool = False, slotValues: list = None):\n-\t\t\"\"\"\n-\t\tSlot values must include old values AND the new one\n-\t\t\"\"\"\n-\n-\t\tinputt = dict()\n-\n-\t\tif name: inputt['name'] = name\n-\t\tif automaticallyExtensible: inputt['automaticallyExtensible'] = automaticallyExtensible\n-\t\tif matchingStrictness: inputt['matchingStrictness'] = matchingStrictness\n-\t\tif useSynonyms: inputt['useSynonyms'] = useSynonyms\n-\n-\t\tif slotValues:\n-\t\t\tinputt['data'] = self.formatSlotValues(slotValues)\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'patchIntentEntity',\n-\t\t\t'variables' : {\n-\t\t\t\t'intentEntityId': entityId,\n-\t\t\t\t'input' : inputt\n-\t\t\t},\n-\t\t\t'query' : patchIntentEntity\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef delete(self, entityId: str, language: str = None):\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'deleteIntentEntity',\n-\t\t\t'variables' : {\n-\t\t\t\t'email': self._ctx.userEmail,\n-\t\t\t\t'id' : entityId\n-\t\t\t\t# 'lang': language # seems it's not mandatory\n-\t\t\t},\n-\t\t\t'query' : deleteIntentEntity\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\ndiff --git a/core/snips/samkilla/Intent.py b/core/snips/samkilla/Intent.py\ndeleted file mode 100755\n--- a/core/snips/samkilla/Intent.py\n+++ /dev/null\n@@ -1,355 +0,0 @@\n-import hashlib\n-import re\n-import typing\n-\n-from core.ProjectAliceExceptions import HttpError, IntentError, IntentWithUnknownSlotError\n-from core.snips import SamkillaManager\n-from core.snips.samkilla.gql.intents.deleteIntent import deleteIntent\n-from core.snips.samkilla.gql.intents.publishIntent import publishIntent\n-from core.snips.samkilla.gql.intents.queries import fullIntentQuery, intentsByUserIdWithUsageQuery\n-from core.snips.samkilla.gql.skills.patchSkillIntents import patchSkillIntents\n-\n-UTTERANCES_DEFINITION_REGEX = re.compile(r'{(.*?):=>(.*?)}')\n-\n-\n-class Intent:\n-\tGLUE_SLOT_WORD = ':=>'\n-\n-\n-\tdef __init__(self, ctx: SamkillaManager):\n-\t\tself._ctx = ctx\n-\t\tself._cacheInit = False\n-\t\tself._intentsCache = {'cacheId': dict(), 'cacheName': dict()}\n-\n-\n-\tdef getIntentByUserIdAndIntentName(self, userId: str, intentName: str) -> dict:\n-\t\treturn self._intentsCache['cacheName'].get(intentName.lower(), self.listIntentsByUserId(userId, intentFilter=intentName, intentFilterAttribute='name'))\n-\n-\n-\tdef getIntentByUserIdAndIntentId(self, userId: str, intentId: str) -> dict:\n-\t\treturn self._intentsCache['cacheId'].get(intentId, self.listIntentsByUserId(userId, intentFilter=intentId))\n-\n-\n-\tdef listIntentsByUserId(self, userId: str, intentFilter: str = None, languageFilter: str = None, intentFilterAttribute: str = 'id', returnAllCacheIndexedBy: str = None) -> dict:\n-\t\tvariables = {'userId': userId}\n-\n-\t\tif languageFilter:\n-\t\t\tvariables['lang'] = languageFilter\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'IntentsByUserIdWithUsageQuery',\n-\t\t\t'variables' : variables,\n-\t\t\t'query' : intentsByUserIdWithUsageQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\tself._cacheInit = True\n-\n-\t\tfor intent in response['intents']:\n-\t\t\tself._intentsCache['cacheId'][intent['id']] = intent\n-\t\t\tself._intentsCache['cacheName'][intent['name'].lower()] = intent\n-\n-\t\tif returnAllCacheIndexedBy:\n-\t\t\tkey = returnAllCacheIndexedBy[0].upper() + returnAllCacheIndexedBy[1:]\n-\t\t\treturn self._intentsCache['cache' + key]\n-\n-\t\tif intentFilter:\n-\t\t\tif intentFilterAttribute == 'id':\n-\t\t\t\treturn self._intentsCache['cacheId'][intentFilter]\n-\t\t\telif intentFilterAttribute == 'name':\n-\t\t\t\treturn self._intentsCache['cacheName'][intentFilter.lower()]\n-\n-\t\treturn response['intents']\n-\n-\n-\tdef listIntentsByUserIdAndSkillId(self, userId: str, skillId: str, languageFilter: str = None, indexedBy: str = None, fromCache: bool = False) -> typing.Iterable:\n-\t\tif fromCache and self._cacheInit:\n-\t\t\tintents = self._intentsCache['cacheId'].values()\n-\t\telse:\n-\t\t\tintents = self.listIntentsByUserId(userId=userId, languageFilter=languageFilter)\n-\n-\t\tskillIntents = list()\n-\t\tindexedSkillIntents = dict()\n-\n-\t\tfor intent in intents:\n-\t\t\tfor skillMeta in intent['usedIn'] or list():\n-\t\t\t\tif skillMeta['skillId'] == skillId:\n-\t\t\t\t\tif indexedBy:\n-\t\t\t\t\t\tindexedSkillIntents[intent[indexedBy]] = intent\n-\t\t\t\t\telse:\n-\t\t\t\t\t\tskillIntents.append(intent)\n-\n-\t\treturn indexedSkillIntents if indexedBy else skillIntents\n-\n-\n-\tdef listUtterancesByIntentId(self, intentId: str) -> list:\n-\t\tvariables = {'intentId': intentId}\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'FullIntentQuery',\n-\t\t\t'variables' : variables,\n-\t\t\t'query' : fullIntentQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\treturn response['intent']['customIntentData']['utterances']\n-\n-\n-\tdef create(self, userId: str, language: str, skillId: str, name: str = 'Untitled', description: str = '', enabledByDefault: bool = True,\n-\t\t\t attachToSkill: bool = True, typeEntityMatching: dict = None, slotsDefinition: dict = None, utterancesDefinition: list = None) -> str:\n-\t\t\"\"\"\n-\t\tWarning: mind the language parameter if the skill language is EN, intent must set language to EN\n-\t\tno error will be shown and the skill won't be created\n-\t\t\"\"\"\n-\n-\t\tstructuredSlots, entities = self.formatSlotsAndEntities(typeEntityMatching, slotsDefinition)\n-\t\tstructuredUtterances, exempleQueries = self.formatUtterancesAndExempleQueries(utterancesDefinition)\n-\n-\t\tfinalStructuredUtterances = structuredUtterances or [{'data': [{'range': {'start': 0, 'end': 0}, 'text': ''}]}]\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'publishIntent',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': {\n-\t\t\t\t\t'config' : {\n-\t\t\t\t\t\t'author' : self._ctx.userEmail,\n-\t\t\t\t\t\t'description' : description,\n-\t\t\t\t\t\t'displayName' : name,\n-\t\t\t\t\t\t'enabledByDefault': enabledByDefault,\n-\t\t\t\t\t\t'exampleQueries' : exempleQueries,\n-\t\t\t\t\t\t'language' : language,\n-\t\t\t\t\t\t'name' : name,\n-\t\t\t\t\t\t'private' : True,\n-\t\t\t\t\t\t'slots' : structuredSlots,\n-\t\t\t\t\t\t'version' : '0'\n-\t\t\t\t\t},\n-\t\t\t\t\t'dataset': {\n-\t\t\t\t\t\t'entities' : entities,\n-\t\t\t\t\t\t'language' : language,\n-\t\t\t\t\t\t'utterances': finalStructuredUtterances\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : publishIntent\n-\t\t}]\n-\n-\t\ttry:\n-\t\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\t\texcept IntentWithUnknownSlotError as iwuse:\n-\t\t\traise ValueError(f'Inconsistent intent, \"{iwuse.message}\" is using unknown Slots')\n-\t\texcept HttpError as he:\n-\t\t\tif he.status == 409:\n-\t\t\t\tself._ctx.log(f'Duplicate intent with name {name}')\n-\t\t\t\tintentDuplicate = self.getIntentByUserIdAndIntentName(userId, name)\n-\n-\t\t\t\tif intentDuplicate:\n-\t\t\t\t\tif 'usedIn' in intentDuplicate and intentDuplicate['usedIn']:\n-\t\t\t\t\t\tfor skillItem in intentDuplicate['usedIn']:\n-\t\t\t\t\t\t\tself.removeFromSkill(intentId=intentDuplicate['id'], skillId=skillItem['skillId'], userId=userId, deleteAfter=False)\n-\t\t\t\t\tself.delete(intentId=intentDuplicate['id'])\n-\t\t\t\t\treturn self.create(userId, language, skillId, name, description, enabledByDefault, attachToSkill, typeEntityMatching, slotsDefinition, utterancesDefinition)\n-\n-\t\t\traise he\n-\n-\t\tcreatedIntentId = response['publishIntent']['id']\n-\n-\t\tif attachToSkill:\n-\t\t\tself.attachToSkill(userId=userId, skillId=skillId, intentId=createdIntentId, languageFilter=language)\n-\n-\t\treturn createdIntentId\n-\n-\n-\tdef attachToSkill(self, userId: str, skillId: str, intentId: str, languageFilter: str = None):\n-\t\texistingIntents = self.listIntentsByUserIdAndSkillId(userId=userId, skillId=skillId, languageFilter=languageFilter)\n-\t\tvariablesIntents = [{'id': intentId}]\n-\n-\t\tfor existingIntent in existingIntents:\n-\t\t\tvariablesIntents.append({'id': existingIntent['id']})\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'patchSkillIntents',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': {\n-\t\t\t\t\t'id' : skillId,\n-\t\t\t\t\t'intents': variablesIntents\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : patchSkillIntents\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\n-\tdef removeFromSkill(self, userId: str, skillId: str, intentId: str, languageFilter: str = None, deleteAfter: bool = True):\n-\t\texistingIntents = self.listIntentsByUserIdAndSkillId(userId=userId, skillId=skillId, languageFilter=languageFilter)\n-\n-\t\tvariablesIntents = [{'id': x['id']} for x in existingIntents if x['id'] != intentId]\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'patchSkillIntents',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': {\n-\t\t\t\t\t'id' : skillId,\n-\t\t\t\t\t'intents': variablesIntents\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : patchSkillIntents\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\t\tif deleteAfter:\n-\t\t\tself.delete(intentId=intentId)\n-\n-\n-\tdef delete(self, intentId: str):\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'deleteIntent',\n-\t\t\t'variables' : {'intentId': intentId},\n-\t\t\t'query' : deleteIntent\n-\t\t}]\n-\t\treturn self._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\n-\tdef edit(self, intentId: str, userId: str, language: str = None, skillId: str = None, name: str = None, description: str = None, enabledByDefault: bool = True,\n-\t\t\t attachToSkill: bool = False, typeEntityMatching: dict = None, slotsDefinition: dict = None, utterancesDefinition: list = None):\n-\t\tstructuredSlots, entities = self.formatSlotsAndEntities(typeEntityMatching, slotsDefinition)\n-\t\tstructuredUtterances, exempleQueries = self.formatUtterancesAndExempleQueries(utterancesDefinition)\n-\n-\t\tintent = self.getIntentByUserIdAndIntentId(userId=userId, intentId=intentId)\n-\n-\t\tif not intent:\n-\t\t\traise IntentError(4003, f'Intent {intentId} doesn\\'t exist', ['intent'])\n-\n-\t\tif name: intent['name'] = name\n-\t\tif description: intent['description'] = description\n-\t\tif enabledByDefault: intent['enabledByDefault'] = enabledByDefault\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'publishIntent',\n-\t\t\t'variables' : {\n-\t\t\t\t'intentId': intentId,\n-\t\t\t\t'input' : {\n-\t\t\t\t\t'config' : {\n-\t\t\t\t\t\t'author' : intent['author'],\n-\t\t\t\t\t\t'description' : intent['description'],\n-\t\t\t\t\t\t'displayName' : intent['displayName'],\n-\t\t\t\t\t\t'enabledByDefault': intent['enabledByDefault'],\n-\t\t\t\t\t\t'language' : intent['language'],\n-\t\t\t\t\t\t'exampleQueries' : exempleQueries,\n-\t\t\t\t\t\t'slots' : structuredSlots,\n-\t\t\t\t\t\t'version' : intent['version'],\n-\t\t\t\t\t\t'name' : intent['name'],\n-\t\t\t\t\t\t'private' : True,\n-\t\t\t\t\t},\n-\t\t\t\t\t'dataset': {\n-\t\t\t\t\t\t'entities' : entities,\n-\t\t\t\t\t\t'language' : intent['language'],\n-\t\t\t\t\t\t'utterances': structuredUtterances\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : publishIntent\n-\t\t}]\n-\n-\t\ttry:\n-\t\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\t\t\tif attachToSkill:\n-\t\t\t\tself.attachToSkill(userId=userId, skillId=skillId, intentId=intentId, languageFilter=language)\n-\n-\t\texcept IntentWithUnknownSlotError as iwuse:\n-\t\t\tself._ctx.log(f'Inconsistent intent, \"{iwuse.message}\" is using unknown Slots')\n-\n-\tdef formatSlotsAndEntities(self, typeEntityMatching: dict, slotsDefinition: dict) -> tuple:\n-\t\tentities = list()\n-\t\tstructuredSlots = list()\n-\n-\t\tfor slot in slotsDefinition:\n-\t\t\tsnipsSpecialSlot = slot['type'].startswith('snips/')\n-\n-\t\t\tif slot['type'] not in typeEntityMatching and not snipsSpecialSlot:\n-\t\t\t\tcontinue\n-\n-\t\t\tslotEntityId = slot['type'] if snipsSpecialSlot else typeEntityMatching[slot['type']]['entityId']\n-\n-\t\t\tentities.append({'id': slotEntityId, 'name': slotEntityId if snipsSpecialSlot else slot['type']})\n-\n-\t\t\tstructuredSlots.append({\n-\t\t\t\t'entityId' : slotEntityId,\n-\t\t\t\t'id' : self.hashSlotName(slotName=slot['name']),\n-\t\t\t\t'missingQuestion': slot['missingQuestion'],\n-\t\t\t\t'name' : slot['name'],\n-\t\t\t\t'description' : slot['description'],\n-\t\t\t\t'required' : slot['required'],\n-\t\t\t\t'parameters' : None\n-\t\t\t})\n-\n-\t\treturn structuredSlots, entities\n-\n-\n-\tdef formatUtterancesAndExempleQueries(self, utterances: list) -> tuple:\n-\t\texempleQueries = list()\n-\t\tstructuredUtterances = list()\n-\n-\t\tfor utterance in utterances:\n-\t\t\titems = UTTERANCES_DEFINITION_REGEX.findall(utterance)\n-\n-\t\t\tformattedTextUtterance = utterance\n-\t\t\tformattedParsedUtterance = utterance\n-\t\t\tdata = list()\n-\n-\t\t\tlastPieceIndex = 0\n-\t\t\tsumIndexOffset = 0\n-\t\t\tcounterItems = 0\n-\t\t\tmaxItems = len(items)\n-\n-\t\t\tfor item in items:\n-\t\t\t\twordExemple = item[0]\n-\t\t\t\twordSlotName = item[1]\n-\n-\t\t\t\tkeySlot = '{' + wordExemple + self.GLUE_SLOT_WORD + wordSlotName + '}'\n-\t\t\t\tkeyDummy = ''.join(['0'] * len(keySlot))\n-\n-\t\t\t\t# Text\n-\t\t\t\tformattedTextUtterance = formattedTextUtterance.replace(keySlot, wordExemple, 1)\n-\t\t\t\tlenCleanTextUtterance = len(formattedTextUtterance)\n-\n-\t\t\t\t# Parsed\n-\t\t\t\tindexOffset = len(keySlot) - len(wordExemple)\n-\t\t\t\twordSlotIndexStart = formattedParsedUtterance.find(keySlot)\n-\t\t\t\twordSlotIndexEnd = wordSlotIndexStart + len(wordExemple)\n-\n-\t\t\t\tformattedWordSlotIndexStart = wordSlotIndexStart - sumIndexOffset\n-\t\t\t\tformattedWordSlotIndexEnd = wordSlotIndexEnd - sumIndexOffset\n-\n-\t\t\t\t# for next parse processing\n-\t\t\t\tformattedParsedUtterance = formattedParsedUtterance.replace(keySlot, keyDummy, 1)\n-\n-\t\t\t\tif formattedWordSlotIndexStart != 0:\n-\t\t\t\t\tpreviousText = formattedTextUtterance[lastPieceIndex:formattedWordSlotIndexStart]\n-\t\t\t\t\tdata.append(\n-\t\t\t\t\t\t{'text': previousText, 'range': {'start': lastPieceIndex, 'end': formattedWordSlotIndexStart}}\n-\t\t\t\t\t)\n-\n-\t\t\t\tlastPieceIndex = formattedWordSlotIndexEnd\n-\t\t\t\tsumIndexOffset += indexOffset\n-\t\t\t\tcounterItems += 1\n-\n-\t\t\t\tdata.append({'slot_id': self.hashSlotName(slotName=wordSlotName), 'slot_name': wordSlotName, 'text': wordExemple,\n-\t\t\t\t\t\t\t 'range' : {'start': formattedWordSlotIndexStart, 'end': formattedWordSlotIndexEnd}})\n-\n-\t\t\t\tif counterItems == maxItems and lastPieceIndex < lenCleanTextUtterance:\n-\t\t\t\t\tendText = formattedTextUtterance[lastPieceIndex:lenCleanTextUtterance]\n-\t\t\t\t\tdata.append({'text': endText, 'range': {'start': lastPieceIndex, 'end': lenCleanTextUtterance}})\n-\n-\t\t\tif not data:\n-\t\t\t\tdata.append({'text': formattedTextUtterance, 'range': {'start': 0, 'end': len(formattedTextUtterance)}})\n-\n-\t\t\tstructuredUtterances.append({'data': data})\n-\t\t\texempleQueries.append(formattedTextUtterance)\n-\n-\t\treturn structuredUtterances, exempleQueries[0:10]\n-\n-\n-\t@staticmethod\n-\tdef hashSlotName(slotName: str) -> str:\n-\t\treturn hashlib.sha512(slotName.encode('utf-8')).hexdigest()[0:9]\ndiff --git a/core/snips/samkilla/Skill.py b/core/snips/samkilla/Skill.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/Skill.py\n+++ /dev/null\n@@ -1,234 +0,0 @@\n-import typing\n-\n-from core.ProjectAliceExceptions import HttpError\n-from core.snips import SamkillaManager\n-from core.snips.samkilla.gql.assistants.patchAssistantSkills import patchAssistantSkills\n-from core.snips.samkilla.gql.skills.createSkill import createSkill\n-from core.snips.samkilla.gql.skills.deleteSkill import deleteSkill\n-from core.snips.samkilla.gql.skills.editSkill import editSkill\n-from core.snips.samkilla.gql.skills.forkSkillIntent import forkSkillIntent\n-from core.snips.samkilla.gql.skills.queries import skillsWithUsageQuery\n-from core.snips.samkilla.models.EnumSkillImageUrl import EnumSkillImageUrl as EnumSkillImageUrlClass\n-\n-EnumSkillImageUrl = EnumSkillImageUrlClass()\n-\n-import re\n-\n-intent_regex = re.compile(r'intent_([a-zA-Z0-9]+)')\n-\n-\n-class Skill:\n-\n-\tdef __init__(self, ctx: SamkillaManager):\n-\t\tself._ctx = ctx\n-\t\tself._cacheInit = False\n-\t\tself._skillsCache = {'cacheId': dict(), 'cacheName': dict()}\n-\n-\n-\tdef getSkillByUserIdAndSkillName(self, userId: str, skillName: str):\n-\t\treturn self._skillsCache['cachename'].get(skillName, self.listSkillsByUserId(userId, skillFilter=skillName, skillFilterAttribute='name'))\n-\n-\n-\tdef getSkillByUserIdAndSkillId(self, userId: str, skillId: str):\n-\t\treturn self._skillsCache['cacheId'].get(skillId, self.listSkillsByUserId(userId, skillFilter=skillId))\n-\n-\n-\tdef listSkillsByUserId(self, userId: str, skillFilter: str = None, skillFilterAttribute: str = 'id', languageFilter: str = None,\n-\t\t\t\t\t\t intentId: str = None, returnAllCacheIndexedBy: str = None, page: int = 1, totalSkills: int = None) -> typing.Iterable:\n-\t\t#TODO this is strange totalSkills is a int when it is defined (typing) -> line 63 would throw since it tries to append\n-\t\tif not totalSkills:\n-\t\t\ttotalSkills = list()\n-\n-\t\tvariables = {\n-\t\t\t'userId': userId,\n-\t\t\t'offset': (page - 1) * 50,\n-\t\t\t'limit' : 50,\n-\t\t\t'sort' : 'lastUpdated'\n-\t\t}\n-\n-\t\t# 50 is the max limit server side\n-\t\tif languageFilter: variables['lang'] = languageFilter\n-\t\tif intentId: variables['intentId'] = intentId\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'SkillsWithUsageQuery',\n-\t\t\t'variables' : variables,\n-\t\t\t'query' : skillsWithUsageQuery\n-\t\t}]\n-\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\tfor skill in response['skills']['skills']:\n-\t\t\tself._skillsCache['cacheId'][skill['id']] = skill\n-\t\t\tself._skillsCache['cacheName'][skill['name']] = skill\n-\t\t\ttotalSkills.append(skill)\n-\n-\t\tif (page - 1) * 50 < response['skills']['pagination']['total']:\n-\t\t\treturn self.listSkillsByUserId(userId, skillFilter, skillFilterAttribute, languageFilter, intentId, returnAllCacheIndexedBy, page=page + 1, totalSkills=totalSkills)\n-\n-\t\tself._cacheInit = True\n-\n-\t\tif returnAllCacheIndexedBy:\n-\t\t\tkey = returnAllCacheIndexedBy[0].upper() + returnAllCacheIndexedBy[1:]\n-\t\t\treturn self._skillsCache['cache' + key]\n-\n-\t\tif skillFilter:\n-\t\t\tif skillFilterAttribute == 'id':\n-\t\t\t\treturn self._skillsCache['cacheId'][skillFilter]\n-\t\t\telif skillFilterAttribute == 'name':\n-\t\t\t\treturn self._skillsCache['cacheName'][skillFilter]\n-\n-\t\treturn totalSkills\n-\n-\n-\tdef listSkillsByUserIdAndAssistantId(self, userId: str, assistantId: str, languageFilter: str = None, indexedBy: str = None, fromCache: bool = False) -> typing.Iterable:\n-\t\tif fromCache and self._cacheInit:\n-\t\t\tskills = self._skillsCache['cacheId'].values()\n-\t\telse:\n-\t\t\tskills = self.listSkillsByUserId(userId=userId, languageFilter=languageFilter)\n-\n-\t\tassistantSkills = list()\n-\t\tindexedAssistantSkills = dict()\n-\n-\t\tfor skill in skills:\n-\t\t\tfor assistantMeta in skill['usedIn'] or list():\n-\t\t\t\tif assistantMeta['assistantId'] == assistantId:\n-\t\t\t\t\tif indexedBy:\n-\t\t\t\t\t\tindexedAssistantSkills[skill[indexedBy]] = skill\n-\t\t\t\t\telse:\n-\t\t\t\t\t\tassistantSkills.append(skill)\n-\n-\t\treturn indexedAssistantSkills if indexedBy else assistantSkills\n-\n-\n-\tdef create(self, assistantId: str, language: str, name: str = 'Untitled', description: str = '', imageKey: str = EnumSkillImageUrl.default,\n-\t\t\t attachToAssistant: bool = True, intents: typing.Iterable = None) -> str:\n-\t\t\"\"\"\n-\t\tWarning: mind the language parameter if the assistant language is EN, skill must set language to EN\n-\t\tno error will be shown and the skill won't be created\n-\t\t\"\"\"\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'createSkill',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': {\n-\t\t\t\t\t'description': description,\n-\t\t\t\t\t'imageUrl' : EnumSkillImageUrl.getImageUrl(self._ctx.ROOT_URL, imageKey),\n-\t\t\t\t\t'intents' : intents or list(),\n-\t\t\t\t\t'language' : language,\n-\t\t\t\t\t'name' : name,\n-\t\t\t\t\t'private' : True\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : createSkill\n-\t\t}]\n-\t\tresp = self._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\tcreatedSkillId = resp['createSkill']['id']\n-\n-\t\tif attachToAssistant:\n-\t\t\tself.attachToAssistant(assistantId=assistantId, skillId=createdSkillId)\n-\n-\t\treturn createdSkillId\n-\n-\n-\tdef attachToAssistant(self, assistantId: str, skillId: str):\n-\t\texistingSkills = self._ctx.assistant.extractSkillIdentifiers(assistantId=assistantId)\n-\t\tvariablesSkills = [{'id': skillId, 'parameters': None}]\n-\n-\t\tfor existingSkillId in existingSkills:\n-\t\t\tvariablesSkills.append({'id': existingSkillId, 'parameters': None})\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'PatchAssistantSkills',\n-\t\t\t'variables' : {\n-\t\t\t\t'assistantId': assistantId,\n-\t\t\t\t'input' : {\n-\t\t\t\t\t'skills': variablesSkills\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : patchAssistantSkills\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\t\t# Mandatory after a create action to update APOLLO_STATE, @TODO maybe update the state manually to improve performances ?\n-\t\tself._ctx.reloadBrowserPage()\n-\n-\n-\tdef edit(self, skillId: str, name: str = None, description: str = None, imageKey: str = None):\n-\t\tinputt = {'id': skillId}\n-\n-\t\tif name: inputt['name'] = name\n-\t\tif description: inputt['description'] = description\n-\t\tif imageKey: inputt['imageUrl'] = EnumSkillImageUrl.getImageUrl(self._ctx.ROOT_URL, imageKey)\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'editSkill',\n-\t\t\t'variables' : {\n-\t\t\t\t'input': inputt\n-\t\t\t},\n-\t\t\t'query' : editSkill\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\n-\tdef delete(self, skillId: str, reload: bool = True):\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'deleteSkill',\n-\t\t\t'variables' : {'skillId': skillId},\n-\t\t\t'query' : deleteSkill\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest)\n-\n-\t\tif reload:\n-\t\t\t# Mandatory after a create action to update APOLLO_STATE, @TODO maybe update the state manually to improve performances ?\n-\t\t\tself._ctx.reloadBrowserPage()\n-\n-\n-\tdef removeFromAssistant(self, assistantId: str, skillId: str, deleteAfter: str = False):\n-\t\texistingSkills = self._ctx.assistant.extractSkillIdentifiers(assistantId=assistantId)\n-\t\tvariablesSkills = [{'id': x, 'parameters': None} for x in existingSkills if x != skillId]\n-\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'PatchAssistantSkills',\n-\t\t\t'variables' : {\n-\t\t\t\t'assistantId': assistantId,\n-\t\t\t\t'input' : {\n-\t\t\t\t\t'skills': variablesSkills\n-\t\t\t\t}\n-\t\t\t},\n-\t\t\t'query' : patchAssistantSkills\n-\t\t}]\n-\t\tself._ctx.postGQLBrowserly(gqlRequest, rawResponse=True)\n-\n-\t\tif deleteAfter:\n-\t\t\tself.delete(skillId=skillId, reload=False)\n-\n-\t\t# Mandatory after a create action to update APOLLO_STATE, @TODO maybe update the state manually to improve performances ?\n-\t\tself._ctx.reloadBrowserPage()\n-\n-\n-\tdef forkSkillIntent(self, skillId: str, sourceIntentId: str, userId: str, newIntentName: str = None) -> str:\n-\t\tgqlRequest = [{\n-\t\t\t'operationName': 'forkSkillIntent',\n-\t\t\t'variables' : {'skillId': skillId, 'intentId': sourceIntentId, 'newIntentName': newIntentName},\n-\t\t\t'query' : forkSkillIntent\n-\t\t}]\n-\n-\t\ttry:\n-\t\t\tresponse = self._ctx.postGQLBrowserly(gqlRequest)\n-\t\texcept HttpError as he:\n-\t\t\titems = intent_regex.findall(he.message)\n-\n-\t\t\tif len(items) == 1:\n-\t\t\t\toldIntentId = f'intent_{items[0]}'\n-\t\t\t\tintentDuplicate = self._ctx.intent.getIntentByUserIdAndIntentId(userId, oldIntentId)\n-\t\t\t\tself._ctx.log(f\"Duplicate intent with id, name {oldIntentId}, {intentDuplicate['name']}\")\n-\n-\t\t\t\tfor skillItem in intentDuplicate.get('usedIn') or list():\n-\t\t\t\t\tself._ctx.intent.removeFromSkill(intentId=intentDuplicate['id'], skillId=skillItem['skillId'], userId=userId, deleteAfter=False)\n-\t\t\t\tself._ctx.intent.delete(intentId=intentDuplicate['id'])\n-\t\t\t\treturn self.forkSkillIntent(skillId, sourceIntentId, userId, newIntentName)\n-\n-\t\t\traise he\n-\n-\t\treturn response['forkSkillIntent']['intentCopied']['id']\ndiff --git a/core/snips/samkilla/gql/assistants/createAssistant.py b/core/snips/samkilla/gql/assistants/createAssistant.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/assistants/createAssistant.py\n+++ /dev/null\n@@ -1,14 +0,0 @@\n-from core.snips.samkilla.gql.assistants.queries import assistantFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-createAssistant = gql('''\n-mutation CreateAssistant($input: CreateAssistantInput!) {\n-\tcreateAssistant(input: $input) {\n-\t\t...AssistantFieldsFragment\n-\t\tskills {\n-\t\t id\n-\t\t}\n-\t}\n-}\n-${assistantFieldsFragment}\n-''', {'assistantFieldsFragment': assistantFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/assistants/deleteAssistant.py b/core/snips/samkilla/gql/assistants/deleteAssistant.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/assistants/deleteAssistant.py\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-deleteAssistant = gql('''\n-mutation DeleteAssistant($assistantId: ID!) {\n- deleteAssistant(assistantId: $assistantId) {\n-\tid\n- }\n-}\n-''')\ndiff --git a/core/snips/samkilla/gql/assistants/forkAssistantSkill.py b/core/snips/samkilla/gql/assistants/forkAssistantSkill.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/assistants/forkAssistantSkill.py\n+++ /dev/null\n@@ -1,23 +0,0 @@\n-from core.snips.samkilla.gql.skills.queries import skillFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-forkAssistantSkill = gql('''\n-mutation forkAssistantSkill($assistantId: ID!, $skillId: ID!) {\n- forkAssistantSkill(assistantId: $assistantId, skillId: $skillId) {\n-\tcopiedBundleId\n-\tassistant {\n-\t id\n-\t title\n-\t userId\n-\t language\n-\t skills {\n-\t\tintents {\n-\t\t id\n-\t\t}\n-\t\t...SkillFieldsFragment\n-\t }\n-\t}\n- }\n-}\n-${skillFieldsFragment}\n-''', {'skillFieldsFragment': skillFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/assistants/patchAssistant.py b/core/snips/samkilla/gql/assistants/patchAssistant.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/assistants/patchAssistant.py\n+++ /dev/null\n@@ -1,11 +0,0 @@\n-from core.snips.samkilla.gql.assistants.queries import assistantFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-patchAssistant = gql('''\n-mutation PatchAssistant($assistantId: ID!, $input: PatchAssistantInput!) {\n- patchAssistant(id: $assistantId, input: $input) {\n-\t...AssistantFieldsFragment\n- }\n-}\n-${assistantFieldsFragment}\n-''', {'assistantFieldsFragment': assistantFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/assistants/patchAssistantSkills.py b/core/snips/samkilla/gql/assistants/patchAssistantSkills.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/assistants/patchAssistantSkills.py\n+++ /dev/null\n@@ -1,22 +0,0 @@\n-from core.snips.samkilla.gql.skills.queries import skillFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-patchAssistantSkills = gql('''\n-mutation PatchAssistantSkills(\n- $assistantId: ID!\n- $input: PatchAssistantInput!\n-) {\n- patchAssistant(id: $assistantId, input: $input) {\n-\tid\n-\tskills {\n-\t intents {\n-\t\tid\n-\t\taction\n-\t\tversion\n-\t }\n-\t ...SkillFieldsFragment\n-\t}\n- }\n-}\n-${skillFieldsFragment}\n-''', {'skillFieldsFragment': skillFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/assistants/queries.py b/core/snips/samkilla/gql/assistants/queries.py\ndeleted file mode 100755\n--- a/core/snips/samkilla/gql/assistants/queries.py\n+++ /dev/null\n@@ -1,80 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-from core.snips.samkilla.gql.skills.queries import skillFieldsFragment\n-from core.snips.samkilla.gql.training.queries import trainingStatusFieldsFragment\n-\n-assistantFieldsFragment = gql('''\n-fragment AssistantFieldsFragment on Assistant {\n- id\n- title\n- userId\n- language\n- confidenceThreshold\n- hotwordId\n- lastUpdatedAt\n- platform {\n- type\n- }\n- asr {\n- type\n- }\n- }\n-''')\n-\n-allAssistantsQuery = gql('''\n-query AssistantsQuery {\n- assistants {\n- ...AssistantFieldsFragment\n- skills {\n- id\n- intents {\n- id\n- version\n- action\n- }\n- }\n- }\n- }\n- ${assistantFieldsFragment}\n-''', {'assistantFieldsFragment': assistantFieldsFragment})\n-\n-\n-assistantWithSkillsQuery = gql('''\n- query AssistantWithSkillsQuery($assistantId: ID!) {\n- assistant(assistantId: $assistantId) {\n- ...AssistantFieldsFragment\n- skills {\n- ...SkillFieldsFragment\n- intents {\n- id\n- version\n- action\n- }\n- }\n- }\n- }\n- ${assistantFieldsFragment}\n- ${skillFieldsFragment}\n-''', {\n-\t'assistantFieldsFragment': assistantFieldsFragment,\n-\t'skillFieldsFragment': skillFieldsFragment\n-})\n-\n-\n-\n-assistantTrainingStatusQuery = gql('''\n- query AssistantTrainingStatusQuery($assistantId: ID!) {\n- assistant(assistantId: $assistantId) {\n- id\n- training {\n- nluStatus {\n- ...TrainingStatusFieldsFragment\n- }\n- asrStatus {\n- ...TrainingStatusFieldsFragment\n- }\n- approximateDownloadSize\n- }\n- }\n- }\n- ${trainingStatusFieldsFragment}\n-''',{'trainingStatusFieldsFragment': trainingStatusFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/assistants/trainAssistant.py b/core/snips/samkilla/gql/assistants/trainAssistant.py\ndeleted file mode 100755\n--- a/core/snips/samkilla/gql/assistants/trainAssistant.py\n+++ /dev/null\n@@ -1,7 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-trainAssistant = gql('''\n- mutation TrainAssistantV2($assistantId: ID!, $trainingType: String) {\n- trainAssistantV2(assistantId: $assistantId, trainingType: $trainingType)\n- }\n-''')\ndiff --git a/core/snips/samkilla/gql/entities/createIntentEntity.py b/core/snips/samkilla/gql/entities/createIntentEntity.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/entities/createIntentEntity.py\n+++ /dev/null\n@@ -1,15 +0,0 @@\n-from core.snips.samkilla.gql.entities.queries import entityFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-createIntentEntity = gql('''\n-mutation createIntentEntity($input: CreateIntentEntityInput!) {\n- createIntentEntity(input: $input) {\n-\t...EntityFieldsFragment\n-\tusedIn {\n-\t intentId\n-\t intentName\n-\t}\n- }\n-}\n-${entityFieldsFragment}\n-''', {'entityFieldsFragment': entityFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/entities/deleteIntentEntity.py b/core/snips/samkilla/gql/entities/deleteIntentEntity.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/entities/deleteIntentEntity.py\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-deleteIntentEntity = gql('''\n-mutation deleteIntentEntity($id: ID!, $email: String!) {\n- deleteIntentEntity(id: $id, email: $email) {\n-\tid\n- }\n-}\n-''')\ndiff --git a/core/snips/samkilla/gql/entities/patchIntentEntity.py b/core/snips/samkilla/gql/entities/patchIntentEntity.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/entities/patchIntentEntity.py\n+++ /dev/null\n@@ -1,14 +0,0 @@\n-from core.snips.samkilla.gql.entities.queries import fullCustomEntityFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-patchIntentEntity = gql('''\n-mutation patchIntentEntity(\n- $intentEntityId: ID!\n- $input: PatchIntentEntityInput!\n-) {\n- patchIntentEntity(id: $intentEntityId, input: $input) {\n-\t...FullCustomEntityFieldsFragment\n- }\n-}\n-${fullCustomEntityFieldsFragment}\n-''', {'fullCustomEntityFieldsFragment': fullCustomEntityFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/entities/queries.py b/core/snips/samkilla/gql/entities/queries.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/entities/queries.py\n+++ /dev/null\n@@ -1,68 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-entityFieldsFragment = gql('''\n- fragment EntityFieldsFragment on IntentEntity {\n- id\n- name\n- author\n- version\n- language\n- examples\n- useSynonyms\n- matchingStrictness\n- automaticallyExtensible\n- userId\n- langPronunciation\n- dataCount\n- lastUpdatedAt\n- }\n-''')\n-\n-fullCustomEntityFieldsFragment = gql('''\n- fragment FullCustomEntityFieldsFragment on IntentEntity {\n- ...EntityFieldsFragment\n- data {\n- value\n- synonyms\n- fromWikilists {\n- destId\n- propId\n- label\n- }\n- }\n- }\n- ${entityFieldsFragment}\n-''', {'entityFieldsFragment': entityFieldsFragment})\n-\n-fullCustomEntityFieldsFragmentWithoutWikiList = gql('''\n- fragment FullCustomEntityFieldsFragment on IntentEntity {\n- ...EntityFieldsFragment\n- data {\n- value\n- synonyms\n- }\n- }\n- ${entityFieldsFragment}\n-''', {'entityFieldsFragment': entityFieldsFragment})\n-\n-customEntitiesWithUsageQuery = gql('''\n- query customEntitiesWithUsageQuery($email: String!, $lang: String) {\n- entities(email: $email, lang: $lang, searchUsage: true) {\n- ...EntityFieldsFragment\n- usedIn {\n- intentId\n- intentName\n- }\n- }\n- }\n- ${entityFieldsFragment}\n-''', {'entityFieldsFragment': entityFieldsFragment})\n-\n-fullCustomEntityQuery = gql('''\n- query FullCustomEntityQuery($entityId: ID!) {\n- entity(entityId: $entityId) {\n- ...FullCustomEntityFieldsFragment\n- }\n- }\n- ${fullCustomEntityFieldsFragment}\n-''', {'fullCustomEntityFieldsFragment': fullCustomEntityFieldsFragmentWithoutWikiList})\ndiff --git a/core/snips/samkilla/gql/intents/__init__.py b/core/snips/samkilla/gql/intents/__init__.py\ndeleted file mode 100644\ndiff --git a/core/snips/samkilla/gql/intents/deleteIntent.py b/core/snips/samkilla/gql/intents/deleteIntent.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/intents/deleteIntent.py\n+++ /dev/null\n@@ -1,8 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-deleteIntent = gql('''\n-mutation deleteIntent($intentId: ID!) {\n- deleteIntent(intentId: $intentId) {\n-\tid\n- }\n-}''')\ndiff --git a/core/snips/samkilla/gql/intents/publishIntent.py b/core/snips/samkilla/gql/intents/publishIntent.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/intents/publishIntent.py\n+++ /dev/null\n@@ -1,30 +0,0 @@\n-from core.snips.samkilla.gql.intents.queries import intentsCustomDataFragment, intentsFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-publishIntent = gql('''\n-mutation publishIntent($intentId: ID, $input: PublishIntentInput!) {\n- publishIntent(intentId: $intentId, input: $input) {\n-\t...IntentsFieldsFragment\n-\tcustomIntentData {\n-\t ...IntentsCustomDataFragment\n-\t}\n- }\n-}\n-${intentsFieldsFragment}\n-${intentsCustomDataFragment}\n-''', {'intentsFieldsFragment': intentsFieldsFragment, 'intentsCustomDataFragment': intentsCustomDataFragment})\n-\n-publishIntentLight = gql('''\n-mutation publishIntent($intentId: ID, $input: PublishIntentInput!) {\n- publishIntent(intentId: $intentId, input: $input) {\n-\t{\n-\t\t\n-\t}\n-\tcustomIntentData {\n-\t ...IntentsCustomDataFragment\n-\t}\n- }\n-}\n-${intentsFieldsFragment}\n-${intentsCustomDataFragment}\n-''', {'intentsFieldsFragment': intentsFieldsFragment, 'intentsCustomDataFragment': intentsCustomDataFragment})\ndiff --git a/core/snips/samkilla/gql/intents/queries.py b/core/snips/samkilla/gql/intents/queries.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/intents/queries.py\n+++ /dev/null\n@@ -1,87 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-intentsFieldsFragment = gql('''\n-fragment IntentsFieldsFragment on Intent {\n- id\n- name\n- displayName\n- slots {\n- name\n- id\n- entityId\n- missingQuestion\n- required\n- description\n- parameters\n- }\n- isMine\n- author\n- username\n- version\n- language\n- exampleQueries\n- description\n- enabledByDefault\n- lastUpdatedAt\n- statistics {\n- qualityScore\n- utterancesCount\n- slotsCount\n- }\n- }\n-''')\n-\n-intentsCustomDataFragment = gql('''\n- fragment IntentsCustomDataFragment on CustomIntentData {\n- language\n- utterances {\n- id\n- text\n- fromUtteranceImport\n- isAmbiguous\n- fromDataGeneration\n- campaignId\n- data {\n- text\n- range {\n- start\n- end\n- }\n- slotId\n- fromAutotagging\n- disableAutoSpanRange\n- }\n- }\n- }\n-''')\n-\n-intentsByUserIdWithUsageQuery = gql('''\n-query IntentsByUserIdWithUsageQuery($userId: ID!, $lang: String) {\n-intents(\n- userId: $userId\n- lang: $lang\n- version: \"latest\"\n- searchUsage: true\n-) {\n- ...IntentsFieldsFragment\n- usedIn {\n-\tskillId\n-\tskillName\n- }\n-}\n-}\n-${intentsFieldsFragment}\n-''', {'intentsFieldsFragment': intentsFieldsFragment})\n-\n-fullIntentQuery = gql('''\n- query FullIntentQuery($intentId: ID!) {\n- intent(intentId: $intentId, version: \"latest\") {\n- customIntentData {\n- ...IntentsCustomDataFragment\n- }\n- ...IntentsFieldsFragment\n- }\n- }\n- ${intentsFieldsFragment}\n- ${intentsCustomDataFragment}\n-''', {'intentsFieldsFragment': intentsFieldsFragment, 'intentsCustomDataFragment': intentsCustomDataFragment})\ndiff --git a/core/snips/samkilla/gql/skills/__init__.py b/core/snips/samkilla/gql/skills/__init__.py\ndeleted file mode 100644\ndiff --git a/core/snips/samkilla/gql/skills/createSkill.py b/core/snips/samkilla/gql/skills/createSkill.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/skills/createSkill.py\n+++ /dev/null\n@@ -1,11 +0,0 @@\n-from core.snips.samkilla.gql.skills.queries import skillFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-createSkill = gql('''\n-mutation createSkill($input: CreateSkillInput!) {\n- createSkill(input: $input) {\n-\t...SkillFieldsFragment\n- }\n-},\n-${skillFieldsFragment}\n-''', {'skillFieldsFragment': skillFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/skills/deleteSkill.py b/core/snips/samkilla/gql/skills/deleteSkill.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/skills/deleteSkill.py\n+++ /dev/null\n@@ -1,9 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-deleteSkill = gql('''\n-mutation deleteSkill($skillId: ID!) {\n- deleteSkill(skillId: $skillId) {\n-\tid\n- }\n-}\n-''')\ndiff --git a/core/snips/samkilla/gql/skills/editSkill.py b/core/snips/samkilla/gql/skills/editSkill.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/skills/editSkill.py\n+++ /dev/null\n@@ -1,27 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-editSkill = gql('''\n-mutation editSkill($input: PatchSkillInput!, $usePut: Boolean) {\n- patchSkill(input: $input, usePut: $usePut) {\n-\tid\n-\tname\n-\timageUrl\n-\tdescription\n-\tprivate\n-\thidden\n-\tlanguage\n-\tversion\n-\tcanCustomize\n-\tskillType\n-\tactionTemplateName\n-\trepository\n-\thassComponent\n-\tparameters {\n-\t name\n-\t value\n-\t defaultValue\n-\t sensitiveValue\n-\t}\n- }\n-}\n-''')\ndiff --git a/core/snips/samkilla/gql/skills/forkSkillIntent.py b/core/snips/samkilla/gql/skills/forkSkillIntent.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/skills/forkSkillIntent.py\n+++ /dev/null\n@@ -1,35 +0,0 @@\n-from core.snips.samkilla.gql.intents.queries import intentsCustomDataFragment, intentsFieldsFragment\n-from core.snips.samkilla.gql.util import gql\n-\n-forkSkillIntent = gql('''\n-mutation forkSkillIntent(\n- $skillId: ID!\n- $intentId: ID!\n- $newIntentName: String\n-) {\n- forkSkillIntent(\n-\tskillId: $skillId\n-\tintentId: $intentId\n-\tnewIntentName: $newIntentName\n- ) {\n-\toldIntentId\n-\tskill {\n-\t id\n-\t version\n-\t intents {\n-\t\tid\n-\t\tversion\n-\t\taction\n-\t }\n-\t}\n-\tintentCopied {\n-\t customIntentData {\n-\t\t...IntentsCustomDataFragment\n-\t }\n-\t ...IntentsFieldsFragment\n-\t}\n- }\n-}\n-${intentsFieldsFragment}\n-${intentsCustomDataFragment}\n-''', {'intentsFieldsFragment': intentsFieldsFragment, 'intentsCustomDataFragment': intentsCustomDataFragment})\ndiff --git a/core/snips/samkilla/gql/skills/patchSkillIntents.py b/core/snips/samkilla/gql/skills/patchSkillIntents.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/skills/patchSkillIntents.py\n+++ /dev/null\n@@ -1,15 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-patchSkillIntents = gql('''\n-mutation patchSkillIntents($input: PatchSkillInput!) {\n- patchSkill(input: $input) {\n-\tid\n-\tversion\n-\tintents {\n-\t id\n-\t version\n-\t action\n-\t}\n- }\n-}\n-''')\ndiff --git a/core/snips/samkilla/gql/skills/queries.py b/core/snips/samkilla/gql/skills/queries.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/skills/queries.py\n+++ /dev/null\n@@ -1,83 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-skillFieldsFragment = gql('''\n- fragment SkillFieldsFragment on Skill {\n- id\n- name\n- description\n- language\n- userId\n- username\n- canCustomize\n- imageUrl\n- hidden\n- migrated\n- forked\n- version\n- statistics {\n- qualityScore\n- importCount\n- copyCount\n- }\n- rating {\n- average\n- totalNumber\n- myRating\n- }\n- comment {\n- totalNumber\n- }\n- skillType\n- actionTemplateName\n- repository\n- hassComponent\n- parameters {\n- name\n- value\n- defaultValue\n- sensitiveValue\n- }\n- }\n-''')\n-\n-skillsWithUsageQuery = gql('''\n- query SkillsWithUsageQuery(\n- $lang: String\n- $userId: String\n- $intentId: ID\n- $offset: Int\n- $limit: Int\n- $filters: String\n- $sort: String\n- ) {\n- skills(\n- lang: $lang\n- userId: $userId\n- intentId: $intentId\n- offset: $offset\n- limit: $limit\n- filters: $filters\n- sort: $sort\n- searchUsage: true\n- ) {\n- skills {\n- ...SkillFieldsFragment\n- intents {\n- id\n- action\n- version\n- }\n- usedIn {\n- assistantId\n- assistantName\n- }\n- }\n- pagination {\n- offset\n- limit\n- total\n- }\n- }\n- }\n- ${skillFieldsFragment}\n-''', {'skillFieldsFragment': skillFieldsFragment})\ndiff --git a/core/snips/samkilla/gql/training/__init__.py b/core/snips/samkilla/gql/training/__init__.py\ndeleted file mode 100755\ndiff --git a/core/snips/samkilla/gql/training/queries.py b/core/snips/samkilla/gql/training/queries.py\ndeleted file mode 100755\n--- a/core/snips/samkilla/gql/training/queries.py\n+++ /dev/null\n@@ -1,28 +0,0 @@\n-from core.snips.samkilla.gql.util import gql\n-\n-\n-assistantDatasetQuery = gql('''\n- query AssistantDatasetQuery($assistantId: ID!, $intentId: ID!) {\n- assistantIntentDataset(assistantId: $assistantId, intentId: $intentId) {\n- original {\n- text\n- entity\n- slot_name\n- }\n- normalized {\n- text\n- entity\n- slot_name\n- }\n- }\n- }\n-''')\n-\n-trainingStatusFieldsFragment = gql('''\n- fragment TrainingStatusFieldsFragment on TrainingStatus {\n- inProgress\n- needTraining\n- trainingResult\n- }\n-''')\n-\ndiff --git a/core/snips/samkilla/gql/util.py b/core/snips/samkilla/gql/util.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/gql/util.py\n+++ /dev/null\n@@ -1,8 +0,0 @@\n-def gql(query: str, replaceMap: dict = None) -> str:\n-\tquery = query.replace(\"\\n\", ' ').replace(\"\\t\", ' ').replace('\"', '__QUOTES__')\n-\n-\tif replaceMap:\n-\t\tfor toReplaceStr in replaceMap:\n-\t\t\tquery = query.replace('${' + toReplaceStr + '}', replaceMap[toReplaceStr])\n-\n-\treturn query\ndiff --git a/core/snips/samkilla/models/EnumSkillImageUrl.py b/core/snips/samkilla/models/EnumSkillImageUrl.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/models/EnumSkillImageUrl.py\n+++ /dev/null\n@@ -1,79 +0,0 @@\n-import os\n-\n-from core.snips.samkilla.models.Singleton import Singleton\n-\n-DEFAULT_RESOURCE = 'default-bundle.svg'\n-\n-\n-class EnumSkillImageUrl(Singleton):\n-\tdefault = DEFAULT_RESOURCE\n-\tair = 'bundle-air.svg'\n-\tassistant = 'bundle-assistant.svg'\n-\tbank = 'bundle-bank.svg'\n-\tbattery = 'bundle-battery.svg'\n-\tbluetooth = 'bundle-bluetooth.svg'\n-\tbox = 'bundle-box.svg'\n-\tcalculator = 'bundle-calculator.svg'\n-\tcalendar = 'bundle-calendar.svg'\n-\tcamera = 'bundle-camera.svg'\n-\tcar = 'bundle-car.svg'\n-\tcoffee = 'bundle-coffee.svg'\n-\tdirection = 'bundle-direction.svg'\n-\tdrink = 'bundle-drink.svg'\n-\tfilm = 'bundle-film.svg'\n-\tfolder = 'bundle-folder.svg'\n-\tgames = 'bundle-games.svg'\n-\theadphones = 'bundle-headphones.svg'\n-\thome = 'bundle-home.svg'\n-\tkey = 'bundle-key.svg'\n-\tlamp = 'bundle-lamp.svg'\n-\tlights = 'bundle-lights.svg'\n-\tlocation = 'bundle-location.svg'\n-\tlock = 'bundle-lock.svg'\n-\tmap = 'bundle-map.svg'\n-\tmedicine = 'bundle-medicine.svg'\n-\tmicrophone = 'bundle-microphone.svg'\n-\tmonitor = 'bundle-monitor.svg'\n-\tmovie = 'bundle-movie.svg'\n-\tmusic = 'bundle-music.svg'\n-\tplant = 'bundle-plant.svg'\n-\tradio = 'bundle-radio.svg'\n-\train = 'bundle-rain.svg'\n-\trecording = 'bundle-recording.svg'\n-\trestart = 'bundle-restart.svg'\n-\tsecurity = 'bundle-security.svg'\n-\tsettings = 'bundle-settings.svg'\n-\tshutdown = 'bundle-shutdown.svg'\n-\tsport = 'bundle-sport.svg'\n-\tspotify = 'bundle-spotify.svg'\n-\tstar = 'bundle-star.svg'\n-\tstore = 'bundle-store.svg'\n-\tsun = 'bundle-sun.svg'\n-\ttemperature = 'bundle-temperature.svg'\n-\ttime = 'bundle-time.svg'\n-\ttimer = 'bundle-timer.svg'\n-\ttransport = 'bundle-transport.svg'\n-\tvynil = 'bundle-vynil.svg'\n-\twallet = 'bundle-wallet.svg'\n-\tweather = 'bundle-weather.svg'\n-\twind = 'bundle-wind.svg'\n-\tyoga = 'bundle-yoga.svg'\n-\n-\n-\tdef __init__(self):\n-\t\tSingleton.__init__(self, 'EnumSkillImageUrl')\n-\n-\n-\tdef getResourceFileByAttr(self, attrName: str) -> str:\n-\t\treturn getattr(self, attrName)\n-\n-\n-\t@staticmethod\n-\tdef getImageUrl(urlPrefix: str, enumImageUrlKey: str = DEFAULT_RESOURCE):\n-\t\treturn f'{urlPrefix}/images/bundles/{enumImageUrlKey}'\n-\n-\n-\t@staticmethod\n-\tdef urlToResourceKey(url: str) -> str:\n-\t\treturn os.path.basename(url).replace('.svg', '').replace('bundle', '').replace('-', '')\n-\ndiff --git a/core/snips/samkilla/models/Singleton.py b/core/snips/samkilla/models/Singleton.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/models/Singleton.py\n+++ /dev/null\n@@ -1,10 +0,0 @@\n-class Singleton:\n-\tINSTANCE = None\n-\n-\n-\tdef __init__(self, name: str):\n-\t\tif self.INSTANCE:\n-\t\t\traise KeyboardInterrupt\n-\t\telse:\n-\t\t\tself.INSTANCE = self\n-\t\t\tself._name = name\ndiff --git a/core/snips/samkilla/models/__init__.py b/core/snips/samkilla/models/__init__.py\ndeleted file mode 100644\ndiff --git a/core/snips/samkilla/processors/IntentRemoteProcessor.py b/core/snips/samkilla/processors/IntentRemoteProcessor.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/processors/IntentRemoteProcessor.py\n+++ /dev/null\n@@ -1,130 +0,0 @@\n-import hashlib\n-import sys\n-import traceback\n-\n-from core.ProjectAliceExceptions import IntentError\n-from core.snips import SamkillaManager\n-\n-\n-class IntentRemoteProcessor:\n-\n-\tdef __init__(self, ctx: SamkillaManager, intent: dict, intentLanguage: str, assistantId: str):\n-\t\tself._ctx = ctx\n-\t\tself._intent = intent\n-\t\tself._assistantId = assistantId\n-\t\tself._intentLanguage = intentLanguage\n-\t\tself._syncState = None\n-\t\tself._createdInstances = {'intents': list()}\n-\n-\n-\tdef createNewSavedIntent(self) -> dict:\n-\t\treturn {'name': self._intent['name']}\n-\n-\n-\tdef intentValuesToHash(self, typeEntityMatching: dict, intentId: str = '', skillId: str = ''):\n-\t\tintent = self._intent\n-\n-\t\thashSum = f\"{str(intent['name'])}{str(intent['description'])}{str(intent['enabledByDefault'])}\"\n-\n-\t\tfor utteranceText in intent['utterances']:\n-\t\t\thashSum += str(utteranceText)\n-\n-\t\tfor slotHole in intent['slots']:\n-\t\t\thashSum += str(slotHole['name'])\n-\t\t\thashSum += str(slotHole['description'])\n-\t\t\thashSum += str(slotHole['required'])\n-\t\t\thashSum += str(slotHole['type'])\n-\t\t\thashSum += str(slotHole['missingQuestion'])\n-\n-\t\t\tif slotHole['type'] in typeEntityMatching:\n-\t\t\t\thashSum += typeEntityMatching[slotHole['type']]['entityId']\n-\n-\t\thashSum += intentId + '-' + skillId\n-\n-\t\treturn hashlib.sha512(hashSum.encode('utf-8')).hexdigest()\n-\n-\n-\tdef doSyncedIntentExists(self) -> bool:\n-\t\treturn 'hash' in self._syncState and 'intentId' in self._syncState\n-\n-\n-\tdef syncIntent(self, typeEntityMatching: dict, skillId: str, hashComputationOnly: bool = False) -> dict:\n-\t\tintent = self._intent\n-\n-\t\toldInstanceExists = self.doSyncedIntentExists()\n-\t\toldHash = self._syncState['hash'] if oldInstanceExists else ''\n-\t\tintentId = self._syncState['intentId'] if oldInstanceExists else ''\n-\t\tcurHash = self.intentValuesToHash(typeEntityMatching=typeEntityMatching, intentId=intentId, skillId=skillId)\n-\t\tchanges = False\n-\n-\t\tfullIntentName = intent['name']\n-\n-\t\tif hashComputationOnly or (oldInstanceExists and oldHash == curHash):\n-\t\t\tself._ctx.log(f'Intent model {intentId} ({fullIntentName}) has no changes')\n-\t\telif oldInstanceExists:\n-\t\t\tchanges = True\n-\t\t\tself._ctx.log(f'Intent model {intentId} ({fullIntentName}) has been edited')\n-\t\t\tself._ctx.intent.edit(\n-\t\t\t\tuserId=self._ctx.userId,\n-\t\t\t\tintentId=intentId,\n-\t\t\t\tname=fullIntentName,\n-\t\t\t\tdescription=intent['description'],\n-\t\t\t\tenabledByDefault=intent['enabledByDefault'],\n-\t\t\t\ttypeEntityMatching=typeEntityMatching,\n-\t\t\t\tslotsDefinition=intent['slots'],\n-\t\t\t\tutterancesDefinition=intent['utterances'],\n-\t\t\t\tattachToSkill=True,\n-\t\t\t\tskillId=skillId,\n-\t\t\t\tlanguage=self._intentLanguage\n-\t\t\t)\n-\t\telse:\n-\t\t\tchanges = True\n-\t\t\tintentId = self._ctx.intent.create(\n-\t\t\t\tuserId=self._ctx.userId,\n-\t\t\t\tskillId=skillId,\n-\t\t\t\tname=fullIntentName,\n-\t\t\t\tdescription=intent['description'],\n-\t\t\t\tlanguage=self._intentLanguage,\n-\t\t\t\tattachToSkill=True,\n-\t\t\t\tenabledByDefault=intent['enabledByDefault'],\n-\t\t\t\ttypeEntityMatching=typeEntityMatching,\n-\t\t\t\tslotsDefinition=intent['slots'],\n-\t\t\t\tutterancesDefinition=intent['utterances']\n-\t\t\t)\n-\t\t\tself._ctx.log(f'Intent model {intentId} ({fullIntentName}) has been created')\n-\t\t\tself._createdInstances['intents'].append({'id': intentId})\n-\t\t\tcurHash = self.intentValuesToHash(typeEntityMatching=typeEntityMatching, intentId=intentId, skillId=skillId)\n-\n-\t\treturn {'intentId': intentId, 'hash': curHash, 'changes': changes}\n-\n-\n-\tdef syncIntentsOnAssistantSafely(self, typeEntityMatching: dict, skillId: str, intentSyncState: str = None, hashComputationOnly: bool = False):\n-\t\ttry:\n-\t\t\treturn self.syncIntentsOnAssistant(typeEntityMatching=typeEntityMatching, skillId=skillId, intentSyncState=intentSyncState, hashComputationOnly=hashComputationOnly)\n-\t\texcept IntentError as ie:\n-\t\t\tself._ctx.log('Handle error gracefully')\n-\t\t\tself._ctx.log(ie.message)\n-\t\texcept:\n-\t\t\te = sys.exc_info()[0]\n-\t\t\tself._ctx.log('Handle error gracefully')\n-\t\t\tself._ctx.log(e)\n-\t\t\tself._ctx.log(traceback.format_exc())\n-\t\t\tsys.exit(-1)\n-\n-\n-\tdef syncIntentsOnAssistant(self, typeEntityMatching: dict, skillId: str, intentSyncState: str = None, hashComputationOnly: bool = False) -> tuple:\n-\t\t# TODO this is used like a dict and appears to be a dict but typing says it is a string -> somethings wrong here\n-\t\tself._syncState = intentSyncState or self.createNewSavedIntent()\n-\n-\t\tintentMatching = self.syncIntent(typeEntityMatching, skillId, hashComputationOnly)\n-\t\tself._syncState['hash'] = intentMatching['hash']\n-\t\tself._syncState['intentId'] = intentMatching['intentId']\n-\n-\t\treturn self._syncState, intentMatching['changes']\n-\n-\n-\tdef cleanCreatedInstances(self):\n-\t\tself._ctx.log(f\"[Cleanup] Deleting {len(self._createdInstances['intents'])} intents\")\n-\t\tfor intent in self._createdInstances['intents']:\n-\t\t\tself._ctx.entity.delete(intentId=intent['id'])\n-\t\tself._createdInstances['intents'] = list()\ndiff --git a/core/snips/samkilla/processors/MainProcessor.py b/core/snips/samkilla/processors/MainProcessor.py\ndeleted file mode 100755\n--- a/core/snips/samkilla/processors/MainProcessor.py\n+++ /dev/null\n@@ -1,831 +0,0 @@\n-import json\n-import typing\n-from pathlib import Path\n-\n-from core.ProjectAliceExceptions import HttpError\n-from core.base.SuperManager import SuperManager\n-from core.snips import SamkillaManager\n-from core.snips.samkilla.models.EnumSkillImageUrl import EnumSkillImageUrl as EnumSkillImageUrlClass\n-from core.snips.samkilla.processors.IntentRemoteProcessor import IntentRemoteProcessor\n-from core.snips.samkilla.processors.SkillRemoteProcessor import SkillRemoteProcessor\n-from core.snips.samkilla.processors.SlotTypeRemoteProcessor import SlotTypeRemoteProcessor\n-\n-EnumSkillImageUrl = EnumSkillImageUrlClass()\n-\n-\n-class MainProcessor:\n-\tSAVED_ASSISTANTS_DIR = Path('var', 'assistants')\n-\tSAVED_MODULES_DIR = 'skills'\n-\n-\n-\tdef __init__(self, ctx: SamkillaManager):\n-\t\tself._ctx = ctx\n-\t\tself._skills = dict()\n-\t\tself._savedAssistants = dict()\n-\t\tself._savedSlots = dict()\n-\t\tself._savedIntents = dict()\n-\t\tself.initSavedAssistants()\n-\t\tself.initSavedSlots()\n-\t\tself.initSavedIntents()\n-\n-\n-\tdef initSavedIntents(self):\n-\t\tfor lang in self.SAVED_ASSISTANTS_DIR.glob('[!.]*'):\n-\t\t\tif not lang.is_dir(): continue\n-\n-\t\t\tself._savedIntents[lang.name] = dict()\n-\n-\t\t\tfor projectId in lang.iterdir():\n-\t\t\t\tdirectory = projectId / 'intents'\n-\t\t\t\tdirectory.mkdir(parents=True, exist_ok=True)\n-\t\t\t\tself._savedIntents[lang.name][projectId.name] = dict()\n-\n-\t\t\t\tfor intent in directory.iterdir():\n-\t\t\t\t\tintentDefinition = json.loads(intent.read_text())\n-\t\t\t\t\tself._savedIntents[lang.name][projectId.name][intentDefinition['name']] = intentDefinition\n-\n-\n-\tdef initSavedSlots(self):\n-\t\tfor lang in self.SAVED_ASSISTANTS_DIR.glob('[!.]*'):\n-\t\t\tif not lang.is_dir(): continue\n-\n-\t\t\tself._savedSlots[lang.name] = dict()\n-\n-\t\t\tfor projectId in lang.iterdir():\n-\t\t\t\tdirectory = projectId / 'slots'\n-\t\t\t\tdirectory.mkdir(parents=True, exist_ok=True)\n-\t\t\t\tself._savedSlots[lang.name][projectId.name] = dict()\n-\n-\t\t\t\tfor slot in directory.iterdir():\n-\t\t\t\t\tdefinition = json.loads(slot.read_text())\n-\t\t\t\t\tself._savedSlots[lang.name][projectId.name][definition['name']] = definition\n-\n-\n-\tdef initSavedAssistants(self):\n-\t\tfor lang in self.SAVED_ASSISTANTS_DIR.glob('[!.]*'):\n-\t\t\tif not lang.is_dir(): continue\n-\n-\t\t\tself._savedAssistants[lang.name] = dict()\n-\n-\t\t\tfor projectId in lang.iterdir():\n-\t\t\t\tfilename = projectId / '_assistant.json'\n-\t\t\t\tself._savedAssistants[lang.name][projectId.name] = dict()\n-\n-\t\t\t\twholeAssistant = json.loads(filename.read_text())\n-\t\t\t\tself._savedAssistants[lang.name][projectId.name] = wholeAssistant\n-\t\t\t\tself.safeBaseDicts(projectId.name, lang.name)\n-\n-\n-\tdef hasLocalAssistantByIdAndLanguage(self, assistantLanguage: str, assistantId: str) -> bool:\n-\t\treturn assistantId in self._savedAssistants.get(assistantLanguage, dict())\n-\n-\n-\tdef getLocalFirstAssistantByLanguage(self, assistantLanguage: str, returnId: bool = False) -> typing.Any:\n-\t\tassistants = self._savedAssistants.get(assistantLanguage, dict())\n-\t\tif assistants:\n-\t\t\tfirstAssistant = next(iter(assistants.values()))\n-\t\t\treturn firstAssistant['id'] if returnId else firstAssistant\n-\t\treturn None\n-\n-\n-\tdef safeBaseDicts(self, assistantId: str, assistantLanguage: str):\n-\t\tbaseDicts = ['skills', 'slotTypes', 'intents']\n-\n-\t\tfor baseDict in baseDicts:\n-\t\t\tself._savedAssistants[assistantLanguage][assistantId].setdefault(baseDict, dict())\n-\n-\n-\tdef persistToLocalAssistantCache(self, assistantId: str, assistantLanguage: str):\n-\t\tassistantMountpoint = self.SAVED_ASSISTANTS_DIR / assistantLanguage / assistantId\n-\t\tassistantMountpoint.mkdir(parents=True, exist_ok=True)\n-\n-\t\tself.safeBaseDicts(assistantId, assistantLanguage)\n-\n-\t\tstate = self._savedAssistants[assistantLanguage][assistantId]\n-\t\tassistantFile = assistantMountpoint / '_assistant.json'\n-\t\tassistantFile.write_text(json.dumps(state, indent=4, sort_keys=False, ensure_ascii=False))\n-\n-\n-\t# self._ctx.log(f'\\n[Persist] local assistant {assistantId} in {assistantLanguage}')\n-\n-\tdef syncRemoteToLocalAssistant(self, assistantId: str, assistantLanguage: str, assistantTitle: str):\n-\t\tif not self.hasLocalAssistantByIdAndLanguage(assistantId=assistantId, assistantLanguage=assistantLanguage):\n-\t\t\tnewState = {\n-\t\t\t\t'id' : assistantId,\n-\t\t\t\t'name' : assistantTitle,\n-\t\t\t\t'language' : assistantLanguage,\n-\t\t\t\t'skills' : dict(),\n-\t\t\t\t'slotTypes': dict(),\n-\t\t\t\t'intents' : dict()\n-\t\t\t}\n-\n-\t\t\tif not assistantLanguage in self._savedAssistants:\n-\t\t\t\tself._savedAssistants[assistantLanguage] = dict()\n-\n-\t\t\tself._savedAssistants[assistantLanguage][assistantId] = newState\n-\t\t\tself.persistToLocalAssistantCache(assistantId=assistantId, assistantLanguage=assistantLanguage)\n-\t\t\tself.initSavedSlots()\n-\t\t\tself.initSavedIntents()\n-\n-\n-\tdef syncRemoteToLocalSkillCache(self, assistantId: str, assistantLanguage: str, skillName: str, syncState: str, persist: bool = False):\n-\t\tself._savedAssistants[assistantLanguage][assistantId]['skills'][skillName] = syncState\n-\n-\t\tif persist:\n-\t\t\tself.persistToLocalAssistantCache(assistantId=assistantId, assistantLanguage=assistantLanguage)\n-\n-\n-\tdef syncRemoteToLocalSlotTypeCache(self, assistantId: str, assistantLanguage: str, slotTypeName: str, syncState: str, persist: bool = False):\n-\t\tself._savedAssistants[assistantLanguage][assistantId]['slotTypes'][slotTypeName] = syncState\n-\n-\t\tif persist:\n-\t\t\tself.persistToLocalAssistantCache(assistantId=assistantId, assistantLanguage=assistantLanguage)\n-\n-\n-\tdef syncRemoteToLocalIntentCache(self, assistantId: str, assistantLanguage: str, intentName: str, syncState: str, persist: bool = False):\n-\t\tself._savedAssistants[assistantLanguage][assistantId]['intents'][intentName] = syncState\n-\n-\t\tif persist:\n-\t\t\tself.persistToLocalAssistantCache(assistantId=assistantId, assistantLanguage=assistantLanguage)\n-\n-\n-\tdef getSkillFromFile(self, skillFile: Path, skillLanguage: str) -> typing.Optional[dict]:\n-\t\ttry:\n-\t\t\tskill = json.loads(Path(skillFile).read_text())\n-\n-\t\t\tif 'skill' not in skill:\n-\t\t\t\tself._ctx.log(f\"File \\\"{skillFile}\\\" has no 'skill' name definition\")\n-\t\t\t\treturn\n-\n-\t\t\tskill['language'] = skillLanguage\n-\n-\t\t\tif skill['skill'] not in self._skills:\n-\t\t\t\tself._ctx.log(f\"Skill \\\"{skill['skill']}\\\" has a name different from its directory\")\n-\t\t\t\treturn\n-\n-\t\t\tself._skills[skill['skill']][skillLanguage] = skill\n-\t\t\tself._ctx.log(f\"Loading skill {skill['skill']}\")\n-\t\t\treturn skill\n-\n-\t\texcept json.decoder.JSONDecodeError:\n-\t\t\tself._ctx.log(f'\\nInconsistent file, \"{skillFile}\" has a bad json format')\n-\t\t\treturn\n-\n-\tdef getSkillSyncStateByLanguageAndAssistantId(self, skillName: str, language: str, assistantId: str) -> str:\n-\t\treturn self._savedAssistants.get(language, dict()).get(assistantId, dict()).get('skills', dict()).get(skillName, None)\n-\n-\n-\tdef getSlotTypeSyncStateByLanguageAndAssistantId(self, slotTypeName: str, language: str, assistantId: str) -> str:\n-\t\treturn self._savedAssistants.get(language, dict()).get(assistantId, dict()).get('slotTypes', dict()).get(slotTypeName, None)\n-\n-\n-\tdef getIntentSyncStateByLanguageAndAssistantId(self, intentName: str, language: str, assistantId: str) -> str:\n-\t\treturn self._savedAssistants.get(language, dict()).get(assistantId, dict()).get('intents', dict()).get(intentName, None)\n-\n-\n-\tdef persistToGlobalAssistantSlots(self, assistantId: str, assistantLanguage: str, slotNameFilter: str = None):\n-\t\tassistantSlotsMountpoint = self.SAVED_ASSISTANTS_DIR / assistantLanguage / assistantId / 'slots'\n-\t\tassistantSlotsMountpoint.mkdir(parents=True, exist_ok=True)\n-\n-\t\tslotTypes = self._savedSlots[assistantLanguage][assistantId]\n-\n-\t\tfor key, value in slotTypes.items():\n-\t\t\tif slotNameFilter and slotNameFilter != key: continue\n-\n-\t\t\tslotFile = assistantSlotsMountpoint / f'{key}.json'\n-\t\t\tslotFile.write_text(json.dumps(value, indent=4, sort_keys=False, ensure_ascii=False))\n-\t\t# self._ctx.log(f'Global slot {key}')\n-\n-\n-\tdef persistToGlobalAssistantIntents(self, assistantId: str, assistantLanguage: str, intentNameFilter: str = None):\n-\t\tassistantSlotsMountpoint = self.SAVED_ASSISTANTS_DIR / assistantLanguage / assistantId / 'intents'\n-\t\tassistantSlotsMountpoint.mkdir(parents=True, exist_ok=True)\n-\n-\t\tintents = self._savedIntents[assistantLanguage][assistantId]\n-\n-\t\tfor key, value in intents.items():\n-\t\t\tif intentNameFilter and intentNameFilter != key: continue\n-\n-\t\t\tintentFile = assistantSlotsMountpoint / f'{key}.json'\n-\t\t\tintentFile.write_text(json.dumps(value, indent=4, sort_keys=False, ensure_ascii=False))\n-\t\t# self._ctx.log(f'Global slot {key}')\n-\n-\n-\tdef syncGlobalSlotType(self, assistantId: str, assistantLanguage: str, slotTypeName: str, slotDefinition: str, persist: bool = False):\n-\t\tself._savedSlots[assistantLanguage][assistantId][slotTypeName] = slotDefinition\n-\n-\t\tif persist:\n-\t\t\tself.persistToGlobalAssistantSlots(assistantId=assistantId, assistantLanguage=assistantLanguage, slotNameFilter=slotTypeName)\n-\n-\n-\tdef syncGlobalIntent(self, assistantId: str, assistantLanguage: str, intentName: str, intentDefinition: str, persist: bool = False):\n-\t\tself._savedIntents[assistantLanguage][assistantId][intentName] = intentDefinition\n-\n-\t\tif persist:\n-\t\t\tself.persistToGlobalAssistantIntents(assistantId=assistantId, assistantLanguage=assistantLanguage, intentNameFilter=intentName)\n-\n-\n-\tdef mergeSkillSlotTypes(self, slotTypesSkillsValues: dict, assistantId: str, slotLanguage: str = None):\n-\t\tmergedSlotTypes = dict()\n-\t\tslotTypesGlobalValues = dict()\n-\n-\t\tfor slotName in slotTypesSkillsValues:\n-\t\t\tif slotName in self._savedSlots[slotLanguage][assistantId]:\n-\t\t\t\tsavedSlotType = self._savedSlots[slotLanguage][assistantId][slotName]\n-\n-\t\t\t\tslotTypesGlobalValues[savedSlotType['name']] = {'__otherattributes__': {\n-\t\t\t\t\t'name' : savedSlotType['name'],\n-\t\t\t\t\t'matchingStrictness' : savedSlotType['matchingStrictness'],\n-\t\t\t\t\t'automaticallyExtensible': savedSlotType['automaticallyExtensible'],\n-\t\t\t\t\t'useSynonyms' : savedSlotType['useSynonyms'],\n-\t\t\t\t\t'values' : list()\n-\t\t\t\t}}\n-\n-\t\t\t\tfor savedSlotValue in savedSlotType['values']:\n-\t\t\t\t\tif savedSlotValue['value'] not in slotTypesGlobalValues[savedSlotType['name']]:\n-\t\t\t\t\t\tslotTypesGlobalValues[savedSlotType['name']][savedSlotValue['value']] = dict()\n-\n-\t\t\t\t\t\tif 'synonyms' in savedSlotValue:\n-\t\t\t\t\t\t\tfor synonym in savedSlotValue['synonyms']:\n-\t\t\t\t\t\t\t\tif not synonym: continue\n-\t\t\t\t\t\t\t\tslotTypesGlobalValues[savedSlotType['name']][savedSlotValue['value']].setdefault(synonym, True)\n-\n-\t\tfor slotName, slotValue in slotTypesSkillsValues.items():\n-\t\t\tslotTypeCatalogValues = slotTypesGlobalValues.get(slotName, slotValue)\n-\n-\t\t\tmergedSlotTypes[slotName] = slotTypeCatalogValues.pop('__otherattributes__')\n-\t\t\tmergedSlotTypes[slotName]['values'] = [{'value': key, 'synonyms': list(value)} for key, value in slotTypeCatalogValues.items()]\n-\n-\t\t\tself.syncGlobalSlotType(\n-\t\t\t\tassistantId=assistantId,\n-\t\t\t\tassistantLanguage=slotLanguage,\n-\t\t\t\tslotTypeName=slotName,\n-\t\t\t\tslotDefinition=mergedSlotTypes[slotName],\n-\t\t\t\tpersist=True\n-\t\t\t)\n-\n-\t\treturn mergedSlotTypes\n-\n-\n-\tdef mergeSkillIntents(self, intentsSkillsValues: dict, assistantId: str, intentLanguage: str = None) -> dict:\n-\t\tmergedIntents = dict()\n-\t\tintentsGlobalValues = dict()\n-\n-\t\tfor intentName in intentsSkillsValues:\n-\t\t\tif intentName in self._savedIntents[intentLanguage][assistantId]:\n-\t\t\t\tsavedIntent = self._savedIntents[intentLanguage][assistantId][intentName]\n-\n-\t\t\t\tintentsGlobalValues[savedIntent['name']] = {\n-\t\t\t\t\t'__otherattributes__': {\n-\t\t\t\t\t\t'name' : savedIntent['name'],\n-\t\t\t\t\t\t'description' : savedIntent['description'],\n-\t\t\t\t\t\t'enabledByDefault': savedIntent['enabledByDefault'],\n-\t\t\t\t\t\t'utterances' : list(),\n-\t\t\t\t\t\t'slots' : list()\n-\t\t\t\t\t},\n-\t\t\t\t\t'utterances' : dict(),\n-\t\t\t\t\t'slots' : dict()\n-\t\t\t\t}\n-\n-\t\t\t\tfor savedUtterance in savedIntent['utterances']:\n-\t\t\t\t\tintentsGlobalValues[savedIntent['name']]['utterances'].setdefault(savedUtterance, True)\n-\n-\t\t\t\tfor skillSlot in savedIntent['slots']:\n-\t\t\t\t\tintentsGlobalValues[savedIntent['name']]['slots'].setdefault(skillSlot['name'], skillSlot)\n-\n-\t\tfor intentName, intentValue in intentsSkillsValues.items():\n-\t\t\tintentCatalogValues = intentsGlobalValues.get(intentName, intentValue)\n-\n-\t\t\tmergedIntents[intentName] = intentCatalogValues['__otherattributes__']\n-\t\t\tmergedIntents[intentName]['utterances'] = list(intentCatalogValues['utterances'])\n-\t\t\tmergedIntents[intentName]['slots'] = list(intentCatalogValues['slots'].values())\n-\n-\t\t\tself.syncGlobalIntent(\n-\t\t\t\tassistantId=assistantId,\n-\t\t\t\tassistantLanguage=intentLanguage,\n-\t\t\t\tintentName=intentName,\n-\t\t\t\tintentDefinition=mergedIntents[intentName],\n-\t\t\t\tpersist=True\n-\t\t\t)\n-\n-\t\treturn mergedIntents\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef buildMapsFromDialogTemplates(self, runOnAssistantId: str = None, skillFilter: list = None, languageFilter: str = None) -> tuple:\n-\t\tif skillFilter is None:\n-\t\t\tskillFilter = list()\n-\n-\t\tself._skills = dict()\n-\n-\t\trootDir = Path('skills')\n-\t\trootDir.mkdir(exist_ok=True)\n-\n-\t\tslotTypesSkillsValues = dict()\n-\t\tintentsSkillsValues = dict()\n-\t\tintentNameSkillMatching = dict()\n-\n-\t\tfor skillPath in rootDir.iterdir():\n-\t\t\tintentsPath = skillPath / 'dialogTemplate'\n-\n-\t\t\tif not intentsPath.is_dir(): continue\n-\n-\t\t\tself._skills[skillPath.name] = dict()\n-\n-\t\t\tfor languageFile in intentsPath.iterdir():\n-\t\t\t\tlanguage = languageFile.stem\n-\t\t\t\tif languageFilter and languageFilter != language: continue\n-\n-\t\t\t\tskill = self.getSkillFromFile(skillFile=languageFile, skillLanguage=language)\n-\t\t\t\tif not skill:\n-\t\t\t\t\treturn None, None, None\n-\n-\t\t\t\t# We need all slotTypes values of all skills, even if there is a skill filter\n-\t\t\t\tfor skillSlotType in skill['slotTypes']:\n-\t\t\t\t\tif skillSlotType['name'] not in slotTypesSkillsValues:\n-\t\t\t\t\t\tslotTypesSkillsValues[skillSlotType['name']] = {\n-\t\t\t\t\t\t\t'__otherattributes__': {\n-\t\t\t\t\t\t\t\t'name' : skillSlotType['name'],\n-\t\t\t\t\t\t\t\t'matchingStrictness' : skillSlotType['matchingStrictness'],\n-\t\t\t\t\t\t\t\t'automaticallyExtensible': skillSlotType['automaticallyExtensible'],\n-\t\t\t\t\t\t\t\t'useSynonyms' : skillSlotType['useSynonyms'],\n-\t\t\t\t\t\t\t\t'values' : list()\n-\t\t\t\t\t\t\t}\n-\t\t\t\t\t\t}\n-\n-\t\t\t\t\tfor skillSlotValue in skillSlotType['values']:\n-\t\t\t\t\t\tif skillSlotValue['value'] not in slotTypesSkillsValues[skillSlotType['name']]:\n-\t\t\t\t\t\t\tslotTypesSkillsValues[skillSlotType['name']][skillSlotValue['value']] = dict()\n-\n-\t\t\t\t\t\t\tfor synonym in skillSlotValue.get('synonyms', list()):\n-\t\t\t\t\t\t\t\tif not synonym: continue\n-\t\t\t\t\t\t\t\tslotTypesSkillsValues[skillSlotType['name']][skillSlotValue['value']][synonym] = True\n-\n-\t\t\t\t# We need all intents values of all skills, even if there is a skill filters\n-\t\t\t\tfor skillIntent in skill['intents']:\n-\t\t\t\t\tif skillIntent['name'] not in intentsSkillsValues:\n-\t\t\t\t\t\tintentNameSkillMatching[skillIntent['name']] = skillPath.name\n-\n-\t\t\t\t\t\tintentsSkillsValues[skillIntent['name']] = {\n-\t\t\t\t\t\t\t'__otherattributes__': {\n-\t\t\t\t\t\t\t\t'name' : skillIntent['name'],\n-\t\t\t\t\t\t\t\t'description' : skillIntent['description'],\n-\t\t\t\t\t\t\t\t'enabledByDefault': skillIntent['enabledByDefault'],\n-\t\t\t\t\t\t\t\t'utterances' : list(),\n-\t\t\t\t\t\t\t\t'slots' : list()\n-\t\t\t\t\t\t\t},\n-\t\t\t\t\t\t\t'utterances' : dict(),\n-\t\t\t\t\t\t\t'slots' : dict()\n-\t\t\t\t\t\t}\n-\n-\t\t\t\t\tfor skillUtterance in skillIntent.get('utterances', list()):\n-\t\t\t\t\t\tintentsSkillsValues[skillIntent['name']]['utterances'].setdefault(skillUtterance, True)\n-\n-\t\t\t\t\tfor skillSlot in skillIntent.get('slots', list()):\n-\t\t\t\t\t\tintentsSkillsValues[skillIntent['name']]['slots'].setdefault(skillSlot['name'], skillSlot)\n-\n-\t\t\t\tif skillFilter and skillPath.name not in skillFilter:\n-\t\t\t\t\tdel self._skills[skill['skill']]\n-\n-\t\treturn slotTypesSkillsValues, intentsSkillsValues, intentNameSkillMatching\n-\n-\n-\t# TODO to refacto in different method of a new Processor\n-\tdef syncLocalToRemote(self, runOnAssistantId: str, skillFilter: list = None, languageFilter: str = None) -> bool:\n-\n-\t\tslotTypesSkillsValues, intentsSkillsValues, intentNameSkillMatching = self.buildMapsFromDialogTemplates(\n-\t\t\trunOnAssistantId=runOnAssistantId,\n-\t\t\tskillFilter=skillFilter,\n-\t\t\tlanguageFilter=languageFilter\n-\t\t)\n-\n-\t\tif not slotTypesSkillsValues or not intentsSkillsValues or not intentNameSkillMatching:\n-\t\t\treturn False\n-\n-\t\t# Get a dict with all slotTypes\n-\t\ttypeEntityMatching, globalChangesSlotTypes = self.syncLocalToRemoteSlotTypes(\n-\t\t\tslotTypesSkillsValues,\n-\t\t\trunOnAssistantId,\n-\t\t\tlanguageFilter,\n-\t\t\tskillFilter\n-\t\t)\n-\n-\t\tskillNameIdMatching, globalChangesSkills = self.syncLocalToRemoteSkills(\n-\t\t\ttypeEntityMatching,\n-\t\t\trunOnAssistantId,\n-\t\t\tlanguageFilter,\n-\t\t\tskillFilter\n-\t\t)\n-\n-\t\tglobalChangesIntents = self.syncLocalToRemoteIntents(\n-\t\t\tskillNameIdMatching,\n-\t\t\tintentNameSkillMatching,\n-\t\t\ttypeEntityMatching,\n-\t\t\tintentsSkillsValues,\n-\t\t\trunOnAssistantId,\n-\t\t\tlanguageFilter,\n-\t\t\tskillFilter\n-\t\t)\n-\n-\t\treturn globalChangesSlotTypes or globalChangesSkills or globalChangesIntents\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef syncLocalToRemoteSlotTypes(self, slotTypesSkillsValues: dict, runOnAssistantId: str, languageFilter: str = None, skillFilter: list = None) -> tuple:\n-\t\tslotTypesSynced = dict()\n-\t\tglobalChanges = False\n-\n-\t\tmergedSlotTypes = self.mergeSkillSlotTypes(\n-\t\t\tslotTypesSkillsValues=slotTypesSkillsValues,\n-\t\t\tassistantId=runOnAssistantId,\n-\t\t\tslotLanguage=languageFilter\n-\t\t)\n-\n-\t\ttypeEntityMatching = dict()\n-\n-\t\tfor slotName, slotType in mergedSlotTypes.items():\n-\n-\t\t\tslotSyncState = self.getSlotTypeSyncStateByLanguageAndAssistantId(\n-\t\t\t\tslotTypeName=slotName,\n-\t\t\t\tlanguage=languageFilter,\n-\t\t\t\tassistantId=runOnAssistantId\n-\t\t\t)\n-\n-\t\t\tslotRemoteProcessor = SlotTypeRemoteProcessor(\n-\t\t\t\tctx=self._ctx,\n-\t\t\t\tslotType=slotType,\n-\t\t\t\tslotLanguage=languageFilter,\n-\t\t\t\tassistantId=runOnAssistantId,\n-\t\t\t)\n-\n-\t\t\tnewSlotTypeSyncState, changes = slotRemoteProcessor.syncSlotTypesOnAssistantSafely(\n-\t\t\t\tslotTypeSyncState=slotSyncState,\n-\t\t\t\thashComputationOnly=False\n-\t\t\t)\n-\n-\t\t\tif changes: globalChanges = True\n-\n-\t\t\ttypeEntityMatching[slotName] = newSlotTypeSyncState\n-\n-\t\t\tself.syncRemoteToLocalSlotTypeCache(\n-\t\t\t\tassistantId=runOnAssistantId,\n-\t\t\t\tassistantLanguage=languageFilter,\n-\t\t\t\tslotTypeName=slotName,\n-\t\t\t\tsyncState=newSlotTypeSyncState,\n-\t\t\t\tpersist=True\n-\t\t\t)\n-\n-\t\t\tslotTypesSynced[slotName] = True\n-\n-\t\t# Remove deprecated/renamed slotTypes\n-\t\thasDeprecatedSlotTypes = list()\n-\n-\t\tfor slotTypeName in self._savedAssistants[languageFilter][runOnAssistantId]['slotTypes']:\n-\t\t\tif slotTypeName not in slotTypesSynced:\n-\t\t\t\tself._ctx.log(f'Deprecated slotType {slotTypeName}')\n-\t\t\t\tslotTypeCacheData = self._savedAssistants[languageFilter][runOnAssistantId]['slotTypes'][slotTypeName]\n-\n-\t\t\t\tentityId = slotTypeCacheData['entityId']\n-\t\t\t\tself._ctx.entity.delete(entityId=entityId, language=languageFilter)\n-\n-\t\t\t\thasDeprecatedSlotTypes.append(slotTypeName)\n-\n-\t\tif hasDeprecatedSlotTypes:\n-\t\t\tglobalChanges = True\n-\n-\t\t\tfor slotTypeName in hasDeprecatedSlotTypes:\n-\t\t\t\tdel self._savedAssistants[languageFilter][runOnAssistantId]['slotTypes'][slotTypeName]\n-\n-\t\t\t\tif slotTypeName in self._savedSlots[languageFilter][runOnAssistantId]:\n-\t\t\t\t\tdel self._savedSlots[languageFilter][runOnAssistantId][slotTypeName]\n-\n-\t\t\t\t\tglobalSlotTypeFile = self.SAVED_ASSISTANTS_DIR / languageFilter / runOnAssistantId / 'slots' / f'{slotTypeName}.json'\n-\n-\t\t\t\t\tif globalSlotTypeFile.exists():\n-\t\t\t\t\t\tglobalSlotTypeFile.unlink()\n-\n-\t\t\tself.persistToLocalAssistantCache(assistantId=runOnAssistantId, assistantLanguage=languageFilter)\n-\n-\t\treturn typeEntityMatching, globalChanges\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef syncLocalToRemoteIntents(self, skillNameIdMatching: dict, intentNameSkillMatching: dict, typeEntityMatching: dict, intentsSkillsValues: dict,\n-\t runOnAssistantId: str, languageFilter: str = None, skillFilter: list = None) -> bool:\n-\n-\t\tintentsSynced = dict()\n-\t\tglobalChanges = False\n-\n-\t\tmergedIntents = self.mergeSkillIntents(\n-\t\t\tintentsSkillsValues=intentsSkillsValues,\n-\t\t\tassistantId=runOnAssistantId,\n-\t\t\tintentLanguage=languageFilter\n-\t\t)\n-\n-\t\tfor intentName, intent in mergedIntents.items():\n-\n-\t\t\tintentSyncState = self.getIntentSyncStateByLanguageAndAssistantId(\n-\t\t\t\tintentName=intentName,\n-\t\t\t\tlanguage=languageFilter,\n-\t\t\t\tassistantId=runOnAssistantId\n-\t\t\t)\n-\n-\t\t\tintentRemoteProcessor = IntentRemoteProcessor(\n-\t\t\t\tctx=self._ctx,\n-\t\t\t\tintent=intent,\n-\t\t\t\tintentLanguage=languageFilter,\n-\t\t\t\tassistantId=runOnAssistantId,\n-\t\t\t)\n-\n-\t\t\tif intentName not in intentNameSkillMatching or intentNameSkillMatching[intentName] not in skillNameIdMatching:\n-\t\t\t\tintentsSynced[intentName] = True\n-\t\t\t\tcontinue\n-\n-\t\t\tskillId = skillNameIdMatching[intentNameSkillMatching[intentName]]\n-\n-\t\t\tnewIntentSyncState, changes = intentRemoteProcessor.syncIntentsOnAssistantSafely(\n-\t\t\t\ttypeEntityMatching=typeEntityMatching,\n-\t\t\t\tskillId=skillId,\n-\t\t\t\tintentSyncState=intentSyncState,\n-\t\t\t\thashComputationOnly=False\n-\t\t\t)\n-\n-\t\t\tif changes: globalChanges = True\n-\n-\t\t\tself.syncRemoteToLocalIntentCache(\n-\t\t\t\tassistantId=runOnAssistantId,\n-\t\t\t\tassistantLanguage=languageFilter,\n-\t\t\t\tintentName=intentName,\n-\t\t\t\tsyncState=newIntentSyncState,\n-\t\t\t\tpersist=True\n-\t\t\t)\n-\n-\t\t\tintentsSynced[intentName] = True\n-\n-\t\t# Remove deprecated/renamed slotTypes\n-\t\thasDeprecatedIntents = list()\n-\n-\t\tfor intentName in self._savedAssistants[languageFilter][runOnAssistantId]['intents']:\n-\t\t\tif intentName not in intentsSynced:\n-\t\t\t\tself._ctx.log(f'Deprecated intent {intentName}')\n-\t\t\t\tintentCacheData = self._savedAssistants[languageFilter][runOnAssistantId]['intents'][intentName]\n-\n-\t\t\t\tintentId = intentCacheData['intentId']\n-\n-\t\t\t\ttry:\n-\t\t\t\t\tself._ctx.intent.delete(intentId=intentId)\n-\n-\t\t\t\texcept HttpError as he:\n-\t\t\t\t\tisAttachToSkillIds = (json.loads(json.loads(he.message)['message'])['skillIds'])\n-\n-\t\t\t\t\tfor isAttachToSkillId in isAttachToSkillIds:\n-\t\t\t\t\t\tself._ctx.intent.removeFromSkill(intentId=intentId, skillId=isAttachToSkillId, userId=self._ctx.userId, deleteAfter=False)\n-\n-\t\t\t\t\tself._ctx.intent.delete(intentId=intentId)\n-\n-\t\t\t\thasDeprecatedIntents.append(intentName)\n-\n-\t\tif hasDeprecatedIntents:\n-\t\t\tglobalChanges = True\n-\n-\t\t\tfor intentName in hasDeprecatedIntents:\n-\t\t\t\tdel self._savedAssistants[languageFilter][runOnAssistantId]['intents'][intentName]\n-\n-\t\t\t\tif intentName in self._savedIntents[languageFilter][runOnAssistantId]:\n-\t\t\t\t\tdel self._savedIntents[languageFilter][runOnAssistantId][intentName]\n-\n-\t\t\t\t\tglobalIntentFile = self.SAVED_ASSISTANTS_DIR / languageFilter / runOnAssistantId / 'intents' / f'{intentName}.json'\n-\n-\t\t\t\t\tif globalIntentFile.exists():\n-\t\t\t\t\t\tglobalIntentFile.unlink()\n-\n-\t\t\tself.persistToLocalAssistantCache(assistantId=runOnAssistantId, assistantLanguage=languageFilter)\n-\n-\t\treturn globalChanges\n-\n-\n-\tdef syncLocalToRemoteSkills(self, typeEntityMatching: dict, runOnAssistantId: str, languageFilter: str = None, skillFilter: list = None):\n-\t\tskillsSynced = dict()\n-\t\tglobalChanges = False\n-\n-\t\tskillNameIdMatching = dict()\n-\n-\t\tfor skillName, skillSettings in self._skills.items():\n-\t\t\tif languageFilter not in skillSettings:\n-\t\t\t\tcontinue\n-\n-\t\t\tskillSyncState = self.getSkillSyncStateByLanguageAndAssistantId(\n-\t\t\t\tskillName=skillName,\n-\t\t\t\tlanguage=languageFilter,\n-\t\t\t\tassistantId=runOnAssistantId\n-\t\t\t)\n-\n-\t\t\t# Start a SkillRemoteProcessor tasker for each skill(a.k.a skill)\n-\t\t\tskillRemoteProcessor = SkillRemoteProcessor(\n-\t\t\t\tctx=self._ctx,\n-\t\t\t\tassistantId=runOnAssistantId,\n-\t\t\t\tskill=skillSettings[languageFilter],\n-\t\t\t\tskillName=skillName,\n-\t\t\t\tskillLanguage=languageFilter\n-\t\t\t)\n-\n-\t\t\tnewSkillSyncState, changes = skillRemoteProcessor.syncSkillsOnAssistantSafely(\n-\t\t\t\ttypeEntityMatching=typeEntityMatching,\n-\t\t\t\tskillSyncState=skillSyncState,\n-\t\t\t\thashComputationOnly=False\n-\t\t\t)\n-\n-\t\t\tif changes: globalChanges = True\n-\n-\t\t\tskillNameIdMatching[skillName] = newSkillSyncState['skillId']\n-\n-\t\t\tself.syncRemoteToLocalSkillCache(\n-\t\t\t\tassistantId=runOnAssistantId,\n-\t\t\t\tassistantLanguage=languageFilter,\n-\t\t\t\tskillName=skillName,\n-\t\t\t\tsyncState=newSkillSyncState,\n-\t\t\t\tpersist=True\n-\t\t\t)\n-\n-\t\t\tskillsSynced[skillName] = True\n-\n-\t\t# Remove deprecated/renamed skills\n-\t\thasDeprecatedSkills = list()\n-\n-\t\tfor skillName in self._savedAssistants[languageFilter][runOnAssistantId]['skills']:\n-\t\t\tif skillFilter and skillName not in skillFilter:\n-\t\t\t\tcontinue\n-\n-\t\t\tif skillName not in skillsSynced:\n-\t\t\t\tself._ctx.log(f'Deprecated skill {skillName}')\n-\t\t\t\tskillCacheData = self._savedAssistants[languageFilter][runOnAssistantId]['skills'][skillName]\n-\t\t\t\tskillId = skillCacheData['skillId']\n-\n-\t\t\t\tfor slotTypeName in skillCacheData.get('slotTypes', list()):\n-\t\t\t\t\tentityId = skillCacheData['slotTypes'][slotTypeName]['entityId']\n-\t\t\t\t\tself._ctx.entity.delete(entityId=entityId, language=languageFilter)\n-\n-\t\t\t\tfor intentName in skillCacheData.get('intents', list()):\n-\t\t\t\t\tintentId = skillCacheData['intents'][intentName]['intentId']\n-\t\t\t\t\tself._ctx.intent.removeFromSkill(userId=self._ctx.userId, skillId=skillId, intentId=intentId, deleteAfter=True)\n-\n-\t\t\t\tself._ctx.skill.removeFromAssistant(assistantId=runOnAssistantId, skillId=skillId, deleteAfter=True)\n-\n-\t\t\t\thasDeprecatedSkills.append(skillName)\n-\n-\t\tif hasDeprecatedSkills:\n-\t\t\tglobalChanges = True\n-\n-\t\t\tfor skillName in hasDeprecatedSkills:\n-\t\t\t\tdel self._savedAssistants[languageFilter][runOnAssistantId]['skills'][skillName]\n-\n-\t\t\tself.persistToLocalAssistantCache(assistantId=runOnAssistantId, assistantLanguage=languageFilter)\n-\n-\t\treturn skillNameIdMatching, globalChanges\n-\n-\n-\t# TODO to refacto in different method of a new Processor\n-\tdef syncRemoteToLocal(self, runOnAssistantId: str, skillFilter: list = None, languageFilter: str = None):\n-\n-\t\t# Build cache\n-\t\tself._ctx.entity.listEntitiesByUserEmail(userEmail=self._ctx.userEmail, returnAllCacheIndexedBy='id')\n-\t\tremoteIndexedIntents = self._ctx.intent.listIntentsByUserId(userId=self._ctx.userId, returnAllCacheIndexedBy='id')\n-\t\tremoteIndexedSkills = self._ctx.skill.listSkillsByUserId(userId=self._ctx.userId, returnAllCacheIndexedBy='id')\n-\t\thasFork = False\n-\n-\t\t# Check for fork and execute fork if needed\n-\t\tfor assistant in self._ctx.assistant.list(rawResponse=True)['assistants']:\n-\t\t\tif assistant['id'] != runOnAssistantId:\n-\t\t\t\tcontinue\n-\n-\t\t\tfor skill in assistant['skills']:\n-\t\t\t\tskillId = skill['id']\n-\n-\t\t\t\tif skillId not in remoteIndexedSkills:\n-\t\t\t\t\tskillId = self._ctx.assistant.forkAssistantSkill(assistantId=runOnAssistantId, sourceSkillId=skillId)\n-\t\t\t\t\tself._ctx.log(f\"[Forked] Skill from {skill['id']} to {skillId}\")\n-\t\t\t\t\thasFork = True\n-\n-\t\t\t\tfor intent in skill['intents']:\n-\t\t\t\t\tintentId = intent['id']\n-\n-\t\t\t\t\tif intentId not in remoteIndexedIntents:\n-\t\t\t\t\t\tintentId = self._ctx.skill.forkSkillIntent(skillId=skillId, sourceIntentId=intentId, userId=self._ctx.userId)\n-\t\t\t\t\t\tself._ctx.log(f\"[Forked] Intent from {skill['id']} to {intentId} used in skill {skillId}\")\n-\t\t\t\t\t\thasFork = True\n-\n-\t\tif hasFork:\n-\t\t\t# Rebuild cache\n-\t\t\tself._ctx.entity.listEntitiesByUserEmail(userEmail=self._ctx.userEmail)\n-\t\t\tself._ctx.intent.listIntentsByUserId(userId=self._ctx.userId)\n-\t\t\tself._ctx.skill.listSkillsByUserId(userId=self._ctx.userId)\n-\n-\t\t# Build each skill configuration\n-\t\tskills = dict()\n-\n-\t\tcachedIndexedSkills = self._ctx.skill.listSkillsByUserIdAndAssistantId(userId=self._ctx.userId, assistantId=runOnAssistantId, fromCache=True)\n-\n-\t\tfor skill in cachedIndexedSkills:\n-\t\t\tskillName = SuperManager.getInstance().commons.toCamelCase(string=skill['name'], replaceSepCharacters=True, sepCharacters=('/', '-', '_'))\n-\n-\t\t\tif skillFilter and skillName not in skillFilter:\n-\t\t\t\tcontinue\n-\n-\t\t\tskills[skillName] = {\n-\t\t\t\t'skill' : skillName,\n-\t\t\t\t'icon' : EnumSkillImageUrl.urlToResourceKey(skill['imageUrl']),\n-\t\t\t\t'description': skill['description'],\n-\t\t\t\t'slotTypes' : list(),\n-\t\t\t\t'intents' : list()\n-\t\t\t}\n-\t\t\tskillSyncState = {\n-\t\t\t\t'skillId' : skill['id'],\n-\t\t\t\t'name' : skillName,\n-\t\t\t\t'slotTypes': dict(),\n-\t\t\t\t'intents' : dict(),\n-\t\t\t\t'hash' : ''\n-\t\t\t}\n-\n-\t\t\tcachedIndexedIntents = self._ctx.intent.listIntentsByUserIdAndSkillId(userId=self._ctx.userId, skillId=skill['id'], fromCache=True)\n-\t\t\ttypeEntityMatching = dict()\n-\n-\t\t\tfor intent in cachedIndexedIntents:\n-\t\t\t\tintentName = intent['name']\n-\n-\t\t\t\tif intentName.startswith(skill['name'] + '_'):\n-\t\t\t\t\tintentName = intentName.replace(skill['name'] + '_', '')\n-\n-\t\t\t\tintentName = SuperManager.getInstance().commons.toCamelCase(string=intentName, replaceSepCharacters=True, sepCharacters=('/', '-', '_'))\n-\n-\t\t\t\tutterances = list()\n-\t\t\t\tobjectUtterances = self._ctx.intent.listUtterancesByIntentId(intentId=intent['id'])\n-\n-\t\t\t\tslotIdAndNameMatching = {slot['id']: slot for slot in intent['slots']}\n-\n-\t\t\t\tfor objectUtterance in objectUtterances:\n-\t\t\t\t\ttext = objectUtterance['text']\n-\t\t\t\t\tpositionOffset = 0\n-\n-\t\t\t\t\tfor hole in objectUtterance['data']:\n-\t\t\t\t\t\tword = hole['text']\n-\t\t\t\t\t\tstart = hole['range']['start'] + positionOffset\n-\t\t\t\t\t\tend = hole['range']['end'] + positionOffset\n-\t\t\t\t\t\tslotName = slotIdAndNameMatching[hole['slotId']]['name']\n-\t\t\t\t\t\tslotName = SuperManager.getInstance().commons.toCamelCase(string=slotName, replaceSepCharacters=True, sepCharacters=('/', '-', '_'))\n-\t\t\t\t\t\tnewWord = '{' + word + self._ctx.intent.GLUE_SLOT_WORD + slotName + '}'\n-\t\t\t\t\t\ttext = text[:start] + newWord + text[end:]\n-\t\t\t\t\t\tpositionOffset += len(newWord) - len(word)\n-\n-\t\t\t\t\tutterances.append(text)\n-\n-\t\t\t\tcachedIndexedEntities = self._ctx.entity.listEntitiesByUserEmailAndIntentId(userEmail=self._ctx.userEmail, intentId=intent['id'], fromCache=True)\n-\n-\t\t\t\tfor entity in cachedIndexedEntities:\n-\t\t\t\t\tif entity['id'] in typeEntityMatching:\n-\t\t\t\t\t\tcontinue\n-\n-\t\t\t\t\tvalues = self._ctx.entity.listEntityValuesByEntityId(entityId=entity['id'])\n-\t\t\t\t\tentityName = SuperManager.getInstance().commons.toCamelCase(string=entity['name'], replaceSepCharacters=True, sepCharacters=('/', '-', '_'))\n-\t\t\t\t\ttypeEntityMatching[entity['id']] = entityName\n-\n-\t\t\t\t\tskills[skillName]['slotTypes'].append({\n-\t\t\t\t\t\t'name' : entityName,\n-\t\t\t\t\t\t'matchingStrictness' : entity['matchingStrictness'],\n-\t\t\t\t\t\t'automaticallyExtensible': entity['automaticallyExtensible'],\n-\t\t\t\t\t\t'useSynonyms' : entity['useSynonyms'],\n-\t\t\t\t\t\t'values' : values\n-\t\t\t\t\t})\n-\t\t\t\t\tskillSyncState['slotTypes'][entityName] = {\n-\t\t\t\t\t\t'entityId': entity['id'],\n-\t\t\t\t\t\t'hash' : ''\n-\t\t\t\t\t}\n-\n-\t\t\t\tslots = [{\n-\t\t\t\t\t'name' : SuperManager.getInstance().commons.toCamelCase(string=slot['name'], replaceSepCharacters=True, sepCharacters=('/', '-', '_')),\n-\t\t\t\t\t'description' : slot['description'],\n-\t\t\t\t\t'required' : slot['required'],\n-\t\t\t\t\t'type' : slot['entityId'] if slot['entityId'].startswith('snips/') else typeEntityMatching[slot['entityId']],\n-\t\t\t\t\t'missingQuestion': slot['missingQuestion']\n-\t\t\t\t} for slot in intent['slots']]\n-\n-\t\t\t\tskills[skillName]['intents'].append({\n-\t\t\t\t\t'name' : intentName,\n-\t\t\t\t\t'description' : intent['description'],\n-\t\t\t\t\t'enabledByDefault': intent['enabledByDefault'],\n-\t\t\t\t\t'utterances' : utterances,\n-\t\t\t\t\t'slots' : slots\n-\t\t\t\t})\n-\t\t\t\tskillSyncState['intents'][intentName] = {\n-\t\t\t\t\t'intentId': intent['id'],\n-\t\t\t\t\t'hash' : ''\n-\t\t\t\t}\n-\n-\t\t\t# Persist skill configuration\n-\t\t\tskillConfig = skills[skillName]\n-\t\t\tskillIntentsMountpoint = Path(self.SAVED_MODULES_DIR, skillName, 'dialogTemplate')\n-\t\t\tskillIntentsMountpoint.mkdir(parents=True, exist_ok=True)\n-\n-\t\t\tskillIntentsOutputFile = skillIntentsMountpoint / f'{languageFilter}.json'\n-\n-\t\t\tskillIntentsOutputFile.write_text(json.dumps(skillConfig, indent=4, sort_keys=False, ensure_ascii=False))\n-\t\t\tself._ctx.log(f'Finished for skill {skillName}')\ndiff --git a/core/snips/samkilla/processors/SkillRemoteProcessor.py b/core/snips/samkilla/processors/SkillRemoteProcessor.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/processors/SkillRemoteProcessor.py\n+++ /dev/null\n@@ -1,105 +0,0 @@\n-import hashlib\n-import sys\n-import traceback\n-\n-from core.snips import SamkillaManager\n-from core.snips.samkilla.models.EnumSkillImageUrl import EnumSkillImageUrl as EnumSkillImageUrlClass\n-\n-EnumSkillImageUrl = EnumSkillImageUrlClass()\n-\n-\n-class SkillRemoteProcessor:\n-\n-\tdef __init__(self, ctx: SamkillaManager, assistantId: str, skill: dict, skillName: str, skillLanguage: str):\n-\t\tself._ctx = ctx\n-\t\tself._assistantId = assistantId\n-\t\tself._skill = skill\n-\t\tself._skillName = skillName\n-\t\tself._skillLanguage = skillLanguage\n-\t\tself._syncState = None\n-\t\tself._createdInstances = {\n-\t\t\t'skills': list()\n-\t\t}\n-\n-\n-\tdef createNewSavedSkill(self) -> dict:\n-\t\treturn {\n-\t\t\t'skillId': None,\n-\t\t\t'name' : self._skillName\n-\t\t}\n-\n-\n-\t@staticmethod\n-\tdef skillValuesToHash(icon: str, description: str, skillId: str = '') -> str:\n-\t\thashSum = f'{icon}{description}{skillId}'\n-\t\treturn hashlib.sha512(hashSum.encode('utf-8')).hexdigest()\n-\n-\n-\tdef syncedSkillExists(self) -> bool:\n-\t\treturn 'hash' in self._syncState and str(self._syncState['skillId']).startswith('skill_')\n-\n-\n-\tdef syncSkill(self, skillDescription: str, skillIcon: str, hashComputationOnly: bool = False):\n-\t\toldInstanceExists = self.syncedSkillExists()\n-\t\toldHash = self._syncState['hash'] if oldInstanceExists else ''\n-\t\tskillId = self._syncState['skillId'] if oldInstanceExists else ''\n-\t\tcurHash = self.skillValuesToHash(icon=skillIcon, description=skillDescription, skillId=skillId)\n-\t\tchanges = False\n-\n-\t\tif hashComputationOnly or (oldInstanceExists and oldHash == curHash):\n-\t\t\tself._ctx.log(f'Skill model {skillId} ({self._skillName}) has no changes')\n-\t\telif oldInstanceExists:\n-\t\t\tchanges = True\n-\t\t\tself._ctx.log(f'Skill model {skillId} ({self._skillName}) has been edited')\n-\t\t\tself._ctx.skill.edit(skillId, description=skillDescription, imageKey=EnumSkillImageUrl.getResourceFileByAttr(skillIcon))\n-\t\telse:\n-\t\t\tchanges = True\n-\t\t\tskillId = self._ctx.skill.create(\n-\t\t\t\tassistantId=self._assistantId,\n-\t\t\t\tname=self._skillName,\n-\t\t\t\tdescription=skillDescription,\n-\t\t\t\tlanguage=self._skillLanguage,\n-\t\t\t\timageKey=EnumSkillImageUrl.getResourceFileByAttr(skillIcon),\n-\t\t\t\tattachToAssistant=True\n-\t\t\t)\n-\t\t\tself._ctx.log(f'Skill model {skillId} ({self._skillName}) has been created')\n-\t\t\tself._createdInstances['skills'].append({'id': skillId, 'assistantId': self._assistantId})\n-\t\t\tcurHash = self.skillValuesToHash(icon=skillIcon, description=skillDescription, skillId=skillId)\n-\n-\t\treturn {\n-\t\t\t'skillId': skillId,\n-\t\t\t'hash' : curHash,\n-\t\t\t'changes': changes\n-\t\t}\n-\n-\n-\tdef syncSkillsOnAssistantSafely(self, typeEntityMatching: dict, skillSyncState: str = None, hashComputationOnly: bool = False):\n-\t\ttry:\n-\t\t\treturn self.syncSkillsOnAssistant(typeEntityMatching=typeEntityMatching, skillSyncState=skillSyncState, hashComputationOnly=hashComputationOnly)\n-\t\texcept:\n-\t\t\te = sys.exc_info()[0]\n-\t\t\tself._ctx.log('Handle error gracefully')\n-\t\t\tself._ctx.log(e)\n-\t\t\tself._ctx.log(traceback.format_exc())\n-\t\t\tsys.exit(-1)\n-\n-\n-\t# noinspection PyUnusedLocal\n-\tdef syncSkillsOnAssistant(self, typeEntityMatching: dict = None, skillSyncState: str = None, hashComputationOnly: bool = False) -> tuple:\n-\t\t#TODO this appears wrong skillSyncState is a str according to typing while self.createNewSavedSkill() returns a dict\n-\t\t# is is used as a dict aswell. Is the typing wrong?\n-\t\tself._syncState = skillSyncState or self.createNewSavedSkill()\n-\n-\t\tskillData = self.syncSkill(self._skill['description'], self._skill['icon'], hashComputationOnly)\n-\t\tself._syncState['skillId'] = skillData['skillId']\n-\t\tself._syncState['hash'] = skillData['hash']\n-\t\tself._syncState['name'] = self._skillName\n-\n-\t\treturn self._syncState, skillData['changes']\n-\n-\n-\tdef cleanCreatedInstances(self):\n-\t\tself._ctx.log(f\"[Cleanup] Deleting {len(self._createdInstances['skills'])} skills\")\n-\t\tfor skill in self._createdInstances['skills']:\n-\t\t\tself._ctx.skill.removeFromAssistant(assistantId=skill['assistantId'], skillId=skill['id'], deleteAfter=True)\n-\t\tself._createdInstances['skills'] = list()\ndiff --git a/core/snips/samkilla/processors/SlotTypeRemoteProcessor.py b/core/snips/samkilla/processors/SlotTypeRemoteProcessor.py\ndeleted file mode 100644\n--- a/core/snips/samkilla/processors/SlotTypeRemoteProcessor.py\n+++ /dev/null\n@@ -1,108 +0,0 @@\n-import hashlib\n-import sys\n-import traceback\n-\n-from core.snips import SamkillaManager\n-\n-\n-class SlotTypeRemoteProcessor:\n-\n-\tdef __init__(self, ctx: SamkillaManager, slotType: dict, slotLanguage: str, assistantId: str):\n-\t\tself._ctx = ctx\n-\t\tself._slotType = slotType\n-\t\tself._assistantId = assistantId\n-\t\tself._slotTypeLanguage = slotLanguage\n-\t\tself._syncState = None\n-\t\tself._createdInstances = {'entities': list()}\n-\n-\n-\tdef createNewSavedSlotType(self) -> dict:\n-\t\treturn {\n-\t\t\t'name': self._slotType['name']\n-\t\t}\n-\n-\n-\tdef slotTypeValuesToHash(self, entityId: str = '') -> str:\n-\t\tslotType = self._slotType\n-\n-\t\thashSum = f\"{str(slotType['name'])}{str(slotType['matchingStrictness'])}{str(slotType['automaticallyExtensible'])}{str(slotType['useSynonyms'])}\"\n-\n-\t\tfor valueObject in slotType['values']:\n-\t\t\thashSum += str(valueObject['value'])\n-\t\t\tfor synonym in valueObject.get('synonyms', list()):\n-\t\t\t\thashSum += str(synonym)\n-\n-\t\thashSum += entityId\n-\n-\t\treturn hashlib.sha512(hashSum.encode('utf-8')).hexdigest()\n-\n-\n-\tdef syncedSlotTypeExists(self) -> bool:\n-\t\treturn 'hash' in self._syncState and 'entityId' in self._syncState\n-\n-\n-\tdef syncSlotType(self, hashComputationOnly = False) -> dict:\n-\t\tslotType = self._slotType\n-\n-\t\toldInstanceExists = self.syncedSlotTypeExists()\n-\t\toldHash = self._syncState['hash'] if oldInstanceExists else ''\n-\t\tentityId = self._syncState['entityId'] if oldInstanceExists else ''\n-\t\tcurHash = self.slotTypeValuesToHash(entityId=entityId)\n-\t\tchanges = False\n-\n-\t\tif hashComputationOnly or (oldInstanceExists and oldHash == curHash):\n-\t\t\tself._ctx.log(f\"[Sync] Entity|SlotType model {entityId} = {slotType['name']} has no changes\")\n-\t\telif oldInstanceExists:\n-\t\t\tchanges = True\n-\t\t\tself._ctx.log(f\"[Sync] Entity|SlotType model {entityId} = {slotType['name']} has been edited\")\n-\t\t\tself._ctx.entity.edit(\n-\t\t\t\tentityId,\n-\t\t\t\tname=slotType['name'],\n-\t\t\t\tmatchingStrictness=slotType['matchingStrictness'],\n-\t\t\t\tautomaticallyExtensible=slotType['automaticallyExtensible'],\n-\t\t\t\tuseSynonyms=slotType['useSynonyms'],\n-\t\t\t\tslotValues=slotType['values']\n-\t\t\t)\n-\t\telse:\n-\t\t\tchanges = True\n-\t\t\tentityId = self._ctx.entity.create(\n-\t\t\t\tlanguage=self._slotTypeLanguage,\n-\t\t\t\tname=slotType['name'],\n-\t\t\t\tmatchingStrictness=slotType['matchingStrictness'],\n-\t\t\t\tautomaticallyExtensible=slotType['automaticallyExtensible'],\n-\t\t\t\tuseSynonyms=slotType['useSynonyms'],\n-\t\t\t\tslotValues=slotType['values']\n-\t\t\t)\n-\t\t\tself._ctx.log(f\"[Sync] Entity|SlotType model {entityId} = {slotType['name']} has been created\")\n-\t\t\tself._createdInstances['entities'].append({'id': entityId})\n-\t\t\tcurHash = self.slotTypeValuesToHash(entityId=entityId)\n-\n-\t\treturn {'entityId': entityId, 'hash': curHash, 'changes': changes}\n-\n-\n-\tdef syncSlotTypesOnAssistantSafely(self, slotTypeSyncState: str = None, hashComputationOnly: bool = False):\n-\t\ttry:\n-\t\t\treturn self.syncSlotTypesOnAssistant(slotTypeSyncState=slotTypeSyncState, hashComputationOnly=hashComputationOnly)\n-\t\texcept:\n-\t\t\te = sys.exc_info()[0]\n-\t\t\tself._ctx.log('Handle error gracefully')\n-\t\t\tself._ctx.log(e)\n-\t\t\tself._ctx.log(traceback.format_exc())\n-\t\t\tsys.exit(-1)\n-\n-\n-\tdef syncSlotTypesOnAssistant(self, slotTypeSyncState: str = None, hashComputationOnly: bool = False) -> tuple:\n-\t\tself._syncState = slotTypeSyncState or self.createNewSavedSlotType()\n-\n-\t\tslotTypeMatching = self.syncSlotType(hashComputationOnly)\n-\t\tself._syncState['hash'] = slotTypeMatching['hash']\n-\t\tself._syncState['entityId'] = slotTypeMatching['entityId']\n-\n-\t\treturn self._syncState, slotTypeMatching['changes']\n-\n-\n-\tdef cleanCreatedInstances(self):\n-\t\tself._ctx.log(f\"[Cleanup] Deleting {len(self._createdInstances['entities'])} entities\")\n-\t\tfor entity in self._createdInstances['entities']:\n-\t\t\tself._ctx.entity.delete(entityId=entity['id'])\n-\t\tself._createdInstances['entities'] = list()\ndiff --git a/core/snips/samkilla/processors/__init__.py b/core/snips/samkilla/processors/__init__.py\ndeleted file mode 100644\ndiff --git a/core/user/UserManager.py b/core/user/UserManager.py\n--- a/core/user/UserManager.py\n+++ b/core/user/UserManager.py\n@@ -1,6 +1,9 @@\n-from typing import Any, Optional\n+from pathlib import Path\n+from time import time\n+from typing import Any, Dict, Optional\n \n import bcrypt\n+import jwt\n \n from core.base.model.Manager import Manager\n from core.user.model.AccessLevels import AccessLevel\n@@ -8,9 +11,6 @@\n \n \n class UserManager(Manager):\n-\n-\tNAME = 'UserManager'\n-\n \tDATABASE = {\n \t\t'users': [\n \t\t\t'id INTEGER PRIMARY KEY',\n@@ -22,14 +22,16 @@ class UserManager(Manager):\n \t\t\t'tts TEXT',\n \t\t\t'ttsLanguage TEXT',\n \t\t\t'ttsType TEXT',\n-\t\t\t'ttsVoice TEXT'\n+\t\t\t'ttsVoice TEXT',\n+\t\t\t'apiToken TEXT'\n \t\t]\n \t}\n \n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME, self.DATABASE)\n-\t\tself._users = dict()\n+\t\tsuper().__init__(databaseSchema=self.DATABASE)\n+\t\tself._users: Dict[str: User] = dict()\n+\t\tself._validtokens: Dict[str: User] = dict()\n \n \n \tdef onStart(self):\n@@ -41,7 +43,24 @@ def onStart(self):\n \tdef _loadUsers(self):\n \t\trows = self.databaseFetch(tableName='users', query='SELECT * FROM :__table__', method='all')\n \t\tfor row in rows:\n-\t\t\tself._users[row['username']] = User(row)\n+\t\t\tuser = User(row)\n+\t\t\tself._users[user.name] = user\n+\t\t\tself._validtokens[user.apiToken] = user\n+\n+\n+\tdef createApiToken(self, user: User, save: bool = True) -> str:\n+\t\ttoken = jwt.encode({'user': user.name, 'birth': time()}, 'projectalice', algorithm='HS256').decode()\n+\t\tself._validtokens[token] = user\n+\n+\t\tif save:\n+\t\t\tuser.apiToken = token\n+\t\t\tself.DatabaseManager.update(\n+\t\t\t\ttableName='users',\n+\t\t\t\tcallerName=self.name,\n+\t\t\t\tvalues={'apiToken': token},\n+\t\t\t\trow=('username', user.name))\n+\n+\t\treturn token\n \n \n \t@property\n@@ -65,24 +84,25 @@ def addNewUser(self, name: str, access: str = 'guest', state: str = 'home', pinC\n \t\tinsertId = self.databaseInsert(\n \t\t\ttableName='users',\n \t\t\tvalues={\n-\t\t\t\t'username': name.lower(),\n+\t\t\t\t'username' : name.lower(),\n \t\t\t\t'accessLevel': access,\n-\t\t\t\t'state': state,\n-\t\t\t\t'pin': hashedPassword,\n-\t\t\t\t'lang': self.LanguageManager.activeLanguageAndCountryCode\n+\t\t\t\t'state' : state,\n+\t\t\t\t'pin' : hashedPassword,\n+\t\t\t\t'lang' : self.LanguageManager.activeLanguageAndCountryCode\n \t\t\t})\n \t\tif insertId > -1:\n \t\t\tself._users[name] = User({\n-\t\t\t\t'id': insertId,\n-\t\t\t\t'username': name.title(),\n+\t\t\t\t'id' : insertId,\n+\t\t\t\t'username' : name.title(),\n \t\t\t\t'accessLevel': access,\n-\t\t\t\t'state': state,\n-\t\t\t\t'pin': hashedPassword,\n-\t\t\t\t'lang': self.LanguageManager.activeLanguageAndCountryCode,\n-\t\t\t\t'tts': '',\n+\t\t\t\t'state' : state,\n+\t\t\t\t'pin' : hashedPassword,\n+\t\t\t\t'lang' : self.LanguageManager.activeLanguageAndCountryCode,\n+\t\t\t\t'tts' : '',\n \t\t\t\t'ttsLanguage': '',\n-\t\t\t\t'ttsType': '',\n-\t\t\t\t'ttsVoice': ''\n+\t\t\t\t'ttsType' : '',\n+\t\t\t\t'ttsVoice' : '',\n+\t\t\t\t'apiToken' : ''\n \t\t\t})\n \n \n@@ -94,6 +114,25 @@ def addUserPinCode(self, name: str, pinCode: int):\n \t\t\trow=('username', name))\n \n \n+\t# noinspection SqlResolve\n+\tdef deleteUser(self, username: str, keepWakeword: bool = False):\n+\t\tself.DatabaseManager.delete(\n+\t\t\ttableName='users',\n+\t\t\tcallerName=self.name,\n+\t\t\tquery='DELETE FROM :__table__ WHERE username = :username',\n+\t\t\tvalues={\n+\t\t\t\t'username': username\n+\t\t\t}\n+\t\t)\n+\n+\t\tself._users.pop(username)\n+\n+\t\tif not keepWakeword:\n+\t\t\tpath = Path(self.Commons.rootDir(), 'trained/hotwords', username)\n+\t\t\tif path.exists():\n+\t\t\t\tpath.unlink()\n+\n+\n \tdef getUserAccessLevel(self, username: str) -> Optional[Any]:\n \t\tif username not in self._users:\n \t\t\treturn None\n@@ -191,3 +230,15 @@ def hasAccessLevel(self, user: str, requiredAccessLevel: int) -> bool:\n \t\t\trequiredAccessLevel = requiredAccessLevel.value\n \n \t\treturn user.lower() in self._users and AccessLevel[self._users[user.lower()].accessLevel.upper()].value <= requiredAccessLevel\n+\n+\n+\tdef apiTokenValid(self, token: str) -> bool:\n+\t\treturn token != '' and token in self._validtokens\n+\n+\n+\tdef apiTokenLevel(self, token: str) -> AccessLevel:\n+\t\treturn self._validtokens[token].accessLevel\n+\n+\n+\tdef getUserByAPIToken(self, token: str) -> Optional[User]:\n+\t\treturn self._validtokens.get(token, None)\ndiff --git a/core/user/model/AccessLevels.py b/core/user/model/AccessLevels.py\n--- a/core/user/model/AccessLevels.py\n+++ b/core/user/model/AccessLevels.py\n@@ -3,6 +3,7 @@\n \n @unique\n class AccessLevel(IntEnum):\n+\tZERO = 0\n \tADMIN = 1\n \tDEFAULT = 2\n \tKID = 3\ndiff --git a/core/user/model/User.py b/core/user/model/User.py\n--- a/core/user/model/User.py\n+++ b/core/user/model/User.py\n@@ -10,35 +10,35 @@ class User(ProjectAliceObject):\n \tdef __init__(self, row: typing.Optional[dict]):\n \t\tsuper().__init__(logDepth=3)\n \n-\t\t#TODO is it correct to init these values only when row exists?\n+\t\t# TODO is it correct to init these values only when row exists?\n \t\t# -> will throw exception when property is called or should they be\n \t\t# inited to None instead\n \t\tif row:\n-\t\t\tself._id\t\t\t= row['id']\n-\t\t\tself._name\t\t\t= row['username']\n-\t\t\tself._accessLevel\t= row['accessLevel']\n-\t\t\tself._state\t\t\t= row['state']\n-\t\t\tself._pin\t\t\t= row['pin']\n-\t\t\tself._lang\t\t\t= row['lang']\n-\t\t\tself._tts\t\t\t= row['tts']\n-\t\t\tself._ttsLanguage\t= row['ttsLanguage']\n-\t\t\tself._ttsType\t\t= row['ttsType']\n-\t\t\tself._ttsVoice\t\t= row['ttsVoice']\n-\n-\t\tself._home\t\t\t= False\n-\t\tself._goingBed\t\t= False\n-\t\tself._sleeping\t\t= False\n-\t\tself._cooking\t\t= False\n-\t\tself._makeUp\t\t= False\n-\t\tself._watchingTV\t= False\n-\t\tself._eating\t\t= False\n+\t\t\tself._id = row['id']\n+\t\t\tself._name = row['username']\n+\t\t\tself._accessLevel = row['accessLevel']\n+\t\t\tself._state = row['state']\n+\t\t\tself._pin = row['pin']\n+\t\t\tself._lang = row['lang']\n+\t\t\tself._tts = row['tts']\n+\t\t\tself._ttsLanguage = row['ttsLanguage']\n+\t\t\tself._ttsType = row['ttsType']\n+\t\t\tself._ttsVoice = row['ttsVoice']\n+\t\t\tself._apiToken = row['apiToken']\n+\n+\t\tself._home = False\n+\t\tself._goingBed = False\n+\t\tself._sleeping = False\n+\t\tself._cooking = False\n+\t\tself._makeUp = False\n+\t\tself._watchingTV = False\n+\t\tself._eating = False\n \n \t\ttry:\n \t\t\texec(f\"self._{self._state} = 'True'\")\n \t\texcept:\n \t\t\tself.logError(f\"Invalid state \\\"{row['state']}\\\" for user \\\"{self._name}\\\"\")\n \n-\n \t\t# flask login reqs\n \t\tself._isAuthenticated = False\n \t\tself._isActive = True\n@@ -47,15 +47,15 @@ def __init__(self, row: typing.Optional[dict]):\n \n \tdef toJson(self) -> dict:\n \t\treturn {\n-\t\t\t'id': self._id,\n-\t\t\t'name': self._name,\n+\t\t\t'id' : self._id,\n+\t\t\t'name' : self._name,\n \t\t\t'accessLevel': self._accessLevel,\n-\t\t\t'state': self._state,\n-\t\t\t'lang': self._lang,\n-\t\t\t'tts': self._tts,\n+\t\t\t'state' : self._state,\n+\t\t\t'lang' : self._lang,\n+\t\t\t'tts' : self._tts,\n \t\t\t'ttsLanguage': self._ttsLanguage,\n-\t\t\t'ttsType': self._ttsType,\n-\t\t\t'ttsVoice': self._ttsVoice\n+\t\t\t'ttsType' : self._ttsType,\n+\t\t\t'ttsVoice' : self._ttsVoice\n \t\t}\n \n \n@@ -63,114 +63,152 @@ def toJson(self) -> dict:\n \tdef id(self) -> int:\n \t\treturn self._id\n \n+\n \t@property\n \tdef name(self) -> str:\n \t\treturn self._name\n \n+\n \t@property\n \tdef accessLevel(self) -> str:\n \t\treturn self._accessLevel\n \n+\n \t@property\n \tdef pin(self) -> bytes:\n \t\treturn self._pin\n \n+\n \t@property\n \tdef state(self) -> str:\n \t\treturn self._state\n \n+\n \t@property\n \tdef lang(self) -> str:\n \t\treturn self._lang\n \n+\n \t@property\n \tdef tts(self) -> str:\n \t\treturn self._tts\n \n+\n \t@property\n \tdef ttsLanguage(self) -> str:\n \t\treturn self._ttsLanguage\n \n+\n \t@property\n \tdef ttsType(self) -> str:\n \t\treturn self._ttsType\n \n+\n \t@property\n \tdef ttsVoice(self) -> str:\n \t\treturn self._ttsVoice\n \n+\n+\t@property\n+\tdef apiToken(self) -> str:\n+\t\treturn self._apiToken\n+\n+\n+\t@apiToken.setter\n+\tdef apiToken(self, val: str):\n+\t\tself._apiToken = val\n+\n+\n \t@property\n \tdef home(self) -> bool:\n \t\treturn self._home\n \n+\n \t@property\n \tdef goingBed(self) -> bool:\n \t\treturn self._goingBed\n \n+\n \t@property\n \tdef sleeping(self) -> bool:\n \t\treturn self._sleeping\n \n+\n \t@property\n \tdef cooking(self) -> bool:\n \t\treturn self._cooking\n \n+\n \t@property\n \tdef makeUp(self) -> bool:\n \t\treturn self._makeUp\n \n+\n \t@property\n \tdef watchingTV(self) -> bool:\n \t\treturn self._watchingTV\n \n+\n \t@property\n \tdef eating(self) -> bool:\n \t\treturn self._eating\n \n+\n \t@name.setter\n \tdef name(self, value: str):\n \t\tself._name = value\n \n+\n \t@accessLevel.setter\n \tdef accessLevel(self, value: str):\n \t\tself._accessLevel = value\n \n+\n \t@pin.setter\n \tdef pin(self, value: bytes):\n \t\tself._pin = value\n \n+\n \t@state.setter\n \tdef state(self, value: str):\n \t\tself._state = value\n \n+\n \t@home.setter\n \tdef home(self, value: bool):\n \t\tself._home = value\n \n+\n \t@goingBed.setter\n \tdef goingBed(self, value: bool):\n \t\tself._goingBed = value\n \n+\n \t@sleeping.setter\n \tdef sleeping(self, value: bool):\n \t\tself._sleeping = value\n \n+\n \t@cooking.setter\n \tdef cooking(self, value: bool):\n \t\tself._cooking = value\n \n+\n \t@makeUp.setter\n \tdef makeUp(self, value: bool):\n \t\tself._makeUp = value\n \n+\n \t@watchingTV.setter\n \tdef watchingTV(self, value: bool):\n \t\tself._watchingTV = value\n \n+\n \t@eating.setter\n \tdef eating(self, value: bool):\n \t\tself._eating = value\n \n+\n \tdef checkPassword(self, password: str) -> bool:\n \t\tif self.pin is None:\n \t\t\tself.logWarning('No pin defined for this user')\n@@ -178,39 +216,48 @@ def checkPassword(self, password: str) -> bool:\n \n \t\treturn bcrypt.checkpw(str(password).encode(), self.pin)\n \n+\n \t@property\n \tdef isAuthenticated(self) -> bool:\n \t\treturn self.is_authenticated\n \n+\n \t@isAuthenticated.setter\n \tdef isAuthenticated(self, value: bool):\n \t\tself.is_authenticated = value\n \n+\n \t@property\n \tdef isActive(self) -> bool:\n \t\treturn self.is_active\n \n+\n \t@property\n \tdef isAnonymous(self) -> bool:\n \t\treturn self.is_anonymous\n \n+\n \t# Flask login reqs\n \t# Do not rename to our standards!!!\n \tdef get_id(self) -> int:\n \t\treturn self._id\n \n+\n \t@property\n \tdef is_authenticated(self) -> bool:\n \t\treturn self._isAuthenticated\n \n+\n \t@is_authenticated.setter\n \tdef is_authenticated(self, value: bool):\n \t\tself._isAuthenticated = value\n \n+\n \t@property\n \tdef is_active(self) -> bool:\n \t\treturn self._isActive\n \n+\n \t@property\n \tdef is_anonymous(self) -> bool:\n \t\treturn self._isAnonymous\ndiff --git a/core/util/DatabaseManager.py b/core/util/DatabaseManager.py\n--- a/core/util/DatabaseManager.py\n+++ b/core/util/DatabaseManager.py\n@@ -6,12 +6,11 @@\n from core.commons import constants\n \n \n+# noinspection SqlResolve\n class DatabaseManager(Manager):\n \n-\tNAME = 'DatabaseManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \t\tself._tables = list()\n \n \n@@ -186,8 +185,8 @@ def insert(self, tableName: str, query: str = None, callerName: str = None, valu\n \n \tdef update(self, tableName: str, callerName: str, values: dict, query: str = None, row: tuple = None) -> bool:\n \t\tif not query:\n-\t\t\tupdates = [f'{col} = :{val}' for col, val in values.items()]\n-\t\t\tquery = f\"UPDATE :__table__ SET {' ,'.join(updates)} WHERE {row[0]} = {row[1]}\"\n+\t\t\tupdates = [f'{col} = \":{val}\"' for col, val in values.items()]\n+\t\t\tquery = f'UPDATE :__table__ SET {\" ,\".join(updates)} WHERE {row[0]} = \"{row[1]}\"'\n \n \t\tquery = self.basicChecks(tableName, query, callerName, values)\n \t\tif not query:\ndiff --git a/core/util/Decorators.py b/core/util/Decorators.py\n--- a/core/util/Decorators.py\n+++ b/core/util/Decorators.py\n@@ -1,12 +1,14 @@\n from __future__ import annotations\n \n-from typing import Callable, Tuple, Union\n-\n import functools\n import warnings\n+from typing import Any, Callable, Tuple, Union\n+\n+from flask import jsonify, request\n \n from core.base.SuperManager import SuperManager\n from core.base.model.Intent import Intent\n+from core.user.model.AccessLevels import AccessLevel\n from core.util.model.Logger import Logger\n \n \n@@ -30,37 +32,60 @@ def new_func(*args, **kwargs):\n \treturn new_func\n \n \n-def IntentHandler(intent: Union[str, Intent], requiredState: str = None, isProtected: bool = False, authOnly = 0):\n+def IntentHandler(intent: Union[str, Intent], requiredState: str = None, isProtected: bool = False, authLevel: AccessLevel = AccessLevel.ZERO):\n \t\"\"\"Decorator for adding a method as an intent handler.\"\"\"\n \tif isinstance(intent, str):\n-\t\tintent = Intent(intent, isProtected=isProtected, userIntent=True, authOnly=authOnly)\n+\t\tintent = Intent(intent, isProtected=isProtected, userIntent=True, authLevel=authLevel)\n \n \tdef wrapper(func):\n \t\t# store the intent in the function\n \t\tif not hasattr(func, 'intents'):\n \t\t\tfunc.intents = []\n-\t\tfunc.intents.append({'intent':intent, 'requiredState': requiredState})\n+\t\tfunc.intents.append({'intent': intent, 'requiredState': requiredState})\n \t\treturn func\n \n \treturn wrapper\n \n \n-def MqttHandler(intent: Union[str, Intent], requiredState: str = None, isProtected: bool = True, authOnly = 0):\n+def MqttHandler(intent: Union[str, Intent], requiredState: str = None, isProtected: bool = True, authLevel: AccessLevel = AccessLevel.ZERO):\n \t\"\"\"Decorator for adding a method as a mqtt handler.\"\"\"\n \tif isinstance(intent, str):\n-\t\tintent = Intent(intent, isProtected=isProtected, userIntent=False, authOnly=authOnly)\n+\t\tintent = Intent(intent, isProtected=isProtected, userIntent=False, authLevel=authLevel)\n \n \tdef wrapper(func):\n \t\t# store the intent in the function\n \t\tif not hasattr(func, 'intents'):\n \t\t\tfunc.intents = []\n-\t\tfunc.intents.append({'intent':intent, 'requiredState': requiredState})\n+\t\tfunc.intents.append({'intent': intent, 'requiredState': requiredState})\n \t\treturn func\n \n \treturn wrapper\n \n \n-def Online(func: Callable = None, text: str = 'offline', offlineHandler: Callable = None, returnText: bool = False):\n+def _exceptHandler(*args, text: str, exceptHandler: Callable, returnText: bool, **kwargs):\n+\tif exceptHandler:\n+\t\treturn exceptHandler(*args, **kwargs)\n+\n+\tcaller = args[0] if args else None\n+\tskill = getattr(caller, 'name', 'system')\n+\tnewText = SuperManager.getInstance().talkManager.randomTalk(text, skill=skill)\n+\tif not newText and skill != 'system':\n+\t\tnewText = SuperManager.getInstance().talkManager.randomTalk(text, skill='system') or text\n+\n+\tif returnText:\n+\t\treturn newText\n+\n+\tsession = kwargs.get('session')\n+\ttry:\n+\t\tif session.sessionId in SuperManager.getInstance().dialogSessionManager.sessions:\n+\t\t\tSuperManager.getInstance().mqttManager.endDialog(sessionId=session.sessionId, text=newText)\n+\t\telse:\n+\t\t\tSuperManager.getInstance().mqttManager.say(text=newText, client=session.siteId)\n+\texcept AttributeError:\n+\t\treturn newText\n+\n+\n+def Online(func: Callable = None, text: str = 'offline', offlineHandler: Callable = None, returnText: bool = False, catchOnly: bool = False):\n \t\"\"\"\n \t(return a) decorator to mark a function that requires ethernet.\n \n@@ -79,6 +104,7 @@ def Online(func: Callable = None, text: str = 'offline', offlineHandler: Callabl\n \tthe decorator will return the text instead. This behaviour can be enforced aswell using:\n \t\t@online(returnText=True)\n \n+\t:param catchOnly: If catch only, do not raise anything\n \t:param func:\n \t:param text:\n \t:param offlineHandler:\n@@ -92,28 +118,6 @@ def exampleIntent(self, session: DialogSession, **_kwargs):\n \t\t\trequest = requests.get('http://api.open-notify.org')\n \t\t\tself.endDialog(sessionId=session.sessionId, text=request.text)\n \t\"\"\"\n-\tdef _offlineHandler(*args, **kwargs):\n-\t\tif offlineHandler:\n-\t\t\treturn offlineHandler(*args, **kwargs)\n-\n-\t\tcaller = args[0] if args else None\n-\t\tskill = getattr(caller, 'name', 'system')\n-\t\tnewText = SuperManager.getInstance().talkManager.randomTalk(text, skill=skill)\n-\t\tif not newText and skill != 'system':\n-\t\t\tnewText = SuperManager.getInstance().talkManager.randomTalk(text, skill='system') or text\n-\n-\t\tif returnText:\n-\t\t\treturn newText\n-\n-\t\tsession = kwargs.get('session')\n-\t\ttry:\n-\t\t\tif session.sessionId in SuperManager.getInstance().dialogSessionManager.sessions:\n-\t\t\t\tSuperManager.getInstance().mqttManager.endDialog(sessionId=session.sessionId, text=newText)\n-\t\t\telse:\n-\t\t\t\tSuperManager.getInstance().mqttManager.say(text=newText, client=session.siteId)\n-\t\texcept AttributeError:\n-\t\t\treturn newText\n-\n \tdef argumentWrapper(func):\n \t\t@functools.wraps(func)\n \t\tdef offlineDecorator(*args, **kwargs):\n@@ -125,7 +129,10 @@ def offlineDecorator(*args, **kwargs):\n \t\t\t\t\tif internetManager.checkOnlineState():\n \t\t\t\t\t\traise\n \n-\t\t\treturn _offlineHandler(*args, **kwargs)\n+\t\t\tif catchOnly:\n+\t\t\t\treturn\n+\n+\t\t\treturn _exceptHandler(*args, text=text, exceptHandler=offlineHandler, returnText=returnText, **kwargs)\n \n \t\treturn offlineDecorator\n \n@@ -133,29 +140,6 @@ def offlineDecorator(*args, **kwargs):\n \n \n def AnyExcept(func: Callable = None, text: str = 'error', exceptions: Tuple[BaseException, ...] = None, exceptHandler: Callable = None, returnText: bool = False, printStack: bool = False):\n-\n-\tdef _exceptHandler(*args, **kwargs):\n-\t\tif exceptHandler:\n-\t\t\treturn exceptHandler(*args, **kwargs)\n-\n-\t\tcaller = args[0] if args else None\n-\t\tskill = getattr(caller, 'name', 'system')\n-\t\tnewText = SuperManager.getInstance().talkManager.randomTalk(text, skill=skill)\n-\t\tif not newText and skill != 'system':\n-\t\t\tnewText = SuperManager.getInstance().talkManager.randomTalk(text, skill='system') or text\n-\n-\t\tif returnText:\n-\t\t\treturn newText\n-\n-\t\tsession = kwargs.get('session')\n-\t\ttry:\n-\t\t\tif session.sessionId in SuperManager.getInstance().dialogSessionManager.sessions:\n-\t\t\t\tSuperManager.getInstance().mqttManager.endDialog(sessionId=session.sessionId, text=newText)\n-\t\t\telse:\n-\t\t\t\tSuperManager.getInstance().mqttManager.say(text=newText, client=session.siteId)\n-\t\texcept AttributeError:\n-\t\t\treturn newText\n-\n \tdef argumentWrapper(func):\n \t\t@functools.wraps(func)\n \t\tdef exceptionDecorator(*args, **kwargs):\n@@ -163,9 +147,61 @@ def exceptionDecorator(*args, **kwargs):\n \t\t\t\treturn func(*args, **kwargs)\n \t\t\texcept exceptions as e:\n \t\t\t\tLogger(depth=6).logWarning(msg=e, printStack=printStack)\n-\t\t\t\treturn _exceptHandler(*args, **kwargs)\n+\t\t\t\treturn _exceptHandler(*args, text=text, exceptHandler=exceptHandler, returnText=returnText, **kwargs)\n+\n \n \t\treturn exceptionDecorator\n \n \texceptions = exceptions or Exception\n \treturn argumentWrapper(func) if func else argumentWrapper\n+\n+\n+def ApiAuthenticated(func: Callable):\n+\t@functools.wraps(func)\n+\tdef wrapper(*args, **kwargs):\n+\t\tif SuperManager.getInstance().userManager.apiTokenValid(request.headers.get('auth', '')):\n+\t\t\treturn func(*args, **kwargs)\n+\t\telse:\n+\t\t\treturn jsonify(message='ERROR: Unauthorized')\n+\n+\treturn wrapper\n+\n+\n+def IfSetting(func: Callable = None, settingName: str = None, settingValue: Any = None, inverted: bool = False, skillName: str = None):\n+\t\"\"\"\n+\tChecks wheter a setting is equal to the given value before executing the wrapped method\n+\tIf the setting is not equal to the given value, the wrapped method is not called\n+\tBy providing a skill name the wrapper searches for a skill setting, otherwise for a system setting\n+\tBy setting inverted to True one can check for \"not equal to\", in other words, if the settingName is not equal to the settingValue\n+\t:param func:\n+\t:param settingName:\n+\t:param settingValue:\n+\t:param inverted:\n+\t:param skillName:\n+\t:return:\n+\t\"\"\"\n+\n+\n+\tdef argumentWrapper(func: Callable):\n+\t\t@functools.wraps(func)\n+\t\tdef settingDecorator(*args, **kwargs):\n+\t\t\tif not settingName:\n+\t\t\t\tLogger(depth=6).logWarning(msg='Cannot use IfSetting decorator without settingName')\n+\t\t\t\treturn None\n+\n+\t\t\tconfigManager = SuperManager.getInstance().configManager\n+\t\t\tvalue = configManager.getSkillConfigByName(skillName, settingName) if skillName else configManager.getAliceConfigByName(settingName)\n+\n+\t\t\tif value is None:\n+\t\t\t\treturn None\n+\n+\t\t\tif not inverted and value == settingValue:\n+\t\t\t\treturn func(*args, **kwargs)\n+\t\t\telif inverted and value != settingValue:\n+\t\t\t\treturn func(*args, **kwargs)\n+\n+\n+\t\treturn settingDecorator\n+\n+\n+\treturn argumentWrapper(func) if func else argumentWrapper\ndiff --git a/core/util/InternetManager.py b/core/util/InternetManager.py\n--- a/core/util/InternetManager.py\n+++ b/core/util/InternetManager.py\n@@ -2,14 +2,13 @@\n from requests.exceptions import RequestException\n \n from core.base.model.Manager import Manager\n+from core.commons import constants\n \n \n class InternetManager(Manager):\n \n-\tNAME = 'InternetManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \t\tself._online = False\n \n \n@@ -47,9 +46,9 @@ def checkOnlineState(self, addr: str = 'http://clients3.google.com/generate_204'\n \n \t\tif self._online and not online:\n \t\t\tself._online = False\n-\t\t\tself.broadcast(method='onInternetLost', exceptions=[self.name], propagateToSkills=True)\n+\t\t\tself.broadcast(method=constants.EVENT_INTERNET_LOST, exceptions=[self.name], propagateToSkills=True)\n \t\telif not self._online and online:\n \t\t\tself._online = True\n-\t\t\tself.broadcast(method='onInternetConnected', exceptions=[self.name], propagateToSkills=True)\n+\t\t\tself.broadcast(method=constants.EVENT_INTERNET_CONNECTED, exceptions=[self.name], propagateToSkills=True)\n \n \t\treturn online\ndiff --git a/core/util/Stopwatch.py b/core/util/Stopwatch.py\n--- a/core/util/Stopwatch.py\n+++ b/core/util/Stopwatch.py\n@@ -22,7 +22,7 @@ def start(self):\n \t\tself._startTime = time.time()\n \n \n-\tdef lap(self) -> int:\n+\tdef lap(self) -> float:\n \t\tcurrentTime = time.time()\n \t\tstartTime = self._startTime\n \t\tself._startTime = currentTime\n@@ -44,4 +44,4 @@ def __exit__(self, tpe, value, tb):\n \n \n \tdef __str__(self) -> str:\n-\t\treturn f'{self.time:.{self._precision}f}'\n\\ No newline at end of file\n+\t\treturn f'{self.time:.{self._precision}f}'\ndiff --git a/core/util/TelemetryManager.py b/core/util/TelemetryManager.py\n--- a/core/util/TelemetryManager.py\n+++ b/core/util/TelemetryManager.py\n@@ -6,7 +6,6 @@\n \n \n class TelemetryManager(Manager):\n-\tNAME = 'TelemetryManager'\n \n \tDATABASE = {\n \t\t'telemetry': [\n@@ -55,7 +54,7 @@ class TelemetryManager(Manager):\n \n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME, self.DATABASE)\n+\t\tsuper().__init__(databaseSchema=self.DATABASE)\n \t\tself._data = list()\n \n \n@@ -86,7 +85,7 @@ def loadData(self):\n \n \n \t# noinspection SqlResolve\n-\tdef storeData(self, ttype: TelemetryType, value: str, service: str, siteId: str, timestamp = None):\n+\tdef storeData(self, ttype: TelemetryType, value: str, service: str, siteId: str, timestamp=None):\n \t\tif not self.isActive:\n \t\t\treturn\n \n@@ -98,18 +97,21 @@ def storeData(self, ttype: TelemetryType, value: str, service: str, siteId: str,\n \t\t\tvalues={'type': ttype.value, 'value': value, 'service': service, 'siteId': siteId, 'timestamp': round(timestamp)}\n \t\t)\n \n+\t\ttelemetrySkill = self.SkillManager.getSkillInstance('Telemetry')\n \t\tmessages = self.TELEMETRY_MAPPINGS.get(ttype, dict())\n \t\tfor message, settings in messages.items():\n \t\t\tif settings is None:\n-\t\t\t\tself.broadcast(method=message, exceptions=[self.name], propagateToSkills=True, args=[service])\n+\t\t\t\tself.broadcast(method=message, exceptions=[self.name], propagateToSkills=True, service=service)\n \t\t\t\tbreak\n \n-\t\t\t#TODO check if Telemetry skill available\n+\t\t\tif not telemetrySkill:\n+\t\t\t\tcontinue\n+\n \t\t\tthreshold = float(self.ConfigManager.getSkillConfigByName('Telemetry', settings[1]) if isinstance(settings[1], str) else settings[1])\n \t\t\tvalue = float(value)\n \t\t\tif settings[0] == 'upperThreshold' and value > threshold or \\\n-\t\t\t\tsettings[0] == 'lowerThreshold' and value < threshold:\n-\t\t\t\tself.broadcast(method=message, exceptions=[self.name], propagateToSkills=True, args=[service])\n+\t\t\t\t\tsettings[0] == 'lowerThreshold' and value < threshold:\n+\t\t\t\tself.broadcast(method=message, exceptions=[self.name], propagateToSkills=True, service=service)\n \t\t\t\tbreak\n \n \ndiff --git a/core/util/ThreadManager.py b/core/util/ThreadManager.py\n--- a/core/util/ThreadManager.py\n+++ b/core/util/ThreadManager.py\n@@ -8,14 +8,12 @@\n \n class ThreadManager(Manager):\n \n-\tNAME = 'ThreadManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n-\t\tself._timers\t= list()\n-\t\tself._threads \t= dict()\n-\t\tself._events \t= dict()\n+\t\tself._timers = list()\n+\t\tself._threads = dict()\n+\t\tself._events = dict()\n \n \n \tdef onStop(self):\n@@ -33,15 +31,15 @@ def onStop(self):\n \t\t\t\tevent.clear()\n \n \tdef onQuarterHour(self):\n-\t\ti = 0\n+\t\tdeadTimers = 0\n \t\tfor threadTimer in self._timers:\n \t\t\tif not threadTimer.timer.isAlive():\n \t\t\t\tself._timers.remove(threadTimer)\n-\t\t\t\ti += 1\n-\t\tself.logInfo(f'Cleaned {i} dead timers')\n+\t\t\t\tdeadTimers += 1\n+\t\tself.logInfo(f'Cleaned {deadTimers} dead timers')\n \n \n-\tdef newTimer(self, interval: float, func: str, autoStart: bool = True, args: list = None, kwargs: dict = None) -> threading.Timer:\n+\tdef newTimer(self, interval: float, func: Callable, autoStart: bool = True, args: list = None, kwargs: dict = None) -> threading.Timer:\n \t\targs = args or list()\n \t\tkwargs = kwargs or dict()\n \n@@ -57,7 +55,7 @@ def newTimer(self, interval: float, func: str, autoStart: bool = True, args: lis\n \t\treturn t\n \n \n-\tdef doLater(self, interval: float, func: str, args: list = None, kwargs: dict = None):\n+\tdef doLater(self, interval: float, func: Callable, args: list = None, kwargs: dict = None):\n \t\tself.newTimer(interval=interval, func=func, args=args, kwargs=kwargs)\n \n \n@@ -67,7 +65,7 @@ def onTimerEnd(self, t: ThreadTimer):\n \n \n \tdef removeTimer(self, t: ThreadTimer):\n-\t\tif t.timer.isAlive():\n+\t\tif t.timer.is_alive():\n \t\t\tt.timer.cancel()\n \n \t\tif t in self._timers:\n@@ -98,13 +96,13 @@ def terminateThread(self, name: str):\n \t\t\t\tif t.name == name:\n \t\t\t\t\tthread = t\n \n-\t\tif thread and thread.isAlive():\n+\t\tif thread and thread.is_alive():\n \t\t\tthread.join(timeout=1)\n \n \n \tdef isThreadAlive(self, name: str) -> bool:\n \t\tif name not in self._threads:\n-\t\t\treturn any(t.name == name and t.isAlive() for t in threading.enumerate())\n+\t\t\treturn any(t.name == name and t.is_alive() for t in threading.enumerate())\n \n \t\treturn self._threads[name].isAlive()\n \ndiff --git a/core/util/TimeManager.py b/core/util/TimeManager.py\n--- a/core/util/TimeManager.py\n+++ b/core/util/TimeManager.py\n@@ -1,21 +1,20 @@\n from datetime import datetime\n \n from core.base.model.Manager import Manager\n+from core.commons import constants\n \n \n class TimeManager(Manager):\n \n-\tNAME = 'TimeManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n \n \tdef onBooted(self):\n-\t\tself.timerSignal(1, 'onFullMinute')\n-\t\tself.timerSignal(5, 'onFiveMinute')\n-\t\tself.timerSignal(15, 'onQuarterHour')\n-\t\tself.timerSignal(60, 'onFullHour')\n+\t\tself.timerSignal(1, constants.EVENT_FULL_MINUTE)\n+\t\tself.timerSignal(5, constants.EVENT_FIVE_MINUTE)\n+\t\tself.timerSignal(15, constants.EVENT_QUARTER_HOUR)\n+\t\tself.timerSignal(60, constants.EVENT_FULL_HOUR)\n \n \n \tdef timerSignal(self, minutes: int, signal: str, running: bool = False):\ndiff --git a/core/util/model/Logger.py b/core/util/model/Logger.py\n--- a/core/util/model/Logger.py\n+++ b/core/util/model/Logger.py\n@@ -23,6 +23,11 @@ def logDebug(self, msg: str):\n \n \tdef logFatal(self, msg: str):\n \t\tself.doLog(function='fatal', msg=msg)\n+\t\ttry:\n+\t\t\tfrom core.base.SuperManager import SuperManager\n+\t\t\tSuperManager.getInstance().projectAlice.onStop()\n+\t\texcept:\n+\t\t\texit()\n \n \n \tdef logWarning(self, msg: str, printStack: bool = False):\n@@ -46,4 +51,4 @@ def decorate(self, msg: str, depth: int) -> str:\n \t\ttry:\n \t\t\treturn f'[{inspect.getmodulename(inspect.stack()[depth][1])}] {msg}'\n \t\texcept Exception:\n-\t\t\treturn '[Unknown] {msg}'\n+\t\t\treturn f'[Unknown] {msg}'\ndiff --git a/core/util/model/ThreadTimer.py b/core/util/model/ThreadTimer.py\n--- a/core/util/model/ThreadTimer.py\n+++ b/core/util/model/ThreadTimer.py\n@@ -1,26 +1,11 @@\n-class ThreadTimer:\n-\tdef __init__(self, callback: str, args: list, kwargs: dict):\n-\t\tself._timer \t= None\n-\t\tself._callback \t= callback\n-\t\tself._args \t\t= args\n-\t\tself._kwargs \t= kwargs\n-\n-\t@property\n-\tdef timer(self):\n-\t\treturn self._timer\n-\n-\t@timer.setter\n-\tdef timer(self, t):\n-\t\tself._timer = t\n+from dataclasses import dataclass, field\n+from threading import Timer\n+from typing import Callable\n \n-\t@property\n-\tdef callback(self):\n-\t\treturn self._callback\n \n-\t@property\n-\tdef args(self):\n-\t\treturn self._args\n-\n-\t@property\n-\tdef kwargs(self):\n-\t\treturn self._kwargs\n\\ No newline at end of file\n+@dataclass\n+class ThreadTimer:\n+\tcallback: Callable\n+\targs: list = field(default_factory=list)\n+\tkwargs: dict = field(default_factory=dict)\n+\ttimer: Timer = None\ndiff --git a/core/voice/ASRManager.py b/core/voice/ASRManager.py\ndeleted file mode 100755\n--- a/core/voice/ASRManager.py\n+++ /dev/null\n@@ -1,92 +0,0 @@\n-import time\n-\n-from core.base.model.Intent import Intent\n-from core.base.model.Manager import Manager\n-from core.commons import constants\n-from core.dialog.model.DialogSession import DialogSession\n-from core.voice.model import ASR\n-from core.voice.model.SnipsASR import SnipsASR\n-\n-\n-class ASRManager(Manager):\n-\n-\tNAME = 'ASRManager'\n-\n-\tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n-\t\tself._asr = None\n-\n-\n-\tdef onStart(self):\n-\t\tsuper().onStart()\n-\n-\t\tif self.ConfigManager.getAliceConfigByName(configName='asr').lower() == 'google' and not self.ConfigManager.getAliceConfigByName('keepASROffline') and not self.ConfigManager.getAliceConfigByName('stayCompletlyOffline'):\n-\t\t\t# noinspection PyUnresolvedReferences\n-\t\t\tfrom core.voice.model.GoogleASR import GoogleASR\n-\n-\t\t\tself._asr = GoogleASR()\n-\t\t\tself.SnipsServicesManager.runCmd('stop', ['snips-asr'])\n-\t\t\tself.logInfo('Turned Snips ASR off')\n-\t\telse:\n-\t\t\tself._asr = SnipsASR()\n-\t\t\tself.SnipsServicesManager.runCmd('start', ['snips-asr'])\n-\t\t\tself.logInfo('Started Snips ASR')\n-\n-\n-\t@property\n-\tdef asr(self) -> ASR:\n-\t\treturn self._asr\n-\n-\n-\tdef onInternetConnected(self):\n-\t\tif not self.ConfigManager.getAliceConfigByName('keepASROffline'):\n-\t\t\tasr = self.ConfigManager.getAliceConfigByName('asr').lower()\n-\t\t\tif asr != 'snips' and not self.ConfigManager.getAliceConfigByName('keepASROffline') and not self.ConfigManager.getAliceConfigByName('stayCompletlyOffline'):\n-\t\t\t\tself.logInfo('Connected to internet, switching ASR')\n-\t\t\t\tself.SnipsServicesManager.runCmd('stop', ['snips-asr'])\n-\t\t\t\tif asr == 'google':\n-\t\t\t\t\t# TODO needs better handling. A header import with some checks if needed or not\n-\t\t\t\t\t# noinspection PyUnresolvedReferences\n-\t\t\t\t\tfrom core.voice.model.GoogleASR import GoogleASR\n-\t\t\t\t\tself._asr = GoogleASR()\n-\n-\n-\tdef onInternetLost(self):\n-\t\tif not isinstance(self._asr, SnipsASR):\n-\t\t\tself.logInfo('Internet lost, switching to snips ASR')\n-\t\t\tself.SnipsServicesManager.runCmd('start', ['snips-asr'])\n-\t\t\tself._asr = SnipsASR()\n-\n-\n-\tdef onStartListening(self, session: DialogSession, *args, **kwargs):\n-\t\tif isinstance(self._asr, SnipsASR):\n-\t\t\treturn\n-\n-\t\tstart = time.time()\n-\t\tresult = self._asr.onListen()\n-\t\tend = time.time()\n-\t\tprocessing = float(end - start)\n-\n-\t\tif result:\n-\t\t\t# Stop listener as fast as possible\n-\t\t\tself.MqttManager.publish(topic=constants.TOPIC_STOP_LISTENING, payload={'sessionId': session.sessionId, 'siteId': session.siteId})\n-\n-\t\t\tresult = self.LanguageManager.sanitizeNluQuery(result)\n-\t\t\tself.logDebug(f'{self._asr.__class__.__name__} output: \"{result}\"')\n-\n-\t\t\tsupportedIntents = session.intentFilter or self.SkillManager.supportedIntents\n-\t\t\tintentFilter = [intent.justTopic for intent in supportedIntents if isinstance(intent, Intent) and not intent.protected]\n-\n-\t\t\t# Add Global Intents\n-\t\t\tintentFilter.append(Intent('GlobalStop').justTopic)\n-\n-\t\t\tself.MqttManager.publish(topic=constants.TOPIC_TEXT_CAPTURED, payload={'sessionId': session.sessionId, 'text': result, 'siteId': session.siteId, 'likelihood': 1, 'seconds': processing})\n-\n-\t\t\tself.MqttManager.publish(topic=constants.TOPIC_NLU_QUERY, payload={'id':session.sessionId, 'input': result, 'intentFilter': intentFilter, 'sessionId': session.sessionId})\n-\t\telse:\n-\t\t\tself.MqttManager.publish(topic=constants.TOPIC_INTENT_NOT_RECOGNIZED)\n-\t\t\tself.MqttManager.playSound(\n-\t\t\t\tsoundFilename='error',\n-\t\t\t\tlocation='assistant/custom_dialogue/sound',\n-\t\t\t\tsiteId=session.siteId\n-\t\t\t)\ndiff --git a/core/voice/LanguageManager.py b/core/voice/LanguageManager.py\n--- a/core/voice/LanguageManager.py\n+++ b/core/voice/LanguageManager.py\n@@ -1,7 +1,7 @@\n import json\n-import re\n from pathlib import Path\n-from typing import Optional\n+\n+import re\n \n from core.ProjectAliceExceptions import LanguageManagerLangNotSupported\n from core.base.model.Manager import Manager\n@@ -9,22 +9,19 @@\n \n class LanguageManager(Manager):\n \n-\tNAME = 'LanguageManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n-\t\tself._supportedLanguages \t\t= list()\n-\t\tself._activeLanguage \t\t\t= ''\n-\t\tself._activeCountryCode \t\t= ''\n-\t\tself._defaultLanguage \t\t\t= ''\n-\t\tself._defaultCountryCode \t\t= ''\n-\t\tself._activeSnipsProjectId \t\t= ''\n+\t\tsuper().__init__()\n+\t\tself._supportedLanguages = list()\n+\t\tself._activeLanguage = ''\n+\t\tself._activeCountryCode = ''\n+\t\tself._defaultLanguage = ''\n+\t\tself._defaultCountryCode = ''\n \n-\t\tself._stringsData \t\t\t\t= dict()\n-\t\tself._locals \t\t\t\t\t= list()\n+\t\tself._stringsData = dict()\n+\t\tself._locals = list()\n \n-\t\tself._floatExpressionPattern \t= re.compile(r'([0-9]+\\.[0-9]+)')\n-\t\tself._mathSigns = ('+', '-', '/', '*', '%')\n+\t\tself._floatExpressionPattern = re.compile(r'([0-9]+\\.[0-9]+)')\n+\t\tself._mathSigns = ('+', '-', '/', '*', '%')\n \n \n \tdef onStart(self):\n@@ -35,15 +32,15 @@ def onStart(self):\n \n \tdef onBooted(self):\n \t\tdata = self.TalkManager.langData\n-\t\tif self.NAME in data:\n-\t\t\tself._locals = data[self.NAME]\n+\t\tif self._name in data:\n+\t\t\tself._locals = data[self._name]\n \n \n \tdef sanitizeNluQuery(self, query: str = '') -> str:\n \t\tfor sign, langsValues in self._stringsData['system'].items():\n \t\t\tif sign in self._mathSigns:\n \t\t\t\tif sign == '-':\n-\t\t\t\t\tquery = query.replace(' ' + sign + ' ', langsValues[self.activeLanguage][0])\n+\t\t\t\t\tquery = query.replace(f' {sign} ', langsValues[self.activeLanguage][0])\n \t\t\t\telse:\n \t\t\t\t\tquery = query.replace(sign, langsValues[self.activeLanguage][0])\n \n@@ -67,10 +64,11 @@ def loadStrings(self, skillToLoad: str = ''):\n \t\t\t\tcontinue\n \n \n-\tdef getTranslations(self, skill: str, key: str, toLang: str = '') -> Optional[list]:\n+\tdef getTranslations(self, skill: str, key: str, toLang: str = '') -> list:\n \t\tif not toLang:\n \t\t\ttoLang = self.activeLanguage\n-\t\tif not skill in self._stringsData:\n+\n+\t\tif skill not in self._stringsData:\n \t\t\tself.logError(f'Asked to get translation from skill \"{skill}\" but does not exist')\n \t\t\treturn list()\n \t\telif key not in self._stringsData[skill]:\n@@ -100,7 +98,6 @@ def _loadSupportedLanguages(self):\n \t\t\tif langCode == activeLangDef:\n \t\t\t\tself._activeLanguage = langCode\n \t\t\t\tself._activeCountryCode = settings['countryCode']\n-\t\t\t\tself._activeSnipsProjectId = settings['snipsProjectId']\n \n \t\tif not self._activeLanguage and self._defaultLanguage:\n \t\t\tself.logWarning(f'No active language defined, falling back to {self._defaultLanguage}')\n@@ -122,10 +119,6 @@ def _loadSupportedLanguages(self):\n \t\t\tself._activeCountryCode = self._defaultCountryCode = 'US'\n \n \n-\t\tif not self._activeSnipsProjectId:\n-\t\t\tself.logInfo('No active snips project id set')\n-\n-\n \tdef localize(self, string: str) -> str:\n \t\tstring = string.lower()\n \n@@ -152,21 +145,6 @@ def changeActiveLanguage(self, toLang: str):\n \t\tself._loadSupportedLanguages()\n \n \n-\tdef changeActiveSnipsProjectIdForLanguage(self, projectId: str, forLang: str):\n-\t\tforLang = forLang.lower()\n-\n-\t\tif forLang not in self._supportedLanguages:\n-\t\t\traise LanguageManagerLangNotSupported\n-\n-\t\tself.ConfigManager.changeActiveSnipsProjectIdForLanguage(projectId, forLang)\n-\t\tself._loadSupportedLanguages()\n-\n-\n-\t@property\n-\tdef activeSnipsProjectId(self) -> str:\n-\t\treturn self._activeSnipsProjectId\n-\n-\n \t@property\n \tdef activeLanguage(self) -> str:\n \t\treturn self._activeLanguage\n@@ -190,7 +168,7 @@ def defaultCountryCode(self) -> str:\n \t@property\n \tdef activeLanguageAndCountryCode(self) -> str:\n \t\treturn f'{self._activeLanguage}-{self._activeCountryCode}'\n-\t\n+\n \n \t@property\n \tdef supportedLanguages(self) -> list:\ndiff --git a/core/voice/TTSManager.py b/core/voice/TTSManager.py\n--- a/core/voice/TTSManager.py\n+++ b/core/voice/TTSManager.py\n@@ -10,10 +10,9 @@\n \n \n class TTSManager(Manager):\n-\tNAME = 'TTSManager'\n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n \t\tself._fallback = None\n \t\tself._tts = None\n@@ -40,10 +39,7 @@ def _loadTTS(self, tts: str, user: User = None) -> TTSEnum:\n \t\texcept:\n \t\t\ttts = TTSEnum.SNIPS\n \n-\t\tif tts == TTSEnum.SNIPS:\n-\t\t\tfrom core.voice.model.SnipsTTS import SnipsTTS\n-\t\t\tself._tts = SnipsTTS(user)\n-\t\telif tts == TTSEnum.PICO:\n+\t\tif tts == TTSEnum.PICO:\n \t\t\tself._tts = PicoTTS(user)\n \t\telif tts == TTSEnum.MYCROFT:\n \t\t\tif not Path(Path(self.Commons.rootDir()).parent, 'mimic/voices').is_dir():\n@@ -55,10 +51,16 @@ def _loadTTS(self, tts: str, user: User = None) -> TTSEnum:\n \t\t\t\tself._tts = MycroftTTS(user)\n \t\telif tts == TTSEnum.AMAZON:\n \t\t\tfrom core.voice.model.AmazonTTS import AmazonTTS\n+\n \t\t\tself._tts = AmazonTTS(user)\n \t\telif tts == TTSEnum.GOOGLE:\n-\t\t\tfrom core.voice.model.GoogleTTS import GoogleTTS\n-\t\t\tself._tts = GoogleTTS(user)\n+\t\t\tif not Path(self.Commons.rootDir(), 'credentials/googlecredentials.json').exists():\n+\t\t\t\tself.logWarning('No Google credentials found for Google Wavenet, falling back to pico')\n+\t\t\t\tself._tts = PicoTTS(user)\n+\t\t\telse:\n+\t\t\t\tfrom core.voice.model.GoogleTTS import GoogleTTS\n+\n+\t\t\t\tself._tts = GoogleTTS(user)\n \t\telse:\n \t\t\tfrom core.voice.model.SnipsTTS import SnipsTTS\n \t\t\tself._tts = SnipsTTS(user)\ndiff --git a/core/voice/TalkManager.py b/core/voice/TalkManager.py\n--- a/core/voice/TalkManager.py\n+++ b/core/voice/TalkManager.py\n@@ -1,16 +1,15 @@\n import json\n-import random\n from pathlib import Path\n \n+import random\n+\n from core.base.model.Manager import Manager\n \n \n class TalkManager(Manager):\n \n-\tNAME = 'TalkManager'\n-\n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \t\tself._langData = dict()\n \n \n@@ -50,7 +49,8 @@ def loadTalks(self, skillToLoad: str = None):\n \t\t\t\t\tself._langData.setdefault(skillName, dict())[lang] = json.loads(langTalkFile.read_text())\n \t\t\t\texcept FileNotFoundError:\n \t\t\t\t\tcontinue\n-\t\t\t\texcept ValueError:\n+\t\t\t\texcept ValueError as e:\n+\t\t\t\t\tself.logError(f'{e}')\n \t\t\t\t\tcontinue\n \n \ndiff --git a/core/voice/WakewordManager.py b/core/voice/WakewordManager.py\n--- a/core/voice/WakewordManager.py\n+++ b/core/voice/WakewordManager.py\n@@ -1,15 +1,14 @@\n import json\n-from enum import Enum\n from pathlib import Path\n \n import paho.mqtt.client as mqtt\n import shutil\n import struct\n import tempfile\n+from enum import Enum\n from pydub import AudioSegment\n \n from core.base.model.Manager import Manager\n-from core.commons import constants\n from core.dialog.model.DialogSession import DialogSession\n from core.voice.model.Wakeword import Wakeword\n from core.voice.model.WakewordUploadThread import WakewordUploadThread\n@@ -25,19 +24,18 @@ class WakewordManagerState(Enum):\n \n \n class WakewordManager(Manager):\n-\tNAME = 'WakewordManager'\n \n \tRECORD_SECONDS = 2.5\n \tTHRESHOLD = -40.0\n \n \n \tdef __init__(self):\n-\t\tsuper().__init__(self.NAME)\n+\t\tsuper().__init__()\n \n-\t\tself._state = WakewordManagerState.IDLE\n+\t\tself._state = WakewordManagerState.IDLE\n \n-\t\tself._audio = None\n-\t\tself._wakeword = None\n+\t\tself._audio = None\n+\t\tself._wakeword = None\n \t\tself._threshold = 0\n \t\tself._wakewordUploadThreads = list()\n \t\tself._sampleRate = self.ConfigManager.getAliceConfigByName('micSampleRate')\n@@ -59,9 +57,9 @@ def onStop(self):\n \n \tdef onCaptured(self, session: DialogSession):\n \t\tif self.state == WakewordManagerState.RECORDING:\n-\t\t\tself.MqttManager.mqttClient.unsubscribe(constants.TOPIC_AUDIO_FRAME.format('default'))\n-\t\t\tfor device in self.DeviceManager.getDevicesByType('alicesatellite'):\n-\t\t\t\tself.MqttManager.mqttClient.unsubscribe(constants.TOPIC_AUDIO_FRAME.format(device.room))\n+\t\t\t# self.MqttManager.mqttClient.unsubscribe(constants.TOPIC_AUDIO_FRAME.format('default'))\n+\t\t\t# for device in self.DeviceManager.getDevicesByType('alicesatellite'):\n+\t\t\t# \tself.MqttManager.mqttClient.unsubscribe(constants.TOPIC_AUDIO_FRAME.format(device.room))\n \t\t\tself._workAudioFile()\n \n \n@@ -80,12 +78,16 @@ def addASample(self):\n \t\tself.wakeword.newSample()\n \t\tself.state = WakewordManagerState.RECORDING\n \n-\t\tself.MqttManager.mqttClient.subscribe(constants.TOPIC_AUDIO_FRAME.format('default'))\n-\t\tfor device in self.DeviceManager.getDevicesByType('alicesatellite'):\n-\t\t\tself.MqttManager.mqttClient.subscribe(constants.TOPIC_AUDIO_FRAME.format(device.room))\n \n+\t# self.MqttManager.mqttClient.subscribe(constants.TOPIC_AUDIO_FRAME.format('default'))\n+\t# for device in self.DeviceManager.getDevicesByType('alicesatellite'):\n+\t# \tself.MqttManager.mqttClient.subscribe(constants.TOPIC_AUDIO_FRAME.format(device.room))\n+\n+\n+\tdef onAudioFrame(self, message: mqtt.MQTTMessage, siteId: str):\n+\t\tif self.state != WakewordManagerState.RECORDING:\n+\t\t\treturn\n \n-\tdef onAudioFrame(self, message: mqtt.MQTTMessage):\n \t\t# @author DasBasti\n \t\t# https://gist.github.com/DasBasti/050bf6c3232d4bb54c741a1f057459d3\n \n@@ -155,7 +157,7 @@ def _workAudioFile(self):\n \t\tstartTrim = self.detectLeadingSilence(sound)\n \t\tendTrim = self.detectLeadingSilence(sound.reverse())\n \t\tduration = len(sound)\n-\t\ttrimmed = sound[startTrim : duration - endTrim]\n+\t\ttrimmed = sound[startTrim: duration - endTrim]\n \t\treworked = trimmed.set_frame_rate(16000)\n \t\treworked = reworked.set_channels(1)\n \n@@ -175,7 +177,7 @@ def trimLess(self):\n \n \tdef detectLeadingSilence(self, sound):\n \t\ttrim = 0\n-\t\twhile sound[trim : trim + 10].dBFS < self._threshold and trim < len(sound):\n+\t\twhile sound[trim: trim + 10].dBFS < self._threshold and trim < len(sound):\n \t\t\ttrim += 10\n \t\treturn trim\n \n@@ -205,28 +207,28 @@ def finalizeWakeword(self):\n \t\tself._state = WakewordManagerState.FINALIZING\n \n \t\tconfig = {\n-\t\t\t'hotword_key' : self._wakeword.username.lower(),\n-\t\t\t'kind' : 'personal',\n-\t\t\t'dtw_ref' : 0.22,\n-\t\t\t'from_mfcc' : 1,\n-\t\t\t'to_mfcc' : 13,\n-\t\t\t'band_radius' : 10,\n-\t\t\t'shift' : 10,\n-\t\t\t'window_size' : 10,\n-\t\t\t'sample_rate' : 16000,\n-\t\t\t'frame_length_ms' : 25.0,\n-\t\t\t'frame_shift_ms' : 10.0,\n-\t\t\t'num_mfcc' : 13,\n-\t\t\t'num_mel_bins' : 13,\n-\t\t\t'mel_low_freq' : 20,\n-\t\t\t'cepstral_lifter' : 22.0,\n-\t\t\t'dither' : 0.0,\n-\t\t\t'window_type' : 'povey',\n-\t\t\t'use_energy' : False,\n-\t\t\t'energy_floor' : 0.0,\n-\t\t\t'raw_energy' : True,\n+\t\t\t'hotword_key': self._wakeword.username.lower(),\n+\t\t\t'kind': 'personal',\n+\t\t\t'dtw_ref': 0.22,\n+\t\t\t'from_mfcc': 1,\n+\t\t\t'to_mfcc': 13,\n+\t\t\t'band_radius': 10,\n+\t\t\t'shift': 10,\n+\t\t\t'window_size': 10,\n+\t\t\t'sample_rate': 16000,\n+\t\t\t'frame_length_ms': 25.0,\n+\t\t\t'frame_shift_ms': 10.0,\n+\t\t\t'num_mfcc': 13,\n+\t\t\t'num_mel_bins': 13,\n+\t\t\t'mel_low_freq': 20,\n+\t\t\t'cepstral_lifter': 22.0,\n+\t\t\t'dither': 0.0,\n+\t\t\t'window_type': 'povey',\n+\t\t\t'use_energy': False,\n+\t\t\t'energy_floor': 0.0,\n+\t\t\t'raw_energy': True,\n \t\t\t'preemphasis_coefficient': 0.97,\n-\t\t\t'model_version' : 1\n+\t\t\t'model_version': 1\n \t\t}\n \n \t\tpath = Path(self.Commons.rootDir(), 'trained/hotwords', self.wakeword.username.lower())\ndiff --git a/core/voice/model/ASR.py b/core/voice/model/ASR.py\ndeleted file mode 100644\n--- a/core/voice/model/ASR.py\n+++ /dev/null\n@@ -1,7 +0,0 @@\n-class ASR:\n-\tdef __init__(self):\n-\t\tself._capableOfArbitraryCapture = False\n-\n-\t@property\n-\tdef capableOfArbitraryCapture(self) -> bool:\n-\t\treturn self._capableOfArbitraryCapture\ndiff --git a/core/voice/model/GoogleASR.py b/core/voice/model/GoogleASR.py\ndeleted file mode 100755\n--- a/core/voice/model/GoogleASR.py\n+++ /dev/null\n@@ -1,56 +0,0 @@\n-import os\n-from pathlib import Path\n-\n-from google.cloud import speech\n-from google.cloud.speech import enums, types\n-\n-from core.base.SuperManager import SuperManager\n-from core.voice.model.ASR import ASR\n-from core.voice.model.MicrophoneStream import MicrophoneStream\n-\n-\n-# noinspection PyUnresolvedReferences\n-class GoogleASR(ASR):\n-\n-\tdef __init__(self):\n-\t\tsuper().__init__()\n-\n-\t\tos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = str(Path(SuperManager.getInstance().commons.rootDir(), 'credentials/googlecredentials.json'))\n-\n-\t\tself._client = speech.SpeechClient()\n-\t\tself._config = types.RecognitionConfig(\n-\t\t\tencoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n-\t\t\tsample_rate_hertz=SuperManager.getInstance().configManager.getAliceConfigByName('micSampleRate'),\n-\t\t\tlanguage_code=SuperManager.getInstance().languageManager.activeLanguageAndCountryCode\n-\t\t)\n-\t\tself._capableOfArbitraryCapture = True\n-\t\tself._streamingConfig = types.StreamingRecognitionConfig(config=self._config, single_utterance=True, interim_results=False)\n-\n-\n-\t@staticmethod\n-\tdef _listen(responses):\n-\t\tfor response in responses:\n-\t\t\tif not response.results:\n-\t\t\t\tcontinue\n-\n-\t\t\tresult = response.results[0]\n-\t\t\tif not result.alternatives:\n-\t\t\t\tcontinue\n-\n-\t\t\t# Display the transcription of the top alternative.\n-\t\t\ttranscript = result.alternatives[0].transcript\n-\n-\t\t\tif result.is_final:\n-\t\t\t\treturn transcript\n-\n-\n-\tdef onListen(self) -> str:\n-\t\tmicSampleRate = SuperManager.getInstance().configManager.getAliceConfigByName('micSampleRate')\n-\n-\t\twith MicrophoneStream(int(micSampleRate), int(micSampleRate / 10)) as stream:\n-\t\t\taudio_generator = stream.generator()\n-\t\t\trequests = (types.StreamingRecognizeRequest(audio_content=content) for content in audio_generator)\n-\t\t\tresponses = self._client.streaming_recognize(self._streamingConfig, requests)\n-\t\t\tresult = self._listen(responses)\n-\n-\t\treturn result\ndiff --git a/core/voice/model/GoogleTTS.py b/core/voice/model/GoogleTTS.py\n--- a/core/voice/model/GoogleTTS.py\n+++ b/core/voice/model/GoogleTTS.py\n@@ -1,4 +1,3 @@\n-import re\n import subprocess\n from pathlib import Path\n \n@@ -53,32 +52,32 @@ def __init__(self, user: User = None):\n \t\t\t\t\t'en-US-Standard-C': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n-\t\t\t\t\t'en-US-Standard-E' : {\n+\t\t\t\t\t'en-US-Standard-E': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n \t\t\t\t\t'en-US-Wavenet-C': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t},\n-\t\t\t\t\t'en-US-Wavenet-E' : {\n+\t\t\t\t\t'en-US-Wavenet-E': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t},\n-\t\t\t\t\t'en-US-Wavenet-F' : {\n+\t\t\t\t\t'en-US-Wavenet-F': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t},\n \t\t\t'fr-FR': {\n-\t\t\t\t'male' : {\n+\t\t\t\t'male': {\n \t\t\t\t\t'fr-FR-Standard-B': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n \t\t\t\t\t'fr-FR-Standard-D': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n-\t\t\t\t\t'fr-FR-Wavenet-B' : {\n+\t\t\t\t\t'fr-FR-Wavenet-B': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t},\n-\t\t\t\t\t'fr-FR-Wavenet-D' : {\n+\t\t\t\t\t'fr-FR-Wavenet-D': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t}\n \t\t\t\t},\n@@ -89,23 +88,23 @@ def __init__(self, user: User = None):\n \t\t\t\t\t'fr-FR-Standard-C': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n-\t\t\t\t\t'fr-FR-Wavenet-A' : {\n+\t\t\t\t\t'fr-FR-Wavenet-A': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t},\n-\t\t\t\t\t'fr-FR-Wavenet-C' : {\n+\t\t\t\t\t'fr-FR-Wavenet-C': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t},\n \t\t\t'de-DE': {\n-\t\t\t\t'male' : {\n+\t\t\t\t'male': {\n \t\t\t\t\t'de-DE-Standard-B': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n-\t\t\t\t\t'de-DE-Wavenet-B' : {\n+\t\t\t\t\t'de-DE-Wavenet-B': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t},\n-\t\t\t\t\t'de-DE-Wavenet-D' : {\n+\t\t\t\t\t'de-DE-Wavenet-D': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t}\n \t\t\t\t},\n@@ -113,10 +112,10 @@ def __init__(self, user: User = None):\n \t\t\t\t\t'de-DE-Standard-A': {\n \t\t\t\t\t\t'neural': False\n \t\t\t\t\t},\n-\t\t\t\t\t'de-DE-Wavenet-A' : {\n+\t\t\t\t\t'de-DE-Wavenet-A': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t},\n-\t\t\t\t\t'de-DE-Wavenet-C' : {\n+\t\t\t\t\t'de-DE-Wavenet-C': {\n \t\t\t\t\t\t'neural': True\n \t\t\t\t\t}\n \t\t\t\t}\n@@ -128,7 +127,7 @@ def __init__(self, user: User = None):\n \tdef _checkText(session: DialogSession) -> str:\n \t\ttext = session.payload['text']\n \n-\t\tif not re.search('', text):\n+\t\tif not '' in text:\n \t\t\ttext = f'{text}'\n \n \t\treturn text\ndiff --git a/core/voice/model/MycroftTTS.py b/core/voice/model/MycroftTTS.py\n--- a/core/voice/model/MycroftTTS.py\n+++ b/core/voice/model/MycroftTTS.py\n@@ -1,8 +1,8 @@\n import getpass\n-import re\n-import subprocess\n from pathlib import Path\n \n+import re\n+\n from core.base.SuperManager import SuperManager\n from core.dialog.model.DialogSession import DialogSession\n from core.user.model.User import User\n@@ -81,7 +81,7 @@ def __init__(self, user: User = None):\n \t@staticmethod\n \tdef _checkText(session: DialogSession) -> str:\n \t\ttext = session.payload['text']\n-\t\treturn re.sub('<.*?>', '', text)\n+\t\treturn ' '.join(re.sub('<.*?>', ' ', text).split())\n \n \n \tdef onSay(self, session: DialogSession):\n@@ -94,8 +94,7 @@ def onSay(self, session: DialogSession):\n \t\t\tif not Path(self._mimicDirectory, 'voices', self._voice + '.flitevox').exists():\n \t\t\t\thtsvoice = Path(self._mimicDirectory, 'voices', self._voice + '.htsvoice')\n \t\t\t\tif htsvoice.exists():\n-\t\t\t\t\tsubprocess.run([\n-\t\t\t\t\t\t'sudo',\n+\t\t\t\t\tSuperManager.getInstance().commonsManager.runRootSystemCommand([\n \t\t\t\t\t\t'-u', getpass.getuser(),\n \t\t\t\t\t\tself._mimicDirectory,\n \t\t\t\t\t\t'-t', self._text,\n@@ -103,8 +102,7 @@ def onSay(self, session: DialogSession):\n \t\t\t\t\t\t'-voice', htsvoice\n \t\t\t\t\t])\n \t\t\t\telse:\n-\t\t\t\t\tsubprocess.run([\n-\t\t\t\t\t\t'sudo',\n+\t\t\t\t\tSuperManager.getInstance().commonsManager.runRootSystemCommand([\n \t\t\t\t\t\t'-u', getpass.getuser(),\n \t\t\t\t\t\tself._mimicDirectory,\n \t\t\t\t\t\t'-t', self._text,\n@@ -112,8 +110,7 @@ def onSay(self, session: DialogSession):\n \t\t\t\t\t\t'-voice', 'slt'\n \t\t\t\t\t])\n \t\t\telse:\n-\t\t\t\tsubprocess.run([\n-\t\t\t\t\t'sudo',\n+\t\t\t\tSuperManager.getInstance().commonsManager.runRootSystemCommand([\n \t\t\t\t\t'-u', getpass.getuser(),\n \t\t\t\t\tself._mimicDirectory,\n \t\t\t\t\t'-t', self._text,\ndiff --git a/core/voice/model/PicoTTS.py b/core/voice/model/PicoTTS.py\n--- a/core/voice/model/PicoTTS.py\n+++ b/core/voice/model/PicoTTS.py\n@@ -1,6 +1,6 @@\n import re\n-import subprocess\n \n+from core.base.SuperManager import SuperManager\n from core.dialog.model.DialogSession import DialogSession\n from core.user.model.User import User\n from core.voice.model.TTS import TTS\n@@ -63,7 +63,7 @@ def __init__(self, user: User = None):\n \t@staticmethod\n \tdef _checkText(session: DialogSession) -> str:\n \t\ttext = session.payload['text']\n-\t\treturn re.sub('<.*?>', '', text)\n+\t\treturn ' '.join(re.sub('<.*?>', ' ', text).split())\n \n \n \tdef onSay(self, session: DialogSession):\n@@ -73,6 +73,6 @@ def onSay(self, session: DialogSession):\n \t\t\treturn\n \n \t\tif not self._cacheFile.exists():\n-\t\t\tsubprocess.run(['pico2wave', '-l', self._lang, '-w', self._cacheFile, self._text])\n+\t\t\tSuperManager.getInstance().commonsManager.runRootSystemCommand(['pico2wave', '-l', self._lang, '-w', self._cacheFile, self._text])\n \n \t\tself._speak(file=self._cacheFile, session=session)\ndiff --git a/core/voice/model/SnipsASR.py b/core/voice/model/SnipsASR.py\ndeleted file mode 100644\n--- a/core/voice/model/SnipsASR.py\n+++ /dev/null\n@@ -1,8 +0,0 @@\n-from core.voice.model.ASR import ASR\n-\n-\n-class SnipsASR(ASR):\n-\n-\tdef __init__(self):\n-\t\tsuper().__init__()\n-\t\tself._capableOfArbitraryCapture = False\ndiff --git a/core/voice/model/SnipsTTS.py b/core/voice/model/SnipsTTS.py\n--- a/core/voice/model/SnipsTTS.py\n+++ b/core/voice/model/SnipsTTS.py\n@@ -1,5 +1,3 @@\n-import subprocess\n-\n from core.base.SuperManager import SuperManager\n from core.dialog.model.DialogSession import DialogSession\n from core.user.model.User import User\n@@ -85,11 +83,12 @@ def onSay(self, session: DialogSession):\n \t\t\treturn\n \n \t\tif not self._cacheFile.exists():\n-\t\t\tsubprocess.run([\n+\t\t\tSuperManager.getInstance().commonsManager.runSystemCommand([\n \t\t\t\t'snips-makers-tts',\n \t\t\t\t'--output',\n \t\t\t\tself._cacheFile,\n \t\t\t\tf'file://{SuperManager.getInstance().commons.rootDir()}/var/voices/cmu_{SuperManager.getInstance().languageManager.activeCountryCode.lower()}_{self._voice}.flitevox',\n-\t\t\t\tself._text])\n+\t\t\t\tself._text\n+\t\t\t])\n \n \t\tself._speak(file=self._cacheFile, session=session)\ndiff --git a/core/voice/model/TTS.py b/core/voice/model/TTS.py\n--- a/core/voice/model/TTS.py\n+++ b/core/voice/model/TTS.py\n@@ -1,23 +1,24 @@\n-import hashlib\n-import subprocess\n-import tempfile\n+import getpass\n from pathlib import Path\n from typing import Optional\n \n+import hashlib\n+import tempfile\n from pydub import AudioSegment\n \n from core.base.SuperManager import SuperManager\n+from core.base.model.ProjectAliceObject import ProjectAliceObject\n from core.commons import constants\n from core.dialog.model.DialogSession import DialogSession\n from core.user.model.User import User\n-from core.util.model.Logger import Logger\n from core.voice.model.TTSEnum import TTSEnum\n \n \n-class TTS(Logger):\n+class TTS(ProjectAliceObject):\n \tTEMP_ROOT = Path(tempfile.gettempdir(), '/tempTTS')\n \tTTS = None\n \n+\n \tdef __init__(self, user: User = None, *args, **kwargs):\n \t\tsuper().__init__(*args, **kwargs)\n \n@@ -76,21 +77,18 @@ def onStart(self):\n \t\t\tself.logWarning(f'Voice \"{voice}\" not found for the language and type, falling back to \"{self._voice}\"')\n \n \t\tif not self.TEMP_ROOT.is_dir():\n-\t\t\tsubprocess.run(['sudo', 'mkdir', str(self.TEMP_ROOT)])\n-\t\t\tsubprocess.run(['sudo', 'chown', 'pi', str(self.TEMP_ROOT)])\n+\t\t\tSuperManager.getInstance().commonsManager.runRootSystemCommand(['mkdir', str(self.TEMP_ROOT)])\n+\t\t\tSuperManager.getInstance().commonsManager.runRootSystemCommand(['chown', getpass.getuser(), str(self.TEMP_ROOT)])\n \n \t\tif self.TTS == TTSEnum.SNIPS:\n \t\t\tvoiceFile = f'cmu_{SuperManager.getInstance().languageManager.activeCountryCode.lower()}_{self._voice}'\n \t\t\tif not Path(SuperManager.getInstance().commons.rootDir(), 'system/voices', voiceFile).exists():\n \t\t\t\tself.logInfo(f'Using \"{self.TTS.value}\" as TTS with voice \"{self._voice}\" but voice file not found. Downloading...')\n \n-\t\t\t\tprocess = subprocess.run([\n-\t\t\t\t\t'wget', f'https://github.com/MycroftAI/mimic1/blob/development/voices/{voiceFile}.flitevox?raw=true',\n-\t\t\t\t\t'-O', Path(SuperManager.getInstance().commons.rootDir(), f'var/voices/{voiceFile}.flitevox')\n-\t\t\t\t],\n-\t\t\t\tstdout=subprocess.PIPE)\n+\t\t\t\tif not SuperManager.getInstance().commons.downloadFile(\n+\t\t\t\t\t\turl=f'https://github.com/MycroftAI/mimic1/blob/development/voices/{voiceFile}.flitevox?raw=true',\n+\t\t\t\t\t\tdest=Path(SuperManager.getInstance().commons.rootDir(), f'var/voices/{voiceFile}.flitevox')):\n \n-\t\t\t\tif process.returncode > 0:\n \t\t\t\t\tself.logError('Failed downloading voice file, falling back to slt')\n \t\t\t\t\tself._voice = next(iter(self._supportedLangAndVoices[self._lang][self._type]))\n \n@@ -151,7 +149,7 @@ def getWhisperMarkup() -> Optional[tuple]:\n \n \t@staticmethod\n \tdef _mp3ToWave(src: Path, dest: Path):\n-\t\tsubprocess.run(['mpg123', '-q', '-w', str(dest), str(src)])\n+\t\tSuperManager.getInstance().commonsManager.runSystemCommand(['mpg123', '-q', '-w', str(dest), str(src)])\n \n \n \tdef _hash(self, text: str) -> str:\ndiff --git a/main.py b/main.py\n--- a/main.py\n+++ b/main.py\n@@ -13,13 +13,15 @@\n along with this program. If not, see \n \n authors: \t Psycho \n-\t\t\t\t\t\t\tmaxbachmann \n+\n \tretired or\n \tinactive authors: Jierka \n+\t\t\t\t\t\t\tmaxbachmann \n \"\"\"\n import logging.handlers\n import signal\n import sys\n+import time\n import traceback\n from datetime import datetime\n from pathlib import Path\n@@ -61,7 +63,6 @@ def exceptionListener(*exc_info):\n \n from core.ProjectAlice import ProjectAlice\n import subprocess\n-import time\n \n \n # noinspection PyUnusedLocal\n@@ -97,6 +98,7 @@ def main():\n \t\t\ttime.sleep(3)\n \t\t\tsys.stdout.flush()\n \t\t\ttry:\n+\t\t\t\t# Close everything related to ProjectAlice, allows restart without component failing\n \t\t\t\tp = psutil.Process(os.getpid())\n \t\t\t\tfor h in p.open_files() + p.connections():\n \t\t\t\t\tos.close(h.fd)\n", "test_patch": "diff --git a/tests/unittests/base/model/test_AliceSkill.py b/tests/unittests/base/model/test_AliceSkill.py\n--- a/tests/unittests/base/model/test_AliceSkill.py\n+++ b/tests/unittests/base/model/test_AliceSkill.py\n@@ -21,7 +21,7 @@ def testFindDecoratedIntents(self, mock_config, mock_protected):\n \t\tclass ExampleSkill(AliceSkill):\n \t\t\t#ignore all stuff that would happen in the AliceSkill init\n \t\t\tdef __init__(self):\n-\t\t\t\tpass\n+\t\t\t\tself._name = 'ExampleSkill'\n \n \t\t\t@IntentHandler('intent1', authOnly=AccessLevel.ADMIN)\n \t\t\tdef single_decorator(self, *args, **kwargs):\n@@ -56,8 +56,8 @@ def mqtt_decorator(self, *args, **kwargs):\n \t\tself.assertEqual(intent2.fallbackFunction, None)\n \t\tself.assertDictEqual(\n \t\t\tintent2.dialogMapping,\n-\t\t\t{'exampleState': exampleSkill.multiple_decorator,\n-\t\t\t 'exampleState2': exampleSkill.mqtt_decorator})\n+\t\t\t{'ExampleSkill:exampleState': exampleSkill.multiple_decorator,\n+\t\t\t 'ExampleSkill:exampleState2': exampleSkill.mqtt_decorator})\n \t\tself.assertEqual(str(intent2), 'hermes/intent/unittest:intent2')\n \n \t\tself.assertTrue(intent3.protected)\n@@ -81,8 +81,8 @@ def testBuildIntentList(self, mock_decoratedFuncs, mock_config, mock_protected):\n \t\tclass ExampleSkill(AliceSkill):\n \t\t\t#ignore all stuff that would happen in the AliceSkill init\n \t\t\tdef __init__(self):\n-\t\t\t\tpass\n-\t\t\t\n+\t\t\t\tself._name = 'ExampleSkill'\n+\n \t\t\tdef exampleFunc(self):\n \t\t\t\tpass\n \n@@ -105,10 +105,10 @@ def exampleFunc(self):\n \t\t]\n \n \t\tmappings = exampleSkill.buildIntentList(initIntents)\n-\t\tintent1 = mappings[str(Intent('Intent1'))]\n-\t\tintent2 = mappings[str(Intent('Intent2'))]\n-\t\tintent3 = mappings[str(Intent('intent3'))]\n-\t\tintent4 = mappings[str(Intent('intent4'))]\n+\t\tintent1 = mappings[str(Intent('Intent1'))]\n+\t\tintent2 = mappings[str(Intent('Intent2'))]\n+\t\tintent3 = mappings[str(Intent('intent3'))]\n+\t\tintent4 = mappings[str(Intent('intent4'))]\n \n \t\tself.assertFalse(intent1.protected)\n \t\tself.assertEqual(intent1.authOnly, AccessLevel.ADMIN)\n@@ -147,7 +147,7 @@ def exampleFunc(self):\n \t\t]\n \n \t\tmappings = exampleSkill.buildIntentList(initIntents)\n-\t\tintent1 = mappings[str(Intent('intent1'))]\n+\t\tintent1 = mappings[str(Intent('intent1'))]\n \n \t\tself.assertFalse(intent1.protected)\n \t\tself.assertEqual(intent1.authOnly, AccessLevel.ADMIN)\ndiff --git a/tests/unittests/base/model/test_Version.py b/tests/unittests/base/model/test_Version.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/unittests/base/model/test_Version.py\n@@ -0,0 +1,26 @@\n+import unittest\n+\n+from core.base.model.Version import Version\n+\n+class TestVersion(unittest.TestCase):\n+\n+\tdef test_fromString(self):\n+\t\tself.assertEqual(Version.fromString('1.2.3-a4'), Version(1, 2, 3, 'a', 4))\n+\t\tself.assertEqual(Version.fromString('1.2.3'), Version(1, 2, 3, 'release', 1))\n+\t\tself.assertEqual(Version.fromString('1.2'), Version(1, 2, 0, 'release', 1))\n+\t\tself.assertEqual(Version.fromString('test'), Version(0, 0, 0, '', 0))\n+\t\tself.assertFalse(Version.fromString('test').isVersionNumber)\n+\t\tself.assertTrue(Version.fromString('1.2').isVersionNumber)\n+\n+\tdef test_stringConvertsion(self):\n+\t\tself.assertEqual(str(Version(1, 2, 0, 'release', 1)), '1.2.0')\n+\t\tself.assertEqual(str(Version(1, 2, 0, 'a', 3)), '1.2.0-a3')\n+\n+\tdef test_comparison(self):\n+\t\tself.assertTrue(\n+\t\t\tVersion(1, 0, 0, 'release', 1) > Version(1, 0, 0, 'rc', 1) > Version(1, 0, 0, 'b', 1) > Version(1, 0, 0, 'a', 1) > Version(0, 9, 0, 'release', 1)\n+\t\t)\n+\n+\n+if __name__ == \"__main__\":\n+\tunittest.main()\ndiff --git a/tests/unittests/commons/test_CommonsManager.py b/tests/unittests/commons/test_CommonsManager.py\n--- a/tests/unittests/commons/test_CommonsManager.py\n+++ b/tests/unittests/commons/test_CommonsManager.py\n@@ -1,12 +1,11 @@\n import unittest\n from unittest import mock\n-from unittest.mock import MagicMock\n \n from core.commons.CommonsManager import CommonsManager\n from core.commons import constants\n \n class TestCommonsManager(unittest.TestCase):\n-\t\n+\n \tdef test_getFunctionCaller(self):\n \t\tself.assertEqual(CommonsManager.getFunctionCaller(1), 'test_CommonsManager')\n \ndiff --git a/tests/unittests/util/test_Decorators.py b/tests/unittests/util/test_Decorators.py\n--- a/tests/unittests/util/test_Decorators.py\n+++ b/tests/unittests/util/test_Decorators.py\n@@ -80,10 +80,10 @@ def checkOnlineState(self) -> bool:\n \t\t# when Internet is lost\n \t\tmock_internetManager = mock.PropertyMock(return_value=InternetManager(True))\n \t\ttype(mock_instance).internetManager = mock_internetManager\n-\t\t\n+\n \t\tself.assertEqual(exampleObject.offline(), 'offline')\n \t\tmock_instance.talkManager.randomTalk.assert_called_once_with('offline', skill='AliceSkill')\n-\t\t\n+\n \t\tmock_internetManager = mock.PropertyMock(return_value=InternetManager(False))\n \t\ttype(mock_instance).internetManager = mock_internetManager\n \t\tmock_instance.reset_mock()\ndiff --git a/tests/unittests/util/test_InternetManager.py b/tests/unittests/util/test_InternetManager.py\n--- a/tests/unittests/util/test_InternetManager.py\n+++ b/tests/unittests/util/test_InternetManager.py\n@@ -1,6 +1,6 @@\n import unittest\n from unittest import mock\n-from unittest.mock import MagicMock\n+from unittest.mock import MagicMock, PropertyMock\n from requests.exceptions import RequestException\n \n from core.util.InternetManager import InternetManager\n@@ -9,9 +9,13 @@ class TestInternetManager(unittest.TestCase):\n \n \t@mock.patch('core.util.InternetManager.Manager.broadcast')\n \t@mock.patch('core.util.InternetManager.requests')\n-\tdef test_checkOnlineState(self, mock_requests, mock_broadcast):\n-\t\tinternetManager = InternetManager()\n+\t@mock.patch('core.util.InternetManager.InternetManager.Commons', new_callable=PropertyMock)\n+\tdef test_checkOnlineState(self, mock_commons, mock_requests, mock_broadcast):\n+\t\tcommon_mock = MagicMock()\n+\t\tcommon_mock.getFunctionCaller.return_value = 'InternetManager'\n+\t\tmock_commons.return_value = common_mock\n \n+\t\tinternetManager = InternetManager()\n \n \t\t# request returns status code 204\n \t\tmock_requestsResult = MagicMock()\n@@ -21,7 +25,7 @@ def test_checkOnlineState(self, mock_requests, mock_broadcast):\n \n \t\tinternetManager.checkOnlineState()\n \t\tmock_requests.get.assert_called_once_with('http://clients3.google.com/generate_204')\n-\t\tmock_broadcast.assert_called_once_with(method='onInternetConnected', exceptions=[InternetManager.NAME], propagateToSkills=True)\n+\t\tmock_broadcast.assert_called_once_with(method='internetConnected', exceptions=['InternetManager'], propagateToSkills=True)\n \t\tself.assertEqual(internetManager.online, True)\n \t\tmock_broadcast.reset_mock()\n \t\tmock_requests.reset_mock()\n@@ -45,7 +49,7 @@ def test_checkOnlineState(self, mock_requests, mock_broadcast):\n \t\t# when wrong status code is returned (and currently online)\n \t\tinternetManager.checkOnlineState()\n \t\tmock_requests.get.assert_called_once_with('http://clients3.google.com/generate_204')\n-\t\tmock_broadcast.assert_called_once_with(method='onInternetLost', exceptions=[InternetManager.NAME], propagateToSkills=True)\n+\t\tmock_broadcast.assert_called_once_with(method='internetLost', exceptions=['InternetManager'], propagateToSkills=True)\n \t\tself.assertEqual(internetManager.online, False)\n \t\tmock_broadcast.reset_mock()\n \t\tmock_requests.reset_mock()\n@@ -73,7 +77,7 @@ def test_checkOnlineState(self, mock_requests, mock_broadcast):\n \t\tmock_requests.get.side_effect = RequestException\n \t\tinternetManager.checkOnlineState()\n \t\tmock_requests.get.assert_called_once_with('http://clients3.google.com/generate_204')\n-\t\tmock_broadcast.assert_called_once_with(method='onInternetLost', exceptions=[InternetManager.NAME], propagateToSkills=True)\n+\t\tmock_broadcast.assert_called_once_with(method='internetLost', exceptions=['InternetManager'], propagateToSkills=True)\n \t\tself.assertEqual(internetManager.online, False)\n \n \ndiff --git a/tests/unittests/voice/test_TalkManager.py b/tests/unittests/voice/test_TalkManager.py\n--- a/tests/unittests/voice/test_TalkManager.py\n+++ b/tests/unittests/voice/test_TalkManager.py\n@@ -1,10 +1,17 @@\n import unittest\n+from unittest import mock\n+from unittest.mock import MagicMock, PropertyMock\n \n from core.voice.TalkManager import TalkManager\n \n class TestTalkManager(unittest.TestCase):\n \n-\tdef test_chooseTalk(self):\n+\t@mock.patch('core.voice.TalkManager.TalkManager.Commons', new_callable=PropertyMock)\n+\tdef test_chooseTalk(self, mock_commons):\n+\t\tcommon_mock = MagicMock()\n+\t\tcommon_mock.getFunctionCaller.return_value = 'TalkManager'\n+\t\tmock_commons.return_value = common_mock\n+\n \t\ttalkManager = TalkManager()\n \n \t\t# when short and default version exist\n", "problem_statement": "", "hints_text": "", "created_at": "2020-02-22T18:48:32Z"}