-
Notifications
You must be signed in to change notification settings - Fork 11
/
mycroft_skill.py
312 lines (269 loc) · 13.3 KB
/
mycroft_skill.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# Copyright 2019 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
import shutil
from os.path import join, exists, dirname
from json_database import JsonStorage
from ovos_bus_client import MessageBusClient, Message
from ovos_utils.log import LOG, log_deprecation, deprecated
from ovos_workshop.decorators.compat import backwards_compat
from ovos_workshop.filesystem import FileSystemAccess
from ovos_workshop.skills.ovos import OVOSSkill, is_classic_core, _OVOSSkillMetaclass
class _SkillMetaclass(_OVOSSkillMetaclass):
"""
This metaclass ensures we can load skills like regular python objects.
mycroft-core required a skill loader helper class, which created the skill
and then finished object init. This meant skill_id and bus were not
available in init method, so mycroft introduced a method named `initialize`
that was called after `skill_id` and `bus` were defined.
To make skills pythonic and standalone, this metaclass is used to auto init
old skills and help in migrating to new standards.
To override isinstance checks we also need to use a metaclass
TODO: remove compat ovos-core 0.2.0 at the latest, including MycroftSkill class
"""
def __instancecheck_classic__(self, instance):
# instance imported from vanilla mycroft
from mycroft.skills import MycroftSkill as _CoreSkill
from ovos_workshop.app import OVOSAbstractApplication
if issubclass(instance.__class__, _CoreSkill):
return True
return issubclass(instance.__class__, OVOSSkill) and \
not issubclass(instance.__class__, OVOSAbstractApplication)
@backwards_compat(classic_core=__instancecheck_classic__)
def __instancecheck__(self, instance):
from ovos_workshop.app import OVOSAbstractApplication
if issubclass(instance.__class__, OVOSAbstractApplication):
return False
return super().__instancecheck__(instance) or \
issubclass(instance.__class__, OVOSSkill)
def __call__(cls, *args, **kwargs):
from ovos_bus_client import MessageBusClient
from ovos_utils.messagebus import FakeBus
bus = None
skill_id = None
if "bus" not in kwargs:
for a in args:
if isinstance(a, MessageBusClient) or isinstance(a, FakeBus):
bus = a
LOG.warning(
f"bus should be a kwarg, guessing {a} is the bus")
break
else:
LOG.warning("skill initialized without bus!! this is legacy "
"behaviour and requires you to call skill.bind(bus)"
" or skill._startup(skill_id, bus)\n"
"bus will be required starting on ovos-core 0.1.0")
return super().__call__(*args, **kwargs)
if "skill_id" in kwargs:
skill_id = kwargs.pop("skill_id")
if "bus" in kwargs:
bus = kwargs.pop("bus")
if not skill_id:
LOG.warning(f"skill_id should be a kwarg, please update "
f"{cls.__name__}")
if args and isinstance(args[0], str):
a = args[0]
if a[0].isupper():
# in mycroft name is CamelCase by convention, not skill_id
LOG.debug(f"ambiguous skill_id, ignoring {a} as it appears "
f"to be a CamelCase name")
else:
LOG.warning(f"ambiguous skill_id, assuming positional "
f"argument: {a}")
skill_id = a
if not skill_id:
LOG.error("skill initialized without skill_id!! this is legacy "
"behaviour. skill_id will be required starting on ovos-core 0.1.0")
# by convention skill_id is the folder name
# usually repo.author
skill_id = dirname(inspect.getfile(cls)).split("/")[-1]
LOG.warning(f"missing skill_id, assuming folder name convention: {skill_id}")
try:
# skill follows latest best practices,
# accepts kwargs and does its own init
return super().__call__(skill_id=skill_id, bus=bus, **kwargs)
except TypeError:
LOG.warning(f"Legacy skill signature detected for {skill_id};"
f" attempting to init skill manually, self.bus and "
f"self.skill_id will only be available in "
f"self.initialize. `__init__` method needs to accept "
f"`skill_id` and `bus` to resolve this.")
# skill did not update its init method, init it manually
# NOTE: no try/except because all skills must accept this initialization
# this is what skill loader does internally
skill = super().__call__(*args, **kwargs)
skill._startup(bus, skill_id)
return skill
class MycroftSkill(OVOSSkill, metaclass=_SkillMetaclass):
"""
Base class for mycroft skills providing common behaviour and parameters
to all Skill implementations. This class is kept for backwards-compat. It is
recommended to implement `OVOSSkill` to properly implement new methods.
"""
@deprecated("mycroft-core has been deprecated, please move to ovos-core", "0.1.0")
def __classic_init__(self, name: str = None, bus: MessageBusClient = None,
use_settings: bool = True, *args, **kwargs):
"""
Create a MycroftSkill object.
@param name: DEPRECATED skill_name
@param bus: MessageBusClient to bind to skill
@param use_settings: DEPRECATED option to disable settings sync
"""
super().__init__(name=name, bus=bus, *args, **kwargs)
self._initial_settings = {}
self.settings_write_path = None
self.settings_manager = None
# old kludge from fallback skills, unused according to grep
if use_settings is False:
log_deprecation("use_settings has been deprecated! "
"skill settings are always enabled", "0.1.0")
self.settings_write_path = self.root_dir
@backwards_compat(classic_core=__classic_init__)
@deprecated("MycroftSkill class has been deprecated, please subclass from OVOSSkill", "0.1.0")
def __init__(self, name: str = None, bus: MessageBusClient = None,
use_settings: bool = True, *args, **kwargs):
"""
Create a MycroftSkill object.
@param name: DEPRECATED skill_name
@param bus: MessageBusClient to bind to skill
@param use_settings: DEPRECATED option to disable settings sync
"""
super().__init__(name=name, bus=bus, *args, **kwargs)
self._initial_settings = {}
self.settings_write_path = None
self.settings_manager = None
@property
def file_system(self) -> FileSystemAccess:
"""
Get an object that provides managed access to a local Filesystem.
"""
if not self._file_system:
self._file_system = FileSystemAccess(join('skills', self.name))
LOG.warning(f"with MycroftSkill self.file_system does not respect self.skill_id, path: {self._file_system.path}")
return self._file_system
@file_system.setter
def file_system(self, val):
LOG.warning("you are not supposed to override self.file_system, expect breakage!")
self._file_system = val
@property
def settings(self) -> dict:
"""
Get settings specific to this skill
"""
if self._settings is None:
self._settings = JsonStorage(self.settings_write_path,
disable_lock=True)
LOG.warning(f"with MycroftSkill self.settings may not respect self.skill_id, path: {self._settings.path}")
return self._settings
@settings.setter
def settings(self, val):
LOG.warning("Skills are not supposed to override self.settings, expect breakage! Set individual dict keys instead")
self._settings = val
def _init_settings(self):
"""
Set up skill settings. Defines settings in the specified file path,
handles any settings passed to skill init, and starts watching the
settings file for changes.
"""
self.log.debug(f"initializing skill settings for {self.skill_id}")
if self._settings is None:
self._settings = JsonStorage(self.settings_write_path,
disable_lock=True)
# starting on ovos-core 0.0.8 a bus event is emitted
# all settings.json files are monitored for changes in ovos-core
self.add_event("ovos.skills.settings_changed", self._handle_settings_changed)
if self._monitor_own_settings:
self._start_filewatcher()
def __init_settings_manager_classic(self):
super()._init_settings_manager()
from mycroft.skills.settings import SettingsMetaUploader
self._settings_meta = SettingsMetaUploader(self.root_dir,
self.skill_id)
def __init_settings_manager_standalone(self):
super()._init_settings_manager()
@backwards_compat(classic_core=__init_settings_manager_classic,
no_core=__init_settings_manager_standalone)
def _init_settings_manager(self):
super()._init_settings_manager()
# backwards compat - self.settings_meta has been deprecated
# in favor of settings manager
from mycroft.deprecated.skills.settings import SettingsMetaUploader
self._settings_meta = SettingsMetaUploader(self.root_dir,
self.skill_id)
def __init_settings_classic(self):
# migrate settings if needed
if not exists(self.settings_path) and \
exists(self._old_settings_path):
LOG.warning("Found skill settings at pre-xdg location, "
"migrating!")
shutil.copy(self._old_settings_path, self.settings_path)
LOG.info(f"{self._old_settings_path} moved to "
f"{self.settings_path}")
super()._init_settings()
@backwards_compat(classic_core=__init_settings_classic)
def _init_settings(self):
"""Setup skill settings."""
super()._init_settings()
# patched due to functional (internal) differences under mycroft-core
def __on_end_classic(self, message: Message, handler_info: str,
skill_data: dict, is_intent: bool = False):
# mycroft-core style settings
if self.settings != self._initial_settings:
try:
from mycroft.skills.settings import save_settings
save_settings(self.settings_write_path, self.settings)
self._initial_settings = dict(self.settings)
except Exception as e:
LOG.exception(f"Failed to save skill settings: {e}")
if handler_info:
msg_type = handler_info + '.complete'
message.context["skill_id"] = self.skill_id
self.bus.emit(message.forward(msg_type, skill_data))
@backwards_compat(classic_core=__on_end_classic)
def _on_event_end(self, message: Message, handler_info: str,
skill_data: dict, is_intent: bool = False):
"""
Store settings and indicate that the skill handler has completed
"""
return super()._on_event_end(message, handler_info, skill_data, is_intent)
# refactored - backwards compat + log warnings
@property
def settings_meta(self):
log_deprecation("Use `self.settings_manager`", "0.1.0")
return self._settings_meta
# refactored - backwards compat + log warnings
@settings_meta.setter
def settings_meta(self, val):
log_deprecation("Use `self.settings_manager`", "0.1.0")
self._settings_meta = val
# internal - deprecated under ovos-core
@property
def _old_settings_path(self):
log_deprecation("This path is no longer used", "0.1.0")
old_dir = self.config_core.get("data_dir") or "/opt/mycroft"
old_folder = self.config_core.get("skills", {}).get("msm", {}) \
.get("directory") or "skills"
return join(old_dir, old_folder, self.skill_id, 'settings.json')
# patched due to functional (internal) differences under mycroft-core
def __get_settings_pclassic(self):
if self.settings_write_path and \
self.settings_write_path != self.root_dir:
log_deprecation("`self.settings_write_path` is no longer used",
"0.1.0")
return join(self.settings_write_path, 'settings.json')
return super().settings_path
@property
@backwards_compat(classic_core=__get_settings_pclassic)
def settings_path(self):
return super().settings_path