2018-07-06 02:08:38 +02:00
|
|
|
import ast
|
2022-04-07 00:18:11 +02:00
|
|
|
import contextlib
|
2021-10-16 22:35:37 +02:00
|
|
|
import datetime
|
2018-07-05 09:15:53 +02:00
|
|
|
import hashlib
|
2017-12-18 01:10:51 +01:00
|
|
|
import importlib
|
2018-07-06 02:08:38 +02:00
|
|
|
import inspect
|
2017-12-18 01:10:51 +01:00
|
|
|
import logging
|
2018-01-27 04:31:09 +01:00
|
|
|
import os
|
2021-02-12 22:43:34 +01:00
|
|
|
import pathlib
|
2019-03-16 19:28:47 +01:00
|
|
|
import re
|
2022-11-21 12:30:38 +01:00
|
|
|
import rsa
|
2017-12-20 20:25:08 +01:00
|
|
|
import signal
|
2019-02-05 02:30:20 +01:00
|
|
|
import socket
|
2018-11-01 23:34:14 +01:00
|
|
|
import ssl
|
2019-02-06 11:51:44 +01:00
|
|
|
import urllib.request
|
2021-10-16 22:35:37 +02:00
|
|
|
from typing import Optional, Tuple, Union
|
2017-12-18 01:10:51 +01:00
|
|
|
|
2021-10-16 22:35:37 +02:00
|
|
|
from dateutil import parser, tz
|
2021-06-26 11:14:26 +02:00
|
|
|
from redis import Redis
|
2022-11-21 12:30:38 +01:00
|
|
|
from rsa.key import PublicKey, PrivateKey
|
2021-06-26 11:14:26 +02:00
|
|
|
|
2020-09-27 01:33:38 +02:00
|
|
|
logger = logging.getLogger('utils')
|
2017-12-18 01:10:51 +01:00
|
|
|
|
2019-07-01 22:26:04 +02:00
|
|
|
|
2017-12-25 17:23:09 +01:00
|
|
|
def get_module_and_method_from_action(action):
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Input : action=music.mpd.play
|
|
|
|
Output : ('music.mpd', 'play')"""
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
tokens = action.split('.')
|
|
|
|
module_name = str.join('.', tokens[:-1])
|
|
|
|
method_name = tokens[-1:][0]
|
2019-07-01 22:26:04 +02:00
|
|
|
return module_name, method_name
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_message_class_by_type(msgtype):
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Gets the class of a message type given as string"""
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
module = importlib.import_module('platypush.message.' + msgtype)
|
2018-02-20 22:58:13 +01:00
|
|
|
except ImportError as e:
|
2018-06-06 20:09:18 +02:00
|
|
|
logger.warning('Unsupported message type {}'.format(msgtype))
|
2017-12-20 20:25:08 +01:00
|
|
|
raise RuntimeError(e)
|
|
|
|
|
|
|
|
cls_name = msgtype[0].upper() + msgtype[1:]
|
|
|
|
|
|
|
|
try:
|
|
|
|
msgclass = getattr(module, cls_name)
|
|
|
|
except AttributeError as e:
|
2022-04-07 00:18:11 +02:00
|
|
|
logger.warning('No such class in {}: {}'.format(module.__name__, cls_name))
|
2017-12-20 20:25:08 +01:00
|
|
|
raise RuntimeError(e)
|
|
|
|
|
|
|
|
return msgclass
|
|
|
|
|
|
|
|
|
2021-04-05 00:58:44 +02:00
|
|
|
# noinspection PyShadowingBuiltins
|
2017-12-24 01:03:26 +01:00
|
|
|
def get_event_class_by_type(type):
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Gets an event class by type name"""
|
2017-12-24 01:03:26 +01:00
|
|
|
event_module = importlib.import_module('.'.join(type.split('.')[:-1]))
|
|
|
|
return getattr(event_module, type.split('.')[-1])
|
|
|
|
|
|
|
|
|
2019-07-01 22:26:04 +02:00
|
|
|
def get_plugin_module_by_name(plugin_name):
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Gets the module of a plugin by name (e.g. "music.mpd" or "media.vlc")"""
|
2019-07-01 22:26:04 +02:00
|
|
|
|
|
|
|
module_name = 'platypush.plugins.' + plugin_name
|
|
|
|
try:
|
|
|
|
return importlib.import_module('platypush.plugins.' + plugin_name)
|
|
|
|
except ImportError as e:
|
|
|
|
logger.error('Cannot import {}: {}'.format(module_name, str(e)))
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def get_plugin_class_by_name(plugin_name):
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Gets the class of a plugin by name (e.g. "music.mpd" or "media.vlc")"""
|
2019-07-01 22:26:04 +02:00
|
|
|
|
|
|
|
module = get_plugin_module_by_name(plugin_name)
|
|
|
|
if not module:
|
|
|
|
return
|
|
|
|
|
2022-04-07 00:18:11 +02:00
|
|
|
class_name = getattr(
|
|
|
|
module, ''.join([_.capitalize() for _ in plugin_name.split('.')]) + 'Plugin'
|
|
|
|
)
|
2019-07-01 22:26:04 +02:00
|
|
|
try:
|
2022-04-07 00:18:11 +02:00
|
|
|
return getattr(
|
|
|
|
module, ''.join([_.capitalize() for _ in plugin_name.split('.')]) + 'Plugin'
|
|
|
|
)
|
2019-07-01 22:26:04 +02:00
|
|
|
except Exception as e:
|
|
|
|
logger.error('Cannot import class {}: {}'.format(class_name, str(e)))
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2020-09-27 01:33:38 +02:00
|
|
|
def get_plugin_name_by_class(plugin) -> Optional[str]:
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Gets the common name of a plugin (e.g. "music.mpd" or "media.vlc") given its class."""
|
2020-09-19 00:50:22 +02:00
|
|
|
|
|
|
|
from platypush.plugins import Plugin
|
|
|
|
|
|
|
|
if isinstance(plugin, Plugin):
|
|
|
|
plugin = plugin.__class__
|
|
|
|
|
|
|
|
class_name = plugin.__name__
|
|
|
|
class_tokens = [
|
2022-04-07 00:18:11 +02:00
|
|
|
token.lower()
|
|
|
|
for token in re.sub(r'([A-Z])', r' \1', class_name).split(' ')
|
2020-09-19 00:50:22 +02:00
|
|
|
if token.strip() and token != 'Plugin'
|
|
|
|
]
|
|
|
|
|
|
|
|
return '.'.join(class_tokens)
|
|
|
|
|
|
|
|
|
2020-09-27 01:33:38 +02:00
|
|
|
def get_backend_name_by_class(backend) -> Optional[str]:
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Gets the common name of a backend (e.g. "http" or "mqtt") given its class."""
|
2020-09-27 01:33:38 +02:00
|
|
|
|
|
|
|
from platypush.backend import Backend
|
|
|
|
|
|
|
|
if isinstance(backend, Backend):
|
|
|
|
backend = backend.__class__
|
|
|
|
|
|
|
|
class_name = backend.__name__
|
|
|
|
class_tokens = [
|
2022-04-07 00:18:11 +02:00
|
|
|
token.lower()
|
|
|
|
for token in re.sub(r'([A-Z])', r' \1', class_name).split(' ')
|
2020-09-27 01:33:38 +02:00
|
|
|
if token.strip() and token != 'Backend'
|
|
|
|
]
|
|
|
|
|
|
|
|
return '.'.join(class_tokens)
|
|
|
|
|
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
def set_timeout(seconds, on_timeout):
|
|
|
|
"""
|
|
|
|
Set a function to be called if timeout expires without being cleared.
|
|
|
|
It only works on the main thread.
|
|
|
|
|
|
|
|
Params:
|
|
|
|
seconds -- Timeout in seconds
|
|
|
|
on_timeout -- Function invoked on timeout unless clear_timeout is called before
|
|
|
|
"""
|
|
|
|
|
2021-04-05 00:58:44 +02:00
|
|
|
def _sighandler(*_):
|
2017-12-20 20:25:08 +01:00
|
|
|
on_timeout()
|
|
|
|
|
|
|
|
signal.signal(signal.SIGALRM, _sighandler)
|
|
|
|
signal.alarm(seconds)
|
|
|
|
|
|
|
|
|
|
|
|
def clear_timeout():
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Clear any previously set timeout"""
|
2017-12-20 20:25:08 +01:00
|
|
|
signal.alarm(0)
|
|
|
|
|
2017-12-18 01:10:51 +01:00
|
|
|
|
2018-07-05 09:15:53 +02:00
|
|
|
def get_hash(s):
|
2022-04-07 00:18:11 +02:00
|
|
|
"""Get the SHA256 hash hex digest of a string input"""
|
2018-07-05 09:15:53 +02:00
|
|
|
return hashlib.sha256(s.encode('utf-8')).hexdigest()
|
|
|
|
|
|
|
|
|
2018-07-17 01:23:12 +02:00
|
|
|
def get_decorators(cls, climb_class_hierarchy=False):
|
|
|
|
"""
|
|
|
|
Get the decorators of a class as a {"decorator_name": [list of methods]} dictionary
|
2021-09-16 17:53:40 +02:00
|
|
|
|
|
|
|
:param cls: Class type
|
|
|
|
:param climb_class_hierarchy: If set to True (default: False), it will search return the decorators in the parent
|
|
|
|
classes as well
|
2018-07-17 01:23:12 +02:00
|
|
|
:type climb_class_hierarchy: bool
|
|
|
|
"""
|
|
|
|
|
2018-07-06 02:08:38 +02:00
|
|
|
decorators = {}
|
|
|
|
|
2021-09-16 17:53:40 +02:00
|
|
|
# noinspection PyPep8Naming
|
2018-07-06 02:08:38 +02:00
|
|
|
def visit_FunctionDef(node):
|
|
|
|
for n in node.decorator_list:
|
|
|
|
if isinstance(n, ast.Call):
|
2021-09-16 17:53:40 +02:00
|
|
|
# noinspection PyUnresolvedReferences
|
2018-07-06 02:08:38 +02:00
|
|
|
name = n.func.attr if isinstance(n.func, ast.Attribute) else n.func.id
|
|
|
|
else:
|
|
|
|
name = n.attr if isinstance(n, ast.Attribute) else n.id
|
|
|
|
|
2018-07-17 01:23:12 +02:00
|
|
|
decorators[name] = decorators.get(name, set())
|
|
|
|
decorators[name].add(node.name)
|
|
|
|
|
|
|
|
if climb_class_hierarchy:
|
|
|
|
targets = inspect.getmro(cls)
|
|
|
|
else:
|
|
|
|
targets = [cls]
|
2018-07-06 02:08:38 +02:00
|
|
|
|
|
|
|
node_iter = ast.NodeVisitor()
|
|
|
|
node_iter.visit_FunctionDef = visit_FunctionDef
|
2018-07-17 01:23:12 +02:00
|
|
|
|
|
|
|
for target in targets:
|
2022-04-07 00:18:11 +02:00
|
|
|
with contextlib.suppress(TypeError):
|
2018-07-17 01:23:12 +02:00
|
|
|
node_iter.visit(ast.parse(inspect.getsource(target)))
|
|
|
|
|
2018-07-06 02:08:38 +02:00
|
|
|
return decorators
|
|
|
|
|
|
|
|
|
2018-09-20 12:49:57 +02:00
|
|
|
def get_redis_queue_name_by_message(msg):
|
|
|
|
from platypush.message import Message
|
|
|
|
|
|
|
|
if not isinstance(msg, Message):
|
|
|
|
logger.warning('Not a valid message (type: {}): {}'.format(type(msg), msg))
|
|
|
|
|
|
|
|
return 'platypush/responses/{}'.format(msg.id) if msg.id else None
|
|
|
|
|
|
|
|
|
2022-04-07 00:18:11 +02:00
|
|
|
def _get_ssl_context(
|
|
|
|
context_type=None, ssl_cert=None, ssl_key=None, ssl_cafile=None, ssl_capath=None
|
|
|
|
):
|
2018-11-01 23:34:14 +01:00
|
|
|
if not context_type:
|
2022-04-07 00:18:11 +02:00
|
|
|
ssl_context = ssl.create_default_context(cafile=ssl_cafile, capath=ssl_capath)
|
2018-11-01 23:34:14 +01:00
|
|
|
else:
|
2019-06-21 02:13:14 +02:00
|
|
|
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
2018-11-01 23:34:14 +01:00
|
|
|
|
|
|
|
if ssl_cafile or ssl_capath:
|
2022-04-07 00:18:11 +02:00
|
|
|
ssl_context.load_verify_locations(cafile=ssl_cafile, capath=ssl_capath)
|
2018-11-01 23:34:14 +01:00
|
|
|
|
|
|
|
ssl_context.load_cert_chain(
|
|
|
|
certfile=os.path.abspath(os.path.expanduser(ssl_cert)),
|
2022-04-07 00:18:11 +02:00
|
|
|
keyfile=os.path.abspath(os.path.expanduser(ssl_key)) if ssl_key else None,
|
2018-11-01 23:34:14 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
return ssl_context
|
|
|
|
|
|
|
|
|
2022-04-07 00:18:11 +02:00
|
|
|
def get_ssl_context(ssl_cert=None, ssl_key=None, ssl_cafile=None, ssl_capath=None):
|
|
|
|
return _get_ssl_context(
|
|
|
|
context_type=None,
|
|
|
|
ssl_cert=ssl_cert,
|
|
|
|
ssl_key=ssl_key,
|
|
|
|
ssl_cafile=ssl_cafile,
|
|
|
|
ssl_capath=ssl_capath,
|
|
|
|
)
|
2018-11-01 23:34:14 +01:00
|
|
|
|
|
|
|
|
2022-04-07 00:18:11 +02:00
|
|
|
def get_ssl_server_context(
|
|
|
|
ssl_cert=None, ssl_key=None, ssl_cafile=None, ssl_capath=None
|
|
|
|
):
|
|
|
|
return _get_ssl_context(
|
|
|
|
context_type=ssl.PROTOCOL_TLS_SERVER,
|
|
|
|
ssl_cert=ssl_cert,
|
|
|
|
ssl_key=ssl_key,
|
|
|
|
ssl_cafile=ssl_cafile,
|
|
|
|
ssl_capath=ssl_capath,
|
|
|
|
)
|
2018-11-01 23:34:14 +01:00
|
|
|
|
|
|
|
|
2022-04-07 00:18:11 +02:00
|
|
|
def get_ssl_client_context(
|
|
|
|
ssl_cert=None, ssl_key=None, ssl_cafile=None, ssl_capath=None
|
|
|
|
):
|
|
|
|
return _get_ssl_context(
|
|
|
|
context_type=ssl.PROTOCOL_TLS_CLIENT,
|
|
|
|
ssl_cert=ssl_cert,
|
|
|
|
ssl_key=ssl_key,
|
|
|
|
ssl_cafile=ssl_cafile,
|
|
|
|
ssl_capath=ssl_capath,
|
|
|
|
)
|
2018-11-01 23:34:14 +01:00
|
|
|
|
2021-09-16 17:53:40 +02:00
|
|
|
|
2019-01-10 23:45:13 +01:00
|
|
|
def set_thread_name(name):
|
|
|
|
global logger
|
|
|
|
|
|
|
|
try:
|
|
|
|
import prctl
|
2022-04-07 00:18:11 +02:00
|
|
|
|
2021-04-05 00:58:44 +02:00
|
|
|
# noinspection PyUnresolvedReferences
|
2019-01-10 23:45:13 +01:00
|
|
|
prctl.set_name(name)
|
|
|
|
except ImportError:
|
|
|
|
logger.debug('Unable to set thread name: prctl module is missing')
|
|
|
|
|
2020-01-17 21:15:27 +01:00
|
|
|
|
2019-02-03 17:43:30 +01:00
|
|
|
def find_bins_in_path(bin_name):
|
2022-02-07 01:47:38 +01:00
|
|
|
return [
|
|
|
|
os.path.join(p, bin_name)
|
|
|
|
for p in os.environ.get('PATH', '').split(':')
|
2022-04-07 00:18:11 +02:00
|
|
|
if os.path.isfile(os.path.join(p, bin_name))
|
|
|
|
and (os.name == 'nt' or os.access(os.path.join(p, bin_name), os.X_OK))
|
|
|
|
]
|
2018-11-01 23:34:14 +01:00
|
|
|
|
2017-12-18 01:10:51 +01:00
|
|
|
|
2019-02-05 00:15:36 +01:00
|
|
|
def find_files_by_ext(directory, *exts):
|
|
|
|
"""
|
|
|
|
Finds all the files in the given directory with the provided extensions
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not exts:
|
|
|
|
raise AttributeError('No extensions provided')
|
|
|
|
|
|
|
|
if not os.path.isdir(directory):
|
|
|
|
raise AttributeError('{} is not a valid directory'.format(directory))
|
|
|
|
|
|
|
|
min_len = len(min(exts, key=len))
|
|
|
|
max_len = len(max(exts, key=len))
|
|
|
|
result = []
|
|
|
|
|
2022-04-07 00:18:11 +02:00
|
|
|
for _, __, files in os.walk(directory):
|
2021-09-16 17:53:40 +02:00
|
|
|
for i in range(min_len, max_len + 1):
|
2019-02-05 00:15:36 +01:00
|
|
|
result += [f for f in files if f[-i:] in exts]
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def is_process_alive(pid):
|
|
|
|
try:
|
|
|
|
os.kill(pid, 0)
|
|
|
|
return True
|
|
|
|
except OSError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2019-02-05 02:30:20 +01:00
|
|
|
def get_ip_or_hostname():
|
|
|
|
ip = socket.gethostbyname(socket.gethostname())
|
2021-07-17 22:14:15 +02:00
|
|
|
if ip.startswith('127.') or ip.startswith('::1'):
|
2021-01-14 00:15:35 +01:00
|
|
|
try:
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
sock.connect(('10.255.255.255', 1))
|
|
|
|
ip = sock.getsockname()[0]
|
|
|
|
sock.close()
|
2021-04-05 00:58:44 +02:00
|
|
|
except Exception as e:
|
|
|
|
logger.debug(e)
|
2021-01-14 00:15:35 +01:00
|
|
|
|
|
|
|
return ip
|
2019-02-05 02:30:20 +01:00
|
|
|
|
|
|
|
|
2019-02-06 11:51:44 +01:00
|
|
|
def get_mime_type(resource):
|
2019-02-06 13:22:58 +01:00
|
|
|
import magic
|
2022-04-07 00:18:11 +02:00
|
|
|
|
2019-02-06 11:51:44 +01:00
|
|
|
if resource.startswith('file://'):
|
2022-04-07 00:18:11 +02:00
|
|
|
resource = resource[len('file://') :]
|
2019-02-06 11:51:44 +01:00
|
|
|
|
2021-09-16 17:53:40 +02:00
|
|
|
# noinspection HttpUrlsUsage
|
2019-02-06 11:51:44 +01:00
|
|
|
if resource.startswith('http://') or resource.startswith('https://'):
|
|
|
|
with urllib.request.urlopen(resource) as response:
|
|
|
|
return response.info().get_content_type()
|
|
|
|
else:
|
2019-06-21 13:40:45 +02:00
|
|
|
if hasattr(magic, 'detect_from_filename'):
|
|
|
|
mime = magic.detect_from_filename(resource)
|
|
|
|
elif hasattr(magic, 'from_file'):
|
|
|
|
mime = magic.from_file(resource, mime=True)
|
|
|
|
else:
|
2022-04-07 00:18:11 +02:00
|
|
|
raise RuntimeError(
|
|
|
|
'The installed magic version provides neither detect_from_filename nor from_file'
|
|
|
|
)
|
2019-06-21 13:40:45 +02:00
|
|
|
|
2019-06-21 02:13:14 +02:00
|
|
|
if mime:
|
2021-01-14 00:15:35 +01:00
|
|
|
return mime.mime_type if hasattr(mime, 'mime_type') else mime
|
2019-02-06 11:51:44 +01:00
|
|
|
|
2020-01-17 21:15:27 +01:00
|
|
|
|
2019-03-16 19:28:47 +01:00
|
|
|
def camel_case_to_snake_case(string):
|
|
|
|
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
|
|
|
|
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
|
|
|
|
2019-02-06 11:51:44 +01:00
|
|
|
|
2020-01-17 21:15:27 +01:00
|
|
|
def grouper(n, iterable, fillvalue=None):
|
|
|
|
"""
|
|
|
|
Split an iterable in groups of max N elements.
|
|
|
|
grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
|
|
|
|
"""
|
|
|
|
from itertools import zip_longest
|
2022-04-07 00:18:11 +02:00
|
|
|
|
2020-01-17 21:15:27 +01:00
|
|
|
args = [iter(iterable)] * n
|
|
|
|
|
|
|
|
if fillvalue:
|
2022-12-10 15:57:28 +01:00
|
|
|
return zip_longest(*args, fillvalue=fillvalue)
|
2020-01-17 21:15:27 +01:00
|
|
|
|
|
|
|
for chunk in zip_longest(*args):
|
|
|
|
yield filter(None, chunk)
|
|
|
|
|
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
def is_functional_procedure(obj) -> bool:
|
|
|
|
return callable(obj) and hasattr(obj, 'procedure')
|
|
|
|
|
|
|
|
|
|
|
|
def is_functional_hook(obj) -> bool:
|
|
|
|
return callable(obj) and hasattr(obj, 'hook')
|
|
|
|
|
|
|
|
|
2020-10-13 23:25:27 +02:00
|
|
|
def is_functional_cron(obj) -> bool:
|
|
|
|
return callable(obj) and hasattr(obj, 'cron') and hasattr(obj, 'cron_expression')
|
|
|
|
|
|
|
|
|
2020-04-09 23:50:08 +02:00
|
|
|
def run(action, *args, **kwargs):
|
2020-04-08 23:22:54 +02:00
|
|
|
from platypush.context import get_plugin
|
2022-04-07 00:18:11 +02:00
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
(module_name, method_name) = get_module_and_method_from_action(action)
|
|
|
|
plugin = get_plugin(module_name)
|
|
|
|
method = getattr(plugin, method_name)
|
2020-04-10 00:06:36 +02:00
|
|
|
response = method(*args, **kwargs)
|
|
|
|
|
|
|
|
if response.errors:
|
|
|
|
raise RuntimeError(response.errors[0])
|
|
|
|
|
|
|
|
return response.output
|
2020-04-08 23:22:54 +02:00
|
|
|
|
|
|
|
|
2022-12-10 15:57:28 +01:00
|
|
|
def generate_rsa_key_pair(
|
|
|
|
key_file: Optional[str] = None, size: int = 2048
|
|
|
|
) -> Tuple[PublicKey, PrivateKey]:
|
2021-02-12 22:43:34 +01:00
|
|
|
"""
|
|
|
|
Generate an RSA key pair.
|
|
|
|
|
|
|
|
:param key_file: Target file for the private key (the associated public key will be stored in ``<key_file>.pub``.
|
|
|
|
If no key file is specified then the public and private keys will be returned in ASCII format in a dictionary
|
|
|
|
with the following structure:
|
|
|
|
|
|
|
|
.. code-block:: json
|
|
|
|
|
|
|
|
{
|
|
|
|
"private": "private key here",
|
|
|
|
"public": "public key here"
|
|
|
|
}
|
|
|
|
|
|
|
|
:param size: Key size (default: 2048 bits).
|
|
|
|
:return: A tuple with the generated ``(priv_key_str, pub_key_str)``.
|
|
|
|
"""
|
2022-11-21 12:30:38 +01:00
|
|
|
logger.info('Generating RSA keypair')
|
|
|
|
pub_key, priv_key = rsa.newkeys(size)
|
|
|
|
logger.info('Generated RSA keypair')
|
|
|
|
public_key_str = pub_key.save_pkcs1('PEM').decode()
|
|
|
|
private_key_str = priv_key.save_pkcs1('PEM').decode()
|
2021-02-12 22:43:34 +01:00
|
|
|
|
|
|
|
if key_file:
|
|
|
|
logger.info('Saving private key to {}'.format(key_file))
|
2022-04-07 00:18:11 +02:00
|
|
|
with open(os.path.expanduser(key_file), 'w') as f1, open(
|
|
|
|
os.path.expanduser(key_file) + '.pub', 'w'
|
|
|
|
) as f2:
|
2021-02-12 22:43:34 +01:00
|
|
|
f1.write(private_key_str)
|
|
|
|
f2.write(public_key_str)
|
|
|
|
os.chmod(key_file, 0o600)
|
|
|
|
|
2022-11-21 12:30:38 +01:00
|
|
|
return pub_key, priv_key
|
2021-02-12 22:43:34 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_or_generate_jwt_rsa_key_pair():
|
|
|
|
from platypush.config import Config
|
|
|
|
|
|
|
|
key_dir = os.path.join(Config.get('workdir'), 'jwt')
|
|
|
|
priv_key_file = os.path.join(key_dir, 'id_rsa')
|
|
|
|
pub_key_file = priv_key_file + '.pub'
|
|
|
|
|
|
|
|
if os.path.isfile(priv_key_file) and os.path.isfile(pub_key_file):
|
2022-12-10 15:57:28 +01:00
|
|
|
with open(pub_key_file, 'r') as f1, open(priv_key_file, 'r') as f2:
|
2022-11-21 12:30:38 +01:00
|
|
|
return (
|
|
|
|
rsa.PublicKey.load_pkcs1(f1.read().encode()),
|
|
|
|
rsa.PrivateKey.load_pkcs1(f2.read().encode()),
|
|
|
|
)
|
2021-02-12 22:43:34 +01:00
|
|
|
|
|
|
|
pathlib.Path(key_dir).mkdir(parents=True, exist_ok=True, mode=0o755)
|
|
|
|
return generate_rsa_key_pair(priv_key_file, size=2048)
|
|
|
|
|
|
|
|
|
2021-02-19 02:54:12 +01:00
|
|
|
def get_enabled_plugins() -> dict:
|
|
|
|
from platypush.config import Config
|
|
|
|
from platypush.context import get_plugin
|
|
|
|
|
|
|
|
plugins = {}
|
2022-04-07 00:18:11 +02:00
|
|
|
for name in Config.get_plugins():
|
2021-02-19 02:54:12 +01:00
|
|
|
try:
|
|
|
|
plugin = get_plugin(name)
|
|
|
|
if plugin:
|
|
|
|
plugins[name] = plugin
|
2021-04-05 00:58:44 +02:00
|
|
|
except Exception as e:
|
2022-02-07 01:47:38 +01:00
|
|
|
logger.warning(f'Could not initialize plugin {name}')
|
|
|
|
logger.exception(e)
|
2021-02-19 02:54:12 +01:00
|
|
|
|
|
|
|
return plugins
|
|
|
|
|
|
|
|
|
2021-06-26 11:14:26 +02:00
|
|
|
def get_redis() -> Redis:
|
|
|
|
from platypush.config import Config
|
2022-04-07 00:18:11 +02:00
|
|
|
|
|
|
|
return Redis(
|
|
|
|
**(
|
|
|
|
(Config.get('backend.redis') or {}).get('redis_args', {})
|
|
|
|
or Config.get('redis')
|
|
|
|
or {}
|
|
|
|
)
|
|
|
|
)
|
2021-06-26 11:14:26 +02:00
|
|
|
|
2021-10-16 22:35:37 +02:00
|
|
|
|
|
|
|
def to_datetime(t: Union[str, int, float, datetime.datetime]) -> datetime.datetime:
|
2022-04-07 00:18:11 +02:00
|
|
|
if isinstance(t, (int, float)):
|
2021-10-16 22:35:37 +02:00
|
|
|
return datetime.datetime.fromtimestamp(t, tz=tz.tzutc())
|
|
|
|
if isinstance(t, str):
|
|
|
|
return parser.parse(t)
|
|
|
|
return t
|
|
|
|
|
|
|
|
|
2019-02-03 17:43:30 +01:00
|
|
|
# vim:sw=4:ts=4:et:
|