Просмотр исходного кода

【新增】添加 PageOS 登录扩展

- 新增 PageOS 登录扩展,提供与 PageOS 系统进行登录认证的功能
- 实现了连接、认证、启动会话等核心功能
- 提供了详细的适配指南和示例代码
- 更新了相关文档,包括设计文档和使用说明
PJ568 1 год назад
Родитель
Сommit
9bb7272e36
7 измененных файлов с 416 добавлено и 4 удалено
  1. 1 1
      Cargo.lock
  2. 1 1
      Cargo.toml
  3. 3 0
      README.en.md
  4. 6 2
      README.md
  5. 122 0
      doc/Scrach 适配细则.txt
  6. 8 0
      doc/design.md
  7. 275 0
      src/pageos-greet-extension.js

+ 1 - 1
Cargo.lock

@@ -600,7 +600,7 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
 
 
 [[package]]
 [[package]]
 name = "pageos-greet"
 name = "pageos-greet"
-version = "1.1.1"
+version = "1.2.0"
 dependencies = [
 dependencies = [
  "axum",
  "axum",
  "clap",
  "clap",

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 [package]
 name = "pageos-greet"
 name = "pageos-greet"
-version = "1.1.1"
+version = "1.2.0"
 authors = ["PJ568 <[email protected]>"]
 authors = ["PJ568 <[email protected]>"]
 edition = "2024"
 edition = "2024"
 license = "MPL-2.0"
 license = "MPL-2.0"

+ 3 - 0
README.en.md

@@ -68,8 +68,11 @@ Yes! Bro! You just need to do these two things:
 
 
 2. **Interface Adaptation**: Ensure your page/project contains all display (output) and input controls, and adapts to the login logic/message format.
 2. **Interface Adaptation**: Ensure your page/project contains all display (output) and input controls, and adapts to the login logic/message format.
    Reference:
    Reference:
+
    - [Example web page](doc/login.html)
    - [Example web page](doc/login.html)
    - [Adapter details](doc/design-adapter.md)
    - [Adapter details](doc/design-adapter.md)
+   - [Turbowarp 扩展](src/pageos-greet-extension.js)
+   - [Scrach 适配细则](doc/Scrach%20适配细则.txt)
 
 
 ```
 ```
 
 

+ 6 - 2
README.md

@@ -64,8 +64,12 @@ _不是哥们,那我要怎么适配我的页面或 Scratch 以使用 pageos-gr
    }
    }
    ```
    ```
 2. 接口适配:保证您的页面或项目中包含所有的显示(输出)和输入控件并适配了登录逻辑和消息格式;
 2. 接口适配:保证您的页面或项目中包含所有的显示(输出)和输入控件并适配了登录逻辑和消息格式;
-
-   可参考[示例网页](doc/login.html)和[适配详解](doc/design-adapter.md)
+   可参考:
+   
+   - [示例网页](doc/login.html)
+   - [适配详解](doc/design-adapter.md)
+   - [Turbowarp 扩展](src/pageos-greet-extension.js)
+   - [Scrach 适配细则](doc/Scrach%20适配细则.txt)
 
 
 ## 项目信息
 ## 项目信息
 
 

+ 122 - 0
doc/Scrach 适配细则.txt

