예제 #1
0
 def __init__(self, engine, app, sio):
     """Set up connection instance attributes."""
     self.engine = engine
     self.app = app
     self.sio = sio
     self.store = dotdict()
     self.reset_store()
예제 #2
0
 async def get_plugin_as_root(self, name, workspace):
     """Get a plugin api as root user."""
     self.current_user.set(self.root_user)
     workspace = self.get_workspace(workspace)
     if not workspace:
         raise Exception(f"Workspace {workspace} does not exist.")
     self.current_workspace.set(workspace)
     return dotdict(await self.get_plugin(name))
예제 #3
0
    def register_codec(self, config):
        """Register a codec."""
        assert "name" in config
        assert "encoder" in config or "decoder" in config
        if "type" in config:
            for codec_type, codec in list(self._codecs.items()):
                if codec.type == config["type"] or codec_type == config["name"]:
                    logger.info("Removing duplicated codec: %s", codec_type)
                    del self._codecs[codec_type]

        self._codecs[config["name"]] = dotdict(config)
예제 #4
0
    async def init(self):
        """initialize the plugin."""
        opt = dotdict(id=self.pid, secret=self.secret)
        self.conn = PluginConnection(self, opt)
        self.conn.setup()
        self.terminated = False
        initialized = self.loop.create_future()
        self.on_plugin_message("initialized", initialized)
        self.on_plugin_message("disconnected", self.terminate)
        await initialized

        workers = [
            self.message_worker(self.janus_queue.async_q, self.conn.abort)
            for i in range(2)
        ]
        asyncio.ensure_future(asyncio.gather(*workers))
예제 #5
0
    def __init__(
        self,
        core_interface: CoreInterface,
        port: int,
        in_docker: bool = False,
        apps_dir: str = "./apps",
    ):
        """Initialize the class."""
        self._status: StatusEnum = StatusEnum.not_initialized
        self.browser = None
        self.plugin_parser = None
        self.browser_pages = {}
        self.apps_dir = Path(apps_dir)
        os.makedirs(self.apps_dir, exist_ok=True)
        self.controller_id = str(ServerAppController.instance_counter)
        ServerAppController.instance_counter += 1
        self.port = int(port)
        self.in_docker = in_docker
        self.server_url = f"http://127.0.0.1:{self.port}"
        event_bus = self.event_bus = core_interface.event_bus
        self.core_interface = core_interface
        core_interface.register_interface("get_app_controller",
                                          self.get_public_api)
        core_interface.register_interface("getAppController",
                                          self.get_public_api)
        self.core_api = dotdict(core_interface.get_interface())
        self.jinja_env = Environment(loader=PackageLoader("imjoy"),
                                     autoescape=select_autoescape())
        self.templates_dir = Path(__file__).parent / "templates"
        self.builtin_apps_dir = Path(__file__).parent / "apps"
        router = APIRouter()
        self._initialize_future: Optional[asyncio.Future] = None

        @router.get("/apps/{path:path}")
        def get_app_file(path: str) -> Response:
            path = safe_join(str(self.apps_dir), path)
            if os.path.exists(path):
                return FileResponse(path)

            return JSONResponse(
                status_code=404,
                content={
                    "success": False,
                    "detail": f"File not found: {path}"
                },
            )

        # The following code is a hacky solution to call self.initialize
        # We need to find a better way to call it
        # If we try to run initialize() in the startup event callback,
        # It give connection error.
        @router.get("/initialize-apps")
        async def initialize_apps() -> JSONResponse:
            await self.initialize()
            return JSONResponse({"status": "OK"})

        def do_initialization() -> None:
            while True:
                try:
                    time.sleep(0.2)
                    response = requests.get(self.server_url +
                                            "/initialize-apps")
                    if response.ok:
                        logger.info("Server apps intialized.")
                        break
                except requests.exceptions.ConnectionError:
                    pass

        threading.Thread(target=do_initialization, daemon=True).start()

        core_interface.register_router(router)

        def close() -> None:
            asyncio.get_running_loop().create_task(self.close())

        event_bus.on("shutdown", close)
예제 #6
0
 def get_workspace_as_root(self, name="root"):
     """Get a workspace api as root user."""
     self.current_user.set(self.root_user)
     return dotdict(self.get_workspace_interface(name))
예제 #7
0
    def __init__(self, app, imjoy_api=None, app_controller=None):
        """Set up instance."""
        self.event_bus = EventBus()
        self.current_user = ContextVar("current_user")
        self.current_plugin = ContextVar("current_plugin")
        self.current_workspace = ContextVar("current_workspace")
        self._all_users: Dict[str, UserInfo] = {}  # uid:user_info
        self._all_workspaces: Dict[str,
                                   WorkspaceInfo] = {}  # wid:workspace_info
        self._app = app
        self.app_controller = app_controller
        self.disconnect_delay = 1
        imjoy_api = imjoy_api or {}
        self._codecs = {}
        self._disconnected_plugins = []
        self._imjoy_api = dotdict({
            "_rintf": True,
            "log": self.info,
            "info": self.info,
            "error": self.error,
            "warning": self.warning,
            "critical": self.critical,
            "registerService": self.register_service,
            "register_service": self.register_service,
            "listServices": self.list_services,
            "list_services": self.list_services,
            "getService": self.get_service,
            "get_service": self.get_service,
            "utils": {},
            "listPlugins": self.list_plugins,
            "list_plugins": self.list_plugins,
            "getPlugin": self.get_plugin,
            "get_plugin": self.get_plugin,
            "generateToken": self.generate_token,
            "generate_token": self.generate_token,
            "create_workspace": self.create_workspace,
            "createWorkspace": self.create_workspace,
            "get_workspace": self.get_workspace_interface,
            "getWorkspace": self.get_workspace_interface,
            "list_workspaces": self.list_workspaces,
            "listWorkspaces": self.list_workspaces,
            "disconnect": self.disconnect,
        })
        self._imjoy_api.update(imjoy_api)

        # Add public workspace
        self.register_workspace(
            WorkspaceInfo.parse_obj({
                "name": "public",
                "persistent": True,
                "owners": ["root"],
                "allow_list": [],
                "deny_list": [],
                "visibility": "public",
            }))

        # Create root user
        self.root_user = UserInfo(
            id="root",
            is_anonymous=False,
            email=None,
            parent=None,
            roles=[],
            scopes=[],
            expires_at=None,
        )
        # Create root workspace
        self.root_workspace = WorkspaceInfo(
            name="root",
            owners=["root"],
            visibility=VisibilityEnum.protected,
            persistent=True,
        )
        self.root_workspace.set_global_event_bus(self.event_bus)
        self.register_workspace(self.root_workspace)
        self.load_extensions()