傳送: a file or a few words from any device of the account to any other
Outside the chats and without a bot: computer → phone, phone → computer, computer → computer. - The brain is the post office (src/drops.rs). The sender hands the file over in 2 MB pieces; the brain keeps it in drops/ and pushes it piece by piece to the destination computer (device/run tool `drop_put`), going on from where a broken link stopped and waiting up to 7 days for a computer that is off. What is for the phone waits at the brain to be downloaded. - Files land in Downloads/AnyBot with a notification; words go on the clipboard. A computer takes parcels only from its own brain. - Window: an ↑ button at the bottom of the sidebar opens 傳送到其他裝置 (pick a device, drop files or paste text, the last 7 days below). - Phone: 傳送到其他裝置 in the account menu (send, download, copy). - Bots: a `send_to_device` tool, gated like send_file. - Owner only; the account server is unchanged. Without an account, this computer and a phone connected to it directly can exchange. - Docs: FEATURES §36, protocol, architecture, multi-device (zh and en). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
This commit is contained in:
parent
b4ba710eb4
commit
c6c9a1674a
41
FEATURES.md
41
FEATURES.md
|
|
@ -1630,6 +1630,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
||||||
- 帶給模型的記憶(你的訊息才有)
|
- 帶給模型的記憶(你的訊息才有)
|
||||||
- 截圖不存。
|
- 截圖不存。
|
||||||
- **記憶和索引**(同一個資料夾裡,詳見 [docs/memory.md](docs/memory.md)):
|
- **記憶和索引**(同一個資料夾裡,詳見 [docs/memory.md](docs/memory.md)):
|
||||||
|
- `drops/`:「傳送到其他裝置」的東西。大腦上是還沒送達或等手機下載的檔案(`<編號>.bin`)和清單 `index.json`,保留 7 天;每台電腦上是收到一半的檔案(`in-<編號>.part`)和收過什麼 `received.json`(最近 100 筆)。收好的檔案在「下載/AnyBot」,不在這裡。
|
||||||
- `memory.db`:每個 Bot 的記憶(記得的事、做過的事、整理過的、最近刪除)和它們的向量。每晚在 `backups/memory-日期.db` 備份一份,保留 7 天。
|
- `memory.db`:每個 Bot 的記憶(記得的事、做過的事、整理過的、最近刪除)和它們的向量。每晚在 `backups/memory-日期.db` 備份一份,保留 7 天。
|
||||||
- `docs.db`:文件索引,壞了可以重建。
|
- `docs.db`:文件索引,壞了可以重建。
|
||||||
- `oplog/audit.db`:稽核紀錄,留 30 天。
|
- `oplog/audit.db`:稽核紀錄,留 30 天。
|
||||||
|
|
@ -1781,7 +1782,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
||||||
- 台南兩天一夜行程的對話(先用 Grok,再換 Claude)。
|
- 台南兩天一夜行程的對話(先用 Grok,再換 Claude)。
|
||||||
- 研究助理的「AI 新聞早報」例行任務(每個工作日 09:00)。
|
- 研究助理的「AI 新聞早報」例行任務(每個工作日 09:00)。
|
||||||
- 電腦助手正在等你允許整理照片的指令「mkdir -p 2026-04 2026-05 2026-06 && mv IMG_04*.jpg 2026-04/」,並排入一則補充「2026-06 的照片先不要動」。
|
- 電腦助手正在等你允許整理照片的指令「mkdir -p 2026-04 2026-05 2026-06 && mv IMG_04*.jpg 2026-04/」,並排入一則補充「2026-06 的照片先不要動」。
|
||||||
- 可以指定要拍的畫面:聊天、設定(AI 供應商)、Bot 設定、選單、收合的側邊欄、例行任務、設定(電腦)、設定(自動審核)、記憶頁(`memory`)、輸入框的記憶小卡片(`composer`,草稿可以用 `ANYBOT_SHOT_DRAFT` 換)。也可以把彈出視窗藏起來,單獨檢查每個畫面。
|
- 可以指定要拍的畫面:聊天、設定(AI 供應商)、Bot 設定、選單、收合的側邊欄、例行任務、設定(電腦)、設定(自動審核)、記憶頁(`memory`)、輸入框的記憶小卡片(`composer`,草稿可以用 `ANYBOT_SHOT_DRAFT` 換)、傳送到其他裝置(`drops`)。也可以把彈出視窗藏起來,單獨檢查每個畫面。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -1833,7 +1834,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
||||||
- 「這台 Mac」要先在設定裡打開才會出現。
|
- 「這台 Mac」要先在設定裡打開才會出現。
|
||||||
- 操作方式:點一下是左鍵;長按是右鍵;點兩下是雙擊;「右鍵:開」之後每次點都是右鍵。
|
- 操作方式:點一下是左鍵;長按是右鍵;點兩下是雙擊;「右鍵:開」之後每次點都是右鍵。
|
||||||
- 「⌨︎ 打字」可以打中文,會打進目前的視窗;還有 Enter、Esc、Tab、⌫ 和捲動按鈕。
|
- 「⌨︎ 打字」可以打中文,會打進目前的視窗;還有 Enter、Esc、Tab、⌫ 和捲動按鈕。
|
||||||
- 右上角頭像:開啟通知(只有用帳號登入時才有;iPhone 要先加入主畫面)、切換到別台 AnyBot、登出這支手機。
|
- 右上角頭像:傳送到其他裝置(只有擁有者有,見下面「傳送到其他裝置」)、開啟通知(只有用帳號登入時才有;iPhone 要先加入主畫面)、切換到別台 AnyBot、登出這支手機。
|
||||||
- 手機做的事都交給電腦版原本的功能處理(同一套規則、同一份資料),不是另外寫一套。
|
- 手機做的事都交給電腦版原本的功能處理(同一套規則、同一份資料),不是另外寫一套。
|
||||||
- 團隊(用帳號伺服器分享時)權限跟以前一樣:
|
- 團隊(用帳號伺服器分享時)權限跟以前一樣:
|
||||||
- 成員只能聊天和附檔;
|
- 成員只能聊天和附檔;
|
||||||
|
|
@ -1897,6 +1898,40 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
||||||
- 詢問會出現在發出動作的那台 AnyBot,也就是手機或那台電腦的視窗。原版是在被操作的那台裝置上詢問。
|
- 詢問會出現在發出動作的那台 AnyBot,也就是手機或那台電腦的視窗。原版是在被操作的那台裝置上詢問。
|
||||||
- 經過帳號伺服器,最多等 35 秒(原版的裝置工具等 30 秒)。
|
- 經過帳號伺服器,最多等 35 秒(原版的裝置工具等 30 秒)。
|
||||||
|
|
||||||
|
### 傳送到其他裝置(檔案和文字,任意兩台之間)
|
||||||
|
|
||||||
|
不經過聊天、也不經過 Bot,把檔案或一段文字從帳號裡任何一台裝置傳到任何另一台:電腦 → 手機、手機 → 電腦、電腦 → 電腦。
|
||||||
|
|
||||||
|
- **從電腦傳**:側邊欄底部名字右邊的「↑」按鈕(滑過顯示「傳送檔案或文字到其他裝置」)打開「傳送到其他裝置」(`shots/drops.png`)。
|
||||||
|
- 最上面一排是帳號裡的其他裝置:大腦那台、每一台螢幕和手腳電腦、「手機」。離線的寫「· 離線」,一樣可以選。預設選上次用的那台,沒有就選第一台在線上的。
|
||||||
|
- 把檔案拖到視窗上(這個視窗開著時,拖進來的檔案是要傳送的,不會變成聊天附件),或按「選擇檔案…」。一次可以很多個,各自有進度條。
|
||||||
|
- 下面一行可以貼一段文字或網址,按「傳送」或 Enter。
|
||||||
|
- 「最近 7 天」列出帳號裡所有傳送:檔名、大小、「誰 → 誰」和狀態。到了這台的檔案有「顯示」(在 Finder 裡選中它),文字有「複製」,沒送達的有「再試一次」,每一列都能「移除」。
|
||||||
|
- **從手機傳**:左上頭像選單 ›「傳送到其他裝置」。選裝置,「選擇檔案或照片」(可多選),或貼文字按「傳送文字」。下面同樣是最近 7 天的清單。
|
||||||
|
- **收到時**
|
||||||
|
- 電腦:檔案放進「下載/AnyBot」資料夾(同名的會變成「檔名 (2)」),跳系統通知「某某 傳來的」,並響提示音(設定裡開著時)。文字會直接放進剪貼簿,通知寫「已複製到剪貼簿」。沒有視窗的電腦(手腳、伺服器)只存檔,不動剪貼簿。
|
||||||
|
- 手機:收到推播通知(開了通知的話)。打開「傳送到其他裝置」,檔案按「下載」,文字按「複製」。
|
||||||
|
- 目的地沒開機也可以傳:大腦先收著,那台一上線就送過去(每 15–20 秒試一次),最多保留 7 天。
|
||||||
|
- **狀態**:正在交給大腦 N% → 等「某台」開機上線,會自動送達 → 傳送中 N% → 已送達(給手機的:在手機的「傳送」裡可以拿 → 手機已下載);沒送達時紅字寫原因。
|
||||||
|
- **怎麼走的**(`src/drops.rs`)
|
||||||
|
- 大腦是中繼站。傳的那台把檔案切成 2 MB 一段交給大腦(一段沒到就從大腦說的位置重傳),大腦存在資料資料夾的 `drops/`,再一段一段推給目的地;連線中斷時從對方已經收到的位置接著傳,不用重來。送達後大腦那份就刪掉。
|
||||||
|
- 給手機的留在大腦上等手機來拿(4 MB 一段),保留 7 天,期間可以重複下載。
|
||||||
|
- 單一檔案最大 2 GB(估計值);文字最多 10 萬字。資料夾要先壓縮成一個檔案。
|
||||||
|
- 檔名只留最後一段、去掉開頭的點,所以不會寫到「下載/AnyBot」以外,也不會變成隱藏檔。收到的檔案不會被打開或執行。
|
||||||
|
- **誰可以用**
|
||||||
|
- 只有帳號擁有者(手機)和擁有者自己的電腦。團隊的管理員和成員不行。
|
||||||
|
- 電腦只收「自己的大腦」推來的東西;不用開「裝置連結」也收得到(它只是把檔案放進下載資料夾,不是操作這台電腦)。
|
||||||
|
- 對方的 AnyBot 還是舊版時,狀態會寫「某台的 AnyBot 要先更新才收得到」,更新後自動送達。
|
||||||
|
- **沒登入帳號時**:只有這台電腦和直接連到它的手機(同一個網路、手機密碼登入)可以互傳。
|
||||||
|
- **Bot 也可以傳**:工具 `send_to_device`(步驟顯示「傳到你的另一台裝置」)。你說「把這個檔傳到我的手機」「放到 Mac mini」時,Bot 從它正在用的電腦(或你指定的那台,別台電腦上的檔案最多 20 MB)拿檔案,交給大腦傳過去。檔案離開電腦的規則和 `send_file` 一樣:工作資料夾外的檔案先問你,機密檔案不傳。只是要把結果交給你時,Bot 仍然用 `send_file` 傳進聊天。
|
||||||
|
- **驗證過的**(2026-11-11,這台 Mac 上開一個測試用的帳號伺服器、一個大腦、一台手腳)
|
||||||
|
- 手機(用程式模擬)傳 7.5 MB 到手腳電腦:上傳 0.26 秒,全程 2 秒,內容逐位元組相同;傳文字、傳到大腦自己那台也都到了。
|
||||||
|
- 手腳電腦關掉時傳:狀態是「等它上線」;重新打開後 39 秒內送達(之後把重試間隔從 30 秒改成 15 秒)。
|
||||||
|
- 電腦走螢幕的路徑傳 23 MB 到大腦:0.7 秒交完,內容相同;電腦傳給手機,手機分段下載後內容相同。
|
||||||
|
- 手機網頁在 Chrome(手機尺寸)裡實際操作:傳文字、傳 5 MB 檔案、下載 5.3 MB 的檔案都成功。
|
||||||
|
- 沒有在真的手機、真的跨網路連線、或很慢的網路上試過;中途斷線續傳只有單元測試(模擬第三段沒到)。
|
||||||
|
- 測試:`drops::tests::a_file_goes_from_one_computer_to_another_through_a_bad_link`、`the_phone_downloads_and_the_brain_keeps_its_own`、`a_computer_takes_only_what_is_sound`、`remote::tests::sending_between_devices_is_the_owners_and_the_brains`、`drops_ui::tests::a_row_says_where_the_parcel_is`;對著真的帳號伺服器跑:`live_send_from_a_screen`(預設不跑)。
|
||||||
|
|
||||||
### 團隊(分享給其他帳號)
|
### 團隊(分享給其他帳號)
|
||||||
|
|
||||||
- 在「設定 › 手機與帳號 › 分享給團隊」輸入對方在帳號伺服器上的帳號,選擇成員或管理員,按「分享」。
|
- 在「設定 › 手機與帳號 › 分享給團隊」輸入對方在帳號伺服器上的帳號,選擇成員或管理員,按「分享」。
|
||||||
|
|
@ -2134,7 +2169,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
||||||
- 群組標題按右鍵可以重新命名、刪除群組(裡面的 Bot 移到未分區);雙擊標題也能改名。
|
- 群組標題按右鍵可以重新命名、刪除群組(裡面的 Bot 移到未分區);雙擊標題也能改名。
|
||||||
- 空的群組會留著,顯示「把 Bot 拖進來」;沒分群組的 Bot 在「未分區」。
|
- 空的群組會留著,顯示「把 Bot 拖進來」;沒分群組的 Bot 在「未分區」。
|
||||||
- 每列 54 px、圓角 12、40 px 頭像、名字 15 px、最後一句 13 px;未讀是藍點,等你允許是強調色的點。
|
- 每列 54 px、圓角 12、40 px 頭像、名字 15 px、最後一句 13 px;未讀是藍點,等你允許是強調色的點。
|
||||||
- 最下面是你(縮寫頭像和名字,點了打開設定),右邊是連接器市集(打開 設定 › 整合,直接捲到市集)。這一列固定在側欄底部,不會被切到。
|
- 最下面是你(縮寫頭像和名字,點了打開設定),右邊是「傳送到其他裝置」(↑,第 36 節)和連接器市集(打開 設定 › 整合,直接捲到市集)。這一列固定在側欄底部,不會被切到。
|
||||||
- + 選單:新增 Bot、新增群組、群組聊天、從範本建立。
|
- + 選單:新增 Bot、新增群組、群組聊天、從範本建立。
|
||||||
- 驗證過的:用模擬點擊確認帳號列、市集鈕、+ 選單、群組右鍵都有反應(`shots/sidebar-clicks.png`),也模擬了拖拉。
|
- 驗證過的:用模擬點擊確認帳號列、市集鈕、+ 選單、群組右鍵都有反應(`shots/sidebar-clicks.png`),也模擬了拖拉。
|
||||||
- **輸入框**:
|
- **輸入框**:
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ AnyBot 是一個 Rust 程式(`anybot`),用 egui/eframe 畫介面。同一
|
||||||
| `model.rs` | 資料:State、Bot、Message、設定;讀寫 `state.json` |
|
| `model.rs` | 資料:State、Bot、Message、設定;讀寫 `state.json` |
|
||||||
| `agent.rs` | 一個回合:組系統指示、送模型、收串流、跑工具、核准關卡、長對話摘要;每一步用哪個模型(`StepPlan`:Bot 的模型規劃、出問題時和收尾,快速模型照計畫執行) |
|
| `agent.rs` | 一個回合:組系統指示、送模型、收串流、跑工具、核准關卡、長對話摘要;每一步用哪個模型(`StepPlan`:Bot 的模型規劃、出問題時和收尾,快速模型照計畫執行) |
|
||||||
| `memory.rs`、`memstore.rs`、`app/memory_ui.rs` | 記憶:三種(記得的事、做過的事、整理過的),存在 memory.db。搜尋用 jieba 斷詞(加中文連續兩字)和本機語意向量,各給 0–1 分;釘選的放系統指示,其他的只在相關時附在那則訊息後面(打字時看得到、可以勾選);每晚把舊的做過的事壓成每週、每月一行。記憶頁、輸入框的記憶小卡片、remember 去重、search_memory。完整設計見 [memory.md](memory.md) |
|
| `memory.rs`、`memstore.rs`、`app/memory_ui.rs` | 記憶:三種(記得的事、做過的事、整理過的),存在 memory.db。搜尋用 jieba 斷詞(加中文連續兩字)和本機語意向量,各給 0–1 分;釘選的放系統指示,其他的只在相關時附在那則訊息後面(打字時看得到、可以勾選);每晚把舊的做過的事壓成每週、每月一行。記憶頁、輸入框的記憶小卡片、remember 去重、search_memory。完整設計見 [memory.md](memory.md) |
|
||||||
|
| `drops.rs`、`app/drops_ui.rs` | 傳送到其他裝置:檔案或文字從帳號裡任何一台到任何另一台。大腦當中繼站(`drops/`),2 MB 一段收進來、一段一段推給目的地的電腦(`/api/device/run` 的 `drop_put`,斷了從對方有的位置接著傳,離線就等它上線,7 天),給手機的留在大腦等它下載 |
|
||||||
| `embed.rs`、`m2v.rs` | 語意搜尋的向量:預設本機模型(minishlab/potion-multilingual-128M,下載時就轉成 int8,約 130 MB;要用時才載入,閒置 10 分鐘放掉),也可選 Ollama 或關閉。大腦載入;螢幕設了文件索引資料夾才載入;手腳不載 |
|
| `embed.rs`、`m2v.rs` | 語意搜尋的向量:預設本機模型(minishlab/potion-multilingual-128M,下載時就轉成 int8,約 130 MB;要用時才載入,閒置 10 分鐘放掉),也可選 Ollama 或關閉。大腦載入;螢幕設了文件索引資料夾才載入;手腳不載 |
|
||||||
| `facts.rs` | 電腦現況:每台電腦一段唯讀小腳本讀出系統、桌面、systemd、sudo、網路、套件管理、常用指令和 App,30 分鐘快取,回合開始時放進系統指示 |
|
| `facts.rs` | 電腦現況:每台電腦一段唯讀小腳本讀出系統、桌面、systemd、sudo、網路、套件管理、常用指令和 App,30 分鐘快取,回合開始時放進系統指示 |
|
||||||
| `providers.rs` | 各家模型的 API(OpenAI 相容、Anthropic、OpenCode Go…)、串流、重試、看不到圖時的看圖小幫手 |
|
| `providers.rs` | 各家模型的 API(OpenAI 相容、Anthropic、OpenCode Go…)、串流、重試、看不到圖時的看圖小幫手 |
|
||||||
|
|
@ -68,6 +69,7 @@ AnyBot 是一個 Rust 程式(`anybot`),用 egui/eframe 畫介面。同一
|
||||||
| `browser/` | AnyBot 瀏覽器的設定檔(登入狀態) |
|
| `browser/` | AnyBot 瀏覽器的設定檔(登入狀態) |
|
||||||
| `brain-copy.json` | 螢幕電腦保留的大腦副本(離線時還能看) |
|
| `brain-copy.json` | 螢幕電腦保留的大腦副本(離線時還能看) |
|
||||||
| `brain-files/` | 螢幕電腦從大腦下載的附件 |
|
| `brain-files/` | 螢幕電腦從大腦下載的附件 |
|
||||||
|
| `drops/` | 傳送到其他裝置:大腦上是在路上的檔案和清單(7 天);每台電腦上是收到一半的檔案和收過什麼。收好的檔案在「下載/AnyBot」 |
|
||||||
| `image-notes.json` | 看圖小幫手對每張圖的描述(不用重看) |
|
| `image-notes.json` | 看圖小幫手對每張圖的描述(不用重看) |
|
||||||
| `memory.db` | 每個 Bot 的記憶(記得的事、做過的事、整理過的、最近刪除 30 天)和它們的向量。最重要的一個:每晚在 `backups/memory-日期.db` 留一份,保留 7 天 |
|
| `memory.db` | 每個 Bot 的記憶(記得的事、做過的事、整理過的、最近刪除 30 天)和它們的向量。最重要的一個:每晚在 `backups/memory-日期.db` 留一份,保留 7 天 |
|
||||||
| `docs.db` | 文件索引(文件資料夾的段落和向量)。是快取,刪掉會重建 |
|
| `docs.db` | 文件索引(文件資料夾的段落和向量)。是快取,刪掉會重建 |
|
||||||
|
|
@ -127,6 +129,20 @@ AnyBot 是一個 Rust 程式(`anybot`),用 egui/eframe 畫介面。同一
|
||||||
|
|
||||||
大腦的 Bot 呼叫工具時可以指定 `computer`。如果是帳號裡的另一台,就透過長連線送 `/api/device/run` 給它,由它在自己身上執行(螢幕、檔案、指令、它的 AnyBot 瀏覽器),再把文字和截圖傳回來。那台要開「裝置連結」才接受;若設了只給某個大腦用(`hands_for`),帳號伺服器會附上是哪一台在問,不是那台就拒絕。指令在那台的工作資料夾(Bot 的 `workdir`)跑;連線經過帳號伺服器只有 35 秒,所以手腳上的指令超過 25 秒就移到背景,用同一台的 `read_terminal` 追蹤(computer 填那台)。
|
大腦的 Bot 呼叫工具時可以指定 `computer`。如果是帳號裡的另一台,就透過長連線送 `/api/device/run` 給它,由它在自己身上執行(螢幕、檔案、指令、它的 AnyBot 瀏覽器),再把文字和截圖傳回來。那台要開「裝置連結」才接受;若設了只給某個大腦用(`hands_for`),帳號伺服器會附上是哪一台在問,不是那台就拒絕。指令在那台的工作資料夾(Bot 的 `workdir`)跑;連線經過帳號伺服器只有 35 秒,所以手腳上的指令超過 25 秒就移到背景,用同一台的 `read_terminal` 追蹤(computer 填那台)。
|
||||||
|
|
||||||
|
### 傳送到其他裝置
|
||||||
|
|
||||||
|
檔案和文字不經過聊天,在裝置之間直接傳(`drops.rs`)。大腦是中繼站,所以不用改帳號伺服器,也不用兩台同時在線:
|
||||||
|
|
||||||
|
```
|
||||||
|
手機 ──/h/<大腦>/api/drop/…──┐ ┌─ /api/device/run(drop_put,一段一段推)→ 電腦:下載/AnyBot
|
||||||
|
├→ 大腦:drops/<編號>.bin ┤
|
||||||
|
螢幕 ──/api/sync/drop/…──────┘ └─ 留在大腦 → 手機 GET /api/drop/file 分段下載
|
||||||
|
```
|
||||||
|
|
||||||
|
- 每一段 2 MB,所以帳號伺服器一次請求 35 秒、30 MB 的上限都碰不到;兩個方向都是「對方說它有多少,就從那裡接著傳」。
|
||||||
|
- 電腦只收自己的大腦(`brain_id`,或手腳的 `hands_for`)推來的;檔名只留最後一段,落在「下載/AnyBot」。
|
||||||
|
- 大腦的背景工作每 20 秒(有新東西時馬上)看一次清單;目的地離線就留著,15 秒後再試,最多 7 天。
|
||||||
|
|
||||||
### 配對碼
|
### 配對碼
|
||||||
|
|
||||||
已登入的手機或 AnyBot 向帳號伺服器要一組 6 位數字(10 分鐘、一次)。新電腦用這組數字換到自己的身分(主機 id 和金鑰),不經過密碼。配對碼記得它是給哪個大腦的,新電腦就只讓那個大腦使用。
|
已登入的手機或 AnyBot 向帳號伺服器要一組 6 位數字(10 分鐘、一次)。新電腦用這組數字換到自己的身分(主機 id 和金鑰),不經過密碼。配對碼記得它是給哪個大腦的,新電腦就只讓那個大腦使用。
|
||||||
|
|
|
||||||
|
|
@ -24,11 +24,11 @@ Models Tools (tools.rs, cloudbox.rs, botbrowser.rs, computer.rs,
|
||||||
routines.rs, triggers.rs, channels.rs)
|
routines.rs, triggers.rs, channels.rs)
|
||||||
```
|
```
|
||||||
|
|
||||||
Key modules: `agent.rs` (one turn: system prompt, streaming, tool loop, approval gates, per-step model routing `StepPlan`), `providers.rs` (OpenAI-compatible/Anthropic/OpenCode… + streaming + retries + a vision helper for models that can't see images), `policy.rs` (allow/ask/deny per action), `computer.rs` (one `computer` tool: screenshot, click/type, plus semantic actions `menu_click`/`fill_form`/`wait_for`; macOS reads the real accessibility tree, screenshots are annotated with numbered marks), `cloudbox.rs`+`box/` (the bot's own Docker computer with desktop + browser), `vnc.rs` (view/take over the bot's computer through the relay), `httpd.rs` (tiny shared HTTP server), `mobile/index.html` (phone UI, single embedded file), `memstore.rs`+`memory.rs`+`app/memory_ui.rs` (memory: facts, a line per finished task, weekly/monthly rollups; jieba words + CJK bigrams and local vectors, each scored 0–1; pinned ones in the system prompt, the rest attached to the message they fit, visible and pickable while typing; folded nightly), `embed.rs`+`m2v.rs` (vectors: a local Model2Vec model, minishlab/potion-multilingual-128M, quantised to int8 while it downloads, ~130 MB, loaded on demand and dropped after 10 idle minutes; or Ollama; or off). The full memory design is in `docs/memory.md` (Traditional Chinese).
|
Key modules: `agent.rs` (one turn: system prompt, streaming, tool loop, approval gates, per-step model routing `StepPlan`), `providers.rs` (OpenAI-compatible/Anthropic/OpenCode… + streaming + retries + a vision helper for models that can't see images), `policy.rs` (allow/ask/deny per action), `computer.rs` (one `computer` tool: screenshot, click/type, plus semantic actions `menu_click`/`fill_form`/`wait_for`; macOS reads the real accessibility tree, screenshots are annotated with numbered marks), `cloudbox.rs`+`box/` (the bot's own Docker computer with desktop + browser), `vnc.rs` (view/take over the bot's computer through the relay), `httpd.rs` (tiny shared HTTP server), `mobile/index.html` (phone UI, single embedded file), `memstore.rs`+`memory.rs`+`app/memory_ui.rs` (memory: facts, a line per finished task, weekly/monthly rollups; jieba words + CJK bigrams and local vectors, each scored 0–1; pinned ones in the system prompt, the rest attached to the message they fit, visible and pickable while typing; folded nightly), `embed.rs`+`m2v.rs` (vectors: a local Model2Vec model, minishlab/potion-multilingual-128M, quantised to int8 while it downloads, ~130 MB, loaded on demand and dropped after 10 idle minutes; or Ollama; or off). The full memory design is in `docs/memory.md` (Traditional Chinese). `drops.rs`+`app/drops_ui.rs` (send a file or text from any device of the account to any other, outside the chats: the brain is the post office — it takes the parcel in 2 MB pieces into `drops/`, pushes it piece by piece to the destination computer, resuming where a broken link stopped and waiting up to 7 days for a computer that is off, or keeps it for the phone to download; files land in Downloads/AnyBot, text on the clipboard).
|
||||||
|
|
||||||
## Storage
|
## Storage
|
||||||
|
|
||||||
All in the data dir (macOS `~/Library/Application Support/AnyBot/`, Linux `~/.local/share/AnyBot/`, `%APPDATA%\AnyBot\`; `ANYBOT_DATA_DIR` overrides): `state.json` (bots, chats, settings, keys — written via temp file + rename, never half-written), `attachments/`, `browser/` (bot browser profile), `oplog/bot-<id>.jsonl` (append-only work log: every step written to disk *before* it runs; used to repair chats and offer a "continue" card after a crash), `image-notes.json`, `anybot.lock` (OS file lock: one AnyBot per data dir), `memory.db` (every bot's memories and their vectors; copied nightly to `backups/memory-<date>.db`, 7 kept), `docs.db` (the document index: a cache, rebuilt if lost), `oplog/audit.db` (the audit trail, 30 days; older versions kept memories and documents here and move them out on first start), `models/potion-multilingual-128M/` (the local embedding model; `ANYBOT_HF_BASE` picks a Hugging Face mirror).
|
All in the data dir (macOS `~/Library/Application Support/AnyBot/`, Linux `~/.local/share/AnyBot/`, `%APPDATA%\AnyBot\`; `ANYBOT_DATA_DIR` overrides): `state.json` (bots, chats, settings, keys — written via temp file + rename, never half-written), `attachments/`, `browser/` (bot browser profile), `oplog/bot-<id>.jsonl` (append-only work log: every step written to disk *before* it runs; used to repair chats and offer a "continue" card after a crash), `image-notes.json`, `anybot.lock` (OS file lock: one AnyBot per data dir), `memory.db` (every bot's memories and their vectors; copied nightly to `backups/memory-<date>.db`, 7 kept), `docs.db` (the document index: a cache, rebuilt if lost), `oplog/audit.db` (the audit trail, 30 days; older versions kept memories and documents here and move them out on first start), `drops/` (parcels on their way between devices: on the brain the files and their list, kept 7 days; on every computer half-received files and what arrived), `models/potion-multilingual-128M/` (the local embedding model; `ANYBOT_HF_BASE` picks a Hugging Face mirror).
|
||||||
|
|
||||||
## Security design
|
## Security design
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,8 @@ Proxying: `/h/<host>/api/...` (phone → that AnyBot, role owner/admin/member);
|
||||||
|
|
||||||
Reachable only through the relay (or on the LAN with the phone password). Highlights: `GET /api/state?since=` (bots, activity, pending approvals; long-poll ≤20 s), `GET /api/bots/<id>`, `POST /api/bots/<id>/<action>` (`send`, `stop`, `answer`, `read`, `new`, `upload`…; `send` may carry `"memories": [...]`, the memories ticked above the composer — empty means none, absent means the brain chooses), `POST /api/memory` (owner only) and `POST /api/sync/memory` (mirror) for the memory page and composer suggestions (`{op, bot, …}`; reads `suggest`/`search`/`list`/`stats`/`overview`, writes `add`/`pin`/`edit`/`forget`/`restore`/`merge`/`tidy`/`empty_trash`; see `docs/memory.md`), `GET/POST /api/screen/mac` (drive this Mac from the phone, if enabled), `/screen` + `/api/vnc` (view the bot's computer, noVNC), and the brain-sync family: `GET /api/sync?since=`, `POST /api/sync/edit` (`{ops, client, seq}`), `/api/sync/act`, `/api/sync/upload/<bot>`, `GET /api/sync/file`, `POST /api/sync/models`, `POST/GET /api/sync/screen` (thumbnails; `{kind:"hold"|"wake"}`).
|
Reachable only through the relay (or on the LAN with the phone password). Highlights: `GET /api/state?since=` (bots, activity, pending approvals; long-poll ≤20 s), `GET /api/bots/<id>`, `POST /api/bots/<id>/<action>` (`send`, `stop`, `answer`, `read`, `new`, `upload`…; `send` may carry `"memories": [...]`, the memories ticked above the composer — empty means none, absent means the brain chooses), `POST /api/memory` (owner only) and `POST /api/sync/memory` (mirror) for the memory page and composer suggestions (`{op, bot, …}`; reads `suggest`/`search`/`list`/`stats`/`overview`, writes `add`/`pin`/`edit`/`forget`/`restore`/`merge`/`tidy`/`empty_trash`; see `docs/memory.md`), `GET/POST /api/screen/mac` (drive this Mac from the phone, if enabled), `/screen` + `/api/vnc` (view the bot's computer, noVNC), and the brain-sync family: `GET /api/sync?since=`, `POST /api/sync/edit` (`{ops, client, seq}`), `/api/sync/act`, `/api/sync/upload/<bot>`, `GET /api/sync/file`, `POST /api/sync/models`, `POST/GET /api/sync/screen` (thumbnails; `{kind:"hold"|"wake"}`).
|
||||||
|
|
||||||
|
Sending between devices (`src/drops.rs`; owner's phone at `/api/drop/<what>`, the owner's screens at `/api/sync/drop/<what>`): `GET targets` → `{targets: [{id, name, online, kind}], you}`; `GET list` → `{items}` (last 7 days); `POST new` `{name, bytes, to}` or `{text, to}` → `{id, chunk}`; `POST chunk?id=&at=` (raw bytes, 2 MB a piece) → `{have}` (a piece that isn't the next one is not written; the sender continues from `have`); `POST done` `{id}`; `GET file?id=&at=&len=` (phone only: a piece of a file waiting for the phone); `POST remove` / `retry` `{id}`. The brain pushes a parcel to a computer through `/api/device/run` with `tool: "drop_put"` and `args` `{id, name, bytes, from}` plus `{probe: true}` (how much do you have?), `{at, data}` (one base64 piece) or `{text}`; the answer is `{ok, have, done, text}`. A computer accepts `drop_put` only from its own brain, with or without 裝置連結.
|
||||||
|
|
||||||
## Wire format (`src/wire.rs`)
|
## Wire format (`src/wire.rs`)
|
||||||
|
|
||||||
WebSocket binary frames, each message: `[4-byte big-endian header length][header JSON][raw body]` — bodies are not base64'd; `z: true` means the body is deflate-compressed, `z_ok: true` says the asker understands compressed replies.
|
WebSocket binary frames, each message: `[4-byte big-endian header length][header JSON][raw body]` — bodies are not base64'd; `z: true` means the body is deflate-compressed, `z_ok: true` says the asker understands compressed replies.
|
||||||
|
|
|
||||||
|
|
@ -94,7 +94,16 @@ ANYBOT_ACCOUNT_PASSWORD=… anybot setup --server https://… --user 帳號 [--b
|
||||||
|
|
||||||
打開帳號伺服器的網址,登入。可以「加入主畫面」當 App 用、開通知。帳號裡有螢幕電腦時,手機會直接打開它們用的大腦。
|
打開帳號伺服器的網址,登入。可以「加入主畫面」當 App 用、開通知。帳號裡有螢幕電腦時,手機會直接打開它們用的大腦。
|
||||||
|
|
||||||
## 三、連不上時
|
## 三、在裝置之間傳檔案和文字
|
||||||
|
|
||||||
|
接好之後,帳號裡任何兩台都能互傳,不用經過聊天:
|
||||||
|
|
||||||
|
- 電腦:側邊欄底部名字右邊的「↑」›「傳送到其他裝置」,選裝置,把檔案拖進去(或貼一段文字)。
|
||||||
|
- 手機:左上頭像 ›「傳送到其他裝置」。
|
||||||
|
|
||||||
|
檔案會出現在對方的「下載/AnyBot」資料夾並跳通知;文字會直接在對方的剪貼簿裡;傳給手機的,在手機同一個畫面按「下載」。對方沒開機也可以先傳,大腦會留 7 天,它一上線就送到。每一台都要更新到有這個功能的版本(`make update`;伺服器 `make update-server`)。細節見 [FEATURES.md](../FEATURES.md) 第 36 節。
|
||||||
|
|
||||||
|
## 四、連不上時
|
||||||
|
|
||||||
畫面上方會說是哪一段連不到:
|
畫面上方會說是哪一段連不到:
|
||||||
|
|
||||||
|
|
@ -118,7 +127,7 @@ anybot-relay --data <資料夾> --reset-password <帳號>
|
||||||
|
|
||||||
舊的加密備份是用舊密碼鎖的,改完之後在電腦上按一次「立刻備份」。
|
舊的加密備份是用舊密碼鎖的,改完之後在電腦上按一次「立刻備份」。
|
||||||
|
|
||||||
## 四、安全
|
## 五、安全
|
||||||
|
|
||||||
- 模型金鑰、訊息管道的 Token、連接器的密碼只在大腦上。螢幕電腦看到的是「已設定,在大腦上」,在螢幕上改設定也不會洗掉真的金鑰。
|
- 模型金鑰、訊息管道的 Token、連接器的密碼只在大腦上。螢幕電腦看到的是「已設定,在大腦上」,在螢幕上改設定也不會洗掉真的金鑰。
|
||||||
- 手腳只接受帳號裡的 AnyBot,用配對碼加入的只接受那一個大腦。
|
- 手腳只接受帳號裡的 AnyBot,用配對碼加入的只接受那一個大腦。
|
||||||
|
|
|
||||||
|
|
@ -77,17 +77,19 @@
|
||||||
| GET | `/api/state?since=` | 手機 | Bot 清單、誰在工作、等核准的事(有變化才回,最多等 20 秒) |
|
| GET | `/api/state?since=` | 手機 | Bot 清單、誰在工作、等核准的事(有變化才回,最多等 20 秒) |
|
||||||
| GET | `/api/bots/<id>?since=` | 手機 | 一個 Bot 的訊息 |
|
| GET | `/api/bots/<id>?since=` | 手機 | 一個 Bot 的訊息 |
|
||||||
| POST | `/api/bots/<id>/<動作>` | 手機 | `send`、`stop`、`answer`、`read`、`new`、`upload`…。`send` 可以帶 `"memories": [...]`:輸入框勾的記憶(空陣列=這次不帶;沒有這欄=大腦自己挑) |
|
| POST | `/api/bots/<id>/<動作>` | 手機 | `send`、`stop`、`answer`、`read`、`new`、`upload`…。`send` 可以帶 `"memories": [...]`:輸入框勾的記憶(空陣列=這次不帶;沒有這欄=大腦自己挑) |
|
||||||
|
| GET/POST | `/api/drop/<動作>` | 手機(只限擁有者) | 傳送到其他裝置(`src/drops.rs`)。`GET targets` → `{targets: [{id, name, online, kind}], you}`;`GET list` → `{items}`(最近 7 天);`POST new` `{name, bytes, to}` 或 `{text, to}` → `{id, chunk}`;`POST chunk?id=&at=`(原始位元組,一段 2 MB)→ `{have}`(`at` 不是下一段時不寫入,只回目前有多少);`POST done` `{id}`;`GET file?id=&at=&len=` → 給手機的檔案的一段;`POST remove`、`POST retry` `{id}` |
|
||||||
| POST | `/api/memory` | 手機(只限擁有者) | 記憶頁和輸入框的記憶:`{op, bot, …}`,讀取是 `suggest`、`search`、`list`、`stats`、`overview`,寫入是 `add`、`pin`、`edit`、`forget`、`restore`、`merge`、`tidy`、`empty_trash`(見 [memory.md](memory.md)) |
|
| POST | `/api/memory` | 手機(只限擁有者) | 記憶頁和輸入框的記憶:`{op, bot, …}`,讀取是 `suggest`、`search`、`list`、`stats`、`overview`,寫入是 `add`、`pin`、`edit`、`forget`、`restore`、`merge`、`tidy`、`empty_trash`(見 [memory.md](memory.md)) |
|
||||||
| GET/POST | `/api/screen/mac` | 手機 | 看這台 Mac 的畫面、點擊打字(開了「從手機操作」才可以) |
|
| GET/POST | `/api/screen/mac` | 手機 | 看這台 Mac 的畫面、點擊打字(開了「從手機操作」才可以) |
|
||||||
| GET | `/screen`、`/novnc.js` | 任何人 | 看 Bot 的電腦的網頁(noVNC);本身沒有資料 |
|
| GET | `/screen`、`/novnc.js` | 任何人 | 看 Bot 的電腦的網頁(noVNC);本身沒有資料 |
|
||||||
| WebSocket | `/api/vnc?t=` | 手機(同一個網路) | VNC,直接到這台的 Bot 的電腦(見 vnc.rs) |
|
| WebSocket | `/api/vnc?t=` | 手機(同一個網路) | VNC,直接到這台的 Bot 的電腦(見 vnc.rs) |
|
||||||
| GET | `/api/sync/screen` | mirror | Bot 的電腦的小縮圖(JPEG,寬 320) |
|
| GET | `/api/sync/screen` | mirror | Bot 的電腦的小縮圖(JPEG,寬 320) |
|
||||||
| POST | `/api/sync/screen` | mirror | `{kind: "hold", on}`(接管時 Bot 等你)、`{kind: "wake"}` |
|
| POST | `/api/sync/screen` | mirror | `{kind: "hold", on}`(接管時 Bot 等你)、`{kind: "wake"}` |
|
||||||
| POST | `/api/device/run` | device | `{tool, args, who}` → `{text, ok, image}`:在這台跑一個工具 |
|
| POST | `/api/device/run` | device | `{tool, args, who}` → `{text, ok, image}`:在這台跑一個工具。`tool: "drop_put"` 是大腦推來的傳送:`args` 是 `{id, name, bytes, from}` 加上 `{probe: true}`(問已經收了多少)、`{at, data}`(一段,base64)或 `{text}`,回 `{ok, have, done, text}`。只收自己的大腦推來的,不用開裝置連結 |
|
||||||
| GET | `/api/sync?since=&client=` | mirror | 大腦的變化(見 architecture.md) |
|
| GET | `/api/sync?since=&client=` | mirror | 大腦的變化(見 architecture.md) |
|
||||||
| POST | `/api/sync/edit` | mirror | `{ops, client, seq}` → `{ok, applied}` |
|
| POST | `/api/sync/edit` | mirror | `{ops, client, seq}` → `{ok, applied}` |
|
||||||
| POST | `/api/sync/act` | mirror | `{bot, action, …}`:send、stop、answer、read、new、regenerate、reply、restore。`send` 和手機一樣可以帶 `memories` |
|
| POST | `/api/sync/act` | mirror | `{bot, action, …}`:send、stop、answer、read、new、regenerate、reply、restore。`send` 和手機一樣可以帶 `memories` |
|
||||||
| POST | `/api/sync/memory` | mirror | 和 `/api/memory` 一樣,螢幕當作擁有者 |
|
| POST | `/api/sync/memory` | mirror | 和 `/api/memory` 一樣,螢幕當作擁有者 |
|
||||||
|
| GET/POST | `/api/sync/drop/<動作>` | mirror | 和 `/api/drop/<動作>` 一樣(沒有 `file`);寄件人是問的那台電腦 |
|
||||||
| POST | `/api/sync/upload/<bot>?name=` | mirror | 原始檔案內容 → `{path}` |
|
| POST | `/api/sync/upload/<bot>?name=` | mirror | 原始檔案內容 → `{path}` |
|
||||||
| GET | `/api/sync/file?path=` | mirror | 大腦上的附件(只限 `attachments/` 裡的檔案) |
|
| GET | `/api/sync/file?path=` | mirror | 大腦上的附件(只限 `attachments/` 裡的檔案) |
|
||||||
| POST | `/api/sync/models` | mirror | `{provider}` → `{models}`:用大腦的金鑰取得模型清單 |
|
| POST | `/api/sync/models` | mirror | `{provider}` → `{models}`:用大腦的金鑰取得模型清單 |
|
||||||
|
|
|
||||||
|
|
@ -326,6 +326,19 @@ textarea.field{min-height:96px;line-height:1.5}
|
||||||
.sheet .opt.danger,.sheet .opt.danger .ic{color:var(--danger)}
|
.sheet .opt.danger,.sheet .opt.danger .ic{color:var(--danger)}
|
||||||
.sheet .opt .ck{margin-left:auto;color:var(--accent)}
|
.sheet .opt .ck{margin-left:auto;color:var(--accent)}
|
||||||
.sheet .opt .x{margin-left:auto;font-size:13px;color:var(--text3)}
|
.sheet .opt .x{margin-left:auto;font-size:13px;color:var(--text3)}
|
||||||
|
.drop-to{display:flex;gap:6px;flex-wrap:wrap}
|
||||||
|
.drop-to button{height:32px;padding:0 12px;border-radius:16px;font-size:13.5px;box-shadow:inset 0 0 0 .5px var(--line);color:var(--text2)}
|
||||||
|
.drop-to button.on{background:var(--primary);color:var(--on-primary);box-shadow:none}
|
||||||
|
.drop-to button.off{color:var(--text3)}
|
||||||
|
.drop-row{display:flex;align-items:center;gap:10px;padding:9px 18px}
|
||||||
|
.drop-row .ic{flex:none;color:var(--text3)}
|
||||||
|
.drop-row .dw{flex:1;min-width:0}
|
||||||
|
.drop-row .dn{font-size:14.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||||
|
.drop-row .ds{font-size:12px;color:var(--text3);line-height:1.4}
|
||||||
|
.drop-row .ds.bad{color:var(--danger)}
|
||||||
|
.drop-row .btn{flex:none}
|
||||||
|
.drop-bar{height:4px;border-radius:2px;background:var(--line);overflow:hidden;margin-top:4px}
|
||||||
|
.drop-bar i{display:block;height:100%;background:var(--primary)}
|
||||||
.sheet .grp{font-size:12px;font-weight:600;color:var(--text3);padding:12px 20px 4px}
|
.sheet .grp{font-size:12px;font-weight:600;color:var(--text3);padding:12px 20px 4px}
|
||||||
.emojis{display:flex;gap:6px;padding:6px 16px 10px;flex-wrap:wrap}
|
.emojis{display:flex;gap:6px;padding:6px 16px 10px;flex-wrap:wrap}
|
||||||
.emojis button{font-size:24px;width:44px;height:44px;border-radius:12px;background:var(--hover)}
|
.emojis button{font-size:24px;width:44px;height:44px;border-radius:12px;background:var(--hover)}
|
||||||
|
|
@ -511,6 +524,7 @@ textarea.field{min-height:96px;line-height:1.5}
|
||||||
"use strict";
|
"use strict";
|
||||||
// Lucide icons (ISC licence), the set the desktop app uses.
|
// Lucide icons (ISC licence), the set the desktop app uses.
|
||||||
const LUCIDE = {
|
const LUCIDE = {
|
||||||
|
"send": '<path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"/><path d="m21.854 2.147-10.94 10.939"/>',
|
||||||
"image": '<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
|
"image": '<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
|
||||||
"file": '<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/>',
|
"file": '<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/>',
|
||||||
"file-text": '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',
|
"file-text": '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',
|
||||||
|
|
@ -975,6 +989,7 @@ $("b-me").onclick = () => {
|
||||||
items.push({icon: "moon", label: "這支手機的外觀", x: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], on: () => {
|
items.push({icon: "moon", label: "這支手機的外觀", x: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], on: () => {
|
||||||
sheet("這支手機的外觀", THEMES.map(([k, n]) => ({label: n, check: phoneTheme() === k, on: () => { try { localStorage.setItem("anybot.theme", k); } catch (_) {} applyTheme(); }})));
|
sheet("這支手機的外觀", THEMES.map(([k, n]) => ({label: n, check: phoneTheme() === k, on: () => { try { localStorage.setItem("anybot.theme", k); } catch (_) {} applyTheme(); }})));
|
||||||
}});
|
}});
|
||||||
|
if (isOwner()) items.push({icon: "send", label: "傳送到其他裝置", on: dropsSheet});
|
||||||
if (S.relay) items.push({icon: "bell", label: "通知", on: notifySheet});
|
if (S.relay) items.push({icon: "bell", label: "通知", on: notifySheet});
|
||||||
if (S.mac) items.push({icon: "monitor", label: "看這台 Mac 的螢幕", on: () => go("screen")});
|
if (S.mac) items.push({icon: "monitor", label: "看這台 Mac 的螢幕", on: () => go("screen")});
|
||||||
if (S.relay && owner()) items.push({icon: "plus", label: "加一台電腦(Linux、伺服器)", on: pair});
|
if (S.relay && owner()) items.push({icon: "plus", label: "加一台電腦(Linux、伺服器)", on: pair});
|
||||||
|
|
@ -2164,6 +2179,131 @@ $("b-type").onclick = () => { const t = $("typein").value; if (!t) return; $("ty
|
||||||
$("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } });
|
$("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } });
|
||||||
$("k-right").onclick = () => { S.right = !S.right; $("k-right").textContent = "右鍵:" + (S.right ? "開" : "關"); };
|
$("k-right").onclick = () => { S.right = !S.right; $("k-right").textContent = "右鍵:" + (S.right ? "開" : "關"); };
|
||||||
|
|
||||||
|
// ---------- 傳送: a file or a few words to another device of the account ----------
|
||||||
|
// The brain carries it (src/drops.rs): to a computer it lands in 下載/AnyBot (words: on its
|
||||||
|
// clipboard); what was sent to the phone waits at the brain and is downloaded here.
|
||||||
|
const DROP = {to: "", targets: [], items: [], jobs: [], timer: 0};
|
||||||
|
const dropApi = (what, opts) => api(base() + "api/drop/" + what, opts);
|
||||||
|
const dropSize = (n) => n < 1024 ? n + " B" : n < 1048576 ? Math.round(n / 1024) + " KB" : n < 1073741824 ? (n / 1048576).toFixed(1) + " MB" : (n / 1073741824).toFixed(2) + " GB";
|
||||||
|
function dropAgo(ms) { const d = Math.max(0, (Date.now() - ms) / 1000); return d < 60 ? "剛剛" : d < 3600 ? Math.floor(d / 60) + " 分鐘前" : d < 86400 ? Math.floor(d / 3600) + " 小時前" : Math.floor(d / 86400) + " 天前"; }
|
||||||
|
function dropState(p) {
|
||||||
|
const pct = Math.min(100, Math.floor((p.sent || 0) * 100 / Math.max(1, p.bytes)));
|
||||||
|
switch (p.state) {
|
||||||
|
case "uploading": return ["正在交給大腦 " + pct + "%"];
|
||||||
|
case "waiting": return [/更新/.test(p.note || "") ? p.note : `等「${p.to_name}」開機上線,會自動送達`];
|
||||||
|
case "sending": return ["傳送中 " + pct + "%"];
|
||||||
|
case "ready": return [p.text ? "給手機的文字" : "可以下載(保留 7 天)"];
|
||||||
|
case "done": return [(p.to === "phone" && !p.text ? "已下載 · " : "已送達 · ") + dropAgo(p.at)];
|
||||||
|
default: return ["沒有送達:" + (p.note || "不知道原因"), true];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function dropDraw() {
|
||||||
|
const box = document.getElementById("drops"); if (!box) return false;
|
||||||
|
box.querySelector("#drop-to").innerHTML = DROP.targets.length ? DROP.targets.map((t) => `<button data-id="${esc(t.id)}" class="${t.id === DROP.to ? "on" : t.online ? "" : "off"}">${esc(t.name)}${t.online ? "" : " · 離線"}</button>`).join("") : `<span class="ds" style="color:var(--text3);font-size:13px">正在找帳號裡的裝置…</span>`;
|
||||||
|
box.querySelectorAll("#drop-to button").forEach((b) => b.onclick = () => { DROP.to = b.dataset.id; try { localStorage.setItem("anybot.dropto", DROP.to); } catch (_) {} dropDraw(); });
|
||||||
|
box.querySelector("#drop-jobs").innerHTML = DROP.jobs.map((j) => `<div class="drop-row"><div class="dw"><div class="dn">${esc(j.name)}</div><div class="ds">${dropSize(j.sent)} / ${dropSize(j.total)}</div><div class="drop-bar"><i style="width:${j.total ? Math.floor(j.sent * 100 / j.total) : 0}%"></i></div></div></div>`).join("");
|
||||||
|
box.querySelector("#drop-list").innerHTML = (DROP.items.length ? `<div class="grp">最近 7 天</div>` : "") + DROP.items.slice(0, 40).map((p, i) => {
|
||||||
|
const [st, bad] = dropState(p), mine = p.to === "phone";
|
||||||
|
const btns = (p.text ? `<button class="btn sm" data-copy="${i}">複製</button>` : mine && (p.state === "ready" || p.state === "done") ? `<button class="btn sm ${p.state === "ready" ? "main" : ""}" data-get="${i}">下載</button>` : "") + (bad ? `<button class="btn sm" data-retry="${i}">再試</button>` : "") + `<button class="btn sm" data-rm="${i}">${ic("x", 14)}</button>`;
|
||||||
|
return `<div class="drop-row">${ic(p.text ? "copy" : "file", 20)}<div class="dw"><div class="dn">${esc(p.name)}</div><div class="ds ${bad ? "bad" : ""}">${p.text ? "" : dropSize(p.bytes) + " · "}${esc(p.from)} → ${esc(p.to_name)} · ${esc(st)}</div></div>${btns}</div>`;
|
||||||
|
}).join("");
|
||||||
|
const at = (b, k) => DROP.items[+b.dataset[k]];
|
||||||
|
box.querySelectorAll("[data-copy]").forEach((b) => b.onclick = () => copyText(at(b, "copy").text));
|
||||||
|
box.querySelectorAll("[data-get]").forEach((b) => b.onclick = () => dropDownload(at(b, "get"), b));
|
||||||
|
box.querySelectorAll("[data-retry]").forEach((b) => b.onclick = async () => { try { await dropApi("retry", {json: {id: at(b, "retry").id}}); } catch (e) { toast(e.message); } dropRefresh(); });
|
||||||
|
box.querySelectorAll("[data-rm]").forEach((b) => b.onclick = async () => { const p = at(b, "rm"); DROP.items = DROP.items.filter((x) => x !== p); dropDraw(); try { await dropApi("remove", {json: {id: p.id}}); } catch (e) { toast(e.message); } });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
async function dropRefresh() {
|
||||||
|
try {
|
||||||
|
const v = await dropApi("list");
|
||||||
|
DROP.items = v.items || [];
|
||||||
|
} catch (_) {}
|
||||||
|
clearTimeout(DROP.timer);
|
||||||
|
if (!dropDraw()) return;
|
||||||
|
const moving = DROP.jobs.length || DROP.items.some((p) => ["uploading", "sending", "waiting"].includes(p.state));
|
||||||
|
DROP.timer = setTimeout(dropRefresh, moving ? 1500 : 6000);
|
||||||
|
}
|
||||||
|
async function dropsSheet() {
|
||||||
|
sheet("傳送到其他裝置", [], `<div id="drops"><div class="form"><div class="drop-to" id="drop-to"></div><button class="btn main" id="drop-pick">${ic("arrow-up", 16)}選擇檔案或照片</button><textarea class="field" id="drop-text" style="min-height:56px" placeholder="或貼上一段文字、網址(電腦收到就在剪貼簿裡)"></textarea><button class="btn" id="drop-say">傳送文字</button></div><div id="drop-jobs"></div><div id="drop-list"></div><input type="file" id="drop-file" multiple hidden></div>`);
|
||||||
|
const box = document.getElementById("drops");
|
||||||
|
const need = () => { if (!DROP.to) { toast("先選要傳到哪一台"); return false; } return true; };
|
||||||
|
box.querySelector("#drop-pick").onclick = () => { if (need()) box.querySelector("#drop-file").click(); };
|
||||||
|
box.querySelector("#drop-file").onchange = (e) => { [...e.target.files].forEach(dropUpload); e.target.value = ""; };
|
||||||
|
box.querySelector("#drop-say").onclick = async () => {
|
||||||
|
const ta = box.querySelector("#drop-text"), text = ta.value.trim();
|
||||||
|
if (!text || !need()) return;
|
||||||
|
try { await dropApi("new", {json: {text, to: DROP.to}}); ta.value = ""; toast("已傳送"); } catch (e) { toast(e.message); }
|
||||||
|
dropRefresh();
|
||||||
|
};
|
||||||
|
dropDraw(); dropRefresh();
|
||||||
|
try {
|
||||||
|
const v = await dropApi("targets");
|
||||||
|
// (The phone itself isn't somewhere to send to from the phone.)
|
||||||
|
DROP.targets = (v.targets || []).filter((t) => t.id !== v.you);
|
||||||
|
let last = ""; try { last = localStorage.getItem("anybot.dropto") || ""; } catch (_) {}
|
||||||
|
if (!DROP.targets.some((t) => t.id === DROP.to)) DROP.to = (DROP.targets.find((t) => t.id === last) || DROP.targets.find((t) => t.online) || {id: ""}).id;
|
||||||
|
dropDraw();
|
||||||
|
} catch (e) { toast(e.message); }
|
||||||
|
}
|
||||||
|
// One file, handed to the brain in pieces (a piece that didn't get through is sent again from
|
||||||
|
// where the brain says it is).
|
||||||
|
async function dropUpload(f) {
|
||||||
|
const job = {name: f.name, total: f.size, sent: 0};
|
||||||
|
DROP.jobs.push(job); dropDraw();
|
||||||
|
let id = "";
|
||||||
|
try {
|
||||||
|
const v = await dropApi("new", {json: {name: f.name, bytes: f.size, to: DROP.to}});
|
||||||
|
id = v.id;
|
||||||
|
const step = v.chunk || 2097152;
|
||||||
|
let at = 0, stuck = 0;
|
||||||
|
while (at < f.size) {
|
||||||
|
let r = null;
|
||||||
|
try { r = await api(base() + `api/drop/chunk?id=${id}&at=${at}`, {method: "POST", body: f.slice(at, at + step), headers: {"Content-Type": "application/octet-stream"}, raw: true}); } catch (_) {}
|
||||||
|
if (r && r.ok) {
|
||||||
|
const have = (await r.json()).have;
|
||||||
|
stuck = have > at ? 0 : stuck + 1;
|
||||||
|
at = have;
|
||||||
|
} else if (r && r.status < 500) {
|
||||||
|
let m = ""; try { m = (await r.json()).error; } catch (_) {}
|
||||||
|
throw new Error(m || "大腦沒有收下");
|
||||||
|
} else { stuck++; await new Promise((ok) => setTimeout(ok, 2000)); }
|
||||||
|
if (stuck > 5) throw new Error("傳不過去:連線一直斷");
|
||||||
|
job.sent = at; dropDraw();
|
||||||
|
}
|
||||||
|
await dropApi("done", {json: {id}});
|
||||||
|
toast("「" + f.name + "」已交給大腦");
|
||||||
|
} catch (e) {
|
||||||
|
toast(e.message);
|
||||||
|
if (id) dropApi("remove", {json: {id}}).catch(() => {});
|
||||||
|
}
|
||||||
|
DROP.jobs.splice(DROP.jobs.indexOf(job), 1);
|
||||||
|
dropRefresh();
|
||||||
|
}
|
||||||
|
// What was sent to the phone: read from the brain in pieces, then saved (or shared, on a phone
|
||||||
|
// that can hand a file to another app).
|
||||||
|
async function dropDownload(p, btn) {
|
||||||
|
if (btn.disabled) return;
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const parts = [];
|
||||||
|
let at = 0;
|
||||||
|
while (at < p.bytes) {
|
||||||
|
const r = await api(base() + `api/drop/file?id=${p.id}&at=${at}&len=4194304`, {raw: true});
|
||||||
|
if (!r.ok) { let m = ""; try { m = (await r.json()).error; } catch (_) {} throw new Error(m || "下載不了"); }
|
||||||
|
const b = await r.arrayBuffer();
|
||||||
|
if (!b.byteLength) throw new Error("下載到一半斷了");
|
||||||
|
parts.push(b); at += b.byteLength;
|
||||||
|
btn.textContent = Math.floor(at * 100 / p.bytes) + "%";
|
||||||
|
}
|
||||||
|
const file = new File(parts, p.name, {type: "application/octet-stream"});
|
||||||
|
const u = URL.createObjectURL(file);
|
||||||
|
const a = document.createElement("a"); a.href = u; a.download = p.name; document.body.appendChild(a); a.click(); a.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(u), 120000);
|
||||||
|
} catch (e) { toast(e.message); }
|
||||||
|
dropRefresh();
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- 加一台電腦, notifications ----------
|
// ---------- 加一台電腦, notifications ----------
|
||||||
// A code for a new computer (ten minutes, once), as hands for this AnyBot.
|
// A code for a new computer (ten minutes, once), as hands for this AnyBot.
|
||||||
async function pair() {
|
async function pair() {
|
||||||
|
|
|
||||||
34
src/agent.rs
34
src/agent.rs
|
|
@ -1433,7 +1433,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
// read on the way: read_file's walls and read_file's questions, before either
|
// read on the way: read_file's walls and read_file's questions, before either
|
||||||
// tool below touches it. Both used to run with no check but the secrets list.
|
// tool below touches it. Both used to run with no check but the secrets list.
|
||||||
// (A web address isn't a file.)
|
// (A web address isn't a file.)
|
||||||
if call.name == "send_file" || call.name == "open_for_person" {
|
if call.name == "send_file" || call.name == "open_for_person" || call.name == "send_to_device" {
|
||||||
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
||||||
let web = call.name == "open_for_person" && (path.starts_with("http://") || path.starts_with("https://"));
|
let web = call.name == "open_for_person" && (path.starts_with("http://") || path.starts_with("https://"));
|
||||||
if let (false, Ok(t)) = (web, target_for(&job, &call.args)) {
|
if let (false, Ok(t)) = (web, target_for(&job, &call.args)) {
|
||||||
|
|
@ -1445,7 +1445,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
let decision = match tools::decide_file_out(&t, &path, &grants) {
|
let decision = match tools::decide_file_out(&t, &path, &grants) {
|
||||||
// Using this computer is switched off: its files are asked for one by one.
|
// Using this computer is switched off: its files are asked for one by one.
|
||||||
Decision::Allow if local && !direct && !(tools_on && local_on) => {
|
Decision::Allow if local && !direct && !(tools_on && local_on) => {
|
||||||
Decision::Ask { reason: format!("{}「{}」上的檔案:{what}", if call.name == "send_file" { "把檔案傳到聊天,來自" } else { "在你的螢幕上打開" }, t.name), grant: String::new() }
|
Decision::Ask { reason: format!("{}「{}」上的檔案:{what}", if call.name == "send_file" { "把檔案傳到聊天,來自" } else if call.name == "send_to_device" { "把檔案傳到你的另一台裝置,來自" } else { "在你的螢幕上打開" }, t.name), grant: String::new() }
|
||||||
}
|
}
|
||||||
// 直接操作 goes ahead where reading the file would.
|
// 直接操作 goes ahead where reading the file would.
|
||||||
Decision::Ask { .. } if direct => Decision::Allow,
|
Decision::Ask { .. } if direct => Decision::Allow,
|
||||||
|
|
@ -1474,7 +1474,8 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 傳檔案: put a file the bot made into the chat as a card the person can open.
|
// 傳檔案: put a file the bot made into the chat as a card the person can open.
|
||||||
if call.name == "send_file" {
|
// 傳送 (send_to_device): the same file, to another device of the person's account.
|
||||||
|
if call.name == "send_file" || call.name == "send_to_device" {
|
||||||
started();
|
started();
|
||||||
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
||||||
let local = match target_for(&job, &call.args) {
|
let local = match target_for(&job, &call.args) {
|
||||||
|
|
@ -1502,7 +1503,32 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
};
|
};
|
||||||
// Secrets (SSH keys, the app's own data folder, .env…) never ride into the chat,
|
// Secrets (SSH keys, the app's own data folder, .env…) never ride into the chat,
|
||||||
// same rule as read_file/edit_file.
|
// same rule as read_file/edit_file.
|
||||||
let local = local.and_then(|p| if tools::is_ignored(&p) || tools::is_ignored(std::path::Path::new(&path)) { Err("這個檔案是機密的,不能傳到聊天。".to_string()) } else { Ok(p) });
|
let local = local.and_then(|p| if tools::is_ignored(&p) || tools::is_ignored(std::path::Path::new(&path)) { Err("這個檔案是機密的,不能傳出去。".to_string()) } else { Ok(p) });
|
||||||
|
if call.name == "send_to_device" {
|
||||||
|
let to = tools::args_of(&call.args)["to"].as_str().unwrap_or("").to_string();
|
||||||
|
let sent = local.and_then(|p| {
|
||||||
|
let (id, name) = crate::drops::target_called(&to).ok_or_else(|| {
|
||||||
|
let names: Vec<String> = crate::drops::targets().iter().filter_map(|t| t["name"].as_str().map(String::from)).collect();
|
||||||
|
if names.is_empty() { "沒有登入帳號,找不到其他裝置。".to_string() } else { format!("帳號裡沒有叫「{to}」的裝置。可以傳到:{}。", names.join("、")) }
|
||||||
|
})?;
|
||||||
|
let bytes = std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0);
|
||||||
|
let from_id = format!("bot-{bot_id}");
|
||||||
|
crate::drops::office().add_file(&p, &id, &name, &job.via_name, &from_id)?;
|
||||||
|
crate::drops::kick();
|
||||||
|
let file = p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||||
|
Ok(if id == crate::drops::PHONE {
|
||||||
|
format!("已把「{file}」({})送到手機:使用者會收到通知,在手機 AnyBot 的「傳送到其他裝置」裡下載(保留 7 天)。", crate::attach::human(bytes))
|
||||||
|
} else {
|
||||||
|
format!("已把「{file}」({})交給大腦傳到「{name}」:它在線上的話馬上會出現在那台的 下載/AnyBot 資料夾並跳通知;沒開機的話,7 天內一開機就會收到。", crate::attach::human(bytes))
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let _ = std::fs::remove_dir_all(std::env::temp_dir().join(format!("anybot-fetch-{}", std::process::id())));
|
||||||
|
match sent {
|
||||||
|
Ok(out) => finish(&mut history, &out, ToolStatus::Done, None),
|
||||||
|
Err(e) => finish(&mut history, &e, ToolStatus::Failed, None),
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let stored = local.and_then(|p| crate::attach::store(bot_id, &p));
|
let stored = local.and_then(|p| crate::attach::store(bot_id, &p));
|
||||||
// (A file fetched from another computer was only parked here on its way.)
|
// (A file fetched from another computer was only parked here on its way.)
|
||||||
let _ = std::fs::remove_dir_all(std::env::temp_dir().join(format!("anybot-fetch-{}", std::process::id())));
|
let _ = std::fs::remove_dir_all(std::env::temp_dir().join(format!("anybot-fetch-{}", std::process::id())));
|
||||||
|
|
|
||||||
32
src/app.rs
32
src/app.rs
|
|
@ -37,6 +37,7 @@ mod welcome_ui;
|
||||||
mod mirror_ui;
|
mod mirror_ui;
|
||||||
mod pages_ui;
|
mod pages_ui;
|
||||||
mod voice_ui;
|
mod voice_ui;
|
||||||
|
mod drops_ui;
|
||||||
mod memory_ui;
|
mod memory_ui;
|
||||||
|
|
||||||
// Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (),
|
// Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (),
|
||||||
|
|
@ -212,6 +213,9 @@ pub struct App {
|
||||||
/// 記憶: the composer's suggestions per bot, and the memory page when open.
|
/// 記憶: the composer's suggestions per bot, and the memory page when open.
|
||||||
mem_suggest: HashMap<u64, memory_ui::Suggest>,
|
mem_suggest: HashMap<u64, memory_ui::Suggest>,
|
||||||
mem_page: Option<memory_ui::MemPage>,
|
mem_page: Option<memory_ui::MemPage>,
|
||||||
|
/// 傳送到其他裝置, when its dialog is open; and the device chosen last time.
|
||||||
|
drop_page: Option<drops_ui::DropPage>,
|
||||||
|
drop_last: String,
|
||||||
nightly_checked: Option<Instant>,
|
nightly_checked: Option<Instant>,
|
||||||
/// Files and pictures waiting to go with the next message.
|
/// Files and pictures waiting to go with the next message.
|
||||||
att: attach_ui::AttachUi,
|
att: attach_ui::AttachUi,
|
||||||
|
|
@ -355,6 +359,8 @@ impl App {
|
||||||
page_view: None,
|
page_view: None,
|
||||||
mem_suggest: HashMap::new(),
|
mem_suggest: HashMap::new(),
|
||||||
mem_page: None,
|
mem_page: None,
|
||||||
|
drop_page: None,
|
||||||
|
drop_last: String::new(),
|
||||||
nightly_checked: None,
|
nightly_checked: None,
|
||||||
att: Default::default(),
|
att: Default::default(),
|
||||||
ch: Default::default(),
|
ch: Default::default(),
|
||||||
|
|
@ -470,6 +476,24 @@ impl App {
|
||||||
app.settings_tab = SettingsTab::Voice;
|
app.settings_tab = SettingsTab::Voice;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 傳送到其他裝置: its dialog with a few devices and parcels.
|
||||||
|
Ok("drops") => {
|
||||||
|
app.approvals.clear();
|
||||||
|
let now = crate::model::now_ms();
|
||||||
|
let j = |v: serde_json::Value| v;
|
||||||
|
app.drop_page = Some(drops_ui::DropPage::shown(
|
||||||
|
vec![j(serde_json::json!({"id": "b", "name": "雲端大腦", "online": true, "kind": "brain"})), j(serde_json::json!({"id": "m", "name": "Mac mini", "online": true, "kind": "computer"})), j(serde_json::json!({"id": "l", "name": "客廳 Linux", "online": false, "kind": "computer"})), j(serde_json::json!({"id": "phone", "name": "手機", "online": true, "kind": "phone"}))],
|
||||||
|
vec![
|
||||||
|
j(serde_json::json!({"id": "1", "name": "第三季報表.xlsx", "bytes": 48_211_000, "from": "MacBook Pro", "to": "m", "to_name": "Mac mini", "state": "sending", "sent": 30_100_000, "at": now})),
|
||||||
|
j(serde_json::json!({"id": "2", "name": "IMG_2041.heic", "bytes": 3_420_000, "from": "手機", "to": "x", "to_name": "MacBook Pro", "state": "done", "at": now - 9 * 60_000})),
|
||||||
|
j(serde_json::json!({"id": "3", "name": "https://thsrc.com.tw/booking/…", "bytes": 60, "text": "https://thsrc.com.tw/booking/abc", "from": "MacBook Pro", "to": "phone", "to_name": "手機", "state": "ready", "at": now - 40 * 60_000})),
|
||||||
|
j(serde_json::json!({"id": "4", "name": "備份-2026-11.zip", "bytes": 812_000_000, "from": "MacBook Pro", "to": "l", "to_name": "客廳 Linux", "state": "waiting", "note": "目前離線", "at": now - 3 * 3600_000})),
|
||||||
|
j(serde_json::json!({"id": "5", "name": "合約草稿.pdf", "bytes": 1_250_000, "from": "研究助理", "to": "m", "to_name": "Mac mini", "state": "failed", "note": "那台電腦的磁碟滿了", "at": now - 26 * 3600_000})),
|
||||||
|
],
|
||||||
|
"x",
|
||||||
|
"m",
|
||||||
|
));
|
||||||
|
}
|
||||||
// 記憶: the memory page (memory), and the composer's suggestions (composer).
|
// 記憶: the memory page (memory), and the composer's suggestions (composer).
|
||||||
Ok(v @ ("memory" | "composer")) => {
|
Ok(v @ ("memory" | "composer")) => {
|
||||||
crate::memstore::seed_demo(1, crate::model::now_ms());
|
crate::memstore::seed_demo(1, crate::model::now_ms());
|
||||||
|
|
@ -921,6 +945,12 @@ impl App {
|
||||||
"link": {"type": "string"}}, "required": ["kind", "title"]}}));
|
"link": {"type": "string"}}, "required": ["kind", "title"]}}));
|
||||||
tool_specs.push(serde_json::json!({"name": "react", "description": "Put an emoji reaction on the person's latest message, like a friend would (e.g. ❤️ for thanks or good news, 👍 for OK, 😂 for a joke, 🎉 for a win, 👀 when you'll look into it). Use it now and then where it fits; you can still answer in words.",
|
tool_specs.push(serde_json::json!({"name": "react", "description": "Put an emoji reaction on the person's latest message, like a friend would (e.g. ❤️ for thanks or good news, 👍 for OK, 😂 for a joke, 🎉 for a win, 👀 when you'll look into it). Use it now and then where it fits; you can still answer in words.",
|
||||||
"parameters": {"type": "object", "properties": {"emoji": {"type": "string", "description": "One emoji"}}, "required": ["emoji"]}}));
|
"parameters": {"type": "object", "properties": {"emoji": {"type": "string", "description": "One emoji"}}, "required": ["emoji"]}}));
|
||||||
|
// 傳送: a file from a computer the bot works on to another device of the account
|
||||||
|
// (only where there is an account to find the devices in).
|
||||||
|
if !self.state.remote.relay_url.is_empty() {
|
||||||
|
tool_specs.push(serde_json::json!({"name": "send_to_device", "description": "Send a file to another device of the person's account, outside the chat: one of their computers (it lands in that computer's Downloads/AnyBot folder, with a notification; a computer that is off gets it when it is next on, within 7 days) or their phone (`to`: \"手機\"; they download it in AnyBot on the phone). Use it when the person asks to have a file on another device (\"傳到我的手機\", \"放到 Mac mini\"); to simply hand over a result in this chat use send_file. The file is read from `computer` (default: where you are working); from another of the person's computers up to 20 MB.",
|
||||||
|
"parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "File path (relative to your folder)"}, "computer": {"type": "string", "enum": names.clone(), "description": "The computer the file is on now."}, "to": {"type": "string", "description": "The device to send it to, by its name (as the person calls it), or 手機."}}, "required": ["path", "to"]}}));
|
||||||
|
}
|
||||||
tool_specs.push(serde_json::json!({"name": "send_file", "description": "Send a file (spreadsheet, document, Markdown, web page, picture, PDF…) into the chat as a file card the person can preview and download, straight from whichever computer it is on — your own or one of the person's (pass computer; up to 20 MB from theirs). Use this to hand over results instead of only saying where the file is; never copy a file to another computer first just to send it.",
|
tool_specs.push(serde_json::json!({"name": "send_file", "description": "Send a file (spreadsheet, document, Markdown, web page, picture, PDF…) into the chat as a file card the person can preview and download, straight from whichever computer it is on — your own or one of the person's (pass computer; up to 20 MB from theirs). Use this to hand over results instead of only saying where the file is; never copy a file to another computer first just to send it.",
|
||||||
"parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "File path (relative to your folder)"}, "computer": {"type": "string", "enum": names.clone()}}, "required": ["path"]}}));
|
"parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "File path (relative to your folder)"}, "computer": {"type": "string", "enum": names.clone()}}, "required": ["path"]}}));
|
||||||
tool_specs.push(serde_json::json!({"name": "open_for_person", "description": "Open a file you made (a web page, chart, report, picture, document) on the person's screen so they can see it, or a web address. From the bot's computer it is copied over first.",
|
tool_specs.push(serde_json::json!({"name": "open_for_person", "description": "Open a file you made (a web page, chart, report, picture, document) on the person's screen so they can see it, or a web address. From the bot's computer it is copied over first.",
|
||||||
|
|
@ -3888,6 +3918,7 @@ impl App {
|
||||||
self.watchdog();
|
self.watchdog();
|
||||||
self.poll_fetches();
|
self.poll_fetches();
|
||||||
self.poll_import();
|
self.poll_import();
|
||||||
|
self.drops_tick(ctx);
|
||||||
// (Where the memories are: the brain. A screen's own file is empty.)
|
// (Where the memories are: the brain. A screen's own file is empty.)
|
||||||
if !self.demo && !hands && !self.mir.on {
|
if !self.demo && !hands && !self.mir.on {
|
||||||
self.memory_nightly();
|
self.memory_nightly();
|
||||||
|
|
@ -4239,6 +4270,7 @@ impl eframe::App for App {
|
||||||
self.main_pane(ui);
|
self.main_pane(ui);
|
||||||
self.bot_editor(ctx);
|
self.bot_editor(ctx);
|
||||||
self.memory_page(ctx);
|
self.memory_page(ctx);
|
||||||
|
self.drops_page(ctx);
|
||||||
self.settings(ctx);
|
self.settings(ctx);
|
||||||
self.delete_dialog(ctx);
|
self.delete_dialog(ctx);
|
||||||
self.routines_window(ctx);
|
self.routines_window(ctx);
|
||||||
|
|
|
||||||
|
|
@ -51,7 +51,8 @@ impl App {
|
||||||
|
|
||||||
/// Files dropped on the window, the picker's answer, and ⌘V with a picture on the clipboard.
|
/// Files dropped on the window, the picker's answer, and ⌘V with a picture on the clipboard.
|
||||||
pub(super) fn attachments_poll(&mut self, ctx: &egui::Context, bot_id: u64, composer_focused: bool) {
|
pub(super) fn attachments_poll(&mut self, ctx: &egui::Context, bot_id: u64, composer_focused: bool) {
|
||||||
let dropped: Vec<PathBuf> = ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty()).collect());
|
// (While 傳送到其他裝置 is open, dropped files are for sending, not for this chat.)
|
||||||
|
let dropped: Vec<PathBuf> = if self.drop_page.is_some() { vec![] } else { ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty()).collect()) };
|
||||||
if !dropped.is_empty() {
|
if !dropped.is_empty() {
|
||||||
self.add_attachment_paths(bot_id, dropped);
|
self.add_attachment_paths(bot_id, dropped);
|
||||||
}
|
}
|
||||||
|
|
@ -96,7 +97,7 @@ impl App {
|
||||||
|
|
||||||
/// "Drop to attach" while files hover over the window.
|
/// "Drop to attach" while files hover over the window.
|
||||||
pub(super) fn drop_overlay(&self, ctx: &egui::Context) {
|
pub(super) fn drop_overlay(&self, ctx: &egui::Context) {
|
||||||
if !ctx.input(|i| !i.raw.hovered_files.is_empty()) {
|
if self.drop_page.is_some() || !ctx.input(|i| !i.raw.hovered_files.is_empty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let p = self.pal;
|
let p = self.pal;
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,7 @@ pub fn status_phrase(tool: Option<&str>, on_box: bool, waiting: bool, has_text:
|
||||||
"read_file" | "list_dir" | "search" => "正在讀取檔案".into(),
|
"read_file" | "list_dir" | "search" => "正在讀取檔案".into(),
|
||||||
"edit_file" => "正在記下來".into(),
|
"edit_file" => "正在記下來".into(),
|
||||||
"send_file" => "正在傳檔案給你".into(),
|
"send_file" => "正在傳檔案給你".into(),
|
||||||
|
"send_to_device" => "正在傳到你的另一台裝置".into(),
|
||||||
"computer_use_show" => "正在把畫面傳給你".into(),
|
"computer_use_show" => "正在把畫面傳給你".into(),
|
||||||
"shell" | "write_terminal" => "正在執行幾個指令".into(),
|
"shell" | "write_terminal" => "正在執行幾個指令".into(),
|
||||||
"read_terminal" => "正在等待結果".into(),
|
"read_terminal" => "正在等待結果".into(),
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,405 @@
|
||||||
|
// 傳送 in the window: pick a device of the account (a computer, the phone), then drop files on
|
||||||
|
// the dialog, choose them, or paste a few words. Below: what was sent and what arrived in the
|
||||||
|
// last 7 days, with where each one is. What arrives on this computer is announced here too
|
||||||
|
// (words go on the clipboard). The carrying itself is drops.rs.
|
||||||
|
|
||||||
|
use super::sidebar_ui::shorten_width;
|
||||||
|
use super::*;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::mpsc::{channel, Receiver};
|
||||||
|
|
||||||
|
const PAGE_W: f32 = 560.0;
|
||||||
|
|
||||||
|
struct Job {
|
||||||
|
name: String,
|
||||||
|
total: u64,
|
||||||
|
sent: Arc<AtomicU64>,
|
||||||
|
rx: Receiver<Result<(), String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DropPage {
|
||||||
|
/// The chosen destination (its id).
|
||||||
|
to: String,
|
||||||
|
targets: Vec<Value>,
|
||||||
|
you: String,
|
||||||
|
rx_targets: Option<Receiver<Value>>,
|
||||||
|
items: Vec<Value>,
|
||||||
|
rx_list: Option<Receiver<Value>>,
|
||||||
|
asked: Instant,
|
||||||
|
text: String,
|
||||||
|
jobs: Vec<Job>,
|
||||||
|
picked: Option<Receiver<Vec<PathBuf>>>,
|
||||||
|
note: String,
|
||||||
|
loaded: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DropPage {
|
||||||
|
fn new() -> Self {
|
||||||
|
DropPage { to: String::new(), targets: vec![], you: String::new(), rx_targets: None, items: vec![], rx_list: None, asked: Instant::now(), text: String::new(), jobs: vec![], picked: None, note: String::new(), loaded: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Already filled (screenshots).
|
||||||
|
pub fn shown(targets: Vec<Value>, items: Vec<Value>, you: &str, to: &str) -> Self {
|
||||||
|
DropPage { targets, items, you: you.into(), to: to.into(), loaded: true, ..Self::new() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a parcel's row says about where it is.
|
||||||
|
pub(crate) fn state_words(p: &Value, now: i64) -> (String, bool) {
|
||||||
|
let pct = |p: &Value| {
|
||||||
|
let (a, b) = (p["sent"].as_u64().unwrap_or(0), p["bytes"].as_u64().unwrap_or(0).max(1));
|
||||||
|
(a * 100 / b).min(100)
|
||||||
|
};
|
||||||
|
let to = p["to_name"].as_str().unwrap_or("");
|
||||||
|
let note = p["note"].as_str().unwrap_or("");
|
||||||
|
match p["state"].as_str().unwrap_or("") {
|
||||||
|
"uploading" => (format!("{} {}%", t("正在交給大腦"), pct(p)), false),
|
||||||
|
"waiting" if note.contains("更新") => (note.to_string(), false),
|
||||||
|
"waiting" => (format!("{}「{to}」{}", t("等"), t("開機上線,會自動送達")), false),
|
||||||
|
"sending" => (format!("{} {}%", t("傳送中"), pct(p)), false),
|
||||||
|
"ready" => (t("在手機的「傳送」裡可以拿(保留 7 天)"), false),
|
||||||
|
"done" => (format!("{} · {}", t(if p["to"] == crate::drops::PHONE && p["text"].as_str().unwrap_or("").is_empty() { "手機已下載" } else { "已送達" }), crate::pages::ago(p["at"].as_i64().unwrap_or(0), now)), false),
|
||||||
|
_ => (format!("{}:{}", t("沒有送達"), if note.is_empty() { t("不知道原因") } else { note.to_string() }), true),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
fn drop_call(&self, what: &'static str, method: &'static str, body: Value) -> Receiver<Value> {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let repaint = self.repaint_fn();
|
||||||
|
let (s, mirror) = (self.state.remote.clone(), self.mir.on);
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let b = if method == "GET" { vec![] } else { body.to_string().into_bytes() };
|
||||||
|
let _ = tx.send(crate::drops::ask(&s, mirror, what, method, &[], &b).unwrap_or_else(|e| json!({"error": e})));
|
||||||
|
repaint();
|
||||||
|
});
|
||||||
|
rx
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn open_drops(&mut self) {
|
||||||
|
self.drop_page = Some(DropPage::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_send_files(&mut self, pg: &mut DropPage, paths: Vec<PathBuf>) {
|
||||||
|
if pg.to.is_empty() {
|
||||||
|
pg.note = t("先選要傳到哪一台");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pg.note.clear();
|
||||||
|
for path in paths {
|
||||||
|
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||||
|
let total = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
|
||||||
|
let sent = Arc::new(AtomicU64::new(0));
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let repaint = self.repaint_fn();
|
||||||
|
let (s, mirror, to, sent2) = (self.state.remote.clone(), self.mir.on, pg.to.clone(), sent.clone());
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let _ = tx.send(crate::drops::send_file(&s, mirror, &path, &to, &sent2));
|
||||||
|
repaint();
|
||||||
|
});
|
||||||
|
pg.jobs.push(Job { name, total, sent, rx });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every frame, the window open or not: what arrived on this computer since the last look.
|
||||||
|
pub(super) fn drops_tick(&mut self, ctx: &egui::Context) {
|
||||||
|
if self.demo {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let fresh = crate::drops::office().take_fresh();
|
||||||
|
if fresh.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Words the person sent here are for pasting: the newest goes on the clipboard.
|
||||||
|
if let Some(r) = fresh.iter().rev().find(|r| !r.text.is_empty()) {
|
||||||
|
ctx.copy_text(r.text.clone());
|
||||||
|
}
|
||||||
|
if !self.headless && self.state.alert_sound {
|
||||||
|
crate::voice::chime();
|
||||||
|
}
|
||||||
|
if let Some(pg) = self.drop_page.as_mut() {
|
||||||
|
pg.asked = Instant::now() - std::time::Duration::from_secs(60);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn drops_page(&mut self, ctx: &egui::Context) {
|
||||||
|
let Some(mut pg) = self.drop_page.take() else { return };
|
||||||
|
let p = self.pal;
|
||||||
|
// Answers.
|
||||||
|
if let Some(rx) = &pg.rx_targets {
|
||||||
|
if let Ok(v) = rx.try_recv() {
|
||||||
|
pg.rx_targets = None;
|
||||||
|
if let Some(e) = v["error"].as_str() {
|
||||||
|
pg.note = e.to_string();
|
||||||
|
} else {
|
||||||
|
pg.you = v["you"].as_str().unwrap_or("").to_string();
|
||||||
|
pg.targets = v["targets"].as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["id"].as_str() != Some(pg.you.as_str())).collect();
|
||||||
|
if !pg.targets.iter().any(|t| t["id"].as_str() == Some(pg.to.as_str())) {
|
||||||
|
// The one used last time, else the first that is on.
|
||||||
|
let last = self.drop_last.clone();
|
||||||
|
pg.to = pg.targets.iter().find(|t| t["id"].as_str() == Some(last.as_str())).or_else(|| pg.targets.iter().find(|t| t["online"] == true)).and_then(|t| t["id"].as_str()).unwrap_or("").to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pg.loaded = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rx) = &pg.rx_list {
|
||||||
|
if let Ok(v) = rx.try_recv() {
|
||||||
|
pg.rx_list = None;
|
||||||
|
if v.get("error").is_none() {
|
||||||
|
pg.items = v["items"].as_array().cloned().unwrap_or_default();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut finished = false;
|
||||||
|
pg.jobs.retain(|j| match j.rx.try_recv() {
|
||||||
|
Ok(r) => {
|
||||||
|
if let Err(e) = r {
|
||||||
|
pg.note = e;
|
||||||
|
}
|
||||||
|
finished = true;
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Err(_) => true,
|
||||||
|
});
|
||||||
|
if let Some(rx) = &pg.picked {
|
||||||
|
if let Ok(paths) = rx.try_recv() {
|
||||||
|
pg.picked = None;
|
||||||
|
self.drop_send_files(&mut pg, paths);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Files dropped on the window while this is open are for sending (not for the chat).
|
||||||
|
let dropped: Vec<PathBuf> = ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty()).collect());
|
||||||
|
if !dropped.is_empty() {
|
||||||
|
self.drop_send_files(&mut pg, dropped);
|
||||||
|
}
|
||||||
|
// Asking: the devices once (and every 15 s), the list while something is moving.
|
||||||
|
let shot = self.demo;
|
||||||
|
if !shot {
|
||||||
|
if !pg.loaded && pg.rx_targets.is_none() {
|
||||||
|
pg.rx_targets = Some(self.drop_call("targets", "GET", Value::Null));
|
||||||
|
pg.asked = Instant::now() - std::time::Duration::from_secs(60);
|
||||||
|
}
|
||||||
|
let moving = !pg.jobs.is_empty() || pg.items.iter().any(|i| matches!(i["state"].as_str(), Some("uploading" | "sending" | "waiting")));
|
||||||
|
let every = std::time::Duration::from_millis(if moving { 1000 } else { 5000 });
|
||||||
|
if (finished || pg.asked.elapsed() >= every) && pg.rx_list.is_none() {
|
||||||
|
pg.asked = Instant::now();
|
||||||
|
pg.rx_list = Some(self.drop_call("list", "GET", Value::Null));
|
||||||
|
if pg.rx_targets.is_none() && pg.loaded {
|
||||||
|
pg.rx_targets = Some(self.drop_call("targets", "GET", Value::Null));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.request_repaint_after(if moving { std::time::Duration::from_millis(250) } else { every });
|
||||||
|
}
|
||||||
|
// A steady height: the list arrives after the first frame.
|
||||||
|
let max_h = dialog_max_height(ctx).min(620.0) - 60.0;
|
||||||
|
let mut acts: Vec<(&'static str, String)> = vec![];
|
||||||
|
let close = dialog(ctx, "drops", "傳送到其他裝置", PAGE_W, true, p, |ui| {
|
||||||
|
egui::ScrollArea::vertical().id_salt("drops-page").max_height(max_h).min_scrolled_height(max_h).auto_shrink([false, false]).show(ui, |ui| {
|
||||||
|
Frame::new().inner_margin(Margin { left: 20, right: 20, top: 14, bottom: 18 }).show(ui, |ui| {
|
||||||
|
ui.set_width(ui.available_width());
|
||||||
|
ui.spacing_mut().item_spacing.y = 6.0;
|
||||||
|
self.drops_body(ui, &mut pg, &mut acts);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
for (what, id) in acts {
|
||||||
|
match what {
|
||||||
|
"reveal" => crate::preview::reveal(std::path::Path::new(&id)),
|
||||||
|
"copy" => ctx.copy_text(id),
|
||||||
|
"pick" => {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
pg.picked = Some(rx);
|
||||||
|
let c = ctx.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let _ = tx.send(crate::attach::pick_files());
|
||||||
|
c.request_repaint();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
"text" => {
|
||||||
|
let (s, mirror, to, repaint) = (self.state.remote.clone(), self.mir.on, pg.to.clone(), self.repaint_fn());
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let sent = Arc::new(AtomicU64::new(0));
|
||||||
|
let n = id.len() as u64;
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let _ = tx.send(crate::drops::send_text(&s, mirror, &id, &to));
|
||||||
|
repaint();
|
||||||
|
});
|
||||||
|
pg.jobs.push(Job { name: t("一段文字"), total: n, sent, rx });
|
||||||
|
}
|
||||||
|
w => {
|
||||||
|
let w = if w == "retry" { "retry" } else { "remove" };
|
||||||
|
pg.items.retain(|i| w == "retry" || i["id"].as_str() != Some(id.as_str()));
|
||||||
|
let _ = self.drop_call(w, "POST", json!({"id": id}));
|
||||||
|
pg.asked = Instant::now() - std::time::Duration::from_secs(60);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !pg.to.is_empty() {
|
||||||
|
self.drop_last = pg.to.clone();
|
||||||
|
}
|
||||||
|
if !close {
|
||||||
|
self.drop_page = Some(pg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drops_body(&mut self, ui: &mut egui::Ui, pg: &mut DropPage, acts: &mut Vec<(&'static str, String)>) {
|
||||||
|
let p = self.pal;
|
||||||
|
let now = crate::model::now_ms();
|
||||||
|
if self.state.remote.relay_url.is_empty() && !self.demo {
|
||||||
|
ui.label(RichText::new(t("還沒登入帳號:現在只能和直接連到這台的手機互傳。登入帳號後,帳號裡每一台都能互傳(設定 › 一般 › 手機與帳號)。")).size(FONT_XS).color(p.text3));
|
||||||
|
ui.add_space(4.0);
|
||||||
|
}
|
||||||
|
// Where to.
|
||||||
|
ui.label(RichText::new(t("傳到")).size(FONT_XS).color(p.text3));
|
||||||
|
if !pg.loaded {
|
||||||
|
ui.label(RichText::new(t("正在找帳號裡的裝置…")).size(FONT_SM).color(p.text3));
|
||||||
|
} else if pg.targets.is_empty() {
|
||||||
|
ui.label(RichText::new(t("帳號裡還沒有其他裝置。")).size(FONT_SM).color(p.text3));
|
||||||
|
}
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing = vec2(6.0, 6.0);
|
||||||
|
for tg in &pg.targets {
|
||||||
|
let id = tg["id"].as_str().unwrap_or("");
|
||||||
|
let on = pg.to == id;
|
||||||
|
let online = tg["online"] == true;
|
||||||
|
let name = tg["name"].as_str().unwrap_or("");
|
||||||
|
let name = if tg["kind"] == "phone" { t(name) } else { name.to_string() };
|
||||||
|
let label = if online { name } else { format!("{name} · {}", t("離線")) };
|
||||||
|
let (fill, stroke, ink) = if on { (p.accent.gamma_multiply(0.14), Stroke::new(1.0, p.accent.gamma_multiply(0.7)), p.text) } else { (Color32::TRANSPARENT, Stroke::new(1.0, p.border), if online { p.text2 } else { p.text3 }) };
|
||||||
|
let r = ui.add(egui::Button::new(RichText::new(label).size(13.0).color(ink)).fill(fill).stroke(stroke).corner_radius(15).min_size(vec2(0.0, 30.0)));
|
||||||
|
let r = if online { r } else { r.on_hover_text(t("現在沒開:先交給大腦,它一上線就會收到(保留 7 天)")) };
|
||||||
|
if r.clicked() {
|
||||||
|
pg.to = id.to_string();
|
||||||
|
pg.note.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.add_space(8.0);
|
||||||
|
// The place to drop files.
|
||||||
|
let hovering = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
|
||||||
|
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 104.0), egui::Sense::hover());
|
||||||
|
ui.painter().rect_filled(rect, 14, if hovering { p.accent.gamma_multiply(0.10) } else { p.hover.gamma_multiply(0.5) });
|
||||||
|
ui.painter().rect_stroke(rect, 14, Stroke::new(if hovering { 1.6 } else { 1.0 }, if hovering { p.accent } else { p.border }), egui::StrokeKind::Inside);
|
||||||
|
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 26.0), vec2(20.0, 20.0)), crate::icons::Icon::Upload, if hovering { p.accent } else { p.text3 });
|
||||||
|
ui.painter().text(rect.center_top() + vec2(0.0, 50.0), egui::Align2::CENTER_CENTER, t(if hovering { "放開就傳送" } else { "把檔案拖到這裡" }), egui::FontId::proportional(14.0), p.text2);
|
||||||
|
let btn = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 78.0), vec2(96.0, 26.0));
|
||||||
|
if ui.put(btn, egui::Button::new(RichText::new(t("選擇檔案…")).size(12.5)).corner_radius(8)).clicked() {
|
||||||
|
if pg.to.is_empty() {
|
||||||
|
pg.note = t("先選要傳到哪一台");
|
||||||
|
} else {
|
||||||
|
acts.push(("pick", String::new()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// (A widget put inside the zone moved the cursor up to its own bottom.)
|
||||||
|
ui.advance_cursor_after_rect(rect);
|
||||||
|
ui.add_space(4.0);
|
||||||
|
// Or a few words (an address, a code, a paragraph): they land on the other clipboard.
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
let w = ui.available_width() - 78.0;
|
||||||
|
let r = ui.add_sized([w, 30.0], egui::TextEdit::singleline(&mut pg.text).hint_text(t("或貼上一段文字、網址(對方收到就在剪貼簿裡)")).margin(Margin::symmetric(10, 6)));
|
||||||
|
let enter = r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
|
||||||
|
if (ui.add(primary_button("傳送", p)).clicked() || enter) && !pg.text.trim().is_empty() {
|
||||||
|
if pg.to.is_empty() {
|
||||||
|
pg.note = t("先選要傳到哪一台");
|
||||||
|
} else {
|
||||||
|
acts.push(("text", std::mem::take(&mut pg.text)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if !pg.note.is_empty() {
|
||||||
|
ui.label(RichText::new(&pg.note).size(FONT_SM).color(p.danger));
|
||||||
|
}
|
||||||
|
// On their way from this computer.
|
||||||
|
for j in &pg.jobs {
|
||||||
|
let done = j.sent.load(Ordering::Relaxed);
|
||||||
|
let frac = if j.total == 0 { 0.0 } else { (done as f32 / j.total as f32).clamp(0.0, 1.0) };
|
||||||
|
ui.add_space(4.0);
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label(RichText::new(shorten_width(ui, &j.name, ui.available_width() - 150.0, 13.0)).size(FONT_SM).color(p.text));
|
||||||
|
ui.label(RichText::new(format!("{} / {}", crate::attach::human(done), crate::attach::human(j.total))).size(FONT_XS).color(p.text3));
|
||||||
|
});
|
||||||
|
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 4.0), egui::Sense::hover());
|
||||||
|
ui.painter().rect_filled(bar, 2, p.border);
|
||||||
|
ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * frac, 4.0)), 2, p.accent);
|
||||||
|
}
|
||||||
|
// What went and what came.
|
||||||
|
if pg.items.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ui.add_space(12.0);
|
||||||
|
ui.label(RichText::new(t("最近 7 天")).size(FONT_XS).color(p.text3));
|
||||||
|
let here: HashMap<String, String> = if self.demo { HashMap::new() } else { crate::drops::office().received().into_iter().map(|r| (r.id, r.path)).collect() };
|
||||||
|
for it in pg.items.iter().take(40) {
|
||||||
|
let id = it["id"].as_str().unwrap_or("").to_string();
|
||||||
|
let words = it["text"].as_str().unwrap_or("");
|
||||||
|
let (state, bad) = state_words(it, now);
|
||||||
|
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), egui::Sense::hover());
|
||||||
|
let icon = if !words.is_empty() {
|
||||||
|
crate::icons::Icon::Copy
|
||||||
|
} else {
|
||||||
|
match crate::preview::kind_of(it["name"].as_str().unwrap_or("")) {
|
||||||
|
"image" => crate::icons::Icon::FileImage,
|
||||||
|
"video" => crate::icons::Icon::FileVideo,
|
||||||
|
"audio" => crate::icons::Icon::FileAudio,
|
||||||
|
"sheet" | "csv" => crate::icons::Icon::FileSheet,
|
||||||
|
"code" | "html" => crate::icons::Icon::FileCode,
|
||||||
|
"text" | "markdown" | "pdf" | "doc" => crate::icons::Icon::FileText,
|
||||||
|
_ => crate::icons::Icon::File,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.left_center() + vec2(12.0, 0.0), vec2(18.0, 18.0)), icon, p.text3);
|
||||||
|
// Buttons on the right, then the words in what is left.
|
||||||
|
let mut right = rect.right();
|
||||||
|
let mut button = |ui: &mut egui::Ui, label: &str, w: f32| -> bool {
|
||||||
|
let r = egui::Rect::from_min_size(egui::pos2(right - w, rect.center().y - 13.0), vec2(w, 26.0));
|
||||||
|
right -= w + 6.0;
|
||||||
|
ui.put(r, egui::Button::new(RichText::new(t(label)).size(12.0)).corner_radius(8)).clicked()
|
||||||
|
};
|
||||||
|
if button(ui, "移除", 44.0) {
|
||||||
|
acts.push(("remove", id.clone()));
|
||||||
|
}
|
||||||
|
if bad && button(ui, "再試一次", 68.0) {
|
||||||
|
acts.push(("retry", id.clone()));
|
||||||
|
}
|
||||||
|
if !words.is_empty() {
|
||||||
|
if button(ui, "複製", 44.0) {
|
||||||
|
acts.push(("copy", words.to_string()));
|
||||||
|
}
|
||||||
|
} else if let Some(path) = here.get(&id).filter(|f| std::path::Path::new(f).exists()) {
|
||||||
|
if button(ui, "顯示", 44.0) {
|
||||||
|
acts.push(("reveal", path.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let tx = rect.left() + 30.0;
|
||||||
|
let max_w = (right - tx - 6.0).max(60.0);
|
||||||
|
let name = shorten_width(ui, it["name"].as_str().unwrap_or(""), max_w, 13.5);
|
||||||
|
ui.painter().text(egui::pos2(tx, rect.top() + 6.0), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(13.5), p.text);
|
||||||
|
let size = if words.is_empty() { format!("{} · ", crate::attach::human(it["bytes"].as_u64().unwrap_or(0))) } else { String::new() };
|
||||||
|
let to = it["to_name"].as_str().unwrap_or("");
|
||||||
|
let to = if it["to"] == crate::drops::PHONE { t(to) } else { to.to_string() };
|
||||||
|
let sub = format!("{size}{} → {to} · {state}", it["from"].as_str().unwrap_or(""));
|
||||||
|
let sub = shorten_width(ui, &sub, max_w, 11.5);
|
||||||
|
ui.painter().text(egui::pos2(tx, rect.top() + 26.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(11.5), if bad { p.danger } else { p.text3 });
|
||||||
|
ui.advance_cursor_after_rect(rect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_row_says_where_the_parcel_is() {
|
||||||
|
let now = crate::model::now_ms();
|
||||||
|
let row = |state: &str, note: &str| json!({"state": state, "note": note, "sent": 1, "bytes": 4, "to_name": "Mac mini", "at": now});
|
||||||
|
assert_eq!(state_words(&row("uploading", ""), now), ("正在交給大腦 25%".into(), false));
|
||||||
|
assert_eq!(state_words(&row("sending", ""), now), ("傳送中 25%".into(), false));
|
||||||
|
assert!(state_words(&row("waiting", "目前離線"), now).0.contains("等「Mac mini」"));
|
||||||
|
assert!(state_words(&row("waiting", "「Mac mini」的 AnyBot 要先更新才收得到"), now).0.contains("要先更新"));
|
||||||
|
assert_eq!(state_words(&row("done", ""), now), ("已送達 · 剛剛".into(), false));
|
||||||
|
assert_eq!(state_words(&row("failed", "磁碟滿了"), now), ("沒有送達:磁碟滿了".into(), true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -66,6 +66,8 @@ impl App {
|
||||||
remote::hub().set_repaint(Arc::new(move || c.request_repaint()));
|
remote::hub().set_repaint(Arc::new(move || c.request_repaint()));
|
||||||
self.remote_apply_settings();
|
self.remote_apply_settings();
|
||||||
self.mirror_boot();
|
self.mirror_boot();
|
||||||
|
// 傳送: whatever was still on its way when AnyBot stopped goes on.
|
||||||
|
crate::drops::kick();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hand changed settings to the server threads (and restart what depends on them).
|
/// Hand changed settings to the server threads (and restart what depends on them).
|
||||||
|
|
|
||||||
|
|
@ -178,7 +178,7 @@ impl App {
|
||||||
let name = self.person_name();
|
let name = self.person_name();
|
||||||
let initials: String = name.split_whitespace().filter_map(|w| w.chars().next()).take(2).collect::<String>().to_uppercase();
|
let initials: String = name.split_whitespace().filter_map(|w| w.chars().next()).take(2).collect::<String>().to_uppercase();
|
||||||
let initials = if initials.is_empty() { name.chars().take(1).collect() } else { initials };
|
let initials = if initials.is_empty() { name.chars().take(1).collect() } else { initials };
|
||||||
let w = ui.available_width() - 46.0;
|
let w = ui.available_width() - 88.0;
|
||||||
let (rect, r) = ui.allocate_exact_size(vec2(w, 40.0), egui::Sense::click());
|
let (rect, r) = ui.allocate_exact_size(vec2(w, 40.0), egui::Sense::click());
|
||||||
if r.hovered() {
|
if r.hovered() {
|
||||||
ui.painter().rect_filled(rect, 12, p.hover);
|
ui.painter().rect_filled(rect, 12, p.hover);
|
||||||
|
|
@ -193,6 +193,9 @@ impl App {
|
||||||
self.show_settings = true;
|
self.show_settings = true;
|
||||||
self.settings_tab = SettingsTab::General;
|
self.settings_tab = SettingsTab::General;
|
||||||
}
|
}
|
||||||
|
if pill_icon(ui, crate::icons::Icon::Upload, p).on_hover_text(t("傳送檔案或文字到其他裝置")).clicked() {
|
||||||
|
self.open_drops();
|
||||||
|
}
|
||||||
if pill_icon(ui, crate::icons::Icon::Apps, p).on_hover_text(t("連接器市集")).clicked() {
|
if pill_icon(ui, crate::icons::Icon::Apps, p).on_hover_text(t("連接器市集")).clicked() {
|
||||||
self.show_settings = true;
|
self.show_settings = true;
|
||||||
self.settings_tab = SettingsTab::Channels;
|
self.settings_tab = SettingsTab::Channels;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,986 @@
|
||||||
|
//! 傳送: a file, or a few words, from any device of the account to any other one — a computer
|
||||||
|
//! to the phone, the phone to a computer, one computer to another. Nothing to do with a chat.
|
||||||
|
//!
|
||||||
|
//! The brain is the post office. The sender hands it the parcel in pieces (2 MB each, so a slow
|
||||||
|
//! link and the account server's 35 s per request never matter); the brain keeps it in
|
||||||
|
//! `drops/` and carries it on:
|
||||||
|
//! - to a computer: pushed in pieces through 裝置連結's road (`/api/device/run`, tool
|
||||||
|
//! `drop_put`), picked up where it stopped when the link breaks, tried again while the computer
|
||||||
|
//! is off (for 7 days). It lands in that computer's 下載/AnyBot, with a notification; words go
|
||||||
|
//! on its clipboard.
|
||||||
|
//! - to the phone: it waits at the brain; the phone is told (a notification) and downloads it.
|
||||||
|
//! - to the brain's own computer: moved into its 下載/AnyBot.
|
||||||
|
//!
|
||||||
|
//! A computer takes parcels only from its own brain (see `remote::device_run`).
|
||||||
|
|
||||||
|
use base64::Engine;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::io::{Read, Seek, SeekFrom, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Condvar, Mutex, OnceLock};
|
||||||
|
|
||||||
|
/// The tool name a brain uses to push a piece to a computer.
|
||||||
|
pub const PUT: &str = "drop_put";
|
||||||
|
/// The phone as a destination (every phone signed in to the account).
|
||||||
|
pub const PHONE: &str = "phone";
|
||||||
|
/// One piece.
|
||||||
|
pub const CHUNK: usize = 2 * 1024 * 1024;
|
||||||
|
/// The largest file (estimated: the brain keeps a whole copy until it is delivered).
|
||||||
|
pub const MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
|
||||||
|
/// The most words in one go.
|
||||||
|
pub const MAX_TEXT_CHARS: usize = 100_000;
|
||||||
|
/// How long the brain keeps a parcel (delivered or not).
|
||||||
|
const KEEP_MS: i64 = 7 * 24 * 3600 * 1000;
|
||||||
|
/// After a try that didn't get through, how long before the next.
|
||||||
|
const RETRY_MS: i64 = 15_000;
|
||||||
|
/// How many arrived parcels a computer remembers.
|
||||||
|
const RECEIVED_MAX: usize = 100;
|
||||||
|
|
||||||
|
/// One thing on its way. `state`: uploading (the sender is still handing it over), waiting (for
|
||||||
|
/// the destination to be on), sending, ready (the phone can download it), done, failed.
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Default, Debug, PartialEq)]
|
||||||
|
pub struct Parcel {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub bytes: u64,
|
||||||
|
/// Words instead of a file.
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub text: String,
|
||||||
|
/// Who sent it, in words (a computer's name, 手機, a bot's name).
|
||||||
|
pub from: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub from_id: String,
|
||||||
|
pub to: String,
|
||||||
|
pub to_name: String,
|
||||||
|
pub at: i64,
|
||||||
|
pub state: String,
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub note: String,
|
||||||
|
/// Bytes the brain has (while uploading), then bytes the destination has.
|
||||||
|
#[serde(default)]
|
||||||
|
pub sent: u64,
|
||||||
|
#[serde(skip)]
|
||||||
|
next_try: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Something that arrived on this computer.
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Default, Debug, PartialEq)]
|
||||||
|
pub struct Received {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// Where the file is now (empty for words).
|
||||||
|
#[serde(default)]
|
||||||
|
pub path: String,
|
||||||
|
pub bytes: u64,
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub text: String,
|
||||||
|
pub from: String,
|
||||||
|
pub at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Office {
|
||||||
|
dir: PathBuf,
|
||||||
|
/// Where arrived files are put.
|
||||||
|
land: PathBuf,
|
||||||
|
parcels: Mutex<Vec<Parcel>>,
|
||||||
|
received: Mutex<Vec<Received>>,
|
||||||
|
/// Arrived since the window last looked (it copies words to the clipboard and rings).
|
||||||
|
fresh: Mutex<Vec<Received>>,
|
||||||
|
bell: (Mutex<u64>, Condvar),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a try to a computer ended.
|
||||||
|
enum Outcome {
|
||||||
|
Done,
|
||||||
|
Later(String),
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_ms() -> i64 {
|
||||||
|
crate::model::now_ms()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file name safe to put in a folder: no path, no control characters, not hidden, not endless.
|
||||||
|
pub fn safe_name(name: &str) -> String {
|
||||||
|
let last = name.rsplit(['/', '\\']).next().unwrap_or("");
|
||||||
|
let s: String = last.chars().filter(|c| !c.is_control() && *c != ':').collect();
|
||||||
|
let s = s.trim().trim_start_matches('.').trim();
|
||||||
|
let s: String = if s.chars().count() > 120 {
|
||||||
|
// The ending says what the file is: keep it.
|
||||||
|
let ext: String = Path::new(s).extension().map(|e| format!(".{}", e.to_string_lossy())).filter(|e| e.chars().count() <= 12).unwrap_or_default();
|
||||||
|
format!("{}{ext}", s.chars().take(120 - ext.chars().count()).collect::<String>())
|
||||||
|
} else {
|
||||||
|
s.to_string()
|
||||||
|
};
|
||||||
|
if s.is_empty() {
|
||||||
|
"檔案".into()
|
||||||
|
} else {
|
||||||
|
s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn good_id(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= 32 && id.chars().all(|c| c.is_ascii_alphanumeric())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name nothing in `dir` has yet: `報告.pdf`, then `報告 (2).pdf`…
|
||||||
|
fn free_name(dir: &Path, name: &str) -> PathBuf {
|
||||||
|
let first = dir.join(name);
|
||||||
|
if !first.exists() {
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
let p = Path::new(name);
|
||||||
|
let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());
|
||||||
|
let ext = p.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
|
||||||
|
(2..10_000).map(|n| dir.join(format!("{stem} ({n}){ext}"))).find(|c| !c.exists()).unwrap_or(first)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_whole(path: &Path, bytes: &[u8]) {
|
||||||
|
let tmp = path.with_extension("tmp");
|
||||||
|
if std::fs::write(&tmp, bytes).is_ok() {
|
||||||
|
let _ = std::fs::rename(&tmp, path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Words that mean "not now" (the computer is off, the link broke) rather than "no".
|
||||||
|
fn only_for_now(e: &str) -> bool {
|
||||||
|
["離線", "斷線", "斷了", "連不到", "等太久", "沒有回應", "暫時"].iter().any(|w| e.contains(w))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Office {
|
||||||
|
pub fn at(dir: PathBuf, land: PathBuf) -> Office {
|
||||||
|
let _ = std::fs::create_dir_all(&dir);
|
||||||
|
let read = |f: &str| std::fs::read(dir.join(f)).ok();
|
||||||
|
let mut parcels: Vec<Parcel> = read("index.json").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||||
|
// Whatever was half-way when AnyBot stopped: a half upload is gone with its sender;
|
||||||
|
// a delivery starts again (the other side says how much it has).
|
||||||
|
parcels.retain(|p| p.state != "uploading");
|
||||||
|
for p in parcels.iter_mut().filter(|p| p.state == "sending") {
|
||||||
|
p.state = "waiting".into();
|
||||||
|
}
|
||||||
|
let received = read("received.json").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||||
|
Office { dir, land, parcels: Mutex::new(parcels), received: Mutex::new(received), fresh: Mutex::new(vec![]), bell: (Mutex::new(0), Condvar::new()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bin(&self, id: &str) -> PathBuf {
|
||||||
|
self.dir.join(format!("{id}.bin"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, v: &[Parcel]) {
|
||||||
|
write_whole(&self.dir.join("index.json"), &serde_json::to_vec(v).unwrap_or_default());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn change<R>(&self, f: impl FnOnce(&mut Vec<Parcel>) -> R) -> R {
|
||||||
|
let mut g = self.parcels.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let r = f(&mut g);
|
||||||
|
self.save(&g);
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set(&self, id: &str, f: impl FnOnce(&mut Parcel)) -> bool {
|
||||||
|
self.change(|v| v.iter_mut().find(|p| p.id == id).map(f).is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ring(&self) {
|
||||||
|
*self.bell.0.lock().unwrap_or_else(|e| e.into_inner()) += 1;
|
||||||
|
self.bell.1.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- the sender's side (at the brain) ----------
|
||||||
|
|
||||||
|
/// A new parcel. Words are whole at once; a file follows in pieces (`chunk`, then `finish`).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn begin(&self, name: &str, bytes: u64, text: &str, to: &str, to_name: &str, from: &str, from_id: &str) -> Result<String, String> {
|
||||||
|
if to.is_empty() || to_name.is_empty() {
|
||||||
|
return Err("請選要傳到哪一台".into());
|
||||||
|
}
|
||||||
|
if to == from_id {
|
||||||
|
return Err("這就是你現在用的這台,選另一台".into());
|
||||||
|
}
|
||||||
|
let text = text.trim();
|
||||||
|
let id = crate::httpd::random_hex(8);
|
||||||
|
let mut p = Parcel { id: id.clone(), from: from.to_string(), from_id: from_id.to_string(), to: to.to_string(), to_name: to_name.to_string(), at: now_ms(), ..Default::default() };
|
||||||
|
if !text.is_empty() {
|
||||||
|
if text.chars().count() > MAX_TEXT_CHARS {
|
||||||
|
return Err(format!("文字太長了(最多 {MAX_TEXT_CHARS} 個字),請存成檔案再傳"));
|
||||||
|
}
|
||||||
|
p.text = text.to_string();
|
||||||
|
p.name = text.lines().next().unwrap_or("").chars().take(40).collect();
|
||||||
|
p.bytes = text.len() as u64;
|
||||||
|
p.state = "waiting".into();
|
||||||
|
} else {
|
||||||
|
if bytes == 0 {
|
||||||
|
return Err("檔案是空的".into());
|
||||||
|
}
|
||||||
|
if bytes > MAX_BYTES {
|
||||||
|
return Err(format!("「{}」太大了(最多 {})", safe_name(name), crate::attach::human(MAX_BYTES)));
|
||||||
|
}
|
||||||
|
std::fs::write(self.bin(&id), b"").map_err(|e| format!("大腦存不下這個檔案:{e}"))?;
|
||||||
|
p.name = safe_name(name);
|
||||||
|
p.bytes = bytes;
|
||||||
|
p.state = "uploading".into();
|
||||||
|
}
|
||||||
|
self.change(|v| v.push(p));
|
||||||
|
if !text.is_empty() {
|
||||||
|
self.ring();
|
||||||
|
}
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One piece of an upload, at byte `at`. Answers how many bytes the brain has now; a piece
|
||||||
|
/// that isn't the next one changes nothing (the sender goes on from the answer).
|
||||||
|
pub fn chunk(&self, id: &str, at: u64, data: &[u8]) -> Result<u64, String> {
|
||||||
|
let p = self.get(id).filter(|p| p.state == "uploading").ok_or("這次傳送已經取消了")?;
|
||||||
|
let path = self.bin(id);
|
||||||
|
let have = std::fs::metadata(&path).map(|m| m.len()).map_err(|_| "這次傳送已經取消了".to_string())?;
|
||||||
|
if at != have {
|
||||||
|
return Ok(have);
|
||||||
|
}
|
||||||
|
if have + data.len() as u64 > p.bytes {
|
||||||
|
return Err("傳來的比說好的大小還多".into());
|
||||||
|
}
|
||||||
|
let mut f = std::fs::OpenOptions::new().append(true).open(&path).map_err(|e| e.to_string())?;
|
||||||
|
f.write_all(data).map_err(|e| format!("大腦的磁碟寫不進去:{e}"))?;
|
||||||
|
let have = have + data.len() as u64;
|
||||||
|
self.set(id, |p| p.sent = have);
|
||||||
|
Ok(have)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The upload is whole: it can go on to where it is going.
|
||||||
|
pub fn finish(&self, id: &str) -> Result<(), String> {
|
||||||
|
let p = self.get(id).filter(|p| p.state == "uploading").ok_or("這次傳送已經取消了")?;
|
||||||
|
let have = std::fs::metadata(self.bin(id)).map(|m| m.len()).unwrap_or(0);
|
||||||
|
if have != p.bytes {
|
||||||
|
return Err(format!("還沒傳完({} / {})", crate::attach::human(have), crate::attach::human(p.bytes)));
|
||||||
|
}
|
||||||
|
self.set(id, |p| {
|
||||||
|
p.state = "waiting".into();
|
||||||
|
p.sent = 0;
|
||||||
|
});
|
||||||
|
self.ring();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file already on the brain's own disk (its own window, a bot's `send_to_device`).
|
||||||
|
pub fn add_file(&self, path: &Path, to: &str, to_name: &str, from: &str, from_id: &str) -> Result<String, String> {
|
||||||
|
let meta = std::fs::metadata(path).map_err(|_| format!("找不到「{}」", path.display()))?;
|
||||||
|
if meta.is_dir() {
|
||||||
|
return Err(format!("「{}」是資料夾,請先壓縮成一個檔案", path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()));
|
||||||
|
}
|
||||||
|
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||||
|
let id = self.begin(&name, meta.len(), "", to, to_name, from, from_id)?;
|
||||||
|
if let Err(e) = std::fs::copy(path, self.bin(&id)) {
|
||||||
|
self.remove(&id);
|
||||||
|
return Err(format!("讀不到「{name}」:{e}"));
|
||||||
|
}
|
||||||
|
self.finish(&id).inspect_err(|_| self.remove(&id))?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: &str) -> Option<Parcel> {
|
||||||
|
self.parcels.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|p| p.id == id).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything of the last 7 days, the newest first.
|
||||||
|
pub fn list(&self) -> Vec<Parcel> {
|
||||||
|
self.prune(now_ms());
|
||||||
|
let mut v = self.parcels.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
v.sort_by_key(|p| std::cmp::Reverse(p.at));
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A piece of a parcel that waits for the phone. Reading its end marks it done.
|
||||||
|
pub fn read(&self, id: &str, at: u64, len: u64) -> Result<Vec<u8>, String> {
|
||||||
|
let p = self.get(id).filter(|p| p.to == PHONE && p.text.is_empty() && matches!(p.state.as_str(), "ready" | "done")).ok_or("這個檔案已經不在了(保留 7 天)")?;
|
||||||
|
let mut f = std::fs::File::open(self.bin(id)).map_err(|_| "這個檔案已經不在了(保留 7 天)".to_string())?;
|
||||||
|
let len = len.clamp(1, 8 * 1024 * 1024).min(p.bytes.saturating_sub(at)) as usize;
|
||||||
|
let mut buf = vec![0u8; len];
|
||||||
|
f.seek(SeekFrom::Start(at)).and_then(|_| f.read_exact(&mut buf)).map_err(|e| e.to_string())?;
|
||||||
|
if at + len as u64 >= p.bytes {
|
||||||
|
self.set(id, |p| {
|
||||||
|
p.state = "done".into();
|
||||||
|
p.sent = p.bytes;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&self, id: &str) {
|
||||||
|
self.change(|v| v.retain(|p| p.id != id));
|
||||||
|
let _ = std::fs::remove_file(self.bin(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Try a failed one again.
|
||||||
|
pub fn retry(&self, id: &str) {
|
||||||
|
let has_file = self.bin(id).exists();
|
||||||
|
self.set(id, |p| {
|
||||||
|
if p.state == "failed" && (has_file || !p.text.is_empty()) {
|
||||||
|
p.state = "waiting".into();
|
||||||
|
p.note.clear();
|
||||||
|
p.next_try = 0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.ring();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prune(&self, now: i64) {
|
||||||
|
let old: Vec<String> = self.parcels.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|p| now - p.at > KEEP_MS).map(|p| p.id.clone()).collect();
|
||||||
|
for id in old {
|
||||||
|
self.remove(&id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- carrying them on (the brain's worker) ----------
|
||||||
|
|
||||||
|
/// One round: everything that waits is tried. `me`: this brain's own id. `carry` pushes one
|
||||||
|
/// piece to a computer (host id, the tool's args, who it is from) and gives its answer;
|
||||||
|
/// `tell_phone` says a parcel is ready for the phone.
|
||||||
|
pub fn deliver(&self, me: &str, carry: &dyn Fn(&str, &str, &str) -> Result<Value, String>, tell_phone: &dyn Fn(&Parcel)) {
|
||||||
|
let now = now_ms();
|
||||||
|
self.prune(now);
|
||||||
|
let todo: Vec<Parcel> = self.parcels.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|p| p.state == "waiting" && p.next_try <= now).cloned().collect();
|
||||||
|
for p in todo {
|
||||||
|
if p.to == PHONE {
|
||||||
|
self.set(&p.id, |p| p.state = "ready".into());
|
||||||
|
tell_phone(&p);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
self.set(&p.id, |p| p.state = "sending".into());
|
||||||
|
let outcome = if p.to == me {
|
||||||
|
let r = if p.text.is_empty() { self.land_file(&self.bin(&p.id), &p.name, &p.id, &p.from, p.bytes).map(|_| ()) } else { Ok(self.land_text(&p.text, &p.id, &p.from)) };
|
||||||
|
match r {
|
||||||
|
Ok(()) => Outcome::Done,
|
||||||
|
Err(e) => Outcome::Failed(e),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.carry_to(&p, carry)
|
||||||
|
};
|
||||||
|
match outcome {
|
||||||
|
Outcome::Done => {
|
||||||
|
let _ = std::fs::remove_file(self.bin(&p.id));
|
||||||
|
self.set(&p.id, |p| {
|
||||||
|
p.state = "done".into();
|
||||||
|
p.sent = p.bytes;
|
||||||
|
p.note.clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Outcome::Later(why) => {
|
||||||
|
self.set(&p.id, |p| {
|
||||||
|
p.state = "waiting".into();
|
||||||
|
p.note = why;
|
||||||
|
p.next_try = now_ms() + RETRY_MS;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Outcome::Failed(why) => {
|
||||||
|
self.set(&p.id, |p| {
|
||||||
|
p.state = "failed".into();
|
||||||
|
p.note = why;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn carry_to(&self, p: &Parcel, carry: &dyn Fn(&str, &str, &str) -> Result<Value, String>) -> Outcome {
|
||||||
|
let head = json!({"id": p.id, "name": p.name, "bytes": p.bytes, "from": p.from});
|
||||||
|
let ask = |extra: Value| -> Result<Value, Outcome> {
|
||||||
|
let mut a = head.clone();
|
||||||
|
for (k, v) in extra.as_object().into_iter().flatten() {
|
||||||
|
a[k] = v.clone();
|
||||||
|
}
|
||||||
|
carry(&p.to, &a.to_string(), &p.from).map_err(|e| {
|
||||||
|
if e.contains("不能遠端使用") {
|
||||||
|
Outcome::Later(format!("「{}」的 AnyBot 要先更新才收得到", p.to_name))
|
||||||
|
} else if only_for_now(&e) {
|
||||||
|
Outcome::Later(e)
|
||||||
|
} else {
|
||||||
|
Outcome::Failed(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let refused = |v: &Value| Outcome::Failed(v["text"].as_str().filter(|t| !t.is_empty()).unwrap_or("那台電腦沒有收下").to_string());
|
||||||
|
if !p.text.is_empty() {
|
||||||
|
return match ask(json!({"text": p.text})) {
|
||||||
|
Ok(v) if v["done"] == true => Outcome::Done,
|
||||||
|
Ok(v) => refused(&v),
|
||||||
|
Err(o) => o,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// How much it already has (a link that broke half-way goes on from there).
|
||||||
|
let mut at = match ask(json!({"probe": true})) {
|
||||||
|
Ok(v) if v["done"] == true => return Outcome::Done,
|
||||||
|
Ok(v) if v["ok"] == true => v["have"].as_u64().unwrap_or(0).min(p.bytes),
|
||||||
|
Ok(v) => return refused(&v),
|
||||||
|
Err(o) => return o,
|
||||||
|
};
|
||||||
|
let Ok(mut f) = std::fs::File::open(self.bin(&p.id)) else { return Outcome::Failed("大腦上的檔案不見了,請重新傳一次".into()) };
|
||||||
|
let mut resyncs = 0;
|
||||||
|
loop {
|
||||||
|
// Taken back while on its way.
|
||||||
|
if self.get(&p.id).is_none() {
|
||||||
|
return Outcome::Failed("已取消".into());
|
||||||
|
}
|
||||||
|
let n = (CHUNK as u64).min(p.bytes - at) as usize;
|
||||||
|
let mut buf = vec![0u8; n];
|
||||||
|
if f.seek(SeekFrom::Start(at)).and_then(|_| f.read_exact(&mut buf)).is_err() {
|
||||||
|
return Outcome::Failed("大腦上的檔案讀不出來,請重新傳一次".into());
|
||||||
|
}
|
||||||
|
let v = match ask(json!({"at": at, "data": base64::engine::general_purpose::STANDARD.encode(&buf)})) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(o) => return o,
|
||||||
|
};
|
||||||
|
if v["done"] == true {
|
||||||
|
return Outcome::Done;
|
||||||
|
}
|
||||||
|
match (v["ok"] == true, v["have"].as_u64()) {
|
||||||
|
(true, Some(h)) if h > at && h < p.bytes => at = h,
|
||||||
|
// It has a different amount than we thought: go on from what it has.
|
||||||
|
(false, Some(h)) if resyncs < 3 && h < p.bytes => {
|
||||||
|
resyncs += 1;
|
||||||
|
at = h;
|
||||||
|
}
|
||||||
|
_ => return refused(&v),
|
||||||
|
}
|
||||||
|
self.set(&p.id, |p| p.sent = at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- the receiving side (any computer) ----------
|
||||||
|
|
||||||
|
/// A piece pushed by the brain (`drop_put`'s args). Answers `{ok, have, done, text}`.
|
||||||
|
pub fn take(&self, v: &Value) -> Value {
|
||||||
|
let id = v["id"].as_str().unwrap_or("");
|
||||||
|
if !good_id(id) {
|
||||||
|
return json!({"ok": false, "text": "這次傳送的編號不對"});
|
||||||
|
}
|
||||||
|
let from = v["from"].as_str().unwrap_or("").chars().take(60).collect::<String>();
|
||||||
|
// Already here (the brain didn't hear the last "got it").
|
||||||
|
if self.received.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|r| r.id == id) {
|
||||||
|
return json!({"ok": true, "done": true});
|
||||||
|
}
|
||||||
|
if let Some(text) = v["text"].as_str().filter(|t| !t.is_empty()) {
|
||||||
|
if text.chars().count() > MAX_TEXT_CHARS {
|
||||||
|
return json!({"ok": false, "text": "文字太長了"});
|
||||||
|
}
|
||||||
|
self.land_text(text, id, &from);
|
||||||
|
return json!({"ok": true, "done": true});
|
||||||
|
}
|
||||||
|
let bytes = v["bytes"].as_u64().unwrap_or(0);
|
||||||
|
if bytes == 0 || bytes > MAX_BYTES {
|
||||||
|
return json!({"ok": false, "text": "檔案大小不對"});
|
||||||
|
}
|
||||||
|
let part = self.dir.join(format!("in-{id}.part"));
|
||||||
|
let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||||
|
if v["probe"] == true {
|
||||||
|
// All here but never put in place (the folder couldn't be written last time).
|
||||||
|
if have == bytes {
|
||||||
|
return match self.land_file(&part, v["name"].as_str().unwrap_or(""), id, &from, bytes) {
|
||||||
|
Ok(_) => json!({"ok": true, "done": true, "have": have}),
|
||||||
|
Err(e) => json!({"ok": false, "text": e}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if have > bytes {
|
||||||
|
let _ = std::fs::remove_file(&part);
|
||||||
|
return json!({"ok": true, "have": 0});
|
||||||
|
}
|
||||||
|
return json!({"ok": true, "have": have});
|
||||||
|
}
|
||||||
|
let at = v["at"].as_u64().unwrap_or(0);
|
||||||
|
if at != have {
|
||||||
|
return json!({"ok": false, "have": have, "text": "接不上,從已經收到的地方再傳"});
|
||||||
|
}
|
||||||
|
let Some(data) = v["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok()).filter(|d| !d.is_empty() && d.len() <= CHUNK * 2) else {
|
||||||
|
return json!({"ok": false, "have": have, "text": "這一段的內容壞了"});
|
||||||
|
};
|
||||||
|
if have + data.len() as u64 > bytes {
|
||||||
|
let _ = std::fs::remove_file(&part);
|
||||||
|
return json!({"ok": false, "text": "傳來的比說好的大小還多"});
|
||||||
|
}
|
||||||
|
let wrote = std::fs::OpenOptions::new().create(true).append(true).open(&part).and_then(|mut f| f.write_all(&data));
|
||||||
|
if let Err(e) = wrote {
|
||||||
|
return json!({"ok": false, "text": format!("這台電腦存不下:{e}")});
|
||||||
|
}
|
||||||
|
let have = have + data.len() as u64;
|
||||||
|
if have < bytes {
|
||||||
|
return json!({"ok": true, "have": have});
|
||||||
|
}
|
||||||
|
match self.land_file(&part, v["name"].as_str().unwrap_or(""), id, &from, bytes) {
|
||||||
|
Ok(_) => json!({"ok": true, "done": true, "have": have}),
|
||||||
|
Err(e) => json!({"ok": false, "text": e}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A whole file, moved to where the person finds it.
|
||||||
|
fn land_file(&self, src: &Path, name: &str, id: &str, from: &str, bytes: u64) -> Result<PathBuf, String> {
|
||||||
|
std::fs::create_dir_all(&self.land).map_err(|e| format!("建不了「{}」:{e}", self.land.display()))?;
|
||||||
|
let dst = free_name(&self.land, &safe_name(name));
|
||||||
|
// Another disk than the data folder's: copy, then drop the original.
|
||||||
|
if std::fs::rename(src, &dst).is_err() {
|
||||||
|
std::fs::copy(src, &dst).map_err(|e| format!("放不進「{}」:{e}", self.land.display()))?;
|
||||||
|
let _ = std::fs::remove_file(src);
|
||||||
|
}
|
||||||
|
let name = dst.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||||
|
self.arrived(Received { id: id.to_string(), name, path: dst.to_string_lossy().to_string(), bytes, text: String::new(), from: from.to_string(), at: now_ms() });
|
||||||
|
Ok(dst)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn land_text(&self, text: &str, id: &str, from: &str) {
|
||||||
|
let name: String = text.lines().next().unwrap_or("").chars().take(40).collect();
|
||||||
|
self.arrived(Received { id: id.to_string(), name, path: String::new(), bytes: text.len() as u64, text: text.to_string(), from: from.to_string(), at: now_ms() });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arrived(&self, r: Received) {
|
||||||
|
{
|
||||||
|
let mut g = self.received.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
g.insert(0, r.clone());
|
||||||
|
g.truncate(RECEIVED_MAX);
|
||||||
|
write_whole(&self.dir.join("received.json"), &serde_json::to_vec(&*g).unwrap_or_default());
|
||||||
|
}
|
||||||
|
let mut f = self.fresh.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
f.push(r);
|
||||||
|
// (Nobody looks on a computer without a window.)
|
||||||
|
if f.len() > 50 {
|
||||||
|
f.remove(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What arrived on this computer, the newest first.
|
||||||
|
pub fn received(&self) -> Vec<Received> {
|
||||||
|
self.received.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arrived since last asked.
|
||||||
|
pub fn take_fresh(&self) -> Vec<Received> {
|
||||||
|
std::mem::take(&mut *self.fresh.lock().unwrap_or_else(|e| e.into_inner()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- this AnyBot's own office ----------
|
||||||
|
|
||||||
|
fn downloads() -> PathBuf {
|
||||||
|
dirs::download_dir().or_else(|| dirs::home_dir().map(|h| h.join("Downloads"))).unwrap_or_else(std::env::temp_dir).join("AnyBot")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn office() -> &'static Office {
|
||||||
|
static O: OnceLock<Office> = OnceLock::new();
|
||||||
|
O.get_or_init(|| {
|
||||||
|
let dir = crate::model::State::path().parent().map(|p| p.join("drops")).unwrap_or_else(|| std::env::temp_dir().join("anybot-drops"));
|
||||||
|
Office::at(dir, downloads())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start carrying (once), and look at the queue now.
|
||||||
|
pub fn kick() {
|
||||||
|
static STARTED: std::sync::Once = std::sync::Once::new();
|
||||||
|
STARTED.call_once(|| {
|
||||||
|
std::thread::spawn(|| {
|
||||||
|
let o = office();
|
||||||
|
let mut seen = 0;
|
||||||
|
loop {
|
||||||
|
let me = me_id(&crate::remote::hub().settings());
|
||||||
|
let before: Vec<String> = o.received().into_iter().map(|r| r.id).collect();
|
||||||
|
o.deliver(&me, &|host, args, who| crate::remote::run_on_device(host, PUT, args, who), &|p| {
|
||||||
|
let what = if p.text.is_empty() { format!("「{}」({})可以下載了", p.name, crate::attach::human(p.bytes)) } else { format!("一段文字:{}", p.name) };
|
||||||
|
crate::remote::notify(&format!("{} 傳來的", p.from), &what, 0);
|
||||||
|
});
|
||||||
|
// What was for this brain's own computer landed without the device road.
|
||||||
|
let new: Vec<Received> = o.received().into_iter().filter(|r| !before.contains(&r.id)).collect();
|
||||||
|
if !new.is_empty() {
|
||||||
|
new.iter().for_each(tell_here);
|
||||||
|
crate::remote::hub().repaint_now();
|
||||||
|
}
|
||||||
|
let g = o.bell.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let (g, _) = o.bell.1.wait_timeout_while(g, std::time::Duration::from_secs(20), |n| *n == seen).unwrap_or_else(|e| e.into_inner());
|
||||||
|
seen = *g;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
office().ring();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A piece arriving on this computer from its brain: taken, and the person is told when it is whole.
|
||||||
|
pub fn take_here(args: &str) -> Value {
|
||||||
|
let o = office();
|
||||||
|
let v = o.take(&crate::tools::args_of(args));
|
||||||
|
if v["done"] == true {
|
||||||
|
// (The window, when there is one, picks these up for the clipboard; the banner is for
|
||||||
|
// a person who isn't looking at AnyBot.)
|
||||||
|
if let Some(r) = o.fresh.lock().unwrap_or_else(|e| e.into_inner()).last() {
|
||||||
|
tell_here(r);
|
||||||
|
}
|
||||||
|
crate::remote::hub().repaint_now();
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The notification on the computer something arrived on.
|
||||||
|
pub fn tell_here(r: &Received) {
|
||||||
|
let body = if r.text.is_empty() { format!("「{}」({})已放在 下載/AnyBot", r.name, crate::attach::human(r.bytes)) } else { format!("一段文字,已複製到剪貼簿:{}", r.name) };
|
||||||
|
crate::notify::banner(&format!("{} 傳來的", if r.from.is_empty() { "AnyBot" } else { &r.from }), &body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This computer as a destination: its id in the account, or (with no account: only a phone on
|
||||||
|
/// the same network reaches it) a word of its own.
|
||||||
|
fn me_id(s: &crate::remote::Settings) -> String {
|
||||||
|
if s.host_id.is_empty() {
|
||||||
|
"this".into()
|
||||||
|
} else {
|
||||||
|
s.host_id.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a parcel can go, as the brain knows the account: its own computer, the computers that
|
||||||
|
/// show it or lend it their hands, and the phone. (Asks the account server; cached 10 s.)
|
||||||
|
pub fn targets() -> Vec<Value> {
|
||||||
|
static CACHE: Mutex<Option<(std::time::Instant, Vec<Value>)>> = Mutex::new(None);
|
||||||
|
if let Some((t, v)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||||
|
if t.elapsed().as_secs() < 10 {
|
||||||
|
return v.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let s = crate::remote::hub().settings();
|
||||||
|
// No account: this computer and a phone signed in to it directly.
|
||||||
|
if s.relay_url.is_empty() || s.host_id.is_empty() {
|
||||||
|
return vec![json!({"id": me_id(&s), "name": s.host_name, "online": true, "kind": "brain"}), json!({"id": PHONE, "name": "手機", "online": true, "kind": "phone"})];
|
||||||
|
}
|
||||||
|
let mut out = vec![];
|
||||||
|
for (id, name, online) in crate::remote::devices_online(&s) {
|
||||||
|
if id == s.host_id {
|
||||||
|
out.push(json!({"id": id, "name": name, "online": true, "kind": "brain"}));
|
||||||
|
} else {
|
||||||
|
let uses = crate::remote::peer_uses(&id);
|
||||||
|
if uses == s.host_id || (uses.is_empty() && crate::remote::is_hands(&id)) {
|
||||||
|
out.push(json!({"id": id, "name": name, "online": online, "kind": "computer"}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out.is_empty() {
|
||||||
|
// The account server didn't answer: at least this computer and the phone.
|
||||||
|
out.push(json!({"id": s.host_id, "name": s.host_name, "online": true, "kind": "brain"}));
|
||||||
|
}
|
||||||
|
out.push(json!({"id": PHONE, "name": "手機", "online": true, "kind": "phone"}));
|
||||||
|
*CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), out.clone()));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A destination's name (by id), or None when the account has no such device.
|
||||||
|
pub fn target_name(id: &str) -> Option<String> {
|
||||||
|
targets().iter().find(|t| t["id"] == id).and_then(|t| t["name"].as_str().map(String::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A destination by what a person (or a bot) calls it: its name, or 手機 / phone.
|
||||||
|
pub fn target_called(name: &str) -> Option<(String, String)> {
|
||||||
|
let want = name.trim();
|
||||||
|
let phone = ["手機", "手机", "phone", "iphone", "android"].iter().any(|w| want.eq_ignore_ascii_case(w));
|
||||||
|
targets().iter().find(|t| if phone { t["id"] == PHONE } else { t["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(want)) || t["id"] == want }).and_then(|t| Some((t["id"].as_str()?.to_string(), t["name"].as_str()?.to_string())))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The brain's answers to `/api/drop/<what>` (the phone) and `/api/sync/drop/<what>` (a screen).
|
||||||
|
/// `from_id`: the computer asking, or PHONE; `from`: what to call it.
|
||||||
|
pub fn api(what: &str, method: &str, query: &std::collections::HashMap<String, String>, body: &[u8], from: &str, from_id: &str) -> Result<Value, String> {
|
||||||
|
let o = office();
|
||||||
|
let q = |k: &str| query.get(k).cloned().unwrap_or_default();
|
||||||
|
let b = || serde_json::from_slice::<Value>(body).unwrap_or(Value::Null);
|
||||||
|
match (method, what) {
|
||||||
|
("GET", "targets") => Ok(json!({"targets": targets(), "you": from_id})),
|
||||||
|
("GET", "list") => Ok(json!({"items": o.list(), "you": from_id})),
|
||||||
|
("POST", "new") => {
|
||||||
|
let b = b();
|
||||||
|
let to = b["to"].as_str().unwrap_or("");
|
||||||
|
let to_name = target_name(to).ok_or("帳號裡找不到這台裝置(可能剛被移除)")?;
|
||||||
|
let id = o.begin(b["name"].as_str().unwrap_or(""), b["bytes"].as_u64().unwrap_or(0), b["text"].as_str().unwrap_or(""), to, &to_name, from, from_id)?;
|
||||||
|
kick();
|
||||||
|
Ok(json!({"id": id, "chunk": CHUNK}))
|
||||||
|
}
|
||||||
|
("POST", "chunk") => o.chunk(&q("id"), q("at").parse().unwrap_or(0), body).map(|have| json!({"have": have})),
|
||||||
|
("POST", "done") => {
|
||||||
|
o.finish(b()["id"].as_str().unwrap_or(""))?;
|
||||||
|
kick();
|
||||||
|
Ok(json!({"ok": true}))
|
||||||
|
}
|
||||||
|
("POST", "remove") => {
|
||||||
|
o.remove(b()["id"].as_str().unwrap_or(""));
|
||||||
|
Ok(json!({"ok": true}))
|
||||||
|
}
|
||||||
|
("POST", "retry") => {
|
||||||
|
o.retry(b()["id"].as_str().unwrap_or(""));
|
||||||
|
kick();
|
||||||
|
Ok(json!({"ok": true}))
|
||||||
|
}
|
||||||
|
_ => Err("沒有這個動作".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- sending from this computer ----------
|
||||||
|
|
||||||
|
/// Ask this computer's post office: its brain's when it is a screen (`mirror`), else its own.
|
||||||
|
pub fn ask(s: &crate::remote::Settings, mirror: bool, what: &str, method: &str, query: &[(&str, String)], body: &[u8]) -> Result<Value, String> {
|
||||||
|
if mirror {
|
||||||
|
return crate::remote::to_brain(s, method, &format!("/drop/{what}"), query, body, 60);
|
||||||
|
}
|
||||||
|
let q = query.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
|
||||||
|
api(what, method, &q, body, &s.host_name, &me_id(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a file from this computer. `sent` counts the bytes handed over (for a progress bar).
|
||||||
|
pub fn send_file(s: &crate::remote::Settings, mirror: bool, path: &Path, to: &str, sent: &std::sync::atomic::AtomicU64) -> Result<(), String> {
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||||
|
let meta = std::fs::metadata(path).map_err(|_| format!("找不到「{name}」"))?;
|
||||||
|
if meta.is_dir() {
|
||||||
|
return Err(format!("「{name}」是資料夾,請先壓縮成一個檔案"));
|
||||||
|
}
|
||||||
|
if !mirror {
|
||||||
|
let to_name = target_name(to).ok_or("帳號裡找不到這台裝置")?;
|
||||||
|
office().add_file(path, to, &to_name, &s.host_name, &me_id(s))?;
|
||||||
|
sent.store(meta.len(), Ordering::Relaxed);
|
||||||
|
kick();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let id = ask(s, true, "new", "POST", &[], json!({"name": name, "bytes": meta.len(), "to": to}).to_string().as_bytes())?["id"].as_str().unwrap_or("").to_string();
|
||||||
|
let run = || -> Result<(), String> {
|
||||||
|
let mut f = std::fs::File::open(path).map_err(|e| format!("讀不到「{name}」:{e}"))?;
|
||||||
|
let mut at = 0u64;
|
||||||
|
let mut stuck = 0;
|
||||||
|
while at < meta.len() {
|
||||||
|
let mut buf = vec![0u8; (CHUNK as u64).min(meta.len() - at) as usize];
|
||||||
|
f.seek(SeekFrom::Start(at)).and_then(|_| f.read_exact(&mut buf)).map_err(|e| format!("讀不到「{name}」:{e}"))?;
|
||||||
|
match ask(s, true, "chunk", "POST", &[("id", id.clone()), ("at", at.to_string())], &buf) {
|
||||||
|
Ok(v) => {
|
||||||
|
let have = v["have"].as_u64().unwrap_or(at);
|
||||||
|
stuck = if have > at { 0 } else { stuck + 1 };
|
||||||
|
at = have;
|
||||||
|
}
|
||||||
|
// A link that hiccups: a few more tries from where the brain says it is.
|
||||||
|
Err(e) if only_for_now(&e) && stuck < 5 => {
|
||||||
|
stuck += 1;
|
||||||
|
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
if stuck >= 6 {
|
||||||
|
return Err("傳不過去:大腦一直沒有收下".into());
|
||||||
|
}
|
||||||
|
sent.store(at, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
ask(s, true, "done", "POST", &[], json!({"id": id}).to_string().as_bytes()).map(|_| ())
|
||||||
|
};
|
||||||
|
run().inspect_err(|_| {
|
||||||
|
let _ = ask(s, true, "remove", "POST", &[], json!({"id": id}).to_string().as_bytes());
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a few words from this computer.
|
||||||
|
pub fn send_text(s: &crate::remote::Settings, mirror: bool, text: &str, to: &str) -> Result<(), String> {
|
||||||
|
ask(s, mirror, "new", "POST", &[], json!({"text": text, "to": to}).to_string().as_bytes()).map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn scratch(name: &str) -> (Office, PathBuf) {
|
||||||
|
let root = std::env::temp_dir().join(format!("anybot-drops-{name}-{}", crate::httpd::random_hex(4)));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
(Office::at(root.join("data"), root.join("land")), root)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upload(o: &Office, name: &str, body: &[u8], to: &str, piece: usize) -> String {
|
||||||
|
let id = o.begin(name, body.len() as u64, "", to, "那台", "筆電", "laptop").unwrap();
|
||||||
|
let mut at = 0;
|
||||||
|
for c in body.chunks(piece) {
|
||||||
|
at = o.chunk(&id, at, c).unwrap();
|
||||||
|
}
|
||||||
|
o.finish(&id).unwrap();
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole road: a screen uploads in pieces, the brain pushes to another computer, the
|
||||||
|
/// link breaks half-way and goes on from where it was, and the file lands whole.
|
||||||
|
#[test]
|
||||||
|
fn a_file_goes_from_one_computer_to_another_through_a_bad_link() {
|
||||||
|
let (brain, r1) = scratch("brain");
|
||||||
|
let (mini, r2) = scratch("mini");
|
||||||
|
let body: Vec<u8> = (0..(CHUNK * 2 + 12_345)).map(|i| (i % 251) as u8).collect();
|
||||||
|
let id = upload(&brain, "../../報告.pdf", &body, "mini", 700_000);
|
||||||
|
// A piece that isn't the next one changes nothing.
|
||||||
|
assert!(brain.chunk(&id, 0, b"x").is_err(), "an upload that is finished takes no more");
|
||||||
|
let calls = std::cell::Cell::new(0);
|
||||||
|
let carry = |host: &str, args: &str, _who: &str| -> Result<Value, String> {
|
||||||
|
assert_eq!(host, "mini");
|
||||||
|
calls.set(calls.get() + 1);
|
||||||
|
// The third call never arrives.
|
||||||
|
if calls.get() == 3 {
|
||||||
|
return Err("目前離線".into());
|
||||||
|
}
|
||||||
|
Ok(mini.take(&crate::tools::args_of(args)))
|
||||||
|
};
|
||||||
|
brain.deliver("brain", &carry, &|_| panic!("not for the phone"));
|
||||||
|
let p = brain.get(&id).unwrap();
|
||||||
|
assert_eq!((p.state.as_str(), p.note.as_str()), ("waiting", "目前離線"), "off for now: it waits, it didn't fail");
|
||||||
|
assert!(mini.received().is_empty());
|
||||||
|
// Not before its time.
|
||||||
|
brain.deliver("brain", &carry, &|_| {});
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "waiting");
|
||||||
|
brain.set(&id, |p| p.next_try = 0);
|
||||||
|
brain.deliver("brain", &carry, &|_| {});
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "done");
|
||||||
|
let got = mini.received();
|
||||||
|
assert_eq!(got.len(), 1);
|
||||||
|
assert_eq!(got[0].name, "報告.pdf", "no path comes along with the name");
|
||||||
|
assert_eq!(std::fs::read(&got[0].path).unwrap(), body);
|
||||||
|
assert!(Path::new(&got[0].path).starts_with(r2.join("land")));
|
||||||
|
assert!(!brain.bin(&id).exists(), "delivered: the brain keeps no copy");
|
||||||
|
// The second half was sent once (probe + 2 pieces, the second lost; probe again + 2 pieces).
|
||||||
|
assert_eq!(calls.get(), 6);
|
||||||
|
// The same parcel pushed again (a lost "got it") isn't a second file.
|
||||||
|
assert_eq!(mini.take(&json!({"id": id, "name": "報告.pdf", "bytes": body.len(), "probe": true}))["done"], true);
|
||||||
|
// A second file of the same name sits beside the first.
|
||||||
|
let id2 = upload(&brain, "報告.pdf", b"another", "mini", 100);
|
||||||
|
brain.deliver("brain", &carry, &|_| {});
|
||||||
|
assert_eq!(brain.get(&id2).unwrap().state, "done");
|
||||||
|
assert_eq!(mini.received()[0].name, "報告 (2).pdf");
|
||||||
|
assert_eq!(mini.take_fresh().len(), 2);
|
||||||
|
let _ = std::fs::remove_dir_all(r1);
|
||||||
|
let _ = std::fs::remove_dir_all(r2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// To the phone a parcel waits at the brain and is read in pieces; to the brain's own
|
||||||
|
/// computer it is simply moved; words arrive as words.
|
||||||
|
#[test]
|
||||||
|
fn the_phone_downloads_and_the_brain_keeps_its_own() {
|
||||||
|
let (brain, root) = scratch("phone");
|
||||||
|
let body = vec![7u8; 5000];
|
||||||
|
let id = upload(&brain, "照片.jpg", &body, PHONE, 2048);
|
||||||
|
assert!(brain.read(&id, 0, 100).is_err(), "not before it is ready");
|
||||||
|
let told = std::cell::Cell::new(0);
|
||||||
|
let nobody = |_: &str, _: &str, _: &str| -> Result<Value, String> { panic!("no computer involved") };
|
||||||
|
brain.deliver("brain", &nobody, &|_| told.set(told.get() + 1));
|
||||||
|
assert_eq!((brain.get(&id).unwrap().state.as_str(), told.get()), ("ready", 1));
|
||||||
|
let mut got = brain.read(&id, 0, 3000).unwrap();
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "ready", "half read is not done");
|
||||||
|
got.extend(brain.read(&id, 3000, 3000).unwrap());
|
||||||
|
assert_eq!(got, body);
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "done");
|
||||||
|
assert!(brain.read(&id, 0, 10).is_ok(), "it can be downloaded again while it is kept");
|
||||||
|
// Told once, not at every round.
|
||||||
|
brain.deliver("brain", &nobody, &|_| told.set(told.get() + 1));
|
||||||
|
assert_eq!(told.get(), 1);
|
||||||
|
|
||||||
|
// From the phone to the brain's own computer.
|
||||||
|
let id = brain.begin("筆記.txt", 3, "", "brain", "大腦", "手機", PHONE).unwrap();
|
||||||
|
brain.chunk(&id, 0, b"abc").unwrap();
|
||||||
|
assert!(brain.finish(&id).is_ok());
|
||||||
|
brain.deliver("brain", &nobody, &|_| {});
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "done");
|
||||||
|
assert_eq!(std::fs::read(&brain.received()[0].path).unwrap(), b"abc");
|
||||||
|
|
||||||
|
// Words.
|
||||||
|
let id = brain.begin("", 0, " https://example.com/很長的網址\n第二行 ", "brain", "大腦", "手機", PHONE).unwrap();
|
||||||
|
brain.deliver("brain", &nobody, &|_| {});
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "done");
|
||||||
|
let r = &brain.received()[0];
|
||||||
|
assert_eq!((r.text.as_str(), r.name.as_str(), r.path.as_str()), ("https://example.com/很長的網址\n第二行", "https://example.com/很長的網址", ""));
|
||||||
|
|
||||||
|
// What can't be sent says why.
|
||||||
|
assert!(brain.begin("a", 1, "", "", "", "手機", PHONE).is_err());
|
||||||
|
assert!(brain.begin("a", 1, "", PHONE, "手機", "手機", PHONE).unwrap_err().contains("另一台"));
|
||||||
|
assert!(brain.begin("a", 0, "", "brain", "大腦", "手機", PHONE).unwrap_err().contains("空的"));
|
||||||
|
assert!(brain.begin("a", MAX_BYTES + 1, "", "brain", "大腦", "手機", PHONE).unwrap_err().contains("太大"));
|
||||||
|
// An upload that stops short isn't finished, and more than promised is refused.
|
||||||
|
let id = brain.begin("a.bin", 10, "", "brain", "大腦", "手機", PHONE).unwrap();
|
||||||
|
assert_eq!(brain.chunk(&id, 0, b"12345").unwrap(), 5);
|
||||||
|
assert_eq!(brain.chunk(&id, 0, b"12345").unwrap(), 5, "the same piece twice is taken once");
|
||||||
|
assert!(brain.finish(&id).unwrap_err().contains("還沒傳完"));
|
||||||
|
assert!(brain.chunk(&id, 5, b"1234567").is_err());
|
||||||
|
brain.remove(&id);
|
||||||
|
assert!(brain.get(&id).is_none() && !brain.bin(&id).exists());
|
||||||
|
// Kept 7 days.
|
||||||
|
let n = brain.list().len();
|
||||||
|
brain.prune(now_ms() + KEEP_MS + 1000);
|
||||||
|
assert!(n > 0 && brain.list().is_empty());
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real send from a screen, through a running account server and brain (the road the
|
||||||
|
/// window uses: `/api/sync/drop/…` in pieces):
|
||||||
|
/// ANYBOT_DROP_STATE=<a computer's state.json> ANYBOT_DROP_BRAIN=<brain host id>
|
||||||
|
/// ANYBOT_DROP_TO=<host id | phone> ANYBOT_DROP_FILE=<file> cargo test live_send -- --ignored --nocapture
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn live_send_from_a_screen() {
|
||||||
|
let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("{k}"));
|
||||||
|
let st: Value = serde_json::from_slice(&std::fs::read(env("ANYBOT_DROP_STATE")).unwrap()).unwrap();
|
||||||
|
let mut s: crate::remote::Settings = serde_json::from_value(st["remote"].clone()).unwrap();
|
||||||
|
s.brain_id = env("ANYBOT_DROP_BRAIN");
|
||||||
|
let to = env("ANYBOT_DROP_TO");
|
||||||
|
let t = ask(&s, true, "targets", "GET", &[], &[]).unwrap();
|
||||||
|
println!("targets: {}", t["targets"]);
|
||||||
|
let sent = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
let file = PathBuf::from(env("ANYBOT_DROP_FILE"));
|
||||||
|
let t0 = std::time::Instant::now();
|
||||||
|
send_file(&s, true, &file, &to, &sent).unwrap();
|
||||||
|
println!("handed over {} bytes in {:.2}s", sent.load(std::sync::atomic::Ordering::Relaxed), t0.elapsed().as_secs_f64());
|
||||||
|
send_text(&s, true, "從螢幕傳的一段字", &to).unwrap();
|
||||||
|
for _ in 0..80 {
|
||||||
|
let l = ask(&s, true, "list", "GET", &[], &[]).unwrap();
|
||||||
|
let mine: Vec<&Value> = l["items"].as_array().unwrap().iter().filter(|p| p["from_id"] == s.host_id.as_str() && p["to"] == to.as_str()).take(2).collect();
|
||||||
|
if mine.len() == 2 && mine.iter().all(|p| matches!(p["state"].as_str(), Some("done" | "ready" | "failed"))) {
|
||||||
|
for p in mine {
|
||||||
|
println!("{} → {}: {} {}", p["name"], p["to_name"], p["state"], p["note"]);
|
||||||
|
assert_ne!(p["state"], "failed");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
panic!("not delivered in 20 s");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a computer refuses from a brain, and a refusal that is a "no" (not "later").
|
||||||
|
#[test]
|
||||||
|
fn a_computer_takes_only_what_is_sound() {
|
||||||
|
let (mini, root) = scratch("sound");
|
||||||
|
let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b);
|
||||||
|
assert_eq!(mini.take(&json!({"id": "../x", "bytes": 3, "at": 0, "data": b64(b"abc")}))["ok"], false);
|
||||||
|
assert_eq!(mini.take(&json!({"id": "a1", "bytes": 0, "at": 0, "data": b64(b"abc")}))["ok"], false);
|
||||||
|
// More than promised: refused, and nothing is left behind.
|
||||||
|
assert_eq!(mini.take(&json!({"id": "a2", "name": "x", "bytes": 2, "at": 0, "data": b64(b"abc")}))["ok"], false);
|
||||||
|
assert_eq!(mini.take(&json!({"id": "a2", "bytes": 2, "probe": true}))["have"], 0);
|
||||||
|
// A piece out of place says how much is here.
|
||||||
|
assert_eq!(mini.take(&json!({"id": "a3", "name": ".ssh/../.zshrc", "bytes": 6, "at": 0, "data": b64(b"abc")}))["have"], 3);
|
||||||
|
let v = mini.take(&json!({"id": "a3", "bytes": 6, "at": 0, "data": b64(b"abc")}));
|
||||||
|
assert_eq!((v["ok"].as_bool(), v["have"].as_u64()), (Some(false), Some(3)));
|
||||||
|
assert_eq!(mini.take(&json!({"id": "a3", "name": ".ssh/../.zshrc", "bytes": 6, "at": 3, "data": b64(b"def")}))["done"], true);
|
||||||
|
let r = &mini.received()[0];
|
||||||
|
assert_eq!(r.name, "zshrc", "never a hidden file, never outside the folder");
|
||||||
|
assert!(Path::new(&r.path).starts_with(root.join("land")));
|
||||||
|
assert_eq!(safe_name("a/b\\c:d.txt"), "cd.txt");
|
||||||
|
assert_eq!(safe_name("..."), "檔案");
|
||||||
|
assert!(safe_name(&format!("{}.tar.gz", "長".repeat(300))).ends_with(".gz"));
|
||||||
|
|
||||||
|
let (brain, r2) = scratch("refused");
|
||||||
|
let id = upload(&brain, "a.txt", b"hello", "mini", 10);
|
||||||
|
brain.deliver("brain", &|_, _, _| Err("這台電腦只收它自己的大腦傳來的東西".into()), &|_| {});
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "failed");
|
||||||
|
// Tried again when the person says so.
|
||||||
|
brain.retry(&id);
|
||||||
|
brain.deliver("brain", &|_, a, _| Ok(mini.take(&crate::tools::args_of(a))), &|_| {});
|
||||||
|
assert_eq!(brain.get(&id).unwrap().state, "done");
|
||||||
|
// An older AnyBot on the other side: said in words, and tried again later.
|
||||||
|
let id = upload(&brain, "b.txt", b"hello", "mini", 10);
|
||||||
|
brain.deliver("brain", &|_, _, _| Err("那台電腦:這個工具不能遠端使用".into()), &|_| {});
|
||||||
|
let p = brain.get(&id).unwrap();
|
||||||
|
assert!(p.state == "waiting" && p.note.contains("要先更新"), "{p:?}");
|
||||||
|
// Restarted in the middle: a half upload is gone, a delivery starts again.
|
||||||
|
brain.begin("c.bin", 10, "", "mini", "那台", "筆電", "laptop").unwrap();
|
||||||
|
brain.set(&id, |p| p.state = "sending".into());
|
||||||
|
let again = Office::at(brain.dir.clone(), brain.land.clone());
|
||||||
|
let mut left: Vec<(String, String)> = again.list().into_iter().map(|p| (p.name, p.state)).collect();
|
||||||
|
left.sort();
|
||||||
|
assert_eq!(left, vec![("a.txt".to_string(), "done".to_string()), ("b.txt".to_string(), "waiting".to_string())]);
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
let _ = std::fs::remove_dir_all(r2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -648,4 +648,32 @@ pub const ROWS: &[(&str, &str, &str)] = &[
|
||||||
("讓另一台電腦當大腦的手腳:Mac、任何 Linux(含沒有螢幕的)、已登入的 Windows。貼上對應的那一行就會裝好並完成第一次配對,不用帳號密碼。它會在開機或登入後自動執行,只讓這個大腦使用。", "Make another computer this brain's hands: Mac, any Linux (including headless), or a signed-in Windows PC. Paste the matching line — it installs AnyBot if needed, pairs once, and starts at login. No password. Only this brain can use it.", "別のコンピューターをこのブレインの手にする:Mac、任意の Linux(画面なしも)、ログイン中の Windows。対応する行を貼るとインストールと初回ペアリングまで終わり、ログイン時に起動します。パスワード不要。このブレインだけが使えます。"),
|
("讓另一台電腦當大腦的手腳:Mac、任何 Linux(含沒有螢幕的)、已登入的 Windows。貼上對應的那一行就會裝好並完成第一次配對,不用帳號密碼。它會在開機或登入後自動執行,只讓這個大腦使用。", "Make another computer this brain's hands: Mac, any Linux (including headless), or a signed-in Windows PC. Paste the matching line — it installs AnyBot if needed, pairs once, and starts at login. No password. Only this brain can use it.", "別のコンピューターをこのブレインの手にする:Mac、任意の Linux(画面なしも)、ログイン中の Windows。対応する行を貼るとインストールと初回ペアリングまで終わり、ログイン時に起動します。パスワード不要。このブレインだけが使えます。"),
|
||||||
("已複製。Mac 和 Linux 貼終端機那一行,Windows 貼 PowerShell 那一行", "Copied. Paste the terminal line on Mac or Linux, the PowerShell line on Windows", "コピーしました。Mac と Linux はターミナルの行、Windows は PowerShell の行を貼ってください"),
|
("已複製。Mac 和 Linux 貼終端機那一行,Windows 貼 PowerShell 那一行", "Copied. Paste the terminal line on Mac or Linux, the PowerShell line on Windows", "コピーしました。Mac と Linux はターミナルの行、Windows は PowerShell の行を貼ってください"),
|
||||||
("在那台電腦貼上對應的那一行", "Paste the matching line on that computer", "そのコンピューターに対応する行を貼る"),
|
("在那台電腦貼上對應的那一行", "Paste the matching line on that computer", "そのコンピューターに対応する行を貼る"),
|
||||||
|
// 傳送到其他裝置 (drops_ui.rs).
|
||||||
|
("傳送到其他裝置", "Send to another device", "ほかのデバイスに送る"),
|
||||||
|
("傳送檔案或文字到其他裝置", "Send files or text to another device", "ファイルやテキストをほかのデバイスに送る"),
|
||||||
|
("傳到", "Send to", "送り先"),
|
||||||
|
("正在找帳號裡的裝置…", "Looking for the account's devices…", "アカウントのデバイスを探しています…"),
|
||||||
|
("帳號裡還沒有其他裝置。", "The account has no other devices yet.", "アカウントにほかのデバイスがまだありません。"),
|
||||||
|
("還沒登入帳號:現在只能和直接連到這台的手機互傳。登入帳號後,帳號裡每一台都能互傳(設定 › 一般 › 手機與帳號)。", "Not signed in to an account: for now only a phone connected directly to this computer can exchange with it. After signing in, every device of the account can (Settings › General › Phone & account).", "アカウント未ログイン:今はこのコンピュータに直接つないだスマホとだけ送り合えます。ログインするとアカウントの全デバイスで送り合えます(設定 › 一般 › スマホとアカウント)。"),
|
||||||
|
("離線", "offline", "オフライン"),
|
||||||
|
("現在沒開:先交給大腦,它一上線就會收到(保留 7 天)", "Off right now: the brain keeps it and delivers when it comes online (kept 7 days)", "現在オフ:ブレインが預かり、オンラインになったら届けます(7 日間保管)"),
|
||||||
|
("把檔案拖到這裡", "Drop files here", "ここにファイルをドロップ"),
|
||||||
|
("放開就傳送", "Release to send", "離すと送信"),
|
||||||
|
("選擇檔案…", "Choose files…", "ファイルを選ぶ…"),
|
||||||
|
("或貼上一段文字、網址(對方收到就在剪貼簿裡)", "Or paste text or a link (it lands on the other clipboard)", "またはテキストや URL を貼り付け(相手のクリップボードに入ります)"),
|
||||||
|
("傳送", "Send", "送信"),
|
||||||
|
("先選要傳到哪一台", "Choose where to send it first", "先に送り先を選んでください"),
|
||||||
|
("一段文字", "Some text", "テキスト"),
|
||||||
|
("最近 7 天", "Last 7 days", "直近 7 日間"),
|
||||||
|
("再試一次", "Try again", "もう一度"),
|
||||||
|
("顯示", "Show", "表示"),
|
||||||
|
("正在交給大腦", "Handing to the brain", "ブレインに渡しています"),
|
||||||
|
("等", "Waiting for", "待機中:"),
|
||||||
|
("開機上線,會自動送達", "to come online; it will be delivered automatically", "がオンラインになると自動で届きます"),
|
||||||
|
("傳送中", "Sending", "送信中"),
|
||||||
|
("在手機的「傳送」裡可以拿(保留 7 天)", "Available in the phone's Send sheet (kept 7 days)", "スマホの「送る」で受け取れます(7 日間保管)"),
|
||||||
|
("已送達", "Delivered", "届きました"),
|
||||||
|
("手機已下載", "Downloaded on the phone", "スマホでダウンロード済み"),
|
||||||
|
("沒有送達", "Not delivered", "届きませんでした"),
|
||||||
|
("不知道原因", "unknown reason", "原因不明"),
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -60,6 +60,7 @@ mod triggers;
|
||||||
mod embed;
|
mod embed;
|
||||||
mod store;
|
mod store;
|
||||||
mod docindex;
|
mod docindex;
|
||||||
|
mod drops;
|
||||||
mod vault;
|
mod vault;
|
||||||
mod vault_store;
|
mod vault_store;
|
||||||
mod vnc;
|
mod vnc;
|
||||||
|
|
|
||||||
|
|
@ -228,6 +228,12 @@ impl Hub {
|
||||||
r();
|
r();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// Something changed that the window shows (a file arrived): draw again.
|
||||||
|
pub fn repaint_now(&self) {
|
||||||
|
if let Some(r) = self.repaint.lock().unwrap().as_ref() {
|
||||||
|
r();
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn set_repaint(&self, f: Arc<dyn Fn() + Send + Sync>) {
|
pub fn set_repaint(&self, f: Arc<dyn Fn() + Send + Sync>) {
|
||||||
*self.repaint.lock().unwrap() = Some(f);
|
*self.repaint.lock().unwrap() = Some(f);
|
||||||
}
|
}
|
||||||
|
|
@ -477,6 +483,31 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
|
||||||
None => phone_act("memory", b, "owner"),
|
None => phone_act("memory", b, "owner"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 傳送: a file or words from this device to another of the account (drops.rs). The
|
||||||
|
// owner's phone, or one of the owner's computers showing this brain.
|
||||||
|
(m, ["api", "drop", what] | ["api", "sync", "drop", what]) => {
|
||||||
|
if role != "owner" && role != "mirror" {
|
||||||
|
return Resp::error(403, "只有擁有者能在裝置之間傳送");
|
||||||
|
}
|
||||||
|
let (from, from_id) = if role == "mirror" {
|
||||||
|
let id = req.header("x-anybot-from").to_string();
|
||||||
|
let name = peer_name(&id);
|
||||||
|
(if name.is_empty() { "另一台電腦".to_string() } else { name }, id)
|
||||||
|
} else {
|
||||||
|
("手機".to_string(), crate::drops::PHONE.to_string())
|
||||||
|
};
|
||||||
|
if (m, *what) == ("GET", "file") {
|
||||||
|
let n = |k: &str| req.query.get(k).and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
|
||||||
|
return match crate::drops::office().read(req.query.get("id").map(String::as_str).unwrap_or(""), n("at"), n("len")) {
|
||||||
|
Ok(b) => Resp::bytes("application/octet-stream", b),
|
||||||
|
Err(e) => Resp::error(404, &e),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
match crate::drops::api(what, m, &req.query, &req.body, &from, &from_id) {
|
||||||
|
Ok(v) => Resp::json(&v),
|
||||||
|
Err(e) => Resp::error(400, &e),
|
||||||
|
}
|
||||||
|
}
|
||||||
("POST", ["api", "bots", id, action]) => {
|
("POST", ["api", "bots", id, action]) => {
|
||||||
let bot: u64 = id.parse().unwrap_or(0);
|
let bot: u64 = id.parse().unwrap_or(0);
|
||||||
let b = req.json();
|
let b = req.json();
|
||||||
|
|
@ -812,6 +843,17 @@ fn screen_input(which: &str, v: &Value, s: &Settings) -> Resp {
|
||||||
/// 裝置連結: another AnyBot in this account (e.g. the one on the server) runs a screen tool on
|
/// 裝置連結: another AnyBot in this account (e.g. the one on the server) runs a screen tool on
|
||||||
/// this Mac. Only through the relay, and only when this Mac allows it.
|
/// this Mac. Only through the relay, and only when this Mac allows it.
|
||||||
fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp {
|
fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp {
|
||||||
|
// 傳送: a file or words the person sent to this computer, pushed by its brain. Not an
|
||||||
|
// operation on this computer (it only lands in 下載/AnyBot), so it doesn't need 裝置連結 —
|
||||||
|
// but it is taken only from this computer's own brain.
|
||||||
|
if v["tool"] == crate::drops::PUT {
|
||||||
|
let brain = if s.brain_id.is_empty() { &s.hands_for } else { &s.brain_id };
|
||||||
|
let known = if brain.is_empty() { s.device_link } else { from == brain };
|
||||||
|
if !via_relay || !known {
|
||||||
|
return Resp::error(403, "這台電腦只收它自己的大腦傳來的東西");
|
||||||
|
}
|
||||||
|
return Resp::json(&crate::drops::take_here(v["args"].as_str().unwrap_or("{}")));
|
||||||
|
}
|
||||||
if !via_relay || !s.device_link {
|
if !via_relay || !s.device_link {
|
||||||
return Resp::error(403, "這台電腦沒有開放給帳號裡的其他 AnyBot 操作");
|
return Resp::error(403, "這台電腦沒有開放給帳號裡的其他 AnyBot 操作");
|
||||||
}
|
}
|
||||||
|
|
@ -1444,7 +1486,7 @@ fn answer_value(st: u16, bytes: &[u8], whom: &str) -> Result<Value, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ask the brain: over the lasting connection when it is open, else an ordinary request.
|
/// Ask the brain: over the lasting connection when it is open, else an ordinary request.
|
||||||
fn to_brain(s: &Settings, method: &str, rest: &str, query: &[(&str, String)], body: &[u8], secs: u64) -> Result<Value, String> {
|
pub(crate) fn to_brain(s: &Settings, method: &str, rest: &str, query: &[(&str, String)], body: &[u8], secs: u64) -> Result<Value, String> {
|
||||||
let (st, bytes) = to_brain_raw(s, method, rest, query, body, secs)?;
|
let (st, bytes) = to_brain_raw(s, method, rest, query, body, secs)?;
|
||||||
answer_value(st, &bytes, "大腦")
|
answer_value(st, &bytes, "大腦")
|
||||||
}
|
}
|
||||||
|
|
@ -1809,6 +1851,27 @@ mod tests {
|
||||||
Req { method: "POST".into(), path: path.into(), query, headers, body: body.to_vec(), peer: String::new() }
|
Req { method: "POST".into(), path: path.into(), query, headers, body: body.to_vec(), peer: String::new() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 傳送 is the owner's: a team member or an admin can't send through this brain, and a
|
||||||
|
/// computer takes parcels only from its own brain.
|
||||||
|
#[test]
|
||||||
|
fn sending_between_devices_is_the_owners_and_the_brains() {
|
||||||
|
for role in ["admin", "member", "device"] {
|
||||||
|
let r = handle(voice_req("/api/drop/new", role, br#"{"text":"x","to":"phone"}"#), true);
|
||||||
|
assert_eq!(r.status, 403, "{role}");
|
||||||
|
}
|
||||||
|
assert_eq!(handle(voice_req("/api/sync/drop/new", "owner", b"{}"), true).status, 403, "the screens' road isn't the phone's");
|
||||||
|
let put = json!({"tool": crate::drops::PUT, "args": "{}"});
|
||||||
|
let code = |s: &Settings, via_relay: bool, from: &str| device_run(&put, s, via_relay, from).status;
|
||||||
|
// A screen of brain "b", a pair of hands for "b".
|
||||||
|
let screen = Settings { brain_id: "b".into(), ..Default::default() };
|
||||||
|
let hands = Settings { hands_for: "b".into(), device_link: true, ..Default::default() };
|
||||||
|
assert_eq!(code(&screen, true, "other"), 403);
|
||||||
|
assert_eq!(code(&hands, true, "other"), 403);
|
||||||
|
assert_eq!(code(&screen, false, "b"), 403, "only through the account server, which says who asks");
|
||||||
|
// A computer with no brain of its own and 裝置連結 off takes nothing.
|
||||||
|
assert_eq!(code(&Settings::default(), true, "b"), 403);
|
||||||
|
}
|
||||||
|
|
||||||
/// The phone's and the screens' recordings go through the brain's 設定 › 語音.
|
/// The phone's and the screens' recordings go through the brain's 設定 › 語音.
|
||||||
#[test]
|
#[test]
|
||||||
fn the_brain_hears_for_the_phone_and_the_screens() {
|
fn the_brain_hears_for_the_phone_and_the_screens() {
|
||||||
|
|
|
||||||
|
|
@ -83,6 +83,7 @@ pub fn label(name: &str) -> &'static str {
|
||||||
"write_terminal" => "輸入到背景指令",
|
"write_terminal" => "輸入到背景指令",
|
||||||
"open_for_person" => "打開給你看",
|
"open_for_person" => "打開給你看",
|
||||||
"send_file" => "傳檔案給你",
|
"send_file" => "傳檔案給你",
|
||||||
|
"send_to_device" => "傳到你的另一台裝置",
|
||||||
"react" => "按表情",
|
"react" => "按表情",
|
||||||
"view_demo_step" => "看示範",
|
"view_demo_step" => "看示範",
|
||||||
"publish_site" => "發布網站",
|
"publish_site" => "發布網站",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue