Exemple #1
0
def get_manifests_from_conf(
        conf_file: Optional[str] = None) -> Mapping[str, Manifest]:
    import platypush
    from platypush.config import Config

    conf_args = []
    if conf_file:
        conf_args.append(conf_file)

    Config.init(*conf_args)
    app_dir = os.path.dirname(inspect.getfile(platypush))
    manifest_files = set()

    for name in Config.get_backends().keys():
        manifest_files.add(
            os.path.join(app_dir, 'backend', *name.split('.'),
                         'manifest.yaml'))

    for name in Config.get_plugins().keys():
        manifest_files.add(
            os.path.join(app_dir, 'plugins', *name.split('.'),
                         'manifest.yaml'))

    return {
        manifest_file: Manifest.from_file(manifest_file)
        for manifest_file in manifest_files
    }
Exemple #2
0
def index():
    """ Route to the main web panel """
    configured_plugins = Config.get_plugins()
    enabled_templates = {}
    enabled_scripts = {}
    enabled_styles = {}

    js_folder = os.path.abspath(
        os.path.join(template_folder, '..', 'static', 'js'))
    style_folder = os.path.abspath(
        os.path.join(template_folder, '..', 'static', 'css', 'dist'))

    for plugin, conf in configured_plugins.items():
        template_file = os.path.join(template_folder, 'plugins', plugin,
                                     'index.html')

        script_file = os.path.join(js_folder, 'plugins', plugin, 'index.js')
        style_file = os.path.join(style_folder, 'webpanel', 'plugins',
                                  plugin + '.css')

        if os.path.isfile(template_file):
            conf['_template_file'] = '/' + '/'.join(
                template_file.split(os.sep)[-3:])
            enabled_templates[plugin] = conf

        if os.path.isfile(script_file):
            conf['_script_file'] = '/'.join(script_file.split(os.sep)[-4:])
            enabled_scripts[plugin] = conf

        if os.path.isfile(style_file):
            conf['_style_file'] = 'css/dist/' + style_file[len(style_folder) +
                                                           1:]
            enabled_styles[plugin] = conf

    http_conf = Config.get('backend.http')
    return render_template('index.html',
                           templates=enabled_templates,
                           scripts=enabled_scripts,
                           styles=enabled_styles,
                           utils=HttpUtils,
                           token=Config.get('token'),
                           websocket_port=get_websocket_port(),
                           template_folder=template_folder,
                           static_folder=static_folder,
                           plugins=Config.get_plugins(),
                           backends=Config.get_backends(),
                           has_ssl=http_conf.get('ssl_cert') is not None)
Exemple #3
0
def build(args):
    global workdir

    ports = set()
    deps = set()

    parser = argparse.ArgumentParser(prog='platydock build',
                                     description='Build a Platypush image ' +
                                     'from a config.yaml')

    parser.add_argument('-c',
                        '--config',
                        type=str,
                        required=True,
                        help='Path to the platypush configuration file')

    opts, args = parser.parse_known_args(args)

    cfgfile = os.path.abspath(os.path.expanduser(opts.config))
    Config.init(cfgfile)
    register_backends()
    backend_config = Config.get_backends()

    if backend_config.get('http'):
        http_backend = get_backend('http')
        ports.add(http_backend.port)
        if http_backend.websocket_port:
            ports.add(http_backend.websocket_port)

    if backend_config.get('tcp'):
        ports.add(get_backend('tcp').port)

    if backend_config.get('websocket'):
        ports.add(get_backend('websocket').port)

    for name in Config.get_backends().keys():
        deps.update(_parse_deps(get_backend(name)))

    for name in Config.get_plugins().keys():
        try:
            deps.update(_parse_deps(get_plugin(name)))
        except:
            pass

    devdir = os.path.join(workdir, Config.get('device_id'))
    generate_dockerfile(deps=deps, ports=ports, cfgfile=cfgfile, devdir=devdir)

    subprocess.call([
        'docker', 'build', '-t',
        'platypush-{}'.format(Config.get('device_id')), devdir
    ])
Exemple #4
0
def get_enabled_plugins() -> dict:
    from platypush.config import Config
    from platypush.context import get_plugin

    plugins = {}
    for name, config in Config.get_plugins().items():
        try:
            plugin = get_plugin(name)
            if plugin:
                plugins[name] = plugin
        except Exception as e:
            logger.warning(f'Could not initialize plugin {name}')
            logger.exception(e)

    return plugins
Exemple #5
0
    def __init__(self, media_dirs=None, download_dir=None, env=None,
                 *args, **kwargs):
        """
        :param media_dirs: Directories that will be scanned for media files when
            a search is performed (default: none)
        :type media_dirs: list

        :param download_dir: Directory where external resources/torrents will be
            downloaded (default: ~/Downloads)
        :type download_dir: str

        :param env: Environment variables key-values to pass to the
            player executable (e.g. DISPLAY, XDG_VTNR, PULSE_SINK etc.)
        :type env: dict
        """

        super().__init__(**kwargs)

        if media_dirs is None:
            media_dirs = []
        player = None
        player_config = {}

        if self.__class__.__name__ == 'MediaPlugin':
            # Abstract class, initialize with the default configured player
            for plugin in Config.get_plugins().keys():
                if plugin in self._supported_media_plugins:
                    player = plugin
                    if get_plugin(player).is_local():
                        # Local players have priority as default if configured
                        break
        else:
            player = self  # Derived concrete class

        if not player:
            raise AttributeError('No media plugin configured')

        media_dirs = media_dirs or player_config.get('media_dirs', [])

        if self.__class__.__name__ == 'MediaPlugin':
            # Populate this plugin with the actions of the configured player
            plugin = get_plugin(player)
            for act in plugin.registered_actions:
                setattr(self, act, getattr(plugin, act))
                self.registered_actions.add(act)

        self._env = env or {}
        self.media_dirs = set(
            filter(
                lambda _: os.path.isdir(_),
                map(
                    lambda _: os.path.abspath(os.path.expanduser(_)),
                    media_dirs
                )
            )
        )

        self.download_dir = os.path.abspath(os.path.expanduser(
            download_dir or player_config.get('download_dir') or
            os.path.join((os.path.expanduser('~') or self._env.get('HOME') or '/'), 'Downloads')))

        if not os.path.isdir(self.download_dir):
            os.makedirs(self.download_dir, exist_ok=True)

        self.media_dirs.add(self.download_dir)
        self._videos_queue = []
        self._youtube_proc = None
