From 4430045550b936eb7f1068c9c0e262c5430b4554 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?lollipopkit=F0=9F=8F=B3=EF=B8=8F=E2=80=8D=E2=9A=A7?= =?UTF-8?q?=EF=B8=8F?= <10864310+lollipopkit@users.noreply.github.com> Date: Wed, 3 Jul 2024 19:14:27 +0800 Subject: [PATCH] feat: write script into `/dev/shm` (#444) Fixes #443 --- lib/data/model/app/shell_func.dart | 27 ++++---------- lib/data/provider/server.dart | 8 +++-- lib/l10n/app_de.arb | 3 +- lib/l10n/app_en.arb | 3 +- lib/l10n/app_es.arb | 3 +- lib/l10n/app_fr.arb | 3 +- lib/l10n/app_id.arb | 3 +- lib/l10n/app_ja.arb | 3 +- lib/l10n/app_nl.arb | 3 +- lib/l10n/app_pt.arb | 3 +- lib/l10n/app_ru.arb | 3 +- lib/l10n/app_zh.arb | 3 +- lib/l10n/app_zh_tw.arb | 3 +- lib/view/page/server/edit.dart | 56 +++++++----------------------- lib/view/page/setting/entry.dart | 2 +- lib/view/page/snippet/edit.dart | 1 + pubspec.lock | 4 +-- pubspec.yaml | 2 +- 18 files changed, 41 insertions(+), 92 deletions(-) diff --git a/lib/data/model/app/shell_func.dart b/lib/data/model/app/shell_func.dart index 67638a52..9efb383c 100644 --- a/lib/data/model/app/shell_func.dart +++ b/lib/data/model/app/shell_func.dart @@ -12,32 +12,17 @@ enum ShellFunc { suspend, ; - static const _homeVar = '\$HOME'; static const seperator = 'SrvBoxSep'; /// The suffix `\t` is for formatting static const cmdDivider = '\necho $seperator\n\t'; - static const _srvBoxDir = '.config/server_box'; - static const scriptFile = 'mobile_v${BuildData.script}.sh'; - /// Issue #159 - /// - /// Use script commit count as version of shell script. - /// - /// So different version of app can run at the same time. - /// - /// **Can't** use it in SFTP, because SFTP can't recognize `$HOME` - static String getShellPath(String home) => '$home/$_srvBoxDir/$scriptFile'; - - static const srvBoxDir = '$_homeVar/$_srvBoxDir'; - static const _installShellPath = '$_homeVar/$_srvBoxDir/$scriptFile'; - - // Issue #299, chmod ~/.config to avoid permission issue + /// srvboxm -> ServerBox Mobile + static const scriptFile = 'srvboxm_v${BuildData.script}.sh'; + static const scriptPath = '/dev/shm/$scriptFile'; static const installShellCmd = """ -chmod +x ~/.config &> /dev/null -mkdir -p $_homeVar/$_srvBoxDir -cat > $_installShellPath -chmod +x $_installShellPath +cat > $scriptPath +chmod +x $scriptPath """; String get flag { @@ -57,7 +42,7 @@ chmod +x $_installShellPath } } - String get exec => 'sh $_installShellPath -$flag'; + String get exec => 'sh $scriptPath -$flag'; String get name { switch (this) { diff --git a/lib/data/provider/server.dart b/lib/data/provider/server.dart index c4163277..85714f88 100644 --- a/lib/data/provider/server.dart +++ b/lib/data/provider/server.dart @@ -347,9 +347,13 @@ class ServerProvider extends ChangeNotifier { if (homePath == null || homePath.isEmpty) { throw Exception('Got empty home path'); } - final remotePath = ShellFunc.getShellPath(homePath); final reqId = Pros.sftp.add( - SftpReq(spi, remotePath, localPath, SftpReqType.upload), + SftpReq( + spi, + ShellFunc.scriptPath, + localPath, + SftpReqType.upload, + ), completer: completer, ); await completer.future; diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 64df9538..8a7f5cd6 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -25,7 +25,6 @@ "backupTip": "Das Backup wird nur einfach verschlüsselt.\nBitte bewahre die Datei sicher auf.", "backupVersionNotMatch": "Die Backup-Version stimmt nicht überein.", "battery": "Batterie", - "beforeConnect": "ServerBox wird nach der Verbindung ein Skript in `~/.config/server_box` schreiben und ausführen. Für weitere technische Details besuchen Sie bitte [Github]({url}).", "bgRun": "Hintergrundaktualisierung", "bgRunTip": "Dieser Schalter bedeutet nur, dass die App versuchen wird, im Hintergrund zu laufen. Ob sie im Hintergrund laufen kann, hängt davon ab, ob die Berechtigungen aktiviert sind oder nicht. Bei nativem Android deaktivieren Sie bitte \"Batterieoptimierung\" in dieser App, und bei miui ändern Sie bitte die Energiesparrichtlinie auf \"Unbegrenzt\".", "bioAuth": "Biozertifizierung", @@ -340,4 +339,4 @@ "wolTip": "Nach der Konfiguration von WOL (Wake-on-LAN) wird jedes Mal, wenn der Server verbunden wird, eine WOL-Anfrage gesendet.", "write": "Schreiben", "writeScriptFailTip": "Das Schreiben des Skripts ist fehlgeschlagen, möglicherweise aufgrund fehlender Berechtigungen oder das Verzeichnis existiert nicht." -} +} \ No newline at end of file diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 0f5157ed..00d66caf 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -25,7 +25,6 @@ "backupTip": "The exported data is weakly encrypted. \nPlease keep it safe.", "backupVersionNotMatch": "Backup version is not match.", "battery": "Battery", - "beforeConnect": "ServerBox will write and execute a script in `~/.config/server_box` after connection. For more technical details, please visit [Github]({url}).", "bgRun": "Run in background", "bgRunTip": "This switch only means the program will try to run in the background. Whether it can run in the background depends on whether the permission is enabled or not. For AOSP-based Android ROMs, please disable \"Battery Optimization\" in this app. For MIUI / HyperOS, please change the power saving policy to \"Unlimited\".", "bioAuth": "Biometric auth", @@ -340,4 +339,4 @@ "wolTip": "After configuring WOL (Wake-on-LAN), a WOL request is sent each time the server is connected.", "write": "Write", "writeScriptFailTip": "Writing to the script failed, possibly due to lack of permissions or the directory does not exist." -} +} \ No newline at end of file diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 547cb0fa..e1b39568 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -25,7 +25,6 @@ "backupTip": "Los datos exportados solo están encriptados de manera básica, por favor guárdalos en un lugar seguro.", "backupVersionNotMatch": "La versión de la copia de seguridad no coincide, no se puede restaurar", "battery": "Batería", - "beforeConnect": "ServerBox escribirá y ejecutará un script en `~/.config/server_box` después de la conexión. Para más detalles técnicos, por favor visite [Github]({url}).", "bgRun": "Ejecución en segundo plano", "bgRunTip": "Este interruptor solo indica que la aplicación intentará correr en segundo plano, si puede hacerlo o no depende de si tiene el permiso correspondiente. En Android puro, por favor desactiva la “optimización de batería” para esta app, en MIUI por favor cambia la estrategia de ahorro de energía a “Sin restricciones”.", "bioAuth": "Autenticación biométrica", @@ -340,4 +339,4 @@ "wolTip": "Después de configurar WOL (Wake-on-LAN), se envía una solicitud de WOL cada vez que se conecta el servidor.", "write": "Escribir", "writeScriptFailTip": "La escritura en el script falló, posiblemente por falta de permisos o porque el directorio no existe." -} +} \ No newline at end of file diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 6a44df56..d6571e67 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -25,7 +25,6 @@ "backupTip": "Les données exportées sont simplement chiffrées. \nVeuillez les garder en sécurité.", "backupVersionNotMatch": "La version de sauvegarde ne correspond pas.", "battery": "Batterie", - "beforeConnect": "ServerBox écrira et exécutera un script dans `~/.config/server_box` après la connexion. Pour plus de détails techniques, veuillez visiter [Github]({url}).", "bgRun": "Exécution en arrière-plan", "bgRunTip": "Cette option signifie seulement que le programme essaiera de s'exécuter en arrière-plan, que cela soit possible dépend de l'autorisation activée ou non. Pour Android natif, veuillez désactiver l'« Optimisation de la batterie » dans cette application, et pour MIUI, veuillez changer la politique d'économie d'énergie en « Illimité ».", "bioAuth": "Authentification biométrique", @@ -340,4 +339,4 @@ "wolTip": "Après avoir configuré le WOL (Wake-on-LAN), une requête WOL est envoyée chaque fois que le serveur est connecté.", "write": "Écrire", "writeScriptFailTip": "Échec de l'écriture dans le script, probablement en raison d'un manque de permissions ou que le répertoire n'existe pas." -} +} \ No newline at end of file diff --git a/lib/l10n/app_id.arb b/lib/l10n/app_id.arb index 2b07d2b3..5925eb1e 100644 --- a/lib/l10n/app_id.arb +++ b/lib/l10n/app_id.arb @@ -25,7 +25,6 @@ "backupTip": "Data yang diekspor hanya dienkripsi.\nTolong jaga keamanannya.", "backupVersionNotMatch": "Versi cadangan tidak cocok.", "battery": "Baterai", - "beforeConnect": "ServerBox akan menulis dan menjalankan skrip di `~/.config/server_box` setelah koneksi. Untuk detail teknis lebih lanjut, silakan kunjungi [Github]({url}).", "bgRun": "Jalankan di Backgroud", "bgRunTip": "Sakelar ini hanya berarti aplikasi akan mencoba berjalan di latar belakang, apakah aplikasi dapat berjalan di latar belakang tergantung pada apakah izin diaktifkan atau tidak. Untuk Android asli, nonaktifkan \"Pengoptimalan Baterai\" di aplikasi ini, dan untuk miui, ubah kebijakan penghematan daya ke \"Tidak Terbatas\".", "bioAuth": "Biosertifikasi", @@ -340,4 +339,4 @@ "wolTip": "Setelah mengonfigurasi WOL (Wake-on-LAN), permintaan WOL dikirim setiap kali server terhubung.", "write": "Tulis", "writeScriptFailTip": "Penulisan ke skrip gagal, mungkin karena tidak ada izin atau direktori tidak ada." -} +} \ No newline at end of file diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index ee0198dd..217fa225 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -25,7 +25,6 @@ "backupTip": "エクスポートされたデータは簡単に暗号化されています。適切に保管してください。", "backupVersionNotMatch": "バックアップバージョンが一致しないため、復元できません", "battery": "バッテリー", - "beforeConnect": "ServerBoxは接続後に`~/.config/server_box`にスクリプトを書き込み実行します。詳細な技術情報については[Github]({url})をご覧ください。", "bgRun": "バックグラウンド実行", "bgRunTip": "このスイッチはプログラムがバックグラウンドで実行を試みることを意味しますが、実際にバックグラウンドで実行できるかどうかは、権限が有効になっているかに依存します。AOSPベースのAndroid ROMでは、このアプリの「バッテリー最適化」をオフにしてください。MIUIでは、省エネモードを「無制限」に変更してください。", "bioAuth": "生体認証", @@ -340,4 +339,4 @@ "wolTip": "WOL(Wake-on-LAN)を設定した後、サーバーに接続するたびにWOLリクエストが送信されます。", "write": "書き込み", "writeScriptFailTip": "スクリプトの書き込みに失敗しました。権限がないかディレクトリが存在しない可能性があります。" -} +} \ No newline at end of file diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index d995f708..ff28abe1 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -25,7 +25,6 @@ "backupTip": "De geëxporteerde gegevens zijn simpelweg versleuteld. \nBewaar deze aub veilig.", "backupVersionNotMatch": "Back-upversie komt niet overeen.", "battery": "Batterij", - "beforeConnect": "ServerBox zal na verbinding een script schrijven en uitvoeren in `~/.config/server_box`. Voor meer technische details, bezoek [Github]({url}).", "bgRun": "Uitvoeren op de achtergrond", "bgRunTip": "Deze schakelaar betekent alleen dat het programma zal proberen op de achtergrond uit te voeren, of het in de achtergrond kan worden uitgevoerd, hangt af van of de toestemming is ingeschakeld of niet. Voor native Android, schakel \"Batterijoptimalisatie\" uit in deze app, en voor miui, wijzig de energiebesparingsbeleid naar \"Onbeperkt\".", "bioAuth": "Biometrische authenticatie", @@ -340,4 +339,4 @@ "wolTip": "Na het configureren van WOL (Wake-on-LAN), wordt elke keer dat de server wordt verbonden een WOL-verzoek verzonden.", "write": "Schrijven", "writeScriptFailTip": "Het schrijven naar het script is mislukt, mogelijk door gebrek aan rechten of omdat de map niet bestaat." -} +} \ No newline at end of file diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 2e5f897b..87a5aa5f 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -25,7 +25,6 @@ "backupTip": "Os dados exportados são criptografados de forma simples, por favor, guarde-os com segurança.", "backupVersionNotMatch": "Versão de backup não compatível, não é possível restaurar", "battery": "Bateria", - "beforeConnect": "O ServerBox escreverá e executará um script em `~/.config/server_box` após a conexão. Para mais detalhes técnicos, por favor visite [Github]({url}).", "bgRun": "Execução em segundo plano", "bgRunTip": "Este interruptor indica que o programa tentará rodar em segundo plano, mas a capacidade de fazer isso depende das permissões concedidas. No Android nativo, desative a 'Otimização de bateria' para este app, no MIUI, altere a estratégia de economia de energia para 'Sem restrições'.", "bioAuth": "Autenticação biométrica", @@ -340,4 +339,4 @@ "wolTip": "Após configurar o WOL (Wake-on-LAN), um pedido de WOL é enviado cada vez que o servidor é conectado.", "write": "Escrita", "writeScriptFailTip": "Falha ao escrever no script, possivelmente devido à falta de permissões ou o diretório não existe." -} +} \ No newline at end of file diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 946a111a..7345dd68 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -25,7 +25,6 @@ "backupTip": "Экспортированные данные зашифрованы простым способом, пожалуйста, храните их в безопасности.", "backupVersionNotMatch": "Версия резервной копии не совпадает, восстановление невозможно", "battery": "батарея", - "beforeConnect": "ServerBox запишет и выполнит скрипт в `~/.config/server_box` после подключения. Для получения дополнительных технических подробностей, пожалуйста, посетите [Github]({url}).", "bgRun": "работа в фоновом режиме", "bgRunTip": "Этот переключатель означает, что программа будет пытаться работать в фоновом режиме, но фактическое выполнение зависит от того, включено ли разрешение. Для нативного Android отключите «Оптимизацию батареи» для этого приложения, для MIUI измените стратегию энергосбережения на «Без ограничений».", "bioAuth": "биометрическая аутентификация", @@ -340,4 +339,4 @@ "wolTip": "После настройки WOL (Wake-on-LAN) при каждом подключении к серверу отправляется запрос WOL.", "write": "запись", "writeScriptFailTip": "Запись в скрипт не удалась, возможно, из-за отсутствия прав или директории не существует." -} +} \ No newline at end of file diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 3dd48083..e378dd4e 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -25,7 +25,6 @@ "backupTip": "导出的数据仅进行了简单加密,请妥善保管。", "backupVersionNotMatch": "备份版本不匹配,无法恢复", "battery": "电池", - "beforeConnect": "ServerBox 将在连接后,在 `~/.config/server_box` 写入脚本并执行,更多的技术细节请访问 [Github]({url})。", "bgRun": "后台运行", "bgRunTip": "此开关只代表程序会尝试在后台运行,具体能否后台运行取决于是否开启了权限。原生 Android 请关闭本 App 的“电池优化”,MIUI / HyperOS 请修改省电策略为“无限制”。", "bioAuth": "生物认证", @@ -340,4 +339,4 @@ "wolTip": "在配置 WOL 后,每次连接服务器都会先发送一次 WOL 请求", "write": "写", "writeScriptFailTip": "写入脚本失败,可能是没有权限/目录不存在等" -} +} \ No newline at end of file diff --git a/lib/l10n/app_zh_tw.arb b/lib/l10n/app_zh_tw.arb index 60e2f3f0..be09f108 100644 --- a/lib/l10n/app_zh_tw.arb +++ b/lib/l10n/app_zh_tw.arb @@ -25,7 +25,6 @@ "backupTip": "匯出的資料僅進行了簡單加密,請妥善保管。", "backupVersionNotMatch": "備份版本不匹配,無法還原", "battery": "電池", - "beforeConnect": "連接後,ServerBox 將在 `~/.config/server_box` 中寫入腳本並執行,更多技術細節請訪問 [Github]({url})。", "bgRun": "後台運行", "bgRunTip": "此開關只代表程式會嘗試在後台運行,具體能否在後臺運行取決於是否開啟了權限。 原生 Android 請關閉本 App 的“電池優化”,MIUI / HyperOS 請修改省電策略為“無限制”。", "bioAuth": "生物認證", @@ -340,4 +339,4 @@ "wolTip": "在配置 WOL(網絡喚醒)後,每次連接伺服器都會先發送一次 WOL 請求。", "write": "写", "writeScriptFailTip": "寫入腳本失敗,可能是沒有權限/目錄不存在等。" -} +} \ No newline at end of file diff --git a/lib/view/page/server/edit.dart b/lib/view/page/server/edit.dart index 28e32f15..3e9e4c24 100644 --- a/lib/view/page/server/edit.dart +++ b/lib/view/page/server/edit.dart @@ -5,12 +5,9 @@ import 'package:flutter/material.dart'; import 'package:icons_plus/icons_plus.dart'; import 'package:provider/provider.dart'; import 'package:server_box/core/extension/context/locale.dart'; -import 'package:server_box/data/model/app/shell_func.dart'; import 'package:server_box/data/model/server/custom.dart'; import 'package:server_box/data/model/server/wol_cfg.dart'; import 'package:server_box/data/res/provider.dart'; -import 'package:server_box/data/res/store.dart'; -import 'package:server_box/data/res/url.dart'; import '../../../core/route.dart'; import '../../../data/model/server/server_private_info.dart'; @@ -152,44 +149,17 @@ class _ServerEditPageState extends State { Widget _buildDelBtn() { return IconButton( onPressed: () { - var delScripts = false; context.showRoundDialog( title: l10n.attention, child: StatefulBuilder(builder: (ctx, setState) { - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(l10n.askContinue( - '${l10n.delete} ${l10n.server}(${widget.spi!.name})', - )), - UIs.height13, - if (widget.spi?.server?.canViewDetails ?? false) - CheckboxListTile( - value: delScripts, - onChanged: (_) => setState( - () => delScripts = !delScripts, - ), - controlAffinity: ListTileControlAffinity.leading, - title: Text(l10n.deleteScripts), - tileColor: Colors.transparent, - contentPadding: EdgeInsets.zero, - ) - ], - ); + return Text(l10n.askContinue( + '${l10n.delete} ${l10n.server}(${widget.spi!.name})', + )); }), actions: [ TextButton( onPressed: () async { context.pop(); - if (delScripts) { - await context.showLoadingDialog( - fn: () async { - const cmd = 'rm ${ShellFunc.srvBoxDir}/mobile_v*.sh'; - return widget.spi?.server?.client?.run(cmd); - }, - ); - } Pros.server.delServer(widget.spi!.id); context.pop(true); }, @@ -649,16 +619,16 @@ class _ServerEditPageState extends State { wolCfg: wol, ); - final tipShown = Stores.history.writeScriptTipShown; - if (!tipShown.fetch()) { - final ok = await context.showRoundDialog( - title: l10n.attention, - child: SimpleMarkdown(data: l10n.beforeConnect(Urls.thisRepo)), - actions: Btns.oks(onTap: () => context.pop(true)), - ); - if (ok != true) return; - tipShown.put(true); - } + // final tipShown = Stores.history.writeScriptTipShown; + // if (!tipShown.fetch()) { + // final ok = await context.showRoundDialog( + // title: l10n.attention, + // child: SimpleMarkdown(data: l10n.beforeConnect(Urls.thisRepo)), + // actions: Btns.oks(onTap: () => context.pop(true)), + // ); + // if (ok != true) return; + // tipShown.put(true); + // } if (widget.spi == null) { Pros.server.addServer(spi); diff --git a/lib/view/page/setting/entry.dart b/lib/view/page/setting/entry.dart index 3d3831a5..33e69b0f 100644 --- a/lib/view/page/setting/entry.dart +++ b/lib/view/page/setting/entry.dart @@ -1135,7 +1135,7 @@ class _SettingPageState extends State { return ListTile( leading: const Icon(Icons.image), - title: Text('Logo URL'), + title: const Text('Logo URL'), trailing: const Icon(Icons.keyboard_arrow_right), onTap: () { final ctrl = diff --git a/lib/view/page/snippet/edit.dart b/lib/view/page/snippet/edit.dart index fdd39582..93f9d9ab 100644 --- a/lib/view/page/snippet/edit.dart +++ b/lib/view/page/snippet/edit.dart @@ -172,6 +172,7 @@ class _SnippetEditPageState extends State : Text( subtitle, maxLines: 1, + style: UIs.textGrey, overflow: TextOverflow.ellipsis, ), onTap: () async { diff --git a/pubspec.lock b/pubspec.lock index 61991ba6..881479cf 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -385,8 +385,8 @@ packages: dependency: "direct main" description: path: "." - ref: "v1.0.58" - resolved-ref: "5943ffaefa7ffa6a9a243bf5190e8ff303b114d4" + ref: "v1.0.59" + resolved-ref: aaca37cb7052e301bbd723615f6827371ad7f2b8 url: "https://github.com/lppcg/fl_lib" source: git version: "0.0.1" diff --git a/pubspec.yaml b/pubspec.yaml index 0dee40c1..7a113fcf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -58,7 +58,7 @@ dependencies: fl_lib: git: url: https://github.com/lppcg/fl_lib - ref: v1.0.58 + ref: v1.0.59 dependency_overrides: # dartssh2: