From 3c405c7ffe149b5a7d8dbd7cda0a270f78470a26 Mon Sep 17 00:00:00 2001 From: yswef <170477919+yswef@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:45:37 +0000 Subject: [PATCH 1/2] feat(panel): integrate Faster-PC (app_id 13) with Mother Panel Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .gitignore | 5 + CHANGELOG.md | 30 ++ README.md | 51 +++- mother_panel/MOTHER_PANEL_HANDOFF.md | 82 ++++++ mother_panel/app.json | 31 ++ mother_panel/build_zip.py | 80 ++++++ mother_panel/map.json | 54 ++++ mother_panel/min_version.json | 9 + mother_panel/requirements.json | 31 ++ mother_panel/settings.json | 13 + src/core/app_context.py | 11 +- src/gui/admin_panel.py | 215 ++++++++++++++ src/gui/app.py | 87 +++++- src/gui/main_window.py | 91 +----- src/gui/other_apps.py | 148 ++++++++++ src/gui/panel_login_window.py | 268 ++++++++++++++++++ src/panel/__init__.py | 43 +++ src/panel/auth.py | 121 ++++++++ src/panel/client.py | 279 ++++++++++++++++++ src/panel/config.py | 151 ++++++++++ src/panel/control.py | 79 ++++++ src/panel/identity.py | 48 ++++ src/panel/licenses.py | 71 +++++ src/panel/service.py | 229 +++++++++++++++ src/panel/session.py | 205 ++++++++++++++ src/panel/sync.py | 149 ++++++++++ src/panel/telemetry.py | 82 ++++++ src/panel/updates.py | 78 +++++ tests/test_panel.py | 407 +++++++++++++++++++++++++++ 29 files changed, 3044 insertions(+), 104 deletions(-) create mode 100644 mother_panel/MOTHER_PANEL_HANDOFF.md create mode 100644 mother_panel/app.json create mode 100644 mother_panel/build_zip.py create mode 100644 mother_panel/map.json create mode 100644 mother_panel/min_version.json create mode 100644 mother_panel/requirements.json create mode 100644 mother_panel/settings.json create mode 100644 src/gui/admin_panel.py create mode 100644 src/gui/other_apps.py create mode 100644 src/gui/panel_login_window.py create mode 100644 src/panel/__init__.py create mode 100644 src/panel/auth.py create mode 100644 src/panel/client.py create mode 100644 src/panel/config.py create mode 100644 src/panel/control.py create mode 100644 src/panel/identity.py create mode 100644 src/panel/licenses.py create mode 100644 src/panel/service.py create mode 100644 src/panel/session.py create mode 100644 src/panel/sync.py create mode 100644 src/panel/telemetry.py create mode 100644 src/panel/updates.py create mode 100644 tests/test_panel.py diff --git a/.gitignore b/.gitignore index 3eeee14..5a670bb 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,11 @@ changes.json logs/ portable.flag +# لوحة الأم (Mother Panel): إعدادات الاتصال والجلسة — محلية ولا تُرفع أبدًا +panel.json +panel_session.json +mother_panel/dist/ + # معاينات الواجهة (أداة المطور) .preview/ diff --git a/CHANGELOG.md b/CHANGELOG.md index ae4f603..9268c43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ الصيغة مبنية على [Keep a Changelog](https://keepachangelog.com/)، والإصدارات تتبع [Semantic Versioning](https://semver.org/). +## [Unreleased] — الاندماج مع «لوحة الأم» (Mother Panel، app_id 13) + +### أُضيف +- **حزمة `src/panel/`**: عميل بوابة `/api/v1` (JSON فقط، `X-App-Token` + `X-App-Id: 13` + + `X-Req-Id` لكل طلب + `Authorization: Bearer`) يغطي status · auth/register · auth/login · + auth/session · auth/logout · sync · releases/check · licenses/verify · licenses/activate · + telemetry · control — بلا أي وصول مباشر لقاعدة البيانات. +- **تسجيل دخول إلزامي عبر لوحة الأم** (`PanelLoginWindow`) بدل الحسابات المحلية: نفس الحساب يعمل + على أي جهاز، `is_admin` يأتي من `app_users.is_admin` فقط، الجلسة المحفوظة تُتحقق تلقائيًا، + وإنشاء حساب من الشاشة نفسها. عند أول تشغيل تُحفظ إعدادات الاتصال (الرابط + التوكن) في + `panel.json` محليًا ولا تدخل المستودع. +- **مزامنة الإعدادات بين الأجهزة** (sync push/pull مع `sync_version` وكشف التعارض؛ server-wins) + لتفضيلات المستخدم فقط — الحسابات والاختصارات لا تُزامَن. +- **فحص التحديثات** عبر `releases/check` (full/sub/min_version) مع تنبيه وتحديث إجباري. +- **تراخيص** (verify/activate) — تُفعَّل فقط إذا سمح بها خادم اللوحة (`licenses_enabled`). +- **تتبّع خفيف** (telemetry) بلا بيانات شخصية، يمكن إيقافه محليًا، ويتوقف إذا عطّله الخادم. +- **تبويب «لوحة التحكم»** للأدمن (نظرة عامة/مستخدمون/أجهزة/إصدارات/إعدادات/متطلبات من `control`) + وتبويب **«تطبيقات أخرى»** ببطاقات التطبيقات الشقيقة من `status`. +- **حزمة تثبيت للوحة الأم** `mother_panel/` (app.json، map.json بخطوة Verify، لوحة ويب ثابتة + JSON-only، requirements.json، MOTHER_PANEL_HANDOFF.md، build_zip.py). + +### تغيّر +- تبويب «المستخدمون» المحلي أُزيل من الواجهة (إدارة الحسابات تتم في لوحة الأم)؛ + `src/utils/auth.py` و`src/gui/login_window.py` بقيا ككود قديم غير مستخدم في مسار التشغيل. +- لم يعد يُنشأ حساب أدمن افتراضي محلي (`ensure_default_admin`) — الصلاحيات من اللوحة الأم. + +### الأمان +- لا توكنات في الكود أو المستودع أو السجلات؛ `PanelConfig.__repr__` يعرض التوكن مقنّعًا. +- كل استدعاء API يحمل `X-Req-Id` فريدًا ليُسجَّل في `audit_log`/`sync_log` في اللوحة الأم. + ## [2.1.0] — 2026-11-25 إصدار 2.1: دليل تطبيقات وخدمات بمستويات خطورة، تقارير PDF، حماية أوسع من الشاشة الزرقاء، diff --git a/README.md b/README.md index 22716c9..a9d6989 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ ### أهم المزايا **التثبيت والدخول** -- حساب مدير افتراضي يُنشأ تلقائيًا عند أول تشغيل: `yswef` / `yswef1234`، مع زر "إنشاء حساب - جديد" في شاشة الدخول. +- **تسجيل دخول إلزامي عبر «لوحة الأم»** (حساب واحد لكل تطبيق، `is_admin` من الخادم، نفس الحساب + يعمل على كل أجهزتك) مع زر "إنشاء حساب جديد" في شاشة الدخول — انظر قسم «الاتصال بلوحة الأم». - مثبّت رسمي `Faster-PC-Setup.exe` (Inno Setup) يُبنى تلقائيًا مع كل إصدار، أو ملف تنفيذي واحد `FasterPC.exe` يعمل مباشرة. - التثبيت من داخل البرنامج (الإعدادات): اختصار سطح المكتب وقائمة ابدأ، تسجيل التشغيل مع @@ -106,6 +106,8 @@ - تشغيل نسخة واحدة فقط، وينشط النافذة الموجودة عند إعادة الفتح. - بقاء البرنامج في شريط المهام عند إغلاق النافذة (اختياري) مع أيقونة وقائمة سريعة. - مركز تنبيهات داخل البرنامج + تنبيهات شريط المهام. +- تبويب «تطبيقات أخرى» ببطاقات التطبيقات الشقيقة من لوحة الأم، وتبويب «لوحة التحكم» للأدمن + (إحصاءات، مستخدمون، أجهزة، إصدارات، إعدادات، متطلبات). ### التشغيل @@ -114,8 +116,8 @@ pip install -r requirements.txt python main.py ``` -- أول تشغيل: سجّل الدخول بحساب المدير الافتراضي `yswef` / `yswef1234` (أو أنشئ حسابًا من زر - "إنشاء حساب جديد" في شاشة الدخول). +- أول تشغيل: أدخل رابط لوحة الأم وتوكن التطبيق (X-App-Token) مرة واحدة في شاشة الدخول، ثم سجّل + الدخول بحسابك (أو أنشئ حسابًا من زر "إنشاء حساب جديد"). - يفضَّل تشغيل البرنامج كمسؤول (Administrator) لتفعيل كل الميزات (الخدمات، SFC/DISM، نقطة الاستعادة، بعض تحسينات الريجستري). البرنامج يوضح دائمًا متى تكون الصلاحيات ناقصة. @@ -168,7 +170,7 @@ pyinstaller --noconfirm --clean faster_pc.spec ```bash pip install -r requirements-dev.txt -pytest # 55+ اختبارًا للوحدات الأساسية (إعدادات، حماية، تنظيف، سجل، مراقبة) +pytest # 89 اختبارًا للوحدات (إعدادات، حماية، تنظيف، سجل، مراقبة، ولوحة الأم) ruff check . # فحص التنسيق والأخطاء الشائعة ``` @@ -223,6 +225,26 @@ docs/docs.html التوثيق الكامل (مستخدم + مطوّ هذا خط ثابت في المشروع. - كل عملية تلمس النظام تحترم الوضع التجريبي، ومعظمها قابل للتراجع. +### الاتصال بلوحة الأم (Mother Panel — app_id 13) + +التطبيق يعمل **دائمًا أونلاين** عبر بوابة الـ API في لوحة الأم (`/api/v1`، JSON فقط): +تسجيل الدخول، الجلسات، المزامنة بين الأجهزة، فحص التحديثات، التراخيص، المقاييس، ولوحة الإدارة. + +| الغرض | نقطة الـ API | +|---|---| +| حالة التطبيق + الإعدادات + التطبيقات الشقيقة | `status` | +| إنشاء حساب / دخول / جلسة / خروج | `auth/register` · `auth/login` · `auth/session` · `auth/logout` | +| مزامنة الإعدادات (دفع/سحب + كشف تعارض) | `sync` | +| تحديث كامل/فرعي + `min_version` | `releases/check` | +| الترخيص | `licenses/verify` · `licenses/activate` | +| مقاييس خفيفة بلا بيانات شخصية | `telemetry` | +| لوحة الإدارة (للأدمن فقط) | `control` | + +- إعدادات الاتصال تُحفظ محليًا في `%LOCALAPPDATA%\FasterPC\panel.json` (أو من متغيري البيئة + `FASTERPC_PANEL_URL` / `FASTERPC_PANEL_TOKEN`) ولا تدخل المستودع أبدًا. +- عقد الـ API الكامل والجداول المستخدمة ومتطلبات التثبيت في + [`mother_panel/MOTHER_PANEL_HANDOFF.md`](mother_panel/MOTHER_PANEL_HANDOFF.md). + ### الترخيص هذا المشروع مملوك ومحمي بحقوق النشر — راجع ملف [LICENSE](LICENSE). @@ -244,8 +266,8 @@ journal and protection layers that prevent closing important apps or destabilizi ### Highlights **Setup & sign-in** -- A default admin account is created automatically on first launch: `yswef` / `yswef1234`; more - accounts can be created from the sign-in screen. +- **Mandatory sign-in through the Mother Panel** (one account per app, `is_admin` comes from the + server, the same account works on every device) with a "create account" button on the sign-in screen. - An official `Faster-PC-Setup.exe` installer (Inno Setup) is built with every release, or run the single-file `FasterPC.exe` directly. - In-app install (Settings): desktop & Start Menu shortcuts, run with Windows, and optional @@ -319,6 +341,8 @@ journal and protection layers that prevent closing important apps or destabilizi - Single-instance: re-launching activates the existing window. - Optional minimize-to-tray on close, with tray icon and quick actions. - In-app notification center + Windows tray toasts. +- "Other apps" tab with sibling-app cards from the Mother Panel, and an admin-only "Control panel" + tab (overview, users, devices, releases, settings, requirements). ### Getting started @@ -328,8 +352,8 @@ python main.py ``` Run as Administrator for full functionality (services, SFC/DISM, restore points, some -registry tweaks). The app always tells you when elevation is missing. Sign in with the default -admin `yswef` / `yswef1234`, or create a new account from the sign-in screen. +registry tweaks). The app always tells you when elevation is missing. On first launch enter the +Mother Panel URL and the app token (X-App-Token) once, then sign in (or create an account). ### Building @@ -352,6 +376,15 @@ official icon. To also build the `dist\Faster-PC-Setup.exe` installer run - This project contains no code that extracts, decrypts, or exports credentials stored by browsers or other applications. That is a permanent project boundary. +### Mother Panel (app_id 13) + +The app is always online through the Mother Panel API gateway (`/api/v1`, JSON only): sign-in, +sessions, cross-device settings sync, update checks, licenses, lightweight telemetry, and the admin +panel. Connection settings live locally in `%LOCALAPPDATA%\FasterPC\panel.json` (or the +`FASTERPC_PANEL_URL` / `FASTERPC_PANEL_TOKEN` environment variables) and never in the repository. +The full API contract, tables and install requirements are in +[`mother_panel/MOTHER_PANEL_HANDOFF.md`](mother_panel/MOTHER_PANEL_HANDOFF.md). + ### License Proprietary — see [LICENSE](LICENSE). © 2026 Yousef Alhamzy. All rights reserved. diff --git a/mother_panel/MOTHER_PANEL_HANDOFF.md b/mother_panel/MOTHER_PANEL_HANDOFF.md new file mode 100644 index 0000000..c701a41 --- /dev/null +++ b/mother_panel/MOTHER_PANEL_HANDOFF.md @@ -0,0 +1,82 @@ + + +# دليل تسليم اندماج Faster-PC مع «لوحة الأم» (Mother Panel) + +- **معرّف التطبيق (`app_id` / `boards.id`)**: `13` +- **المفتاح (`app_key`)**: `faster_pc` +- **النوع**: تطبيق سطح مكتب (`desktop` / `windows`) +- **المطوّر**: يوسف الحمزي (Yousef Alhamzy) — `https://github.com/yswef` + +--- + +## 1. الملفات المُنشأة والمعدّلة في المستودع + +| المسار | الدور | +|---|---| +| `src/panel/identity.py` | ثوابت الهوية (`APP_ID=13`, `APP_KEY`, `APP_TYPE`, بيانات المطوّر) | +| `src/panel/config.py` | تحميل/حفظ إعدادات الاتصال (`panel.json` أو `FASTERPC_PANEL_URL` / `FASTERPC_PANEL_TOKEN`) مع إخفاء التوكن في السجلات | +| `src/panel/client.py` | عميل `/api/v1` (JSON فقط، `X-App-Token`, `X-App-Id: 13`, `X-Req-Id`, `Authorization: Bearer`) | +| `src/panel/session.py` | تخزين الجلسة وحالة الترخيص وذاكرة الحالة محليًا (`panel_session.json`) + بصمة الجهاز | +| `src/panel/auth.py` | تسجيل الدخول/إنشاء حساب/استعادة الجلسة/الخروج (`is_admin` من الخادم) | +| `src/panel/sync.py` | مزامنة الإعدادات (`SYNC_KEYS` فقط؛ `LOCAL_ONLY_KEYS` لا تغادر الجهاز) مع كشف التعارض (`server-wins`) | +| `src/panel/updates.py` | فحص التحديثات (`releases/check`: `full` / `sub` / `min_version` / `permissions_changed`) | +| `src/panel/licenses.py` | التحقق من الترخيص وتفعيله (تُستخدم فقط عند تفعيل `licenses_enabled`) | +| `src/panel/telemetry.py` | تجميع وإرسال أحداث Telemetry خفيفة بلا بيانات شخصية | +| `src/panel/control.py` | واجهة أقسام لوحة الإدارة للأدمن (`overview`, `users`, `devices`, `releases`, `settings`, `requirements`) | +| `src/panel/service.py` | طبقة الخدمة الموحّدة `PanelService` | +| `src/gui/panel_login_window.py` | شاشة الدخول الإلزامية وإعداد الاتصال أول مرة | +| `src/gui/admin_panel.py` | تبويب «لوحة التحكم» (يظهر للأدمن فقط عند `is_admin=1`) | +| `src/gui/other_apps.py` | تبويب «تطبيقات أخرى» لعرض التطبيقات الشقيقة من `status` | +| `src/core/app_context.py` | ربط `self.panel = PanelService(self.settings)` | +| `src/gui/app.py` | حلقة الدخول الإلزامي، فحص التحديثات، وإرسال Telemetry كل 10 دقائق | +| `src/gui/main_window.py` | استبدال تبويب المستخدمين المحلي بتبويبي «لوحة التحكم» و«تطبيقات أخرى» | +| `tests/test_panel.py` | 24 اختبار وحدة لتكامل لوحة الأم | + +--- + +## 2. نقاط الـ API المستخدمة (`/api/v1`) + +- `GET /api/v1/status` — حالة التطبيق، الإعدادات (`app_settings_kv`)، والتطبيقات الشقيقة (`siblings`). +- `POST /api/v1/auth/register` · `POST /api/v1/auth/login` · `GET /api/v1/auth/session` · `POST /api/v1/auth/logout` — الحسابات لكل تطبيق (`app_id=13`). +- `POST /api/v1/sync` (`op=push` / `op=pull`) — مزامنة الإعدادات مع `sync_version` وكشف التعارض. +- `GET /api/v1/releases/check` — فحص التحديثات (`full` / `sub` / `min_version` / `permissions_changed`). +- `POST /api/v1/licenses/verify` · `POST /api/v1/licenses/activate` — التراخيص. +- `POST /api/v1/telemetry` — إرسال المقاييس. +- `GET /api/v1/control` — أقسام الإدارة للأدمن فقط (`is_admin=1`). + +> **ملاحظة حول `content_packs` (`content`)**: لم يُضف عميل لحزم المحتوى لأن Faster-PC تطبيق سطح مكتب لا يعتمد على حزم محتوى إضافية. +> **ملاحظة حول GitHub (`op=github_token`)**: خيار `github_enabled` معطّل (`false`) في `settings.json`، والتطبيق لا يطلب `op=github_token` أبدًا. + +--- + +## 3. الجداول المشتركة ونطاق `app_id=13` + +جميع العمليات محصورة في الجداول المشتركة للوحة الأم بنطاق `app_id = 13` (لا توجد جداول مخصصة للتطبيق ولا وصول مباشر لقاعدة البيانات من التطبيق): +- `boards` (`id = 13`) +- `app_users` (`app_id`, `email UNIQUE`, `is_admin 0/1`) +- `app_sessions` +- `devices` (`UNIQUE(app_id, device_uid)`) +- `releases` +- `app_settings_kv` +- `app_requirements` +- `sync_log` و `audit_log` (كل طلب يحمل `X-Req-Id` فريدًا) + +--- + +## 4. الصلاحيات والمتطلبات الناقصة + +- **الصلاحيات**: `is_admin` يُقرأ من الخادم فقط (`app_users.is_admin`)، وتبويب «لوحة التحكم» لا يظهر إلا للأدمن مع تحقق الخادم عند كل طلب `control`. +- **متطلب ناقص (`info` / `high`)**: البريد الإلكتروني للمطوّر (`DEVELOPER_EMAIL`) غير متاح حاليًا ومُسجّل في `requirements.json` بحالة `missing`؛ يُستكمل لاحقًا من المطوّر. + +--- + +## 5. خطوات التحقق (Verify) + +1. تطبيق `mother_panel/map.json` على لوحة الأم (أو استيراد `app.json`، `settings.json`، `requirements.json`، `min_version.json`). +2. استدعاء `GET /api/v1/status` بترويسات `X-App-Token` و`X-App-Id: 13` و`X-Req-Id` والتأكد من عودة `"ok": true` و`"requires_login": true` و`"github_enabled": false`. +3. تشغيل التطبيق محليًا وإدخال رابط لوحة الأم و`X-App-Token` في شاشة الدخول، ثم تجربة تسجيل الدخول والمزامنة. + + diff --git a/mother_panel/app.json b/mother_panel/app.json new file mode 100644 index 0000000..c9b514a --- /dev/null +++ b/mother_panel/app.json @@ -0,0 +1,31 @@ +{ + "_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC — app_id 13", + "app_id": 13, + "app_key": "faster_pc", + "name": "Faster-PC", + "display_name": "Faster PC", + "version": "2.1.0", + "type": "desktop", + "platform": "windows", + "description": "أداة سطح مكتب لتحسين وتنظيف وإصلاح ومراقبة نظام ويندوز بواجهة عربية داكنة، متصلة بلوحة الأم لإدارة الحسابات والمزامنة والتحديثات.", + "tags": [ + "windows", + "desktop", + "optimizer", + "cleaner", + "monitor", + "repair", + "pyside6", + "arabic" + ], + "icon": "assets/icon.png", + "docs": "README.md", + "repo_url": "https://github.com/yswef/Faster-PC", + "developer": { + "name": "يوسف الحمزي", + "name_en": "Yousef Alhamzy", + "email": "", + "url": "https://github.com/yswef" + }, + "_end_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC" +} diff --git a/mother_panel/build_zip.py b/mother_panel/build_zip.py new file mode 100644 index 0000000..9a602a8 --- /dev/null +++ b/mother_panel/build_zip.py @@ -0,0 +1,80 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: mother_panel/build_zip.py | app_id (boards.id): 13 +# ============================================================ +"""يبني حزمة ZIP لحزمة التسليم (deliverables) بلوحة الأم. + +الاستخدام: + python mother_panel/build_zip.py # يبني mother_panel/dist/mother_panel_faster_pc.zip + python mother_panel/build_zip.py --list # يعرض محتويات الحزمة فقط + +لا يحتوي أي توكن؛ يُشغَّل محليًا فقط ولا يُرفع مع المستودع (dist/ مُهمَل في .gitignore). +""" + +from __future__ import annotations + +import argparse +import sys +import zipfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parent +DIST = HERE / "dist" +INCLUDE: tuple[str, ...] = ( + "app.json", + "map.json", + "requirements.json", + "settings.json", + "min_version.json", + "MOTHER_PANEL_HANDOFF.md", +) +# ملفات PHP المقترحة للوحة الأم (غير مطلوبة للتشغيل؛ تسليم اختياري) +PANEL_DIR = HERE / "panel" + + +def build_zip() -> Path: + DIST.mkdir(parents=True, exist_ok=True) + target = DIST / "mother_panel_faster_pc.zip" + files: list[Path] = [HERE / name for name in INCLUDE] + if PANEL_DIR.is_dir(): + files += sorted(p for p in PANEL_DIR.rglob("*") if p.is_file()) + missing = [str(p.relative_to(HERE)) for p in files if not p.is_file()] + if missing: + raise SystemExit(f"ملفات ناقصة: {missing}") + with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as zf: + for path in files: + arcname = Path("mother_panel") / path.relative_to(HERE) + zinfo = zipfile.ZipInfo.from_file(path, arcname.as_posix()) + zinfo.compress_type = zipfile.ZIP_DEFLATED + zf.writestr(zinfo, path.read_bytes(), compresslevel=9) + return target + + +def list_zip() -> list[str]: + target = DIST / "mother_panel_faster_pc.zip" + if not target.is_file(): + return [] + with zipfile.ZipFile(target) as zf: + return sorted(zf.namelist()) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="بناء حزمة تسليم لوحة الأم") + parser.add_argument("--list", action="store_true", help="عرض محتويات الحزمة المبنية") + args = parser.parse_args(argv) + if args.list: + for name in list_zip(): + print(name) + return 0 + target = build_zip() + with zipfile.ZipFile(target) as zf: + count = len(zf.namelist()) + print(f"تم بناء الحزمة: {target} ({count} ملفًا)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/mother_panel/map.json b/mother_panel/map.json new file mode 100644 index 0000000..53ceafc --- /dev/null +++ b/mother_panel/map.json @@ -0,0 +1,54 @@ +{ + "_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC — app_id 13", + "app_id": 13, + "app_key": "faster_pc", + "type": "desktop", + "steps": [ + { + "order": 1, + "action": "register_app_data", + "source": "app.json", + "target_table": "boards", + "note": "تحديث بيانات التطبيق app_id=13 (الاسم، الوصف، الوسوم، الإصدار، الأيقونة، التوثيق)." + }, + { + "order": 2, + "action": "apply_settings", + "source": "settings.json", + "target_table": "app_settings_kv", + "note": "ضبط الإعدادات الافتراضية للتطبيق بنطاق app_id=13 (github_enabled=false، licenses_enabled=false)." + }, + { + "order": 3, + "action": "register_requirements", + "source": "requirements.json", + "target_table": "app_requirements", + "note": "تسجيل المتطلبات (يشمل developer_email بحالة missing وأولوية high)." + }, + { + "order": 4, + "action": "set_min_version", + "source": "min_version.json", + "target_table": "releases", + "note": "تحديد min_version=2.1.0 لقناة stable." + }, + { + "order": 5, + "action": "verify", + "endpoint": "GET /api/v1/status", + "headers": { + "X-App-Token": "", + "X-App-Id": "13", + "X-Req-Id": "" + }, + "expected": { + "ok": true, + "app_id": 13, + "settings.requires_login": true, + "settings.github_enabled": false + }, + "note": "التحقق من استجابة status بالـ JSON الصحيح ونطاق app_id=13." + } + ], + "_end_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC" +} diff --git a/mother_panel/min_version.json b/mother_panel/min_version.json new file mode 100644 index 0000000..7ed561e --- /dev/null +++ b/mother_panel/min_version.json @@ -0,0 +1,9 @@ +{ + "_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC — app_id 13", + "app_id": 13, + "min_version": "2.1.0", + "current_version": "2.1.0", + "channel": "stable", + "permissions_changed": false, + "_end_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC" +} diff --git a/mother_panel/requirements.json b/mother_panel/requirements.json new file mode 100644 index 0000000..54bd9ee --- /dev/null +++ b/mother_panel/requirements.json @@ -0,0 +1,31 @@ +{ + "_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC — app_id 13", + "app_id": 13, + "requirements": [ + { + "category": "info", + "priority": "high", + "status": "missing", + "key": "developer_email", + "label": "البريد الإلكتروني للمطوّر (DEVELOPER_EMAIL)", + "note": "غير متاح وقت التسليم؛ يُستكمل من المطوّر في لوحة الأم وفي src/panel/identity.py." + }, + { + "category": "icons", + "priority": "medium", + "status": "provided", + "key": "app_icon", + "label": "أيقونة التطبيق لبطاقة لوحة الأم", + "note": "موجودة في assets/icon.png و assets/icon.ico." + }, + { + "category": "api", + "priority": "critical", + "status": "provided", + "key": "mother_panel_gateway", + "label": "بوابة API لوحة الأم (/api/v1)", + "note": "يعتمد التطبيق على status و auth/* و sync و releases/check و licenses/* و telemetry و control." + } + ], + "_end_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC" +} diff --git a/mother_panel/settings.json b/mother_panel/settings.json new file mode 100644 index 0000000..a291cfe --- /dev/null +++ b/mother_panel/settings.json @@ -0,0 +1,13 @@ +{ + "_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC — app_id 13", + "app_id": 13, + "settings": { + "requires_login": true, + "sync_enabled": true, + "telemetry_enabled": true, + "licenses_enabled": false, + "update_channel": "stable", + "github_enabled": false + }, + "_end_signature": "© Yousef Alhamzy (يوسف الحمزي) — Faster-PC" +} diff --git a/src/core/app_context.py b/src/core/app_context.py index 711096a..79efe85 100644 --- a/src/core/app_context.py +++ b/src/core/app_context.py @@ -1,3 +1,7 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/core/app_context.py | app_id (boards.id): 13 +# ============================================================ """ سياق التطبيق (AppContext) — نقطة تجميع واحدة لكل خدمات البرنامج. @@ -21,6 +25,7 @@ from src.core.optimizer import SystemOptimizer from src.core.repair import SystemRepair from src.core.tweaks import PerformanceTweaks +from src.panel.service import PanelService from src.utils.auth import AuthManager from src.utils.paths import journal_path from src.utils.winapi import is_admin @@ -46,7 +51,9 @@ def __init__(self, settings: SettingsManager | None = None): self.monitor = PerformanceMonitor(self.settings) self.health = HealthMonitor(self.settings) self.installer = SystemInstaller(self.settings, notifier=self.notifications) - self.auth = AuthManager(self.settings) + self.auth = AuthManager(self.settings) # قديم: الحسابات المحلية — لم تعد تُستخدم في مسار الدخول + # لوحة الأم: مصادقة/مزامنة/تحديثات/تراخيص/تتبّع/تحكم (بلا شبكة عند الإنشاء) + self.panel = PanelService(self.settings) self.tasks = TaskManager() self.current_user: dict = {} @@ -97,3 +104,5 @@ def reload_settings(self) -> None: __all__ = ["AppContext"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/gui/admin_panel.py b/src/gui/admin_panel.py new file mode 100644 index 0000000..c2cfe41 --- /dev/null +++ b/src/gui/admin_panel.py @@ -0,0 +1,215 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/gui/admin_panel.py | app_id (boards.id): 13 +# ============================================================ +""" +تبويب «لوحة التحكم» داخل التطبيق — لحساب الأدمن فقط (app_users.is_admin = 1). + +يعرض بيانات التطبيق من نقطة control في لوحة الأم فقط (لا قاعدة بيانات مباشرة): +نظرة عامة (إحصائيات) · المستخدمون · الأجهزة · الإصدارات · الإعدادات · المتطلبات. +الحسابات العادية لا يظهر لها هذا التبويب أصلًا، والخادم يرفض الطلب لغير الأدمن. +""" + +from __future__ import annotations + +import logging + +from PySide6.QtWidgets import ( + QAbstractItemView, + QComboBox, + QGridLayout, + QHBoxLayout, + QHeaderView, + QLabel, + QPushButton, + QTableWidget, + QTableWidgetItem, + QVBoxLayout, + QWidget, +) + +from src.gui.theme import COLORS +from src.gui.widgets import Card +from src.panel.control import SECTIONS, as_rows, as_stats + +logger = logging.getLogger(__name__) + +STAT_LABELS = { + "users": "المستخدمون", + "users_count": "المستخدمون", + "total_users": "إجمالي المستخدمين", + "active_users": "مستخدمون نشطون", + "devices": "الأجهزة", + "devices_count": "الأجهزة", + "sessions": "الجلسات", + "downloads": "التنزيلات", + "downloads_count": "التنزيلات", + "licenses": "التراخيص", + "licenses_count": "التراخيص", + "ratings": "التقييمات", + "rating": "متوسط التقييم", + "rating_avg": "متوسط التقييم", + "version": "الإصدار", + "latest_version": "آخر إصدار", + "min_version": "أدنى إصدار", + "enabled": "مفعّل", + "updated_at": "آخر تحديث", +} + + +def _pretty_key(key: str) -> str: + if key in STAT_LABELS: + return STAT_LABELS[key] + return key.replace("_", " ").replace(".", " — ") + + +class AdminPanelTab(QWidget): + """لوحة إدارة التطبيق من لوحة الأم (قراءة فقط من التطبيق).""" + + def __init__(self, ctx, parent=None): + super().__init__(parent) + self.ctx = ctx + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(8) + + head = QHBoxLayout() + title = QLabel("لوحة التحكم — بيانات Faster-PC من لوحة الأم (app_id 13)") + title.setStyleSheet(f"font-weight: bold; color: {COLORS['text']};") + head.addWidget(title) + head.addStretch() + head.addWidget(QLabel("القسم:")) + self.section_combo = QComboBox() + for key, label in SECTIONS: + self.section_combo.addItem(label, key) + self.section_combo.currentIndexChanged.connect(self.refresh) + head.addWidget(self.section_combo) + self.refresh_btn = QPushButton("تحديث") + self.refresh_btn.setObjectName("primaryButton") + self.refresh_btn.clicked.connect(self.refresh) + head.addWidget(self.refresh_btn) + layout.addLayout(head) + + self.status_label = QLabel("") + self.status_label.setWordWrap(True) + self.status_label.setStyleSheet(f"color: {COLORS['text_muted']};") + layout.addWidget(self.status_label) + + self.stats_card = Card("إحصائيات") + self.stats_grid = QGridLayout() + self.stats_grid.setHorizontalSpacing(12) + self.stats_grid.setVerticalSpacing(10) + self.stats_card.add_layout(self.stats_grid) + layout.addWidget(self.stats_card) + + table_card = Card("التفاصيل") + self.table = QTableWidget(0, 1) + self.table.setHorizontalHeaderLabels(["—"]) + self.table.verticalHeader().setVisible(False) + self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) + self.table.setAlternatingRowColors(True) + self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) + self.table.horizontalHeader().setStretchLastSection(True) + self.table.setMinimumHeight(220) + table_card.add(self.table) + layout.addWidget(table_card, 1) + + if not self.ctx.panel.is_configured: + self.status_label.setText("الاتصال بلوحة الأم غير مُعدّ — لا توجد بيانات لعرضها.") + self._show_stats({"الحالة": "غير متصل"}) + else: + self.status_label.setText("اضغط «تحديث» لجلب البيانات من لوحة الأم.") + + # ------------------------------------------------------------------ + @property + def section(self) -> str: + return str(self.section_combo.currentData() or "overview") + + def refresh(self) -> None: + if not self.ctx.panel.is_configured: + self.status_label.setText("الاتصال بلوحة الأم غير مُعدّ.") + return + section = self.section + self.status_label.setText("جارٍ الجلب من لوحة الأم…") + self.refresh_btn.setEnabled(False) + self.ctx.tasks.run( + lambda: self.ctx.panel.control.section(section, page=1), + on_success=self._show, + on_error=self._error, + label=f"لوحة التحكم: {section}", + ) + + def _error(self, message: str) -> None: + self.refresh_btn.setEnabled(True) + self.status_label.setStyleSheet(f"color: {COLORS['danger']};") + self.status_label.setText(str(message)) + + def _show(self, data: dict) -> None: + self.refresh_btn.setEnabled(True) + self.status_label.setStyleSheet(f"color: {COLORS['text_muted']};") + section = self.section + if section == "overview": + stats = as_stats(data) + self._show_stats(stats or {"الحالة": "لا توجد بيانات"}) + self._show_rows([]) + self.status_label.setText(f"تم جلب النظرة العامة ({len(stats)} مؤشرًا).") + return + rows = as_rows(data) + self._show_rows(rows) + total = "" + if isinstance(data, dict): + for key in ("total", "count"): + if key in data: + total = f" من {data[key]}" + self.status_label.setText(f"تم جلب {len(rows)} سجلًا{total}.") + if not rows: + self._show_stats({"السجلات": "0"}) + + def _show_stats(self, stats: dict) -> None: + while self.stats_grid.count(): + item = self.stats_grid.takeAt(0) + widget = item.widget() + if widget is not None: + widget.deleteLater() + if not stats: + return + columns = 4 + for index, (key, value) in enumerate(list(stats.items())[:24]): + cell = QLabel( + f"
{_pretty_key(str(key))}
" + f"
{value if value != '' else '—'}
" + ) + cell.setStyleSheet(f"background: {COLORS['panel_alt']}; border-radius: 6px; padding: 8px;") + self.stats_grid.addWidget(cell, index // columns, index % columns) + + def _show_rows(self, rows: list[dict]) -> None: + if not rows: + self.table.setRowCount(0) + self.table.setColumnCount(1) + self.table.setHorizontalHeaderLabels(["—"]) + return + headers: list[str] = [] + for row in rows: + for key in row.keys(): + if key not in headers: + headers.append(key) + preferred = ["id", "email", "name", "username", "is_admin", "role", "status", "version", "device_uid", "platform", "created_at", "last_seen"] + headers.sort(key=lambda h: (preferred.index(h) if h in preferred else len(preferred), h)) + self.table.setColumnCount(len(headers)) + self.table.setHorizontalHeaderLabels([_pretty_key(h) for h in headers]) + self.table.setRowCount(len(rows)) + for r, row in enumerate(rows): + for c, key in enumerate(headers): + value = row.get(key, "") + if isinstance(value, bool): + text = "نعم" if value else "لا" + elif isinstance(value, (dict, list)): + text = str(value) + else: + text = "" if value is None else str(value) + self.table.setItem(r, c, QTableWidgetItem(text)) + + +__all__ = ["AdminPanelTab"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/gui/app.py b/src/gui/app.py index 73cdd2d..8f4a65c 100644 --- a/src/gui/app.py +++ b/src/gui/app.py @@ -1,8 +1,13 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/gui/app.py | app_id (boards.id): 13 +# ============================================================ """ نقطة تشغيل التطبيق: - تهيئة البيئة (الأيقونة، DPI، هوية التطبيق لويندوز). - تشغيل نسخة واحدة فقط (منع فتح البرنامج مرتين). -- ضمان وجود حساب الأدمن الافتراضي، ثم تسجيل الدخول، ثم النافذة الرئيسية. +- تسجيل دخول إلزامي عبر لوحة الأم (AppContext.panel) ثم النافذة الرئيسية، + وبعده في الخلفية: مزامنة الإعدادات، فحص التحديثات، وإرسال المقاييس. - التقاط أي خطأ فادح وعرضه برسالة واضحة بدل انهيار صامت. """ @@ -11,14 +16,17 @@ import logging import sys -from PySide6.QtCore import Qt +from PySide6.QtCore import Qt, QTimer, QUrl +from PySide6.QtGui import QDesktopServices from PySide6.QtNetwork import QLocalServer, QLocalSocket from PySide6.QtWidgets import QApplication, QMessageBox from src.core.app_context import AppContext -from src.gui.login_window import LoginWindow from src.gui.main_window import MainWindow, load_app_icon +from src.gui.panel_login_window import PanelLoginWindow from src.gui.theme import dark_palette, stylesheet +from src.panel.identity import APP_ID as PANEL_APP_ID +from src.panel.updates import UpdateInfo from src.utils.logger import install_excepthook, setup_logging from src.utils.paths import ensure_dirs, migrate_legacy_files from src.utils.winapi import ( @@ -28,7 +36,7 @@ message_box, set_app_user_model_id, ) -from src.version import APP_ID, APP_NAME, APP_VERSION +from src.version import APP_ID, APP_NAME, APP_URL, APP_VERSION logger = logging.getLogger(__name__) @@ -135,6 +143,7 @@ def launch_app(argv: list[str] | None = None) -> int: # 2) نسخة واحدة فقط single = SingleInstance() holder: dict = {} + ctx_holder: dict = {} def _activate_existing() -> None: window = holder.get("window") @@ -149,39 +158,41 @@ def _activate_existing() -> None: start_minimized = "--minimized" in argv exit_code = 0 + telemetry_timer = QTimer(app) + telemetry_timer.setInterval(TELEMETRY_FLUSH_MS) + telemetry_timer.timeout.connect(lambda: _flush_telemetry(ctx_holder.get("ctx"))) try: ctx = AppContext() + ctx_holder["ctx"] = ctx _configure_application(app, str((ctx.settings.get("appearance") or {}).get("language", "ar"))) - # 3) ضمان وجود حساب الأدمن الافتراضي تلقائياً بدون معالج إنشاء أدمن - try: - ctx.auth.ensure_default_admin() - except Exception as exc: - logger.warning("Could not ensure default admin: %s", exc) - - # 4) تسجيل الدخول + النافذة الرئيسية (مع دعم تسجيل الخروج وإعادة الدخول) + # 3) تسجيل دخول إلزامي عبر لوحة الأم ثم النافذة الرئيسية (مع دعم الخروج وإعادة الدخول) while True: - login = LoginWindow(ctx.settings) - if login.exec() != LoginWindow.Accepted or login.authenticated_user is None: + login = PanelLoginWindow(ctx.panel) + if login.exec() != PanelLoginWindow.Accepted or login.authenticated_user is None: logger.info("Login cancelled; exiting.") return exit_code - ctx.current_user = login.authenticated_user window = MainWindow(ctx, login.authenticated_user, start_minimized=start_minimized) holder["window"] = window window.show() start_minimized = False + telemetry_timer.start() + _check_updates_async(ctx, window) app.exec() if not window.logged_out: break holder["window"] = None + telemetry_timer.stop() + ctx.panel.logout() return exit_code except Exception as exc: # pragma: no cover logger.exception("Fatal error during startup") _fatal_error_handler(type(exc), exc, exc.__traceback__, "") return 1 finally: + telemetry_timer.stop() try: if single.server is not None: single.server.close() @@ -189,6 +200,47 @@ def _activate_existing() -> None: pass +TELEMETRY_FLUSH_MS = 10 * 60 * 1000 # كل 10 دقائق (best-effort، في خيط خلفي) + + +def _flush_telemetry(ctx) -> None: + """إرسال المقاييس المتراكمة في الخلفية — بلا أي تأثير على الواجهة.""" + if ctx is None or not ctx.panel.is_configured or ctx.panel.telemetry.pending() == 0: + return + ctx.tasks.run(ctx.panel.telemetry.flush, label="إرسال المقاييس") + + +def _check_updates_async(ctx, window) -> None: + """فحص التحديثات (releases/check) بعد الدخول مباشرة في خيط خلفي.""" + if not ctx.panel.is_configured: + return + + def _on_info(info: UpdateInfo) -> None: + if not info.has_update: + return + url = info.url or APP_URL + ctx.notifications.info("يتوفر تحديث لـ Faster PC", f"{info.message}\n{url}", source="updates") + if info.forced: + answer = QMessageBox.warning( + window, + f"{APP_NAME} — تحديث إجباري", + f"{info.message}\n\n{url}", + QMessageBox.Open | QMessageBox.Close, + QMessageBox.Open, + ) + if answer == QMessageBox.Open: + QDesktopServices.openUrl(QUrl(url)) + else: + window.quit_app() + + ctx.tasks.run( + ctx.panel.check_updates, + on_success=_on_info, + on_error=lambda message: logger.info("Update check skipped: %s", message), + label="فحص التحديثات", + ) + + def run_headless_check() -> int: """ فحص سريع بدون واجهة (يُستخدم في الاختبارات وفي التحقق بعد التثبيت): @@ -200,9 +252,16 @@ def run_headless_check() -> int: "version": APP_VERSION, "config": ctx.settings.config_path, "journal": ctx.journal.path, + "mother_panel": { + "app_id": PANEL_APP_ID, + "configured": ctx.panel.is_configured, + "base_url": ctx.panel.config.base_url, + }, } print("OK", info) return 0 __all__ = ["launch_app", "run_headless_check", "SingleInstance"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/gui/main_window.py b/src/gui/main_window.py index 01311b7..1f1ac08 100644 --- a/src/gui/main_window.py +++ b/src/gui/main_window.py @@ -1,3 +1,7 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/gui/main_window.py | app_id (boards.id): 13 +# ============================================================ """ النافذة الرئيسية — كل تبويبات البرنامج وإدارة المهام والأيقونة ومركز التنبيهات. @@ -18,9 +22,7 @@ from PySide6.QtWidgets import ( QAbstractItemView, QCheckBox, - QComboBox, QFileDialog, - QFormLayout, QFrame, QGridLayout, QGroupBox, @@ -28,7 +30,6 @@ QHeaderView, QInputDialog, QLabel, - QLineEdit, QListWidget, QMainWindow, QMenu, @@ -48,6 +49,7 @@ from src.core.app_catalog import get_process_info, get_service_info from src.core.app_context import AppContext from src.core.results import ActionResult +from src.gui.admin_panel import AdminPanelTab from src.gui.dialogs import ( AboutDialog, ConfirmDialog, @@ -55,6 +57,7 @@ ProtectionPickerDialog, TextReportDialog, ) +from src.gui.other_apps import OtherAppsTab from src.gui.settings_window import SettingsWindow from src.gui.theme import COLORS, stylesheet from src.gui.widgets import Card, SectionHeader, StatCard, ToastManager # noqa: F401 @@ -133,8 +136,10 @@ def _build_ui(self) -> None: self.tabs.addTab(self._tab_health(), "الأعطال والصحة") self.tabs.addTab(self._tab_journal(), "سجل التغييرات") self.tabs.addTab(self._tab_logs(), "سجل العمليات") + # لوحة الأم: إدارة التطبيق للأدمن (is_admin=1 من app_users) والتطبيقات الشقيقة للجميع if self.is_admin_role: - self.tabs.addTab(self._tab_users(), "المستخدمون") + self.tabs.addTab(AdminPanelTab(self.ctx), "لوحة التحكم") + self.tabs.addTab(OtherAppsTab(self.ctx), "تطبيقات أخرى") root.addWidget(self.tabs, 1) root.addWidget(self._build_bottom_bar()) @@ -693,41 +698,6 @@ def _tab_logs(self) -> QWidget: logger.info("بدأت جلسة جديدة للمستخدم %s.", self.current_user["username"]) return page - def _tab_users(self) -> QWidget: - page = QWidget() - layout = QVBoxLayout(page) - layout.addWidget(QLabel("إدارة حسابات البرنامج (محلية، مشفّرة، ولا تُرسل لأي مكان).")) - - self.users_list = QListWidget() - layout.addWidget(self.users_list, 1) - - form_box = Card("إضافة مستخدم") - form = QFormLayout() - self.new_username = QLineEdit() - self.new_password = QLineEdit() - self.new_password.setEchoMode(QLineEdit.Password) - self.new_role = QComboBox() - self.new_role.addItems(["user", "admin"]) - form.addRow("اسم المستخدم:", self.new_username) - form.addRow("كلمة المرور:", self.new_password) - form.addRow("الدور:", self.new_role) - form_box.add_layout(form) - - row = QHBoxLayout() - btn_add = QPushButton("إضافة") - btn_add.setObjectName("primaryButton") - btn_add.clicked.connect(self.add_user) - row.addWidget(btn_add) - btn_remove = QPushButton("حذف المحدد") - btn_remove.clicked.connect(self.remove_user) - row.addWidget(btn_remove) - row.addStretch() - form_box.add_layout(row) - layout.addWidget(form_box) - - self.refresh_users() - return page - # ================================================================== # أدوات مساعدة للجداول والبطاقات # ================================================================== @@ -1497,47 +1467,6 @@ def open_logs_folder(self) -> None: except Exception as exc: QMessageBox.information(self, "السجلات", f"مجلد السجلات: {folder}\n({exc})") - # ================================================================== - # المستخدمون - # ================================================================== - def refresh_users(self) -> None: - self.users_list.clear() - for user in self.ctx.auth.list_users(): - self.users_list.addItem( - f"{user.get('username')} — {'مدير' if user.get('role') == 'admin' else 'مستخدم'}" - ) - - def add_user(self) -> None: - username = self.new_username.text().strip() - password = self.new_password.text() - role = self.new_role.currentText() - try: - self.ctx.auth.create_user(username, password, role=role) - except Exception as exc: - QMessageBox.warning(self, "تعذر الإضافة", str(exc)) - return - self.new_username.clear() - self.new_password.clear() - self.ctx.notifications.success("مستخدم جديد", f"أُنشئ الحساب {username} ({role}).") - self.refresh_users() - - def remove_user(self) -> None: - item = self.users_list.currentItem() - if item is None: - return - username = item.text().split(" — ")[0] - if username == self.current_user.get("username"): - QMessageBox.warning(self, "غير مسموح", "لا يمكنك حذف الحساب الذي تستخدمه الآن.") - return - dialog = ConfirmDialog("حذف مستخدم", f"سيتم حذف الحساب {username} نهائيًا.", confirm_text="حذف", parent=self) - if dialog.exec() != ConfirmDialog.Accepted: - return - if self.ctx.auth.delete_user(username): - self.ctx.notifications.info("حذف مستخدم", f"حُذف الحساب {username}.") - self.refresh_users() - else: - QMessageBox.warning(self, "تعذر الحذف", "لا يمكن حذف آخر حساب مدير في البرنامج.") - # ================================================================== # الإعدادات والتوثيق والتنبيهات # ================================================================== @@ -1690,3 +1619,5 @@ def psutil_free(mount: str) -> int: __all__ = ["MainWindow", "load_app_icon"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/gui/other_apps.py b/src/gui/other_apps.py new file mode 100644 index 0000000..53617b2 --- /dev/null +++ b/src/gui/other_apps.py @@ -0,0 +1,148 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/gui/other_apps.py | app_id (boards.id): 13 +# ============================================================ +""" +تبويب «تطبيقات أخرى» — بطاقات التطبيقات الشقيقة عند المطوّر من نقطة status +(كل تطبيق منفصل بمعرّفه وإحصاءاته في لوحة الأم). فتح الرابط يتم في المتصفح الافتراضي. +""" + +from __future__ import annotations + +import logging + +from PySide6.QtCore import Qt, QUrl +from PySide6.QtGui import QDesktopServices +from PySide6.QtWidgets import ( + QFrame, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QVBoxLayout, + QWidget, +) + +from src.gui.theme import COLORS +from src.version import APP_URL + +logger = logging.getLogger(__name__) + + +class OtherAppsTab(QWidget): + def __init__(self, ctx, parent=None): + super().__init__(parent) + self.ctx = ctx + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(8) + + head = QHBoxLayout() + title = QLabel("تطبيقات المطوّر الأخرى") + title.setStyleSheet(f"font-weight: bold; color: {COLORS['text']};") + head.addWidget(title) + head.addStretch() + self.refresh_btn = QPushButton("تحديث القائمة") + self.refresh_btn.setObjectName("primaryButton") + self.refresh_btn.clicked.connect(self.refresh) + head.addWidget(self.refresh_btn) + layout.addLayout(head) + + self.status_label = QLabel("") + self.status_label.setWordWrap(True) + self.status_label.setStyleSheet(f"color: {COLORS['text_muted']};") + layout.addWidget(self.status_label) + + self.scroll = QScrollArea() + self.scroll.setWidgetResizable(True) + self.scroll.setFrameShape(QFrame.NoFrame) + self.container = QWidget() + self.cards_layout = QVBoxLayout(self.container) + self.cards_layout.setSpacing(10) + self.cards_layout.addStretch() + self.scroll.setWidget(self.container) + layout.addWidget(self.scroll, 1) + + self._show(self.ctx.panel.siblings()) + + # ------------------------------------------------------------------ + def refresh(self) -> None: + if not self.ctx.panel.is_configured: + self.status_label.setText("الاتصال بلوحة الأم غير مُعدّ — تعذّر جلب قائمة التطبيقات.") + return + self.status_label.setText("جارٍ جلب قائمة التطبيقات من لوحة الأم…") + self.refresh_btn.setEnabled(False) + + def _load(): + self.ctx.panel.refresh_status() + return self.ctx.panel.siblings() + + self.ctx.tasks.run(_load, on_success=self._loaded, on_error=self._error, label="تطبيقات أخرى") + + def _loaded(self, items: list[dict]) -> None: + self.refresh_btn.setEnabled(True) + self.status_label.setStyleSheet(f"color: {COLORS['text_muted']};") + self.status_label.setText(f"عدد التطبيقات: {len(items)}") + self._show(items) + + def _error(self, message: str) -> None: + self.refresh_btn.setEnabled(True) + self.status_label.setStyleSheet(f"color: {COLORS['danger']};") + self.status_label.setText(str(message)) + + def _clear(self) -> None: + while self.cards_layout.count() > 1: + item = self.cards_layout.takeAt(0) + widget = item.widget() + if widget is not None: + widget.deleteLater() + + def _show(self, items: list[dict]) -> None: + self._clear() + if not items: + placeholder = QLabel( + "لا توجد تطبيقات شقيقة في لوحة الأم حاليًا.\n" + f"يمكنك دائمًا زيارة صفحة المطوّر: {APP_URL}" + ) + placeholder.setWordWrap(True) + placeholder.setStyleSheet(f"color: {COLORS['text_muted']}; padding: 12px;") + self.cards_layout.insertWidget(0, placeholder) + return + for index, app in enumerate(items): + self.cards_layout.insertWidget(index, self._make_card(app)) + + def _make_card(self, app: dict) -> QFrame: + card = QFrame() + card.setObjectName("card") + row = QHBoxLayout(card) + row.setContentsMargins(14, 10, 14, 10) + badge = QLabel((str(app.get("name") or "?")[:1] or "?").upper()) + badge.setFixedSize(40, 40) + badge.setAlignment(Qt.AlignCenter) + badge.setStyleSheet( + f"background: {COLORS['accent']}; color: white; border-radius: 20px; font-weight: bold; font-size: 18px;" + ) + row.addWidget(badge) + text_col = QVBoxLayout() + name = str(app.get("name") or "") + version = str(app.get("version") or "") + title = QLabel(f"{name}" + (f" v{version}" if version else "")) + title.setTextFormat(Qt.RichText) + text_col.addWidget(title) + description = str(app.get("description") or app.get("summary") or "") + desc_label = QLabel(description) + desc_label.setWordWrap(True) + desc_label.setStyleSheet(f"color: {COLORS['text_muted']}; font-size:12px;") + text_col.addWidget(desc_label) + row.addLayout(text_col, 1) + url = str(app.get("url") or app.get("link") or "") + if url: + btn = QPushButton("فتح") + btn.clicked.connect(lambda _=False, u=url: QDesktopServices.openUrl(QUrl(u))) + row.addWidget(btn) + return card + + +__all__ = ["OtherAppsTab"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/gui/panel_login_window.py b/src/gui/panel_login_window.py new file mode 100644 index 0000000..7ce8ea8 --- /dev/null +++ b/src/gui/panel_login_window.py @@ -0,0 +1,268 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/gui/panel_login_window.py | app_id (boards.id): 13 +# ============================================================ +""" +شاشة الدخول عبر لوحة الأم (إلزامية قبل فتح التطبيق). + +- نفس الحساب يعمل على أي جهاز ويُزامَن (الحسابات في app_users بنطاق app_id=13). +- إنشاء حساب جديد من نفس الشاشة (auth/register). +- عند أول تشغيل: إعداد الاتصال (رابط اللوحة + توكن التطبيق X-App-Token) ويُحفظ محليًا + في panel.json — لا يُخزَّن أي توكن في المستودع أو السجلات. +- الجلسة المحفوظة تُتحقق تلقائيًا عند الفتح (auth/session) فلا يُطلب الدخول كل مرة. +- كل الطلبات في خيط خلفي (TaskManager) حتى لا تتجمد الواجهة. +""" + +from __future__ import annotations + +import logging + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import ( + QCheckBox, + QDialog, + QFormLayout, + QGroupBox, + QHBoxLayout, + QLabel, + QLineEdit, + QPushButton, + QVBoxLayout, +) + +from src.gui.theme import COLORS +from src.panel.auth import validate_credentials +from src.panel.config import PanelConfig, normalize_base_url +from src.panel.service import PanelService +from src.utils.workers import TaskManager +from src.version import APP_NAME, APP_VERSION + +logger = logging.getLogger(__name__) + + +class PanelLoginWindow(QDialog): + """تسجيل الدخول/الإنشاء عبر لوحة الأم.""" + + def __init__(self, service: PanelService, parent=None): + super().__init__(parent) + self.service = service + self.authenticated_user: dict | None = None + self._register_mode = False + self._busy = False + self.tasks = TaskManager(self) + + self.setWindowTitle(f"{APP_NAME} {APP_VERSION} — تسجيل الدخول") + self.setMinimumWidth(440) + self.setModal(True) + + layout = QVBoxLayout(self) + layout.setSpacing(12) + + header = QLabel(f"

{APP_NAME}

") + layout.addWidget(header) + layout.addWidget(QLabel( + "سجّل الدخول بحسابك — نفس الحساب يعمل على كل أجهزتك وتُزامَن إعداداتك تلقائيًا." + )) + + # --- إعداد الاتصال (يظهر فقط عندما لا يكون الاتصال مُعدًّا) --- + self.conn_box = QGroupBox("إعداد الاتصال بلوحة الأم (مرة واحدة)") + conn_form = QFormLayout(self.conn_box) + self.base_url_input = QLineEdit(service.config.base_url) + self.base_url_input.setPlaceholderText("https://panel.example.com") + self.app_token_input = QLineEdit(service.config.app_token) + self.app_token_input.setEchoMode(QLineEdit.Password) + self.app_token_input.setPlaceholderText("X-App-Token من لوحة الأم") + conn_form.addRow("رابط اللوحة:", self.base_url_input) + conn_form.addRow("توكن التطبيق:", self.app_token_input) + conn_row = QHBoxLayout() + self.save_conn_btn = QPushButton("حفظ الاتصال") + self.save_conn_btn.clicked.connect(self.save_connection) + conn_row.addWidget(self.save_conn_btn) + conn_row.addStretch() + conn_form.addRow(conn_row) + layout.addWidget(self.conn_box) + + self.conn_status = QLabel("") + self.conn_status.setWordWrap(True) + layout.addWidget(self.conn_status) + + # --- بيانات الدخول --- + form = QFormLayout() + self.email_input = QLineEdit() + self.email_input.setPlaceholderText("name@example.com") + self.email_input.setText(service.store.last_email) + self.password_input = QLineEdit() + self.password_input.setEchoMode(QLineEdit.Password) + form.addRow("البريد الإلكتروني:", self.email_input) + form.addRow("كلمة المرور:", self.password_input) + + self.name_input = QLineEdit() + self.name_input.setPlaceholderText("اختياري") + self.confirm_input = QLineEdit() + self.confirm_input.setEchoMode(QLineEdit.Password) + form.addRow("الاسم:", self.name_input) + form.addRow("تأكيد كلمة المرور:", self.confirm_input) + layout.addLayout(form) + + self.error_label = QLabel("") + self.error_label.setWordWrap(True) + self.error_label.setStyleSheet(f"color: {COLORS['danger']};") + layout.addWidget(self.error_label) + + self.status_label = QLabel("") + self.status_label.setWordWrap(True) + self.status_label.setStyleSheet(f"color: {COLORS['text_muted']};") + layout.addWidget(self.status_label) + + self.remember_cb = QCheckBox("تذكر البريد على هذا الجهاز") + self.remember_cb.setChecked(True) + layout.addWidget(self.remember_cb) + + row = QHBoxLayout() + self.submit_btn = QPushButton("تسجيل الدخول") + self.submit_btn.setObjectName("primaryButton") + self.submit_btn.clicked.connect(self.handle_submit) + row.addWidget(self.submit_btn) + self.mode_btn = QPushButton("إنشاء حساب جديد") + self.mode_btn.clicked.connect(self.toggle_mode) + row.addWidget(self.mode_btn) + cancel_btn = QPushButton("خروج") + cancel_btn.clicked.connect(self.reject) + row.addWidget(cancel_btn) + row.addStretch() + layout.addLayout(row) + + self.password_input.returnPressed.connect(self.handle_submit) + self.confirm_input.returnPressed.connect(self.handle_submit) + self._apply_mode() + self._refresh_conn_state() + + # التحقق من جلسة محفوظة في الخلفية — إن كانت صالحة يُفتح التطبيق مباشرة + if self.service.has_stored_session(): + self._set_busy(True, "جارٍ التحقق من الجلسة المحفوظة…") + self.tasks.run( + self.service.restore_session, + on_success=self._restored, + on_error=self._restore_failed, + label="التحقق من الجلسة", + ) + + # ------------------------------------------------------------------ + def _refresh_conn_state(self) -> None: + configured = self.service.is_configured + self.conn_box.setVisible(not configured) + if configured: + self.conn_status.setStyleSheet(f"color: {COLORS['success']};") + self.conn_status.setText(f"متصل بلوحة الأم: {self.service.config.base_url} (app_id {self.service.config.app_id})") + else: + self.conn_status.setStyleSheet(f"color: {COLORS['warning']};") + self.conn_status.setText("لم يتم إعداد الاتصال بلوحة الأم بعد — أدخل الرابط والتوكن ثم اضغط «حفظ الاتصال».") + self.submit_btn.setEnabled(not self._busy) + + def save_connection(self) -> None: + base_url = normalize_base_url(self.base_url_input.text()) + token = self.app_token_input.text().strip() + if not base_url or not token: + self.error_label.setText("أدخل رابط اللوحة وتوكن التطبيق (X-App-Token).") + return + try: + self.service.reconfigure(PanelConfig(base_url=base_url, app_token=token)) + except Exception as exc: # pragma: no cover - حفظ محلي فقط + self.error_label.setText(f"تعذر حفظ الاتصال: {exc}") + return + self.error_label.setText("") + self.app_token_input.clear() + self._refresh_conn_state() + + # ------------------------------------------------------------------ + def toggle_mode(self) -> None: + self._register_mode = not self._register_mode + self._apply_mode() + + def _apply_mode(self) -> None: + self.name_input.setVisible(self._register_mode) + self.confirm_input.setVisible(self._register_mode) + if self._register_mode: + self.submit_btn.setText("إنشاء الحساب والدخول") + self.mode_btn.setText("لديك حساب؟ سجّل الدخول") + else: + self.submit_btn.setText("تسجيل الدخول") + self.mode_btn.setText("إنشاء حساب جديد") + if not self._busy: + self._clear_error() + + def _clear_error(self) -> None: + self.error_label.setText("") + + def _set_busy(self, busy: bool, message: str = "") -> None: + self._busy = busy + self.status_label.setText(message) + self.submit_btn.setEnabled(not busy) + self.mode_btn.setEnabled(not busy) + self.save_conn_btn.setEnabled(not busy) + if busy: + self.setCursor(Qt.BusyCursor) + else: + self.unsetCursor() + + # ------------------------------------------------------------------ + def handle_submit(self) -> None: + if self._busy: + return + if not self.service.is_configured: + self.save_connection() + if not self.service.is_configured: + return + email = self.email_input.text().strip() + password = self.password_input.text() + name = self.name_input.text().strip() + problem = validate_credentials(email, password) + if not problem and self._register_mode and password != self.confirm_input.text(): + problem = "كلمتا المرور غير متطابقتين." + if problem: + self.error_label.setText(problem) + return + self._clear_error() + if self.remember_cb.isChecked(): + self.service.store.last_email = email + if self._register_mode: + fn = lambda: self.service.register(email, password, name) # noqa: E731 + label = "إنشاء الحساب" + else: + fn = lambda: self.service.login(email, password) # noqa: E731 + label = "تسجيل الدخول" + self.password_input.clear() + self.confirm_input.clear() + self._set_busy(True, "جارٍ التحقق من الحساب عبر لوحة الأم…") + self.tasks.run(fn, on_success=self._login_ok, on_error=self._login_failed, label=label) + + def _login_ok(self, user: dict) -> None: + self._set_busy(False) + self.authenticated_user = user + self.accept() + + def _login_failed(self, message: str) -> None: + self._set_busy(False) + self.error_label.setText(str(message)) + + def _restored(self, user: dict | None) -> None: + if user: + self._set_busy(False) + self.authenticated_user = user + self.accept() + else: + self._set_busy(False) + + def _restore_failed(self, message: str) -> None: + self._set_busy(False) + logger.info("Session restore skipped: %s", message) + + def closeEvent(self, event) -> None: # noqa: N802 + if self._busy: + self.tasks.wait_all(timeout_ms=2000) + super().closeEvent(event) + + +__all__ = ["PanelLoginWindow"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/__init__.py b/src/panel/__init__.py new file mode 100644 index 0000000..7ee055f --- /dev/null +++ b/src/panel/__init__.py @@ -0,0 +1,43 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# package: src/panel | app_id (boards.id): 13 +# ============================================================ +""" +حزمة الاندماج مع «لوحة الأم» لتطبيق Faster-PC (سطح مكتب). + +الترتيب المنطقي للوحدات: + identity → ثوابت التطبيق والمطوّر (app_id=13) + config → إعدادات الاتصال (base_url + X-App-Token) من البيئة أو panel.json + client → عميل /api/v1 (JSON فقط، X-App-Id/X-Req-Id/Bearer) + session → الجلسة المحلية + معرّف الجهاز + auth → auth/register · login · session · logout (is_admin من الخادم) + sync → sync push/pull مع sync_version وكشف التعارض + updates → releases/check (full/sub/min_version) + licenses → licenses/verify · activate + telemetry → telemetry (أحداث خفيفة بلا بيانات شخصية) + control → control (لوحة الإدارة للأدمن) + status (التطبيقات الشقيقة) + service → PanelService: الواجهة الواحدة للواجهة الرسومية +""" + +from src.panel.client import MotherPanelClient, PanelError, UrllibTransport +from src.panel.config import PanelConfig, load_config, save_config +from src.panel.identity import APP_ID, DEVELOPER_NAME, DEVELOPER_NAME_EN, SIGNATURE +from src.panel.service import PanelService +from src.panel.session import SessionStore + +__all__ = [ + "APP_ID", + "DEVELOPER_NAME", + "DEVELOPER_NAME_EN", + "SIGNATURE", + "MotherPanelClient", + "PanelConfig", + "PanelError", + "PanelService", + "SessionStore", + "UrllibTransport", + "load_config", + "save_config", +] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/auth.py b/src/panel/auth.py new file mode 100644 index 0000000..232d141 --- /dev/null +++ b/src/panel/auth.py @@ -0,0 +1,121 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/auth.py | app_id (boards.id): 13 +# ============================================================ +""" +المصادقة عبر لوحة الأم — لا حسابات محلية بعد الآن. + +- تسجيل الدخول إلزامي قبل فتح التطبيق (auth/login)، والحسابات منفصلة لكل تطبيق + (app_users بنطاق app_id=13، UNIQUE(app_id,email)). +- is_admin يأتي من app_users.is_admin (0/1) عبر الـ API فقط؛ لا يُحدَّد محليًا. +- الجلسة (app_sessions) تُحفظ محليًا وتُتحقق منه عند كل تشغيل عبر auth/session. +""" + +from __future__ import annotations + +import logging +import re + +from src.panel.client import MotherPanelClient, PanelError +from src.panel.session import SessionStore, app_user_from_panel + +logger = logging.getLogger(__name__) + +EMAIL_RE = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$") + + +def validate_credentials(email: str, password: str) -> str: + """تحقق محلي أساسي قبل إرسال أي شيء للخادم. يرجع رسالة خطأ أو ''.""" + email = (email or "").strip() + if not EMAIL_RE.match(email): + return "أدخل بريدًا إلكترونيًا صحيحًا." + if len(password or "") < 8: + return "كلمة المرور يجب ألا تقل عن 8 أحرف." + return "" + + +class PanelAuthenticator: + """عمليات auth/*: register · login · session · logout.""" + + def __init__(self, client: MotherPanelClient, store: SessionStore): + self.client = client + self.store = store + + # ------------------------------------------------------------------ + @property + def current_user(self) -> dict | None: + """المستخدم الحالي بشكل الواجهة (username/role/is_admin) أو None.""" + return app_user_from_panel(self.store.user) + + @property + def is_admin(self) -> bool: + user = self.current_user + return bool(user and user.get("is_admin")) + + def has_stored_session(self) -> bool: + return bool(self.store.session_token and self.store.user) + + # ------------------------------------------------------------------ + def _accept(self, data: dict) -> dict: + token = str(data.get("session_token") or data.get("token") or "") + user = data.get("user") if isinstance(data.get("user"), dict) else None + if not token or not user: + raise PanelError("استجابة دخول غير مكتملة من لوحة الأم.", code="bad_response") + self.store.session_token = token + self.store.user = user + self.store.last_email = str(user.get("email") or "") + self.client.set_session(token) + app_user = app_user_from_panel(user) + logger.info("Panel login ok: %s (is_admin=%s)", app_user["username"], app_user["is_admin"]) + return app_user + + def register(self, email: str, password: str, name: str = "") -> dict: + problem = validate_credentials(email, password) + if problem: + raise PanelError(problem, code="validation") + return self._accept(self.client.register(email.strip(), password, name.strip())) + + def login(self, email: str, password: str) -> dict: + problem = validate_credentials(email, password) + if problem: + raise PanelError(problem, code="validation") + return self._accept(self.client.login(email.strip(), password)) + + def restore(self) -> dict | None: + """التحقق من الجلسة المحفوظة عند التشغيل. يرجع المستخدم أو None (بلا جلسة/منتهية).""" + if not self.has_stored_session(): + return None + self.client.set_session(self.store.session_token) + try: + data = self.client.session() + except PanelError as exc: + if exc.is_auth_error: + logger.info("Stored panel session rejected (%s); login required again.", exc.code) + self.store.session_token = "" + self.store.user = None + self.client.set_session("") + else: + logger.warning("Could not verify panel session: %s", exc) + return None + user = data.get("user") if isinstance(data.get("user"), dict) else None + if user: + self.store.user = user + return self.current_user + + def logout(self) -> None: + """إنهاء الجلسة في اللوحة الأم ثم محليًا (أي خطأ شبكة لا يمنع الخروج المحلي).""" + if self.store.session_token: + try: + self.client.logout() + except PanelError as exc: + logger.warning("Panel logout failed (%s); clearing local session anyway.", exc.code) + self.client.set_session("") + self.store.session_token = "" + self.store.user = None + self.store.sync_version = 0 + self.store.save() + + +__all__ = ["EMAIL_RE", "PanelAuthenticator", "validate_credentials"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/client.py b/src/panel/client.py new file mode 100644 index 0000000..2c9ec2a --- /dev/null +++ b/src/panel/client.py @@ -0,0 +1,279 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/client.py | app_id (boards.id): 13 +# ============================================================ +""" +عميل بوابة الـ API في لوحة الأم (JSON فقط — لا HTML أبدًا). + +عقد الاستجابة المتوقع من كل نقطة: + {"ok": true, "req_id": "<نفس X-Req-Id>", "data": {...}} + {"ok": false, "req_id": "...", "error": {"code": "...", "message": "...", "details": {...}}} +وأي استجابة JSON بدون مفتاح ok تُعامل كأنها data مباشرة (تسامح). + +الترويسات المرسلة في كل طلب: + X-App-Token: توكن التطبيق من اللوحة الأم (لا يُسجَّل أبدًا) + X-App-Id: 13 • X-Req-Id: معرّف فريد لكل طلب (يُسجَّل في audit_log/sync_log) + Authorization: Bearer عند وجود جلسة +""" + +from __future__ import annotations + +import json +import logging +import ssl +import uuid +from typing import Any, Protocol +from urllib import error, parse, request + +from src.panel.config import PanelConfig +from src.panel.identity import APP_ID, user_agent +from src.version import APP_VERSION + +logger = logging.getLogger(__name__) + + +class PanelError(Exception): + """خطأ موحّد من بوابة الـ API (شبكة / HTTP / منطقي). يحمل code و req_id للدعم.""" + + AUTH_CODES = {"unauthorized", "session_expired", "forbidden", "not_admin", "invalid_token"} + + def __init__( + self, + message: str, + *, + status: int = 0, + code: str = "", + req_id: str = "", + data: dict | None = None, + ): + super().__init__(message) + self.status = status + self.code = code or (f"http_{status}" if status else "error") + self.req_id = req_id + self.data = data or {} + + @property + def is_auth_error(self) -> bool: + return self.status in (401, 403) or self.code in self.AUTH_CODES + + @property + def is_conflict(self) -> bool: + return self.status == 409 or self.code == "sync_conflict" + + @property + def is_network_error(self) -> bool: + return self.code in {"network", "timeout"} + + +class Transport(Protocol): + """طبقة النقل: تُرجع (status, body) — قابلة للاستبدال في الاختبارات.""" + + def call(self, method: str, url: str, headers: dict, body: bytes | None) -> tuple[int, bytes]: # pragma: no cover + ... + + +class UrllibTransport: + """نقل حقيقي عبر urllib من المكتبة القياسية (بدون اعتماديات إضافية).""" + + def __init__(self, timeout: float = 15.0): + self.timeout = timeout + + def call(self, method: str, url: str, headers: dict, body: bytes | None) -> tuple[int, bytes]: + req = request.Request(url, data=body, method=method, headers=headers) + context = ssl.create_default_context() + try: + with request.urlopen(req, timeout=self.timeout, context=context) as resp: + return resp.status, resp.read() + except error.HTTPError as exc: # 4xx/5xx تحمل جسم JSON من اللوحة + try: + payload = exc.read() + except Exception: # pragma: no cover + payload = b"" + return exc.code, payload + except error.URLError as exc: + reason = str(exc.reason or exc) + if "timed out" in reason.lower() or isinstance(exc.reason, TimeoutError): + raise PanelError("انتهت مهلة الاتصال بلوحة الأم.", code="timeout") from exc + raise PanelError(f"تعذر الاتصال بلوحة الأم: {reason}", code="network") from exc + except (TimeoutError, OSError) as exc: + raise PanelError(f"تعذر الاتصال بلوحة الأم: {exc}", code="network") from exc + + +class MotherPanelClient: + """كل النقاط المطلوبة من بوابة /api/v1 — بنطاق app_id صارم في كل طلب.""" + + def __init__( + self, + config: PanelConfig, + transport: Transport | None = None, + session_token: str = "", + device: dict | None = None, + ): + self.config = config + self.transport = transport or UrllibTransport(timeout=config.timeout_sec) + self.session_token = session_token + self.device = dict(device or {}) + + # ------------------------------------------------------------------ + @property + def is_configured(self) -> bool: + return self.config.is_configured + + def set_session(self, token: str) -> None: + self.session_token = token or "" + + def _url(self, path: str, params: dict | None = None) -> str: + url = f"{self.config.api_base}/{path.lstrip('/')}" + if params: + clean = {k: v for k, v in params.items() if v is not None and v != ""} + if clean: + url += "?" + parse.urlencode(clean) + return url + + def _headers(self, req_id: str, has_body: bool, authenticated: bool) -> dict: + headers = { + "Accept": "application/json", + "X-App-Token": self.config.app_token, + "X-App-Id": str(self.config.app_id), + "X-Req-Id": req_id, + "User-Agent": user_agent(APP_VERSION), + } + if has_body: + headers["Content-Type"] = "application/json" + if authenticated and self.session_token: + headers["Authorization"] = f"Bearer {self.session_token}" + headers.update(self.config.extra_headers) + return headers + + # ------------------------------------------------------------------ + def request( + self, + method: str, + path: str, + body: dict | None = None, + params: dict | None = None, + authenticated: bool = True, + raw: bool = False, + ) -> Any: + """تنفيذ طلب JSON. يرجع data (أو الاستجابة كاملة عند raw=True).""" + if not self.config.is_configured: + raise PanelError("لم يتم إعداد الاتصال بلوحة الأم.", code="not_configured") + req_id = uuid.uuid4().hex + url = self._url(path, params) + data = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None + headers = self._headers(req_id, has_body=data is not None, authenticated=authenticated) + try: + status, payload = self.transport.call(method.upper(), url, headers, data) + except PanelError: + raise + except Exception as exc: # pragma: no cover - أي خطأ غير متوقع في النقل + raise PanelError(f"خطأ في الاتصال بلوحة الأم: {exc}", code="network") from exc + + try: + parsed = json.loads(payload.decode("utf-8")) if payload else {} + except (ValueError, UnicodeDecodeError) as exc: + raise PanelError( + f"استجابة غير صالحة من لوحة الأم (HTTP {status}).", status=status, code="bad_response", req_id=req_id + ) from exc + + if not isinstance(parsed, dict): + parsed = {"ok": True, "req_id": req_id, "data": parsed} + if "ok" not in parsed: # تسامح: استجابة بدون غلاف + parsed = {"ok": True, "req_id": req_id, "data": parsed} + + ok = bool(parsed.get("ok")) + response_req_id = str(parsed.get("req_id") or req_id) + if not ok: + err = parsed.get("error") or {} + message = str(err.get("message") or parsed.get("message") or f"رفضت لوحة الأم الطلب (HTTP {status}).") + code = str(err.get("code") or (f"http_{status}" if status else "error")) + details = err.get("details") if isinstance(err.get("details"), dict) else {} + logger.warning("Panel API %s %s -> %s code=%s req_id=%s", method.upper(), path, status, code, response_req_id) + raise PanelError(message, status=status, code=code, req_id=response_req_id, data=details) + if status >= 400: + raise PanelError(f"خطأ من لوحة الأم (HTTP {status}).", status=status, req_id=response_req_id) + + logger.debug("Panel API %s %s -> %s req_id=%s", method.upper(), path, status, response_req_id) + if raw: + return parsed + data_out = parsed.get("data") + return data_out if data_out is not None else {} + + # ------------------------------------------------------------------ + # النقاط المطلوبة + # ------------------------------------------------------------------ + def status(self) -> dict: + """حالة التطبيق + الإعدادات + التحديثات + التطبيقات الشقيقة.""" + return self.request("GET", "status", authenticated=False) + + def register(self, email: str, password: str, name: str = "") -> dict: + return self.request( + "POST", + "auth/register", + body={"email": email, "password": password, "name": name, "device": self.device}, + authenticated=False, + ) + + def login(self, email: str, password: str) -> dict: + return self.request( + "POST", + "auth/login", + body={"email": email, "password": password, "device": self.device}, + authenticated=False, + ) + + def session(self) -> dict: + return self.request("GET", "auth/session") + + def logout(self) -> dict: + return self.request("POST", "auth/logout") + + def sync_push(self, payload: dict, base_version: int | None) -> dict: + """دفع الإعدادات المحلية مع إصدار المزامنة الأساسي (لكشف التعارض).""" + return self.request( + "POST", + "sync", + body={"op": "push", "device_uid": self.device.get("uid", ""), "base_version": base_version, "payload": payload}, + ) + + def sync_pull(self, since_version: int | None) -> dict: + return self.request( + "POST", + "sync", + body={"op": "pull", "device_uid": self.device.get("uid", ""), "since_version": since_version}, + ) + + def releases_check(self, current_version: str, channel: str = "stable") -> dict: + return self.request( + "GET", "releases/check", params={"current": current_version, "channel": channel}, authenticated=False + ) + + def license_verify(self, license_key: str) -> dict: + return self.request( + "POST", "licenses/verify", body={"license_key": license_key, "device": self.device} + ) + + def license_activate(self, license_key: str) -> dict: + return self.request( + "POST", "licenses/activate", body={"license_key": license_key, "device": self.device} + ) + + def telemetry(self, events: list[dict]) -> dict: + return self.request("POST", "telemetry", body={"device_uid": self.device.get("uid", ""), "events": events}) + + def control(self, section: str, op: str = "", params: dict | None = None) -> dict: + """نظرة عامة/مستخدمون/أجهزة/إصدارات/إعدادات/متطلبات — لحساب الأدمن فقط (is_admin=1).""" + query = {"section": section, "op": op or None} + query.update(params or {}) + return self.request("GET", "control", params=query) + + +__all__ = [ + "APP_ID", + "MotherPanelClient", + "PanelError", + "Transport", + "UrllibTransport", +] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/config.py b/src/panel/config.py new file mode 100644 index 0000000..093e601 --- /dev/null +++ b/src/panel/config.py @@ -0,0 +1,151 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/config.py | app_id (boards.id): 13 +# ============================================================ +""" +إعدادات الاتصال بلوحة الأم (Mother Panel). + +مصادر الإعدادات بالأولوية: + 1) متغيرا البيئة FASTERPC_PANEL_URL / FASTERPC_PANEL_TOKEN (للخوادم والاختبارات). + 2) ملف panel.json في مجلد بيانات التطبيق (يُنشأ من شاشة الدخول عند أول تشغيل). +لا يُخزَّن التوكن في المستودع ولا في السجلات؛ PanelConfig يعرض التوكن مقنّعًا دائمًا. +""" + +from __future__ import annotations + +import json +import logging +import os +import tempfile +from dataclasses import dataclass, field +from urllib.parse import urlsplit, urlunsplit + +from src.panel.identity import APP_ID +from src.utils.paths import writable_path + +logger = logging.getLogger(__name__) + +ENV_URL = "FASTERPC_PANEL_URL" +ENV_TOKEN = "FASTERPC_PANEL_TOKEN" +CONFIG_FILE = "panel.json" +DEFAULT_TIMEOUT_SEC = 15.0 + + +def normalize_base_url(url: str) -> str: + """توحيد رابط لوحة الأم: https افتراضيًا، بلا شرطة زائدة، وبلا لاحقة /api/v1.""" + value = (url or "").strip() + if not value: + return "" + if "://" not in value: + value = "https://" + value + parts = urlsplit(value) + path = parts.path.rstrip("/") + if path.lower().endswith("/api/v1"): + path = path[: -len("/api/v1")].rstrip("/") + return urlunsplit((parts.scheme, parts.netloc, path, "", "")).rstrip("/") + + +@dataclass(frozen=True) +class PanelConfig: + """إعدادات اتصال كاملة بلوحة الأم (غير قابلة للتعديل — أعد الإنشاء عند التغيير).""" + + base_url: str = "" + app_token: str = "" + app_id: int = APP_ID + timeout_sec: float = DEFAULT_TIMEOUT_SEC + extra_headers: dict = field(default_factory=dict) + + @property + def api_base(self) -> str: + return f"{self.base_url}/api/v1" if self.base_url else "" + + @property + def is_configured(self) -> bool: + return bool(self.base_url and self.app_token) + + @property + def masked_token(self) -> str: + token = self.app_token + if not token: + return "" + if len(token) <= 8: + return "****" + return f"{token[:4]}…{token[-4:]}" + + def __repr__(self) -> str: # pragma: no cover - لمنع تسريب التوكن في السجلات + return ( + f"PanelConfig(base_url={self.base_url!r}, app_id={self.app_id}, " + f"app_token={self.masked_token!r}, timeout_sec={self.timeout_sec})" + ) + + +def config_file_path() -> str: + return writable_path(CONFIG_FILE) + + +def _atomic_write(path: str, text: str) -> None: + directory = os.path.dirname(path) or "." + os.makedirs(directory, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".panel-", dir=directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(text) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def load_config(path: str | None = None) -> PanelConfig: + """قراءة الإعدادات: البيئة أولًا ثم الملف. أي خطأ في الملف → إعدادات فارغة (غير مُعدّ).""" + env_url = (os.environ.get(ENV_URL) or "").strip() + env_token = (os.environ.get(ENV_TOKEN) or "").strip() + if env_url and env_token: + return PanelConfig(base_url=normalize_base_url(env_url), app_token=env_token) + data: dict = {} + try: + with open(path or config_file_path(), encoding="utf-8") as handle: + data = json.load(handle) + if not isinstance(data, dict): + data = {} + except FileNotFoundError: + return PanelConfig() + except (OSError, ValueError) as exc: + logger.warning("panel.json unreadable (%s); starting unconfigured.", exc) + return PanelConfig() + return PanelConfig( + base_url=normalize_base_url(str(data.get("base_url") or "")), + app_token=str(data.get("app_token") or ""), + timeout_sec=float(data.get("timeout_sec") or DEFAULT_TIMEOUT_SEC), + ) + + +def save_config(config: PanelConfig, path: str | None = None) -> str: + """حفظ الإعدادات في ملف محلي (atomic). يرجع المسار. لا يسجّل التوكن في السجلات.""" + target = path or config_file_path() + payload = { + "base_url": normalize_base_url(config.base_url), + "app_token": config.app_token, + "timeout_sec": config.timeout_sec, + } + _atomic_write(target, json.dumps(payload, ensure_ascii=False, indent=2)) + logger.info("Mother Panel connection saved to %s (token masked: %s)", target, config.masked_token) + return target + + +__all__ = [ + "CONFIG_FILE", + "DEFAULT_TIMEOUT_SEC", + "ENV_TOKEN", + "ENV_URL", + "PanelConfig", + "config_file_path", + "load_config", + "normalize_base_url", + "save_config", +] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/control.py b/src/panel/control.py new file mode 100644 index 0000000..f663b90 --- /dev/null +++ b/src/panel/control.py @@ -0,0 +1,79 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/control.py | app_id (boards.id): 13 +# ============================================================ +""" +نقطة control للوحة الإدارة داخل التطبيق (لحساب الأدمن فقط — is_admin=1): +overview · users · devices · releases · settings · requirements. + +Faster-PC لا يتعامل مع GitHub وقت التشغيل، لذلك لا يطلب op=github_token أبدًا؛ +خيار «هذا التطبيق يتعامل مع GitHub» يبقى معطّلًا في إعدادات اللوحة (انظر HANDOFF). +""" + +from __future__ import annotations + +import logging +from typing import Any + +from src.panel.client import MotherPanelClient + +logger = logging.getLogger(__name__) + +SECTIONS: tuple[tuple[str, str], ...] = ( + ("overview", "نظرة عامة"), + ("users", "المستخدمون"), + ("devices", "الأجهزة"), + ("releases", "الإصدارات"), + ("settings", "الإعدادات"), + ("requirements", "المتطلبات"), +) + + +def as_rows(data: Any) -> list[dict]: + """تطبيع أي شكل شائع لقائمة صفوف: list · {items:[...]} · {rows:[...]} · {users:[...]}...""" + if isinstance(data, list): + return [row for row in data if isinstance(row, dict)] + if isinstance(data, dict): + for key in ("items", "rows", "list", "data", "users", "devices", "releases", "requirements", "entries"): + value = data.get(key) + if isinstance(value, list): + return [row for row in value if isinstance(row, dict)] + return [] + + +def as_stats(data: Any) -> dict: + """تحويل استجابة overview إلى قاموس {اسم: قيمة نصية} للعرض في بطاقات.""" + if not isinstance(data, dict): + return {} + stats: dict = {} + for key, value in data.items(): + if isinstance(value, (int, float, str, bool)) or value is None: + stats[key] = "" if value is None else value + elif isinstance(value, dict): + for sub_key, sub_value in value.items(): + if isinstance(sub_value, (int, float, str, bool)): + stats[f"{key}.{sub_key}"] = sub_value + return stats + + +class AdminControl: + """واجهة رقيقة لنقطة control مع تطبيع النتائج للواجهة.""" + + def __init__(self, client: MotherPanelClient): + self.client = client + + def section(self, section: str, page: int = 1, op: str = "", extra: dict | None = None) -> dict: + params: dict = {"page": page} + params.update(extra or {}) + return self.client.control(section, op=op, params=params) + + def overview(self) -> dict: + return as_stats(self.section("overview")) + + def rows(self, section: str, page: int = 1) -> list[dict]: + return as_rows(self.section(section, page=page)) + + +__all__ = ["SECTIONS", "AdminControl", "as_rows", "as_stats"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/identity.py b/src/panel/identity.py new file mode 100644 index 0000000..fbda582 --- /dev/null +++ b/src/panel/identity.py @@ -0,0 +1,48 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/identity.py | app_id (boards.id): 13 +# ============================================================ +""" +هوية التطبيق في «لوحة الأم» — ثوابت واحدة لا تتغير من مكان آخر. + +- app_id = 13 هو معرّف التطبيق في اللوحة الأم (boards.id) ويُرسل في كل طلب. +- بيانات المطوّر تُسجَّل هنا وتظهر في «حول» وفي ترويسات طلبات الـ API. +- لا يحتوي هذا الملف أي توكن أو كلمة مرور. +""" + +from __future__ import annotations + +APP_ID = 13 # boards.id في لوحة الأم +APP_KEY = "faster_pc" # مفتاح نصي ثابت للتطبيق (للمسارات والأسماء) +APP_TYPE = "desktop" # نوع التطبيق: سطح مكتب فقط +APP_PLATFORM = "windows" # منصة التشغيل المستهدفة + +DEVELOPER_NAME = "يوسف الحمزي" +DEVELOPER_NAME_EN = "Yousef Alhamzy" +# بريد المطوّر غير مُتاح وقت كتابة هذا الملف — مسجّل كمتطلب ناقص (info/high) +# في MOTHER_PANEL_HANDOFF.md؛ يُستكمل من المطوّر فقط ولا يُخمَّن هنا. +DEVELOPER_EMAIL = "" +DEVELOPER_URL = "https://github.com/yswef" + +SIGNATURE = f"© {DEVELOPER_NAME_EN} ({DEVELOPER_NAME}) — Faster-PC (app_id {APP_ID})" + + +def user_agent(app_version: str) -> str: + """User-Agent لطلبات الـ API (بدون أي بيانات حساسة).""" + return f"FasterPC/{app_version} ({APP_PLATFORM}; {APP_KEY}; app_id={APP_ID})" + + +__all__ = [ + "APP_ID", + "APP_KEY", + "APP_TYPE", + "APP_PLATFORM", + "DEVELOPER_NAME", + "DEVELOPER_NAME_EN", + "DEVELOPER_EMAIL", + "DEVELOPER_URL", + "SIGNATURE", + "user_agent", +] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/licenses.py b/src/panel/licenses.py new file mode 100644 index 0000000..dbdedfc --- /dev/null +++ b/src/panel/licenses.py @@ -0,0 +1,71 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/licenses.py | app_id (boards.id): 13 +# ============================================================ +""" +التراخيص عبر licenses/verify و licenses/activate (إنشاء/إلغاء/تفعيل الترخيص من لوحة الأم فقط). + +التطبيق حاليًا مجاني؛ تفعيل فحص الترخيص يتحكم به خادم اللوحة عبر +status.app.settings.licenses_enabled — لا يُفعَّل محليًا أبدًا. +""" + +from __future__ import annotations + +import logging + +from src.panel.client import MotherPanelClient, PanelError +from src.panel.session import SessionStore + +logger = logging.getLogger(__name__) + + +class LicenseManager: + def __init__(self, client: MotherPanelClient, store: SessionStore): + self.client = client + self.store = store + + # ------------------------------------------------------------------ + @property + def status(self) -> dict: + lic = self.store.license or {} + return { + "key": str(lic.get("key") or ""), + "state": str(lic.get("status") or "none"), + "plan": str(lic.get("plan") or ""), + "expires_at": str(lic.get("expires_at") or ""), + } + + def _record(self, data: dict, default_state: str, license_key: str = "") -> dict: + record = { + "key": str(data.get("license_key") or data.get("key") or license_key or self.status["key"]), + "status": str(data.get("status") or default_state), + "plan": str(data.get("plan") or data.get("tier") or ""), + "expires_at": str(data.get("expires_at") or ""), + "device_uid": self.store.device_uid, + } + self.store.license = record + return record + + def verify(self, license_key: str) -> dict: + """التحقق من ترخيص (بدون تفعيل). يرفع PanelError إن كان غير صالح.""" + data = self.client.license_verify(license_key.strip()) + valid = bool(data.get("valid", True)) + record = self._record(data, "valid" if valid else "invalid", license_key.strip()) + if not valid: + raise PanelError(str(data.get("message") or "الترخيص غير صالح."), code="license_invalid", data=data) + return record + + def activate(self, license_key: str) -> dict: + """تفعيل ترخيص على هذا الجهاز (UNIQUE(app_id, device_uid) في اللوحة الأم).""" + data = self.client.license_activate(license_key.strip()) + if data.get("activated") is False: + raise PanelError(str(data.get("message") or "تعذر تفعيل الترخيص."), code="license_activation_failed", data=data) + return self._record(data, "active", license_key.strip()) + + def clear(self) -> None: + self.store.license = None + + +__all__ = ["LicenseManager"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/service.py b/src/panel/service.py new file mode 100644 index 0000000..9004a67 --- /dev/null +++ b/src/panel/service.py @@ -0,0 +1,229 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/service.py | app_id (boards.id): 13 +# ============================================================ +""" +PanelService — الواجهة الواحدة التي تستخدمها الواجهة الرسومية لكل ما يخص لوحة الأم: +الاتصال والإعدادات، الجلسة والمستخدم، المزامنة، الترخيص، التحديثات، التتبّع، والتحكم. + +مبادئ: +- لا اتصال بالشبكة عند الإنشاء (الاختبارات تبني الواجهة بلا خادم). +- كل الدوال الشبكية حاجبة (blocking) وتُستدعى من خيط مهام (TaskManager) في الواجهة. +- أي خطأ شبكة لا يُسقط التطبيق: يُسجَّل ويُعرض كرسالة واضحة. +""" + +from __future__ import annotations + +import logging + +from src.panel.auth import PanelAuthenticator +from src.panel.client import MotherPanelClient, PanelError, Transport +from src.panel.config import PanelConfig, load_config, save_config +from src.panel.control import AdminControl +from src.panel.licenses import LicenseManager +from src.panel.session import SessionStore +from src.panel.sync import SettingsSync +from src.panel.telemetry import Telemetry +from src.panel.updates import UpdateInfo, evaluate_release +from src.version import APP_VERSION + +logger = logging.getLogger(__name__) + +DEFAULT_APP_SETTINGS: dict = { + "requires_login": True, + "sync_enabled": True, + "telemetry_enabled": True, + "licenses_enabled": False, + "update_channel": "stable", + "github_enabled": False, +} + + +class PanelService: + """تجمع كل خدمات الاندماج مع لوحة الأم في كائن واحد.""" + + def __init__( + self, + settings_manager, + config: PanelConfig | None = None, + transport: Transport | None = None, + store_path: str | None = None, + ): + self.settings = settings_manager + self.config = config or load_config() + self.transport = transport + self.store = SessionStore(store_path) + self.last_error = "" + self._build() + + # ------------------------------------------------------------------ + def _build(self) -> None: + self.client = MotherPanelClient( + self.config, + transport=self.transport, + session_token=self.store.session_token, + device=self.store.device_info(), + ) + self.auth = PanelAuthenticator(self.client, self.store) + self.sync = SettingsSync(self.client, self.store, self.settings) + self.licenses = LicenseManager(self.client, self.store) + self.telemetry = Telemetry( + self.client, enabled=self.telemetry_enabled, device_uid=self.store.device_uid + ) + self.control = AdminControl(self.client) + + def reconfigure(self, config: PanelConfig) -> None: + """تغيير إعدادات الاتصال (من شاشة الدخول) وحفظها محليًا ثم إعادة بناء العميل.""" + self.config = PanelConfig( + base_url=config.base_url, app_token=config.app_token, timeout_sec=config.timeout_sec + ) + save_config(self.config) + self._build() + + # ------------------------------------------------------------------ + @property + def is_configured(self) -> bool: + return self.config.is_configured + + @property + def current_user(self) -> dict | None: + return self.auth.current_user + + @property + def is_admin(self) -> bool: + return self.auth.is_admin + + @property + def has_stored_session(self) -> bool: + return self.auth.has_stored_session + + # ------------------------------------------------------------------ + # status: إعدادات التطبيق من الخادم + التطبيقات الشقيقة + # ------------------------------------------------------------------ + @property + def status(self) -> dict: + return self.store.status_cache or {} + + @property + def app_settings(self) -> dict: + app = self.status.get("app") if isinstance(self.status.get("app"), dict) else {} + remote = app.get("settings") if isinstance(app.get("settings"), dict) else {} + merged = dict(DEFAULT_APP_SETTINGS) + merged.update({k: v for k, v in remote.items() if k in DEFAULT_APP_SETTINGS}) + # المستخدم يستطيع إيقاف التتبّع محليًا (لا يمكن للخادم إجباره) + if self.settings.get("telemetry_enabled", True) is False: + merged["telemetry_enabled"] = False + return merged + + @property + def requires_login(self) -> bool: + return bool(self.app_settings.get("requires_login", True)) + + @property + def sync_enabled(self) -> bool: + return bool(self.app_settings.get("sync_enabled", True)) + + @property + def telemetry_enabled(self) -> bool: + local = self.settings.get("telemetry_enabled", True) + return local is not False and bool(self.app_settings.get("telemetry_enabled", True)) + + @property + def licenses_enabled(self) -> bool: + return bool(self.app_settings.get("licenses_enabled", False)) + + @property + def update_channel(self) -> str: + return str(self.app_settings.get("update_channel", "stable")) + + def refresh_status(self) -> dict: + """GET status — يحدّث الإعدادات البعيدة والتطبيقات الشقيقة (best-effort).""" + data = self.client.status() + if isinstance(data, dict): + self.store.status_cache = data + self.telemetry.enabled = self.telemetry_enabled + return self.status + + def siblings(self) -> list[dict]: + """التطبيقات الأخرى عند المطوّر (من آخر status محفوظة — بلا شبكة).""" + items = self.status.get("siblings") + if not isinstance(items, list): + return [] + return [item for item in items if isinstance(item, dict) and item.get("name")] + + # ------------------------------------------------------------------ + # المصادقة + # ------------------------------------------------------------------ + def login(self, email: str, password: str) -> dict: + user = self.auth.login(email, password) + self.after_login() + return user + + def register(self, email: str, password: str, name: str = "") -> dict: + user = self.auth.register(email, password, name) + self.after_login() + return user + + def restore_session(self) -> dict | None: + user = self.auth.restore() + if user: + self.after_login() + return user + + def logout(self) -> None: + try: + self.telemetry.flush() + except Exception as exc: # pragma: no cover + logger.debug("telemetry flush on logout failed: %s", exc) + self.auth.logout() + + def after_login(self) -> list[str]: + """بعد نجاح الدخول: تحديث status، سحب الإعدادات، تتبّع بدء التشغيل — كل منها best-effort.""" + notes: list[str] = [] + try: + self.refresh_status() + except PanelError as exc: + notes.append(f"تعذر جلب حالة التطبيق من لوحة الأم ({exc.code}).") + if self.sync_enabled: + try: + result = self.sync.pull() + if result.applied_keys: + notes.append(f"طُبّقت إعداداتك من جهاز آخر ({len(result.applied_keys)} إعداد).") + except PanelError as exc: + notes.append(f"تعذرت مزامنة الإعدادات ({exc.code}).") + try: + self.telemetry.track("app_start") + except Exception as exc: # pragma: no cover + logger.debug("telemetry track failed: %s", exc) + self.last_error = "" + return notes + + # ------------------------------------------------------------------ + # المزامنة / التحديثات / الترخيص + # ------------------------------------------------------------------ + def sync_now(self) -> dict: + """دفع الإعدادات المحلية (مع كشف التعارض).""" + return self.sync.push() + + def check_updates(self) -> UpdateInfo: + """releases/check — يفضّل releases داخل status، وإلا يستدعي النقطة مباشرة.""" + app = self.status.get("app") if isinstance(self.status.get("app"), dict) else {} + release = app.get("releases") if isinstance(app.get("releases"), dict) else None + if release is None: + release = self.client.releases_check(APP_VERSION, self.update_channel) + return evaluate_release(release, APP_VERSION) + + def verify_license(self, key: str) -> dict: + return self.licenses.verify(key) + + def activate_license(self, key: str) -> dict: + return self.licenses.activate(key) + + @property + def license_status(self) -> dict: + return self.licenses.status + + +__all__ = ["DEFAULT_APP_SETTINGS", "PanelService"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/session.py b/src/panel/session.py new file mode 100644 index 0000000..155bff6 --- /dev/null +++ b/src/panel/session.py @@ -0,0 +1,205 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/session.py | app_id (boards.id): 13 +# ============================================================ +""" +تخزين الجلسة محليًا (ملف واحد في مجلد بيانات التطبيق، ضمن حساب المستخدم فقط): +session_token، بيانات المستخدم (is_admin)، معرّف الجهاز، إصدار المزامنة، حالة الترخيص، +وآخر حالة للتطبيق من نقطة status. لا يحتوي كلمات مرور. +""" + +from __future__ import annotations + +import json +import logging +import os +import platform +import socket +import tempfile +import uuid +from typing import Any + +from src.utils.paths import writable_path +from src.version import APP_VERSION + +logger = logging.getLogger(__name__) + +SESSION_FILE = "panel_session.json" + + +def _atomic_write(path: str, text: str) -> None: + directory = os.path.dirname(path) or "." + os.makedirs(directory, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".session-", dir=directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(text) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +class SessionStore: + """ملف جلسة محلي بسيط بقيم افتراضية — كل القراءات آمنة حتى لو فُقد الملف.""" + + DEFAULTS: dict = { + "session_token": "", + "user": None, # {id, email, name, is_admin} + "device_uid": "", + "device_name": "", + "sync_version": 0, + "license": None, # {key, status, plan, expires_at, activated_at} + "status_cache": None, # آخر استجابة من نقطة status + "status_cached_at": "", + "last_email": "", + } + + def __init__(self, path: str | None = None): + self.path = path or writable_path(SESSION_FILE) + self._data: dict = dict(self.DEFAULTS) + self.load() + + # ------------------------------------------------------------------ + def load(self) -> dict: + try: + with open(self.path, encoding="utf-8") as handle: + loaded = json.load(handle) + if isinstance(loaded, dict): + self._data.update(loaded) + except FileNotFoundError: + pass + except (OSError, ValueError) as exc: + logger.warning("Panel session file unreadable (%s); starting fresh.", exc) + self._ensure_device() + return dict(self._data) + + def save(self) -> None: + try: + _atomic_write(self.path, json.dumps(self._data, ensure_ascii=False, indent=2)) + except OSError as exc: + logger.warning("Could not persist panel session: %s", exc) + + def clear(self) -> None: + keep_uid = self._data.get("device_uid", "") + keep_email = self._data.get("last_email", "") + self._data = dict(self.DEFAULTS) + self._data["device_uid"] = keep_uid + self._data["last_email"] = keep_email + self._ensure_device() + self.save() + + def _ensure_device(self) -> None: + if not self._data.get("device_uid"): + self._data["device_uid"] = uuid.uuid4().hex + if not self._data.get("device_name"): + try: + self._data["device_name"] = socket.gethostname() or "pc" + except OSError: + self._data["device_name"] = "pc" + + # ------------------------------------------------------------------ + def get(self, key: str, default: Any = None) -> Any: + value = self._data.get(key, self.DEFAULTS.get(key)) + return default if value is None else value + + def set(self, key: str, value: Any, persist: bool = True) -> None: + self._data[key] = value + if persist: + self.save() + + @property + def session_token(self) -> str: + return str(self._data.get("session_token") or "") + + @session_token.setter + def session_token(self, value: str) -> None: + self.set("session_token", value or "") + + @property + def user(self) -> dict | None: + user = self._data.get("user") + return user if isinstance(user, dict) else None + + @user.setter + def user(self, value: dict | None) -> None: + self.set("user", value) + + @property + def device_uid(self) -> str: + return str(self._data.get("device_uid") or "") + + @property + def sync_version(self) -> int: + try: + return int(self._data.get("sync_version") or 0) + except (TypeError, ValueError): + return 0 + + @sync_version.setter + def sync_version(self, value: int) -> None: + self.set("sync_version", int(value or 0)) + + @property + def license(self) -> dict | None: + lic = self._data.get("license") + return lic if isinstance(lic, dict) else None + + @license.setter + def license(self, value: dict | None) -> None: + self.set("license", value) + + @property + def status_cache(self) -> dict | None: + cache = self._data.get("status_cache") + return cache if isinstance(cache, dict) else None + + @status_cache.setter + def status_cache(self, value: dict | None) -> None: + from datetime import datetime, timezone + + self._data["status_cache"] = value + self._data["status_cached_at"] = datetime.now(timezone.utc).isoformat() if value else "" + self.save() + + @property + def last_email(self) -> str: + return str(self._data.get("last_email") or "") + + @last_email.setter + def last_email(self, value: str) -> None: + self.set("last_email", value or "") + + # ------------------------------------------------------------------ + def device_info(self) -> dict: + """بيانات الجهاز المُرسلة في register/login/telemetry (UNIQUE(app_id, device_uid)).""" + return { + "uid": self.device_uid, + "name": self._data.get("device_name") or "pc", + "platform": f"{platform.system()} {platform.release()}".strip(), + "app_version": APP_VERSION, + } + + +def app_user_from_panel(user: dict | None) -> dict | None: + """تحويل مستخدم اللوحة (app_users) إلى شكل المستخدم الذي تتوقعه الواجهة.""" + if not isinstance(user, dict) or not user: + return None + email = str(user.get("email") or user.get("username") or "") + is_admin = bool(user.get("is_admin")) or str(user.get("role") or "").lower() == "admin" + return { + "username": email, + "email": email, + "display_name": str(user.get("name") or email), + "role": "admin" if is_admin else "user", + "is_admin": is_admin, + "panel_user_id": user.get("id"), + } + + +__all__ = ["SESSION_FILE", "SessionStore", "app_user_from_panel"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/sync.py b/src/panel/sync.py new file mode 100644 index 0000000..cae26da --- /dev/null +++ b/src/panel/sync.py @@ -0,0 +1,149 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/sync.py | app_id (boards.id): 13 +# ============================================================ +""" +مزامنة الإعدادات بين الأجهزة عبر نقطة sync (دفع/سحب مع إصدار مزامنة وكشف تعارض). + +ما يُزامَن: تفضيلات المستخدم القابلة للنقل (الاستثناءات، الحماية، المراقبة، الصحة، +التنبيهات، المظهر، بدء التشغيل، الوضع التجريبي...). +ما لا يُزامَن أبدًا: users (حسابات اللوحة في اللوحة الأم)، الاختصارات (خاصة بالجهاز)، +schema_version، وأي بيانات حساسة. + +سياسة التعارض: عند رفض الدفع بسبب تعارض (sync_conflict) تفوز نسخة الخادم (server-wins) +ويُعاد دفع ما بعده لاحقًا — قرار متوقع وآمن لمستخدم واحد بعدة أجهزة. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass, field + +from src.panel.client import MotherPanelClient, PanelError +from src.panel.session import SessionStore + +logger = logging.getLogger(__name__) + +# مفاتيح الإعدادات القابلة للمزامنة (نقل تفضيلات المستخدم فقط) +SYNC_KEYS: tuple[str, ...] = ( + "test_mode", + "auto_clean_temp", + "process_exclusions", + "protected_apps", + "service_exclusions", + "monitoring", + "health", + "notifications", + "appearance", + "startup", + "feature_flags", +) +# مفاتيح لا تغادر الجهاز أبدًا +LOCAL_ONLY_KEYS: tuple[str, ...] = ( + "users", + "setup_completed", + "schema_version", + "shortcuts", + "force_kill_list", + "restore_point_description", + "donate_url", + "donate_message", +) + + +def build_payload(settings_manager) -> dict: + """استخراج الحمولة القابلة للمزامنة من مدير الإعدادات.""" + payload: dict = {} + for key in SYNC_KEYS: + if key in settings_manager.settings: + payload[key] = settings_manager.settings[key] + return payload + + +def filter_payload(payload: dict) -> dict: + """حماية صارمة: أي مفتاح خارج SYNC_KEYS يُهمل حتى لو أرسله الخادم.""" + if not isinstance(payload, dict): + return {} + return {k: v for k, v in payload.items() if k in SYNC_KEYS} + + +def apply_payload(settings_manager, payload: dict) -> list[str]: + """تطبيق حمولة من الخادم على الإعدادات المحلية (مع تحقق SettingsManager). يرجع المفاتيح المطبقة.""" + safe = filter_payload(payload) + if not safe: + return [] + if not settings_manager.save(safe, merge=True): + raise PanelError("تعذر حفظ الإعدادات المزامنة محليًا.", code="local_write") + return sorted(safe.keys()) + + +@dataclass +class SyncResult: + ok: bool + message: str + version: int = 0 + applied_keys: list[str] = field(default_factory=list) + conflict: bool = False + pushed: bool = False + + def __bool__(self) -> bool: + return self.ok + + +class SettingsSync: + """دفع/سحب الإعدادات عبر sync مع sync_version وكشف التعارض.""" + + def __init__(self, client: MotherPanelClient, store: SessionStore, settings_manager): + self.client = client + self.store = store + self.settings = settings_manager + + # ------------------------------------------------------------------ + def pull(self) -> SyncResult: + data = self.client.sync_pull(self.store.sync_version) + version = int(data.get("sync_version") or self.store.sync_version or 0) + payload = data.get("payload") if isinstance(data.get("payload"), dict) else {} + changed = bool(data.get("changed", bool(payload))) + applied = apply_payload(self.settings, payload) if changed else [] + self.store.sync_version = version + logger.info("Settings pulled from Mother Panel: version=%s applied=%s", version, applied) + return SyncResult(True, "تمت مزامنة الإعدادات من لوحة الأم.", version, applied) + + def push(self) -> SyncResult: + payload = build_payload(self.settings) + base_version = self.store.sync_version or None + try: + data = self.client.sync_push(payload, base_version) + except PanelError as exc: + if not exc.is_conflict: + raise + server = self.client.sync_pull(None) + server_payload = server.get("payload") if isinstance(server.get("payload"), dict) else {} + applied = apply_payload(self.settings, server_payload) if server_payload else [] + version = int(server.get("sync_version") or 0) + self.store.sync_version = version + logger.warning("Sync conflict detected; server version %s applied (%s).", version, applied) + return SyncResult( + True, + "اكتُشف تعارض في المزامنة — طُبّقت النسخة الأحدث من لوحة الأم.", + version, + applied, + conflict=True, + ) + version = int(data.get("sync_version") or (base_version or 0) + 1) + self.store.sync_version = version + logger.info("Settings pushed to Mother Panel: version=%s keys=%s", version, sorted(payload)) + return SyncResult(True, "تم رفع الإعدادات إلى لوحة الأم.", version, pushed=True) + + +__all__ = [ + "LOCAL_ONLY_KEYS", + "SYNC_KEYS", + "SettingsSync", + "SyncResult", + "apply_payload", + "build_payload", + "filter_payload", +] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/telemetry.py b/src/panel/telemetry.py new file mode 100644 index 0000000..ded2a34 --- /dev/null +++ b/src/panel/telemetry.py @@ -0,0 +1,82 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/telemetry.py | app_id (boards.id): 13 +# ============================================================ +""" +مقاييس خفيفة عبر نقطة telemetry (تنزيل/تقييم/استخدام) — بلا أي بيانات شخصية: +نوع الحدث، قيمة رقمية/نصية قصيرة، وقت، وإصدار التطبيق. لا تُرسل مسارات ولا أسماء ملفات. + +تُفعَّل فقط إذا سمح بها خادم اللوحة (status.app.settings.telemetry_enabled) ولم يعطلها +المستخدم من الإعدادات. الفشل في الإرسال لا يعطّل شيئًا أبدًا. +""" + +from __future__ import annotations + +import logging +import threading +import time +from collections import deque +from datetime import datetime, timezone + +from src.panel.client import MotherPanelClient, PanelError +from src.version import APP_VERSION + +logger = logging.getLogger(__name__) + +MAX_QUEUE = 200 +BATCH_SIZE = 50 + + +class Telemetry: + def __init__(self, client: MotherPanelClient, enabled: bool = True, device_uid: str = ""): + self.client = client + self.enabled = enabled + self.device_uid = device_uid + self._queue: deque[dict] = deque(maxlen=MAX_QUEUE) + self._lock = threading.Lock() + + # ------------------------------------------------------------------ + def track(self, event_type: str, value=None, **meta) -> dict: + event = { + "type": str(event_type)[:64], + "at": datetime.now(timezone.utc).isoformat(), + "app_version": APP_VERSION, + "value": value if isinstance(value, (int, float, str, bool)) or value is None else str(value), + "meta": {str(k)[:32]: str(v)[:120] for k, v in meta.items()} if meta else {}, + } + with self._lock: + self._queue.append(event) + return event + + def pending(self) -> int: + with self._lock: + return len(self._queue) + + def flush(self) -> int: + """إرسال ما في الطابور على دفعات. يرجع عدد الأحداث المُرسلة (0 عند التعطيل/الفشل).""" + if not self.enabled or not self.client.is_configured: + return 0 + sent = 0 + while True: + with self._lock: + if not self._queue: + break + batch = [self._queue.popleft() for _ in range(min(BATCH_SIZE, len(self._queue)))] + try: + self.client.telemetry(batch) + sent += len(batch) + except PanelError as exc: + # إعادة الأحداث للطابور حتى لا تضيع عند خطأ شبكة مؤقت + with self._lock: + for item in reversed(batch): + if len(self._queue) < MAX_QUEUE: + self._queue.appendleft(item) + logger.info("Telemetry flush skipped: %s", exc.code) + break + time.sleep(0) + return sent + + +__all__ = ["BATCH_SIZE", "MAX_QUEUE", "Telemetry"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/src/panel/updates.py b/src/panel/updates.py new file mode 100644 index 0000000..76a3918 --- /dev/null +++ b/src/panel/updates.py @@ -0,0 +1,78 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: src/panel/updates.py | app_id (boards.id): 13 +# ============================================================ +""" +فحص التحديثات عبر releases/check (إصدار كامل full + تحديثات فرعية sub + min_version). + +لا يُحمَّل أي شيء تلقائيًا هنا: التطبيق يعرض التنبيه ويفتح رابط الإصدار، +والتثبيت يتم من الإصدار الكامل (Faster-PC-Setup.exe أو FasterPC.exe). +""" + +from __future__ import annotations + +import logging +import re +from dataclasses import dataclass, field + +logger = logging.getLogger(__name__) + + +def parse_version(version: str) -> tuple[int, ...]: + """'2.1.0' -> (2, 1, 0)؛ أي نص غير رقمي يُهمل. فارغ -> ().""" + parts = re.findall(r"\d+", str(version or "")) + return tuple(int(p) for p in parts) + + +def is_newer(candidate: str, current: str) -> bool: + a, b = parse_version(candidate), parse_version(current) + if not a: + return False + if not b: + return True + width = max(len(a), len(b)) + return a + (0,) * (width - len(a)) > b + (0,) * (width - len(b)) + + +@dataclass +class UpdateInfo: + current_version: str + latest_version: str = "" + min_version: str = "" + has_update: bool = False + forced: bool = False + permissions_changed: bool = False + full: dict = field(default_factory=dict) # {version, url, size, notes, published_at} + sub: dict = field(default_factory=dict) # {version, url, notes} + url: str = "" + + @property + def message(self) -> str: + if self.forced: + return f"يتطلب التطبيق تحديثًا إجباريًا إلى الإصدار {self.min_version} أو أحدث." + if self.has_update: + return f"يتوفر إصدار جديد {self.latest_version} (الحالي {self.current_version})." + return "" + + +def evaluate_release(release: dict | None, current_version: str) -> UpdateInfo: + """تحويل استجابة releases/check إلى قرار واضح (تحديث/إجباري/لا شيء).""" + release = release if isinstance(release, dict) else {} + full = release.get("full") if isinstance(release.get("full"), dict) else {} + sub = release.get("sub") if isinstance(release.get("sub"), dict) else {} + info = UpdateInfo(current_version=current_version, full=full, sub=sub) + latest = str(full.get("version") or sub.get("version") or release.get("latest_version") or "") + info.latest_version = latest + info.min_version = str(release.get("min_version") or "") + info.permissions_changed = bool(release.get("permissions_changed")) + info.url = str(full.get("url") or release.get("url") or "") + info.has_update = bool(latest) and is_newer(latest, current_version) + info.forced = bool(info.min_version) and parse_version(current_version) < parse_version(info.min_version) + if info.has_update: + logger.info("Update available: %s -> %s (forced=%s)", current_version, latest, info.forced) + return info + + +__all__ = ["UpdateInfo", "evaluate_release", "is_newer", "parse_version"] + +# ==== End of file — © Yousef Alhamzy (يوسف الحمزي) — Faster-PC ==== diff --git a/tests/test_panel.py b/tests/test_panel.py new file mode 100644 index 0000000..1a81c51 --- /dev/null +++ b/tests/test_panel.py @@ -0,0 +1,407 @@ +# ============================================================ +# © Yousef Alhamzy (يوسف الحمزي) — Faster-PC — Mother Panel integration +# file: tests/test_panel.py | app_id (boards.id): 13 +# ============================================================ +"""اختبارات الاندماج مع لوحة الأم (app_id=13) — عبر وسيط نقل وهمي بدون أي شبكة.""" + +from __future__ import annotations + +import json +from urllib.parse import parse_qs, urlsplit + +import pytest + +from src.panel import PanelConfig, PanelError, PanelService, SessionStore +from src.panel.auth import PanelAuthenticator, validate_credentials +from src.panel.client import MotherPanelClient +from src.panel.config import load_config, normalize_base_url, save_config +from src.panel.control import as_rows, as_stats +from src.panel.licenses import LicenseManager +from src.panel.session import app_user_from_panel +from src.panel.sync import SettingsSync, apply_payload, build_payload +from src.panel.telemetry import Telemetry +from src.panel.updates import evaluate_release, is_newer, parse_version + +URL = "https://panel.example.com" +TOKEN = "app-token-12345678" +USER = {"id": 7, "email": "me@example.com", "name": "Me", "is_admin": 1} +SESSION = {"session_token": "sess-abc", "user": USER} + + +def ok(data): + return 200, {"ok": True, "req_id": "r1", "data": data} + + +def fail(code, message, status=400, details=None): + return status, {"ok": False, "req_id": "r1", "error": {"code": code, "message": message, "details": details or {}}} + + +class FakeTransport: + """يسجل كل طلب ويرجع استجابات محددة مسبقًا حسب (method, path).""" + + def __init__(self, responses=None, default=None): + self.calls: list[dict] = [] + self.responses = responses or {} + self.default = default or fail("not_implemented", "no response", 500) + + def call(self, method, url, headers, body): + parts = urlsplit(url) + path = parts.path.split("/api/v1/", 1)[-1] + query = {k: v[0] for k, v in parse_qs(parts.query).items()} + payload = json.loads(body.decode("utf-8")) if body else None + self.calls.append({"method": method, "path": path, "query": query, "body": payload, "headers": headers}) + handler = self.responses.get((method, path), self.default) + status, data = handler(method, path, query, payload, headers) if callable(handler) else handler + return status, json.dumps(data).encode("utf-8") + + def last(self): + return self.calls[-1] + + +def make_client(transport=None, session=""): + return MotherPanelClient(PanelConfig(base_url=URL, app_token=TOKEN), transport or FakeTransport(), session_token=session, + device={"uid": "dev-1", "name": "pc", "platform": "Windows", "app_version": "2.1.0"}) + + +# ---------------------------------------------------------------- config +def test_normalize_base_url(): + assert normalize_base_url("panel.example.com") == "https://panel.example.com" + assert normalize_base_url("https://panel.example.com/") == "https://panel.example.com" + assert normalize_base_url("https://panel.example.com/api/v1/") == "https://panel.example.com" + assert normalize_base_url("http://localhost:8080/panel/") == "http://localhost:8080/panel" + assert normalize_base_url("") == "" + + +def test_config_roundtrip_and_env_override(tmp_path, monkeypatch): + path = str(tmp_path / "panel.json") + monkeypatch.delenv("FASTERPC_PANEL_URL", raising=False) + monkeypatch.delenv("FASTERPC_PANEL_TOKEN", raising=False) + assert load_config(path).is_configured is False + save_config(PanelConfig(base_url=URL, app_token=TOKEN), path) + loaded = load_config(path) + assert loaded.is_configured and loaded.api_base == f"{URL}/api/v1" + assert TOKEN not in repr(loaded) # التوكن مقنّع في repr + monkeypatch.setenv("FASTERPC_PANEL_URL", "https://env.example.com") + monkeypatch.setenv("FASTERPC_PANEL_TOKEN", "env-token") + assert load_config(path).base_url == "https://env.example.com" + + +def test_config_masks_token(): + cfg = PanelConfig(base_url=URL, app_token="abcdefghijklmnop") + assert "abcdefgh" not in repr(cfg) and "…" in cfg.masked_token + + +# ---------------------------------------------------------------- client +def test_client_headers_and_envelope(): + transport = FakeTransport({("GET", "auth/session"): ok({"user": USER})}) + client = make_client(transport, session="tok") + data = client.session() + assert data["user"]["email"] == USER["email"] + call = transport.last() + assert call["headers"]["X-App-Id"] == "13" + assert call["headers"]["X-App-Token"] == TOKEN + assert call["headers"]["Accept"] == "application/json" + assert len(call["headers"]["X-Req-Id"]) == 32 + assert "Authorization" in call["headers"] and call["headers"]["Authorization"].startswith("Bearer ") + + +def test_client_req_id_unique_and_body_json(): + transport = FakeTransport({("POST", "auth/login"): ok(SESSION)}) + client = make_client(transport) + client.login("me@example.com", "secret12") + client.login("me@example.com", "secret12") + ids = {c["headers"]["X-Req-Id"] for c in transport.calls} + assert len(ids) == 2 + assert transport.last()["body"]["email"] == "me@example.com" + assert transport.last()["body"]["device"]["uid"] == "dev-1" + assert transport.last()["headers"]["Content-Type"] == "application/json" + assert "Authorization" not in transport.last()["headers"] # login بلا جلسة + + +def test_client_error_envelope_raises_panel_error(): + transport = FakeTransport({("GET", "auth/session"): fail("session_expired", "انتهت الجلسة", 401)}) + client = make_client(transport, session="old") + with pytest.raises(PanelError) as info: + client.session() + assert info.value.code == "session_expired" and info.value.status == 401 + assert info.value.is_auth_error + + +def test_client_bad_json_and_not_configured(): + class Raw: + def call(self, method, url, headers, body): + return 200, b"not json" + + with pytest.raises(PanelError) as info: + make_client(Raw()).status() + assert info.value.code == "bad_response" + with pytest.raises(PanelError) as info: + MotherPanelClient(PanelConfig(), transport=FakeTransport()).status() + assert info.value.code == "not_configured" + + +def test_client_control_query_and_sync_bodies(): + transport = FakeTransport({("GET", "control"): ok({"items": []}), ("POST", "sync"): ok({"sync_version": 3})}) + client = make_client(transport, session="tok") + client.control("users", op="", params={"page": 1}) + assert transport.last()["query"] == {"section": "users", "page": "1"} + client.sync_push({"monitoring": {}}, 2) + assert transport.last()["body"]["op"] == "push" and transport.last()["body"]["base_version"] == 2 + client.sync_pull(None) + assert transport.last()["body"]["op"] == "pull" + + +# ---------------------------------------------------------------- session/auth +def test_session_store_device_uid_stable_and_clear(tmp_path): + store = SessionStore(str(tmp_path / "s.json")) + uid = store.device_uid + assert uid + info = store.device_info() + assert info["uid"] == uid and info["app_version"] + store.session_token = "t" + store.clear() + assert SessionStore(str(tmp_path / "s.json")).device_uid == uid + assert store.session_token == "" + + +def test_app_user_from_panel_admin_flag(): + assert app_user_from_panel(USER)["role"] == "admin" + assert app_user_from_panel({"email": "x@y.z", "is_admin": 0})["role"] == "user" + assert app_user_from_panel({"email": "x@y.z", "role": "admin"})["is_admin"] is True + assert app_user_from_panel(None) is None + + +def test_validate_credentials(): + assert validate_credentials("bad", "12345678") == "أدخل بريدًا إلكترونيًا صحيحًا." + assert "8" in validate_credentials("a@b.co", "short") + assert validate_credentials("a@b.co", "longenough") == "" + + +def test_authenticator_login_restore_logout(tmp_path): + transport = FakeTransport( + { + ("POST", "auth/login"): ok(SESSION), + ("GET", "auth/session"): ok({"user": USER}), + ("POST", "auth/logout"): ok({}), + } + ) + store = SessionStore(str(tmp_path / "s.json")) + client = make_client(transport) + auth = PanelAuthenticator(client, store) + assert auth.restore() is None # لا جلسة محفوظة → لا طلب + user = auth.login("me@example.com", "secret12") + assert user["username"] == "me@example.com" and auth.is_admin + assert store.session_token == "sess-abc" and client.session_token == "sess-abc" + assert PanelAuthenticator(client, SessionStore(str(tmp_path / "s.json"))).current_user["role"] == "admin" + assert auth.restore()["email"] == "me@example.com" + auth.logout() + assert store.session_token == "" and client.session_token == "" + + +def test_authenticator_restore_rejected_and_logout_offline(tmp_path): + transport = FakeTransport( + { + ("GET", "auth/session"): fail("session_expired", "منتهية", 401), + ("POST", "auth/logout"): fail("network", "down", 503), + } + ) + store = SessionStore(str(tmp_path / "s.json")) + store.session_token = "old" + store.user = USER + client = make_client(transport) + auth = PanelAuthenticator(client, store) + assert auth.restore() is None and store.session_token == "" and store.user is None + store.session_token = "x" + auth.logout() # فشل الخادم لا يمنع الخروج المحلي + assert store.session_token == "" + + +# ---------------------------------------------------------------- sync +def test_sync_payload_whitelist_and_apply(settings): + settings.set("users", [{"username": "local"}], persist=False) + settings.set("process_exclusions", ["a.exe"], persist=False) + payload = build_payload(settings) + assert "process_exclusions" in payload and "users" not in payload + applied = apply_payload(settings, {"users": [{"username": "evil"}], "protected_apps": ["b.exe"]}) + assert applied == ["protected_apps"] + assert settings.get("users") == [{"username": "local"}] + + +def test_sync_pull_and_push_and_conflict(settings, tmp_path): + state = {"server_version": 5} + + def handler(method, path, query, body, headers): + if body["op"] == "pull": + return ok({"sync_version": state["server_version"], "payload": {"protected_apps": ["srv.exe"]}, "changed": True}) + if body["base_version"] != state["server_version"]: + return fail("sync_conflict", "تعارض", 409, {"server_version": state["server_version"]}) + state["server_version"] += 1 + return ok({"sync_version": state["server_version"]}) + + responses = {("POST", "sync"): handler} + store = SessionStore(str(tmp_path / "s.json")) + sync = SettingsSync(make_client(FakeTransport(responses)), store, settings) + pulled = sync.pull() + assert pulled.ok and pulled.version == 5 and pulled.applied_keys == ["protected_apps"] + assert store.sync_version == 5 + pushed = sync.push() + assert pushed.ok and pushed.pushed and store.sync_version == 6 and not pushed.conflict + store.sync_version = 5 # نسخة قديمة → تعارض + conflicted = sync.push() + assert conflicted.conflict and conflicted.ok + assert settings.get("protected_apps") == ["srv.exe"] + + +# ---------------------------------------------------------------- updates/licenses/telemetry/control +def test_updates_evaluate(): + assert parse_version("2.1.0") == (2, 1, 0) and parse_version("") == () + assert is_newer("2.2.0", "2.1.9") and not is_newer("2.1.0", "2.1.0") and not is_newer("x", "1.0") + info = evaluate_release({"full": {"version": "2.2.0", "url": "u"}}, "2.1.0") + assert info.has_update and not info.forced and info.url == "u" and "2.2.0" in info.message + forced = evaluate_release({"min_version": "2.1.0"}, "2.0.3") + assert forced.forced and not forced.has_update + assert evaluate_release(None, "2.1.0").has_update is False + + +def test_licenses_verify_activate(tmp_path): + transport = FakeTransport( + { + ("POST", "licenses/verify"): ok({"valid": True, "plan": "pro", "expires_at": "2027-01-01"}), + ("POST", "licenses/activate"): ok({"activated": True, "status": "active", "plan": "pro"}), + } + ) + store = SessionStore(str(tmp_path / "s.json")) + lic = LicenseManager(make_client(transport, session="tok"), store) + assert lic.status["state"] == "none" + assert lic.verify("KEY-1")["plan"] == "pro" + assert lic.activate("KEY-1")["status"] == "active" + assert LicenseManager(make_client(transport), SessionStore(str(tmp_path / "s.json"))).status["state"] == "active" + + +def test_telemetry_batches_and_retains_on_error(): + sent = [] + + def handler(method, path, query, body, headers): + sent.append(body["events"]) + return ok({"accepted": len(body["events"])}) + + transport = FakeTransport({("POST", "telemetry"): handler}) + client = make_client(transport) + telemetry = Telemetry(client, enabled=True) + assert telemetry.flush() == 0 + for i in range(60): + telemetry.track("clean", i, tab="x") + assert telemetry.flush() == 60 and sum(len(b) for b in sent) == 60 and len(sent[0]) == 50 + assert sent[0][0]["meta"] == {"tab": "x"} and sent[0][0]["app_version"] + # فشل الشبكة يحافظ على الأحداث + broken = FakeTransport(default=fail("network", "down", 503)) + t2 = Telemetry(make_client(broken), enabled=True) + t2.track("app_start") + assert t2.flush() == 0 and t2.pending() == 1 + assert Telemetry(make_client(FakeTransport()), enabled=False).flush() == 0 + + +def test_control_normalizers(): + assert as_rows({"items": [{"id": 1}, "bad"]}) == [{"id": 1}] + assert as_rows([{"a": 1}]) == [{"a": 1}] + assert as_rows({"stats": 1}) == [] + assert as_stats({"users": 5, "app": {"version": "2.1.0", "enabled": True}, "list": []}) == { + "users": 5, + "app.version": "2.1.0", + "app.enabled": True, + } + assert as_stats("nope") == {} + + +# ---------------------------------------------------------------- service +def make_service(settings, tmp_path, responses=None, configured=True): + transport = FakeTransport(responses) + config = PanelConfig(base_url=URL, app_token=TOKEN) if configured else PanelConfig() + return PanelService(settings, config=config, transport=transport, store_path=str(tmp_path / "panel.json")) + + +def test_service_login_after_login_hooks_and_siblings(settings, tmp_path): + transport_responses = { + ("POST", "auth/login"): ok(SESSION), + ("GET", "status"): ok({ + "app": {"id": 13, "settings": {"telemetry_enabled": False, "sync_enabled": True}, "releases": {"full": {"version": "2.1.0"}}}, + "siblings": [{"id": 2, "name": "Other App", "url": "https://x"}, "bad"], + }), + ("POST", "sync"): ok({"sync_version": 2, "payload": {"protected_apps": ["z.exe"]}, "changed": True}), + } + service = make_service(settings, tmp_path, transport_responses) + assert service.is_configured and service.current_user is None + user = service.login("me@example.com", "secret12") + assert user["role"] == "admin" and service.is_admin + assert service.telemetry_enabled is False # الخادم عطّل التتبّع + assert service.sync_enabled + assert [s["name"] for s in service.siblings()] == ["Other App"] + assert settings.get("protected_apps") == ["z.exe"] + assert service.check_updates().has_update is False # من status دون استدعاء إضافي + paths = [c["path"] for c in service.client.transport.calls] + assert "releases/check" not in paths and paths.count("status") == 1 + service.logout() + assert service.current_user is None + + +def test_service_after_login_is_best_effort_and_local_telemetry_opt_out(settings, tmp_path): + service = make_service(settings, tmp_path, {("POST", "auth/login"): ok(SESSION)}, configured=True) + service.client.transport.default = fail("network", "down", 503) # status/sync غير متاحة + notes = service.after_login() + assert notes and any("حالة التطبيق" in n for n in notes) and any("مزامنة" in n for n in notes) + settings.set("telemetry_enabled", False, persist=False) + assert service.telemetry_enabled is False # إيقاف محلي يتفوق على الخادم + + +def test_service_unconfigured_raises_not_configured(settings, tmp_path): + service = make_service(settings, tmp_path, configured=False) + assert service.siblings() == [] and service.telemetry.flush() == 0 + with pytest.raises(PanelError) as info: + service.refresh_status() + assert info.value.code == "not_configured" + + +# ---------------------------------------------------------------- GUI +@pytest.fixture() +def ctx(qapp, settings, tmp_path): + from src.core.app_context import AppContext + + context = AppContext(settings) + context.panel.store = SessionStore(str(tmp_path / "ctx-panel.json")) + context.panel._build() + return context + + +def test_panel_login_window_builds_unconfigured_without_network(qapp, settings, tmp_path): + from src.gui.panel_login_window import PanelLoginWindow + + service = make_service(settings, tmp_path, configured=False) + window = PanelLoginWindow(service) + assert window.conn_box.isVisibleTo(window) # صندوق الإعداد ظاهر + assert window.authenticated_user is None + window.handle_submit() # غير مُعدّ → رسالة خطأ دون أي طلب شبكة + assert window.error_label.text() + assert service.client.transport.calls == [] + window.toggle_mode() + assert window.submit_btn.text() == "إنشاء الحساب والدخول" + window.close() + + +def test_admin_and_other_apps_tabs_build_without_network(qapp, ctx, tmp_path): + from src.gui.admin_panel import AdminPanelTab + from src.gui.other_apps import OtherAppsTab + + ctx.panel.store.status_cache = {"siblings": [{"id": 2, "name": "Sibling", "version": "1.0", "url": "https://s"}]} + other = OtherAppsTab(ctx) + assert other.cards_layout.count() == 2 # بطاقة + stretch + admin = AdminPanelTab(ctx) + assert admin.section == "overview" + admin._show({"users": 3, "app": {"version": "2.1.0"}}) + assert admin.stats_grid.count() == 2 + admin.section_combo.setCurrentIndex(1) # المستخدمون (غير مُعدّ → لا شبكة) + assert admin.section == "users" + admin._show({"items": [{"id": 1, "email": "a@b.co", "is_admin": True}], "total": 1}) + assert admin.table.rowCount() == 1 and admin.table.item(0, 2).text() == "نعم" + assert "1 سجلًا" in admin.status_label.text() + other.close() + admin.close() From 2b14337eba8925b14a8170be37cbb161e4790218 Mon Sep 17 00:00:00 2001 From: yswef <170477919+yswef@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:11:42 +0000 Subject: [PATCH 2/2] feat(panel): allow optional offline login without forcing internet Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- src/gui/app.py | 3 ++- src/gui/panel_login_window.py | 21 +++++++++++++++++++++ tests/test_panel.py | 11 +++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/gui/app.py b/src/gui/app.py index 8f4a65c..b82b6dc 100644 --- a/src/gui/app.py +++ b/src/gui/app.py @@ -178,7 +178,8 @@ def _activate_existing() -> None: window.show() start_minimized = False telemetry_timer.start() - _check_updates_async(ctx, window) + if not login.offline_mode: + _check_updates_async(ctx, window) app.exec() if not window.logged_out: diff --git a/src/gui/panel_login_window.py b/src/gui/panel_login_window.py index 7ce8ea8..952ec1b 100644 --- a/src/gui/panel_login_window.py +++ b/src/gui/panel_login_window.py @@ -47,6 +47,7 @@ def __init__(self, service: PanelService, parent=None): super().__init__(parent) self.service = service self.authenticated_user: dict | None = None + self.offline_mode: bool = False self._register_mode = False self._busy = False self.tasks = TaskManager(self) @@ -126,6 +127,10 @@ def __init__(self, service: PanelService, parent=None): self.mode_btn = QPushButton("إنشاء حساب جديد") self.mode_btn.clicked.connect(self.toggle_mode) row.addWidget(self.mode_btn) + self.offline_btn = QPushButton("متابعة بدون نت") + self.offline_btn.setToolTip("تشغيل التطبيق محليًا بدون إنترنت؛ ستتم المزامنة لاحقًا عند توفر الاتصال.") + self.offline_btn.clicked.connect(self.continue_offline) + row.addWidget(self.offline_btn) cancel_btn = QPushButton("خروج") cancel_btn.clicked.connect(self.reject) row.addWidget(cancel_btn) @@ -257,6 +262,22 @@ def _restore_failed(self, message: str) -> None: self._set_busy(False) logger.info("Session restore skipped: %s", message) + def continue_offline(self) -> None: + """الدخول في وضع الأوفلاين بدون نت أو بدون اتصال بلوحة الأم.""" + self.offline_mode = True + saved = dict(self.service.store.user or {}) + if saved: + saved["offline"] = True + self.authenticated_user = saved + else: + self.authenticated_user = { + "email": "offline@local", + "name": "مستخدم محلي", + "is_admin": False, + "offline": True, + } + self.accept() + def closeEvent(self, event) -> None: # noqa: N802 if self._busy: self.tasks.wait_all(timeout_ms=2000) diff --git a/tests/test_panel.py b/tests/test_panel.py index 1a81c51..e4a8dfa 100644 --- a/tests/test_panel.py +++ b/tests/test_panel.py @@ -405,3 +405,14 @@ def test_admin_and_other_apps_tabs_build_without_network(qapp, ctx, tmp_path): assert "1 سجلًا" in admin.status_label.text() other.close() admin.close() + + +def test_login_window_allows_offline_mode(ctx): + from src.gui.panel_login_window import PanelLoginWindow + + win = PanelLoginWindow(ctx.panel) + win.continue_offline() + assert win.offline_mode is True + assert win.authenticated_user is not None + assert win.authenticated_user["offline"] is True + win.close()