@@ -0,0 +1,122 @@
+// 首先确保已加载 PageOS 登录扩展
+// 然后在角色中创建以下变量:
+// - 服务器地址 (默认值: "ws://127.0.0.1:12801/ws")
+// - 用户名
+// - 密码
+// - 环境变量 (默认值: "LANG=zh_CN.UTF-8")
+// - 启动命令 (默认值: "pageos-core")
+// - 状态信息
+// - 日志内容
+
+// 主控制脚本
+当 ⚑ 被点击
+  清空日志
+  将 [服务器地址] 设为 [ws://127.0.0.1:12801/ws]
+  将 [状态信息] 设为 [准备连接...]
+  更新界面 // 自定义积木
+  连接 [服务器地址] // 使用扩展积木
+
+// 连接建立时的处理
+当建立连接 // 扩展的帽子积木
+  将 [状态信息] 设为 [已连接,请输入用户名]
+  更新界面
+  显示用户名输入界面 // 自定义积木
+
+// 收到消息时的处理
+当收到信息 // 扩展的帽子积木
+  如果 <(获取提示信息类型) = [auth_prompt]> 那么
+    如果 <(获取提示信息) 包含 [密码]> 那么
+      将 [状态信息] 设为 [请输入密码]
+      显示密码输入界面 // 自定义积木
+    否则
+      将 [状态信息] 设为 [获取提示信息]
+      显示通用输入界面 // 自定义积木
+    结束
+  否则
+    如果 <(获取提示信息类型) = [auth_success]> 那么
+      将 [状态信息] 设为 [认证成功!]
+      更新界面
+      等待 (1) 秒
+      发送启动会话响应 环境变量 [环境变量] 启动命令 [启动命令] // 使用扩展积木
+    否则
+      如果 <(获取提示信息类型) = [auth_error]> 那么
+        将 [状态信息] 设为 [连接 [认证失败: ] (获取提示信息)]
+        更新界面
+        等待 (2) 秒
+        重置登录界面 // 自定义积木
+      结束
+    结束
+  结束
+
+// 连接错误处理
+当发生连接错误 // 扩展的帽子积木
+  将 [状态信息] 设为 [连接错误,正在重试...]
+  更新界面
+  等待 (3) 秒
+  连接 [服务器地址] // 重试连接
+
+// 连接关闭处理
+当连接关闭 // 扩展的帽子积木
+  将 [状态信息] 设为 [连接已关闭]
+  更新界面
+  等待 (2) 秒
+  重置登录界面
+
+// 自定义积木: 更新界面
+定义 更新界面
+  清空 // 清除舞台上的所有图形元素
+  绘制界面框架 // 绘制登录框背景
+  绘制状态指示器 // 根据连接状态显示不同颜色
+  显示日志 // 显示最近的日志条目
+
+// 自定义积木: 显示用户名输入界面
+定义 显示用户名输入界面
+  绘制文本 [用户名:] 在位置 x: (-100) y: (20)
+  创建用户名输入框在 x: (0) y: (20) // 实际项目中需使用自制积木实现输入框
+  创建按钮 [提交] 在 x: (80) y: (20) // 点击时调用"处理用户名提交"
+
+// 自定义积木: 显示密码输入界面
+定义 显示密码输入界面
+  绘制文本 [密码:] 在位置 x: (-100) y: (20)
+  创建密码输入框在 x: (0) y: (20) // 显示为星号
+  创建按钮 [提交] 在 x: (80) y: (20) // 点击时调用"处理密码提交"
+
+// 自定义积木: 处理用户名提交
+定义 处理用户名提交
+  将 [用户名] 设为 [用户名输入框的值]
+  发送验证请求 [用户名] // 使用扩展积木
+  将 [状态信息] 设为 [正在验证用户名...]
+  更新界面
+
+// 自定义积木: 处理密码提交
+定义 处理密码提交
+  将 [密码] 设为 [密码输入框的值]
+  发送认证响应 [密码] // 使用扩展积木
+  将 [状态信息] 设为 [正在验证密码...]
+  更新界面
+
+// 自定义积木: 重置登录界面
+定义 重置登录界面
+  将 [用户名] 设为 []
+  将 [密码] 设为 []
+  将 [状态信息] 设为 [准备重新连接...]
+  更新界面
+  连接 [服务器地址] // 重新连接
+
+// 自定义积木: 显示日志
+定义 显示日志
+  将 [日志内容] 设为 (获取日志信息) // 使用扩展积木
+  绘制文本 [日志:] 在位置 x: (-180) y: (-80)
+  绘制多行文本 [日志内容] 在位置 x: (-180) y: (-100) 宽度 (360) 高度 (80) // 带滚动条
+
+// 自定义积木: 绘制状态指示器
+定义 绘制状态指示器
+  如果 <(已连接?)> 那么
+    绘制圆形 x: (180) y: (140) 半径 (15) 颜色 [#00FF00] // 绿色表示已连接
+  否则
+    如果 <(正在加载中?)> 那么
+      绘制圆形 x: (180) y: (140) 半径 (15) 颜色 [#FFFF00] // 黄色表示加载中
+    否则
+      绘制圆形 x: (180) y: (140) 半径 (15) 颜色 [#FF0000] // 红色表示断开
+    结束
+  结束

+ 8 - 0
doc/design.md

@@ -45,6 +45,14 @@ enum WsMessage {
 }
 }
 ```
 ```
 
 
+### 协议映射表
+
+| WebSocket 消息类型 | IPC 请求类型            | 字段映射             |
+| ------------------ | ----------------------- | -------------------- |
+| AUTH_REQUEST       | CreateSession           | username ←→ username |
+| AUTH_RESPONSE      | PostAuthMessageResponse | response ←→ response |
+| START_SESSION      | StartSession            | cmd/env ←→ cmd/env   |
+
 ### 消息转换层
 ### 消息转换层
 
 
 ```rust
 ```rust

+ 275 - 0
src/pageos-greet-extension.js

@@ -0,0 +1,275 @@
+// 本扩展需要非沙盒环境运行:websocket
+// This extension requires disabling sandboxing: websocket
+class PageOSLoginExtension {
+  constructor() {
+    this.ws = null;
+    this.connected = false;
+    this.isLoading = false;
+    this.currentPrompt = "";
+    this.promptType = "info";
+    this.logs = [];
+    this.state = "disconnected";
+  }
+
+  getInfo() {
+    return {
+      id: "pageoslogin",
+      name: "PageOS 登录",
+      color1: "#3498db",
+      color2: "#2980b9",
+      blocks: [
+        {
+          opcode: "connect",
+          blockType: Scratch.BlockType.COMMAND,
+          text: "连接 [URL]",
+          arguments: {
+            URL: {
+              type: Scratch.ArgumentType.STRING,
+              defaultValue: "ws://127.0.0.1:12801/ws",
+            },
+          },
+        },
+        {
+          opcode: "onConnect",
+          blockType: Scratch.BlockType.HAT,
+          text: "当建立连接",
+          isEdgeActivated: false,
+        },
+        {
+          opcode: "isConnected",
+          blockType: Scratch.BlockType.BOOLEAN,
+          text: "已连接?",
+        },
+        {
+          opcode: "onMessage",
+          blockType: Scratch.BlockType.HAT,
+          text: "当收到信息",
+          isEdgeActivated: false,
+        },
+        {
+          opcode: "onError",
+          blockType: Scratch.BlockType.HAT,
+          text: "当发生连接错误",
+          isEdgeActivated: false,
+        },
+        {
+          opcode: "onClose",
+          blockType: Scratch.BlockType.HAT,
+          text: "当连接关闭",
+          isEdgeActivated: false,
+        },
+        {
+          opcode: "sendAuthRequest",
+          blockType: Scratch.BlockType.COMMAND,
+          text: "发送验证请求 用户名 [USERNAME]",
+          arguments: {
+            USERNAME: {
+              type: Scratch.ArgumentType.STRING,
+              defaultValue: "user",
+            },
+          },
+        },
+        {
+          opcode: "sendAuthResponse",
+          blockType: Scratch.BlockType.COMMAND,
+          text: "发送认证响应 信息 [RESPONSE]",
+          arguments: {
+            RESPONSE: {
+              type: Scratch.ArgumentType.STRING,
+              defaultValue: "",
+            },
+          },
+        },
+        {
+          opcode: "sendStartSession",
+          blockType: Scratch.BlockType.COMMAND,
+          text: "发送启动会话响应 环境变量 [ENV] 启动命令 [CMD]",
+          arguments: {
+            ENV: {
+              type: Scratch.ArgumentType.STRING,
+              defaultValue: "LANG=zh_CN.UTF-8",
+            },
+            CMD: {
+              type: Scratch.ArgumentType.STRING,
+              defaultValue: "%SESSION_COMMAND%",
+            },
+          },
+        },
+        {
+          opcode: "getSessionState",
+          blockType: Scratch.BlockType.REPORTER,
+          text: "获取会话状态",
+        },
+        {
+          opcode: "isLoading",
+          blockType: Scratch.BlockType.BOOLEAN,
+          text: "正在加载中?",
+        },
+        {
+          opcode: "getPrompt",
+          blockType: Scratch.BlockType.REPORTER,
+          text: "获取提示信息",
+        },
+        {
+          opcode: "getPromptType",
+          blockType: Scratch.BlockType.REPORTER,
+          text: "获取提示信息类型",
+        },
+        {
+          opcode: "getLogs",
+          blockType: Scratch.BlockType.REPORTER,
+          text: "获取日志信息",
+        },
+        {
+          opcode: "clearLogs",
+          blockType: Scratch.BlockType.COMMAND,
+          text: "清空日志",
+        },
+      ],
+    };
+  }
+
+  connect(args) {
+    const url = args.URL;
+    if (this.ws) {
+      this.ws.close();
+    }
+
+    this.isLoading = true;
+    this.logMessage(`正在连接到: ${url}`, "info");
+    this.state = "connecting";
+
+    this.ws = new WebSocket(url);
+
+    this.ws.onopen = () => {
+      this.connected = true;
+      this.isLoading = false;
+      this.state = "connected";
+      this.logMessage("连接已建立", "info");
+      Scratch.vm.runtime.startHats("pageoslogin_onConnect");
+    };
+
+    this.ws.onmessage = (event) => {
+      try {
+        const msg = JSON.parse(event.data);
+        this.logMessage(`收到消息: ${JSON.stringify(msg)}`, "info");
+
+        if (msg.type === "AUTH_MESSAGE") {
+          this.currentPrompt = msg.message;
+          this.promptType = msg.message_type.toLowerCase();
+        }
+
+        Scratch.vm.runtime.startHats("pageoslogin_onMessage");
+      } catch (e) {
+        this.logMessage(`消息解析错误: ${e}`, "error");
+      }
+    };
+
+    this.ws.onerror = (error) => {
+      this.isLoading = false;
+      this.logMessage(`连接错误: ${error}`, "error");
+      this.state = "error";
+      Scratch.vm.runtime.startHats("pageoslogin_onError");
+    };
+
+    this.ws.onclose = () => {
+      this.connected = false;
+      this.isLoading = false;
+      this.state = "disconnected";
+      this.logMessage("连接已关闭", "warn");
+      Scratch.vm.runtime.startHats("pageoslogin_onClose");
+    };
+  }
+
+  sendAuthRequest(args) {
+    if (!this.connected) return;
+
+    const username = args.USERNAME;
+    this.isLoading = true;
+    this.logMessage(`发送验证请求: ${username}`, "info");
+    this.state = "authenticating";
+
+    this.ws.send(
+      JSON.stringify({
+        type: "AUTH_REQUEST",
+        username: username,
+      })
+    );
+  }
+
+  sendAuthResponse(args) {
+    if (!this.connected) return;
+
+    const response = args.RESPONSE;
+    this.isLoading = true;
+    this.logMessage(`发送认证响应`, "info");
+
+    this.ws.send(
+      JSON.stringify({
+        type: "AUTH_RESPONSE",
+        response: response,
+      })
+    );
+  }
+
+  sendStartSession(args) {
+    if (!this.connected) return;
+
+    const env = args.ENV;
+    const cmd = args.CMD;
+    this.isLoading = true;
+    this.logMessage(`发送启动会话请求`, "info");
+    this.state = "starting_session";
+
+    // 将环境变量和命令字符串转换为数组
+    const envArray = env.split(",").map((item) => item.trim());
+    const cmdArray = cmd
+      .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
+      .map((arg) => arg.replace(/^["']|["']$/g, ""));
+
+    this.ws.send(
+      JSON.stringify({
+        type: "START_SESSION",
+        env: envArray,
+        cmd: cmdArray,
+      })
+    );
+  }
+
+  isConnected() {
+    return this.connected;
+  }
+
+  isLoading() {
+    return this.isLoading;
+  }
+
+  getSessionState() {
+    return this.state;
+  }
+
+  getPrompt() {
+    return this.currentPrompt;
+  }
+
+  getPromptType() {
+    return this.promptType;
+  }
+
+  getLogs() {
+    return this.logs.map((log) => `${log.time}: ${log.message}`).join("\n");
+  }
+
+  clearLogs() {
+    this.logs = [];
+  }
+
+  logMessage(message, type = "info") {
+    const time = new Date().toLocaleTimeString();
+    this.logs.push({ time, message, type });
+    // 限制日志长度
+    if (this.logs.length > 100) this.logs.shift();
+  }
+}
+
+Scratch.extensions.register(new PageOSLoginExtension());