import json import socket from typing import Optional from edmond.bot import Bot from edmond.plugin import Plugin class ShrlokPlugin(Plugin): """Use an available shrlok server to allow sharing longer stuff. This plugin does not do anything on its own, but can be used from other plugins to share longer texts through a Web portal. """ def __init__(self, bot: Bot): super().__init__(bot) self.socket = "" self.file_root = "" self.url_root = "" def on_welcome(self, _): if all( conf in self.config for conf in ("socket_path", "file_root", "url_root") ): self.socket = self.config["socket_path"] self.file_root = self.config["file_root"] self.url_root = self.config["url_root"] self.bot.log_d(f"shrlok socket path '{self.socket}'") else: self.bot.log_d("No socket path specified, shrlok plugin disabled.") self.is_ready = False def post(self, header: dict, data: bytes) -> Optional[str]: encoded_header = json.dumps(header).encode() try: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.connect(self.socket) header_and_data = encoded_header + b"\0" + data length = len(header_and_data) packet = str(length).encode() + b"\0" + header_and_data sock.sendall(packet) response = sock.recv(4096) except OSError as exc: self.bot.log_e(f"Can't post data: {exc}") return None url = response.decode().replace(self.file_root, self.url_root, 1) return url or None # returning empty strings could cause confusion