Exemple #6
0
def index():
    """ Route to the main web panel """
    configured_plugins = Config.get_plugins()
    enabled_templates = {}
    enabled_scripts = {}
    enabled_styles = {}

    enabled_plugins = set(request.args.get('enabled_plugins', '').split(','))
    for plugin in enabled_plugins:
        if plugin not in configured_plugins:
            configured_plugins[plugin] = {}

    configured_plugins['execute'] = {}
    disabled_plugins = set(request.args.get('disabled_plugins', '').split(','))

    js_folder = os.path.abspath(
        os.path.join(template_folder, '..', 'static', 'js'))
    style_folder = os.path.abspath(
        os.path.join(template_folder, '..', 'static', 'css', 'dist'))

    for plugin, conf in configured_plugins.copy().items():
        if plugin in disabled_plugins:
            if plugin == 'execute':
                configured_plugins.pop('execute')
            continue

        template_file = os.path.join(template_folder, 'plugins', plugin,
                                     'index.html')

        script_file = os.path.join(js_folder, 'plugins', plugin, 'index.js')
        style_file = os.path.join(style_folder, 'webpanel', 'plugins',
                                  plugin + '.css')

        if os.path.isfile(template_file):
            conf['_template_file'] = '/' + '/'.join(
                template_file.split(os.sep)[-3:])
            enabled_templates[plugin] = conf

        if os.path.isfile(script_file):
            conf['_script_file'] = '/'.join(script_file.split(os.sep)[-4:])
            enabled_scripts[plugin] = conf

        if os.path.isfile(style_file):
            conf['_style_file'] = 'css/dist/' + style_file[len(style_folder) +
                                                           1:]
            enabled_styles[plugin] = conf

    http_conf = Config.get('backend.http')
    return render_template('index.html',
                           templates=enabled_templates,
                           scripts=enabled_scripts,
                           styles=enabled_styles,
                           utils=HttpUtils,
                           token=Config.get('token'),
                           websocket_port=get_websocket_port(),
                           template_folder=template_folder,
                           static_folder=static_folder,
                           plugins=Config.get_plugins(),
                           backends=Config.get_backends(),
                           procedures=json.dumps(Config.get_procedures(),
                                                 cls=Message.Encoder),
                           has_ssl=http_conf.get('ssl_cert') is not None)
Exemple #7
0
    def __init__(self,
                 media_dirs: Optional[List[str]] = None,
                 download_dir: Optional[str] = None,
                 env: Optional[Dict[str, str]] = None,
                 volume: Optional[Union[float, int]] = None,
                 torrent_plugin: str = 'torrent',
                 *args,
                 **kwargs):
        """
        :param media_dirs: Directories that will be scanned for media files when
            a search is performed (default: none)

        :param download_dir: Directory where external resources/torrents will be
            downloaded (default: ~/Downloads)

        :param env: Environment variables key-values to pass to the
            player executable (e.g. DISPLAY, XDG_VTNR, PULSE_SINK etc.)

        :param volume: Default volume for the player (default: None, maximum volume).

        :param torrent_plugin: Optional plugin to be used for torrent download. Possible values:

            - ``torrent`` - native ``libtorrent``-based plugin (default)
            - ``rtorrent`` - torrent support over rtorrent RPC/XML interface (recommended)
            - ``webtorrent`` - torrent support over webtorrent (unstable)

        """

        super().__init__(**kwargs)

        if media_dirs is None:
            media_dirs = []
        player = None
        player_config = {}

        if self.__class__.__name__ == 'MediaPlugin':
            # Abstract class, initialize with the default configured player
            for plugin in Config.get_plugins().keys():
                if plugin in self._supported_media_plugins:
                    player = plugin
                    if get_plugin(player).is_local():
                        # Local players have priority as default if configured
                        break
        else:
            player = self  # Derived concrete class

        if not player:
            raise AttributeError('No media plugin configured')

        media_dirs = media_dirs or player_config.get('media_dirs', [])

        if self.__class__.__name__ == 'MediaPlugin':
            # Populate this plugin with the actions of the configured player
            plugin = get_plugin(player)
            for act in plugin.registered_actions:
                setattr(self, act, getattr(plugin, act))
                self.registered_actions.add(act)

        self._env = env or {}
        self.media_dirs = set(
            filter(
                lambda _: os.path.isdir(_),
                map(lambda _: os.path.abspath(os.path.expanduser(_)),
                    media_dirs)))

        self.download_dir = os.path.abspath(
            os.path.expanduser(
                download_dir or player_config.get('download_dir')
                or os.path.join(
                    (os.path.expanduser('~') or self._env.get('HOME') or '/'),
                    'Downloads')))

        if not os.path.isdir(self.download_dir):
            os.makedirs(self.download_dir, exist_ok=True)

        self.media_dirs.add(self.download_dir)
        self.volume = volume
        self._videos_queue = []
        self._youtube_proc = None
        self.torrent_plugin = torrent_plugin