diff --git a/controller/app/src/main/java/org/appdevforall/k2go/ModuleRegistry.java b/controller/app/src/main/java/org/appdevforall/k2go/ModuleRegistry.java index 8577d8754..84606c55f 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/ModuleRegistry.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/ModuleRegistry.java @@ -37,7 +37,8 @@ public IiabModule(String endpoint, int nameResId, boolean requires64Bit, String new IiabModule("kiwix", R.string.dash_kiwix, true, "kiwix"), // YAML uses kiwix_install. TRUE = Hidden on 32-bit! new IiabModule("kolibri", R.string.dash_kolibri, false, "kolibri"), // YAML uses kolibri_install new IiabModule("maps", R.string.dash_maps, false, "maps"), // YAML uses maps_install - new IiabModule("matomo", R.string.dash_matomo, false, "matomo") // YAML uses matomo_install + new IiabModule("matomo", R.string.dash_matomo, false, "matomo"), // YAML uses matomo_install + new IiabModule("forgejo", R.string.dash_forgejo, false, "forgejo") // YAML uses forgejo_install // ADFA-4842: "dashboard" is intentionally NOT in the roster. It is no longer an // application/module — it became the REST API core of K2Go; without it maps FQR and all // REST content downloads fail. It is part of the core system, not a user-installable module. diff --git a/controller/app/src/main/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicy.java b/controller/app/src/main/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicy.java index 75b6aabce..b90397d37 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicy.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicy.java @@ -27,6 +27,7 @@ public final class AutoLoginPolicy { /** Box credential-store service names. */ public static final String CALIBRE = "calibre"; public static final String KOLIBRI = "kolibri"; + public static final String FORGEJO = "forgejo"; private AutoLoginPolicy() {} @@ -40,6 +41,7 @@ public static String serviceFor(String url) { if (segment == null) return null; if (segment.equals("books")) return CALIBRE; if (segment.equals("kolibri")) return KOLIBRI; + if (segment.equals("forgejo")) return FORGEJO; return null; } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryHomeFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryHomeFragment.java index e0bfaaa3e..75ec8d24d 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryHomeFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryHomeFragment.java @@ -181,6 +181,7 @@ private void populateCards() { cards.clear(); cards.add(new Card("books", getString(R.string.k2go_card_books), false, R.drawable.ic_card_book)); cards.add(new Card("code", getString(R.string.k2go_card_code), false, R.drawable.ic_card_code)); + cards.add(new Card("forgejo", getString(R.string.k2go_card_forgejo), false, R.drawable.ic_card_forgejo)); cards.add(new Card("kiwix", getString(R.string.k2go_card_wikipedia), true, R.drawable.ic_card_wikipedia)); cards.add(new Card("kolibri", getString(R.string.k2go_card_courses), false, R.drawable.ic_card_courses)); cards.add(new Card("maps", getString(R.string.k2go_card_maps), false, R.drawable.ic_card_maps)); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleCards.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleCards.java index 0e5f46fb6..757d7030b 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleCards.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/ModuleCards.java @@ -63,6 +63,9 @@ public static final class Card { new Card("code", R.string.k2go_mod_code_title, R.string.k2go_mod_code_title, R.string.k2go_mod_code_sub, R.string.k2go_mod_code_desc, R.drawable.k2go_module_placeholder, false), + new Card("forgejo", R.string.k2go_mod_forgejo_title, R.string.k2go_mod_forgejo_title, + R.string.k2go_mod_forgejo_sub, R.string.k2go_mod_forgejo_desc, + R.drawable.k2go_module_placeholder, false), new Card("matomo", R.string.k2go_mod_matomo_title, R.string.k2go_mod_matomo_title, R.string.k2go_mod_matomo_sub, R.string.k2go_mod_matomo_desc, R.drawable.k2go_module_placeholder, false), @@ -108,6 +111,7 @@ public static String license(String key) { case "calibreweb": return "GPL-3.0"; case "kiwix": return "GPL-3.0"; case "code": return "MIT"; + case "forgejo": return "GPL-3.0-or-later"; case "matomo": return "GPL-3.0"; case "maps": return "Mixed data licenses"; // ADFA-4958: OSM ODbL + Natural Earth (PD) + satellite CC BY-NC-SA 4.0 + GeoNames CC BY 4.0 default: return null; @@ -137,6 +141,7 @@ public static int includesRes(String key) { case "calibreweb": return R.string.k2go_mod_calibreweb_includes; case "kiwix": return R.string.k2go_mod_kiwix_includes; case "code": return R.string.k2go_mod_code_includes; + case "forgejo": return R.string.k2go_mod_forgejo_includes; case "matomo": return R.string.k2go_mod_matomo_includes; case "maps": return R.string.k2go_mod_maps_includes; default: return 0; diff --git a/controller/app/src/main/res/drawable/ic_card_forgejo.xml b/controller/app/src/main/res/drawable/ic_card_forgejo.xml new file mode 100644 index 000000000..9cc3bed45 --- /dev/null +++ b/controller/app/src/main/res/drawable/ic_card_forgejo.xml @@ -0,0 +1,3 @@ + + + diff --git a/controller/app/src/main/res/values-ar/strings.xml b/controller/app/src/main/res/values-ar/strings.xml index ab7ce7210..0e2c10266 100644 --- a/controller/app/src/main/res/values-ar/strings.xml +++ b/controller/app/src/main/res/values-ar/strings.xml @@ -1341,4 +1341,8 @@ تستخدم التنزيلات الجديدة الآن بيانات الجوال. قد يترتب على ذلك تكلفة أو يستنفد باقة بياناتك. تنبيهات تكلفة البيانات الدليل + استضف الشيفرة + استضافة الشيفرة + خادم Git خاص على جهازك. خزّن مستودعات الشيفرة وتتبّع المشكلات وراجع التغييرات دون اتصال. لا حاجة إلى الإنترنت. + خادم Git فقط. تنشئ مستودعاتك الخاصة بعد التثبيت. diff --git a/controller/app/src/main/res/values-az/strings.xml b/controller/app/src/main/res/values-az/strings.xml index b9db13fd9..f951140f7 100644 --- a/controller/app/src/main/res/values-az/strings.xml +++ b/controller/app/src/main/res/values-az/strings.xml @@ -1361,4 +1361,8 @@ Yeni yükləmələr indi mobil internetdən istifadə edir. Bu, xərc yarada və ya data paketinizi bitirə bilər. Data xərci bildirişləri Təlimat + Kodu saxla + Kod hostinqi + Cihazınızda özəl Git serveri. Kod anbarlarını saxlayın, problemləri izləyin və dəyişiklikləri oflayn nəzərdən keçirin. İnternet lazım deyil. + Yalnız Git serveri. Quraşdırmadan sonra öz anbarlarınızı yaradırsınız. diff --git a/controller/app/src/main/res/values-bg/strings.xml b/controller/app/src/main/res/values-bg/strings.xml index e8823d50c..bd7ec496c 100644 --- a/controller/app/src/main/res/values-bg/strings.xml +++ b/controller/app/src/main/res/values-bg/strings.xml @@ -1348,4 +1348,8 @@ Новите изтегляния вече използват мобилни данни. Това може да има такса или да изчерпи плана ви за данни. Известия за разход на данни Ръководство + Хостинг на код + Хостинг на код + Частен Git сървър на вашето устройство. Съхранявайте хранилища с код, следете проблеми и преглеждайте промени офлайн. Не е нужен интернет. + Само Git сървърът. Създавате собствените си хранилища след инсталиране. diff --git a/controller/app/src/main/res/values-bn/strings.xml b/controller/app/src/main/res/values-bn/strings.xml index cf0913f04..175dca7eb 100644 --- a/controller/app/src/main/res/values-bn/strings.xml +++ b/controller/app/src/main/res/values-bn/strings.xml @@ -1354,4 +1354,8 @@ নতুন ডাউনলোডগুলি এখন মোবাইল ডেটা ব্যবহার করে। এতে খরচ হতে পারে বা আপনার ডেটা প্ল্যান শেষ হতে পারে। ডেটা খরচের সতর্কতা ম্যানুয়াল + কোড হোস্ট করুন + কোড হোস্টিং + আপনার ডিভাইসে একটি ব্যক্তিগত Git সার্ভার। কোড রিপোজিটরি সংরক্ষণ করুন, সমস্যা ট্র্যাক করুন এবং অফলাইনে পরিবর্তন পর্যালোচনা করুন। ইন্টারনেট লাগবে না। + শুধু Git সার্ভার। ইনস্টল করার পরে আপনি নিজের রিপোজিটরি তৈরি করেন। diff --git a/controller/app/src/main/res/values-cs/strings.xml b/controller/app/src/main/res/values-cs/strings.xml index f80d636bc..48650d56b 100644 --- a/controller/app/src/main/res/values-cs/strings.xml +++ b/controller/app/src/main/res/values-cs/strings.xml @@ -1348,4 +1348,8 @@ Nová stahování nyní používají mobilní data. Může být zpoplatněno nebo vyčerpat váš datový limit. Upozornění na náklady za data Příručka + Hostovat kód + Hostování kódu + Soukromý Git server na vašem zařízení. Ukládejte úložiště kódu, sledujte problémy a kontrolujte změny offline. Internet není potřeba. + Pouze Git server. Vlastní úložiště si vytvoříte po instalaci. diff --git a/controller/app/src/main/res/values-de/strings.xml b/controller/app/src/main/res/values-de/strings.xml index 513fb23d6..cdf7f9b25 100644 --- a/controller/app/src/main/res/values-de/strings.xml +++ b/controller/app/src/main/res/values-de/strings.xml @@ -1341,4 +1341,8 @@ Neue Downloads nutzen jetzt mobile Daten. Das kann Kosten verursachen oder Ihr Datenvolumen aufbrauchen. Warnungen zu Datenkosten Handbuch + Code hosten + Code-Hosting + Ein privater Git-Server auf Ihrer Box. Speichern Sie Code-Repositorys, verfolgen Sie Probleme und prüfen Sie Änderungen offline. Kein Internet nötig. + Nur der Git-Server. Eigene Repositorys erstellen Sie nach der Installation. diff --git a/controller/app/src/main/res/values-el/strings.xml b/controller/app/src/main/res/values-el/strings.xml index fd3f2f5ba..746024427 100644 --- a/controller/app/src/main/res/values-el/strings.xml +++ b/controller/app/src/main/res/values-el/strings.xml @@ -1348,4 +1348,8 @@ Οι νέες λήψεις χρησιμοποιούν τώρα δεδομένα κινητής. Αυτό μπορεί να έχει κόστος ή να εξαντλήσει το πρόγραμμα δεδομένων σας. Ειδοποιήσεις κόστους δεδομένων Εγχειρίδιο + Φιλοξενία κώδικα + Φιλοξενία κώδικα + Ιδιωτικός διακομιστής Git στη συσκευή σας. Αποθηκεύστε αποθετήρια κώδικα, παρακολουθήστε ζητήματα και ελέγξτε αλλαγές εκτός σύνδεσης. Δεν χρειάζεται σύνδεση στο διαδίκτυο. + Μόνο ο διακομιστής Git. Δημιουργείτε τα δικά σας αποθετήρια μετά την εγκατάσταση. diff --git a/controller/app/src/main/res/values-es/strings.xml b/controller/app/src/main/res/values-es/strings.xml index 45f37e316..34ce1c03a 100644 --- a/controller/app/src/main/res/values-es/strings.xml +++ b/controller/app/src/main/res/values-es/strings.xml @@ -1417,4 +1417,8 @@ Las nuevas descargas ahora usan datos móviles. Esto puede tener costo o agotar tu plan de datos. Alertas de costo de datos Manual + Aloja tu código + Alojamiento de código + Un servidor Git privado en tu caja. Guarda repositorios de código, sigue incidencias y revisa cambios sin conexión. No se necesita internet. + Solo el servidor Git. Tú creas tus propios repositorios después de instalarlo. diff --git a/controller/app/src/main/res/values-fa/strings.xml b/controller/app/src/main/res/values-fa/strings.xml index 572c531d8..3d5487602 100644 --- a/controller/app/src/main/res/values-fa/strings.xml +++ b/controller/app/src/main/res/values-fa/strings.xml @@ -1341,4 +1341,8 @@ دانلودهای جدید اکنون از داده تلفن همراه استفاده می‌کنند. این ممکن است هزینه داشته باشد یا بسته داده شما را تمام کند. هشدارهای هزینه داده راهنما + میزبانی کد + میزبانی کد + یک سرور Git خصوصی روی دستگاه شما. مخازن کد را ذخیره کنید، مسائل را دنبال کنید و تغییرات را آفلاین بررسی کنید. به اینترنت نیازی نیست. + فقط سرور Git. پس از نصب، مخازن خود را می‌سازید. diff --git a/controller/app/src/main/res/values-fr/strings.xml b/controller/app/src/main/res/values-fr/strings.xml index faf4293e9..24a4612ea 100644 --- a/controller/app/src/main/res/values-fr/strings.xml +++ b/controller/app/src/main/res/values-fr/strings.xml @@ -1428,4 +1428,8 @@ Les nouveaux téléchargements utilisent désormais les données mobiles. Cela peut coûter cher ou épuiser votre forfait de données. Alertes de coût des données Manuel + Héberger le code + Hébergement de code + Un serveur Git privé sur votre boîtier. Stockez des dépôts de code, suivez les problèmes et examinez les changements hors ligne. Aucune connexion requise. + Le serveur Git seul. Vous créez vos propres dépôts après l\'installation. diff --git a/controller/app/src/main/res/values-gu/strings.xml b/controller/app/src/main/res/values-gu/strings.xml index 86fc46eaa..1f91400fa 100644 --- a/controller/app/src/main/res/values-gu/strings.xml +++ b/controller/app/src/main/res/values-gu/strings.xml @@ -1354,4 +1354,8 @@ નવા ડાઉનલોડ હવે મોબાઇલ ડેટા વાપરે છે. તેનાથી ખર્ચ થઈ શકે અથવા તમારો ડેટા પ્લાન ખતમ થઈ શકે. ડેટા ખર્ચ ચેતવણીઓ માર્ગદર્શિકા + કોડ હોસ્ટ કરો + કોડ હોસ્ટિંગ + તમારા ઉપકરણ પર ખાનગી Git સર્વર. કોડ રિપોઝિટરી સાચવો, સમસ્યાઓ ટ્રૅક કરો અને ફેરફારો ઑફલાઇન સમીક્ષા કરો. ઇન્ટરનેટની જરૂર નથી. + ફક્ત Git સર્વર. ઇન્સ્ટૉલ કર્યા પછી તમે તમારી પોતાની રિપોઝિટરી બનાવો છો. diff --git a/controller/app/src/main/res/values-hi/strings.xml b/controller/app/src/main/res/values-hi/strings.xml index 0082f8868..c09a487d9 100644 --- a/controller/app/src/main/res/values-hi/strings.xml +++ b/controller/app/src/main/res/values-hi/strings.xml @@ -1418,4 +1418,8 @@ नए डाउनलोड अब मोबाइल डेटा का उपयोग करते हैं. इससे शुल्क लग सकता है या आपका डेटा प्लान खत्म हो सकता है. डेटा लागत अलर्ट मैनुअल + कोड होस्ट करें + कोड होस्टिंग + आपके डिवाइस पर एक निजी Git सर्वर। कोड रिपॉज़िटरी सहेजें, समस्याएँ ट्रैक करें और बदलावों की समीक्षा ऑफ़लाइन करें। इंटरनेट की ज़रूरत नहीं। + केवल Git सर्वर। इंस्टॉल करने के बाद आप अपनी रिपॉज़िटरी बनाते हैं। diff --git a/controller/app/src/main/res/values-hu/strings.xml b/controller/app/src/main/res/values-hu/strings.xml index 280654714..9b97f0272 100644 --- a/controller/app/src/main/res/values-hu/strings.xml +++ b/controller/app/src/main/res/values-hu/strings.xml @@ -1341,4 +1341,8 @@ Az új letöltések most mobiladatot használnak. Ez költséggel járhat, vagy elfogyaszthatja az adatkeretét. Adatköltség-figyelmeztetések Kézikönyv + Kód tárolása + Kódtárhely + Privát Git-kiszolgáló a készülékén. Tároljon kódtárakat, kövesse a hibákat, és nézze át a módosításokat offline. Nincs szükség internetre. + Csak a Git-kiszolgáló. A saját tárait a telepítés után hozza létre. diff --git a/controller/app/src/main/res/values-in/strings.xml b/controller/app/src/main/res/values-in/strings.xml index d75a1f87c..1459c1768 100644 --- a/controller/app/src/main/res/values-in/strings.xml +++ b/controller/app/src/main/res/values-in/strings.xml @@ -1348,4 +1348,8 @@ Unduhan baru kini menggunakan data seluler. Ini dapat menimbulkan biaya atau menghabiskan paket data Anda. Peringatan biaya data Manual + Hosting kode + Hosting kode + Server Git pribadi di perangkat Anda. Simpan repositori kode, lacak masalah, dan tinjau perubahan secara offline. Tidak perlu internet. + Hanya server Git. Anda membuat repositori sendiri setelah memasangnya. diff --git a/controller/app/src/main/res/values-it/strings.xml b/controller/app/src/main/res/values-it/strings.xml index 2d7d26a2e..cf782d256 100644 --- a/controller/app/src/main/res/values-it/strings.xml +++ b/controller/app/src/main/res/values-it/strings.xml @@ -1341,4 +1341,8 @@ I nuovi download ora usano i dati mobili. Questo può comportare costi o esaurire il tuo piano dati. Avvisi sui costi dei dati Manuale + Ospita il codice + Hosting del codice + Un server Git privato sul tuo dispositivo. Archivia repository di codice, tieni traccia dei problemi e rivedi le modifiche offline. Nessuna connessione necessaria. + Solo il server Git. Crei i tuoi repository dopo l\'installazione. diff --git a/controller/app/src/main/res/values-ja/strings.xml b/controller/app/src/main/res/values-ja/strings.xml index ff3326073..0f9af9aa6 100644 --- a/controller/app/src/main/res/values-ja/strings.xml +++ b/controller/app/src/main/res/values-ja/strings.xml @@ -1342,4 +1342,8 @@ 新しいダウンロードはモバイルデータを使用します。料金が発生したり、データプランを使い切ったりする可能性があります。 データ料金の通知 マニュアル + コードをホスト + コードのホスティング + デバイス上のプライベート Git サーバー。コードリポジトリを保存し、課題を追跡し、変更をオフラインで確認できます。インターネットは不要です。 + Git サーバーのみ。インストール後にご自身のリポジトリを作成します。 diff --git a/controller/app/src/main/res/values-ko/strings.xml b/controller/app/src/main/res/values-ko/strings.xml index ac536dcf3..2c2a085e0 100644 --- a/controller/app/src/main/res/values-ko/strings.xml +++ b/controller/app/src/main/res/values-ko/strings.xml @@ -1342,4 +1342,8 @@ 새 다운로드가 이제 모바일 데이터를 사용합니다. 요금이 발생하거나 데이터 요금제를 모두 사용할 수 있습니다. 데이터 요금 알림 설명서 + 코드 호스팅 + 코드 호스팅 + 기기의 개인 Git 서버. 코드 저장소를 저장하고 이슈를 추적하며 변경 사항을 오프라인으로 검토하세요. 인터넷이 필요 없습니다. + Git 서버만 제공됩니다. 설치 후 직접 저장소를 만듭니다. diff --git a/controller/app/src/main/res/values-lt/strings.xml b/controller/app/src/main/res/values-lt/strings.xml index cdb475abd..c2f18f247 100644 --- a/controller/app/src/main/res/values-lt/strings.xml +++ b/controller/app/src/main/res/values-lt/strings.xml @@ -1358,4 +1358,8 @@ Nauji atsisiuntimai dabar naudoja mobiliuosius duomenis. Tai gali kainuoti arba išnaudoti duomenų planą. Duomenų sąnaudų įspėjimai Vadovas + Talpinti kodą + Kodo talpinimas + Privatus Git serveris jūsų įrenginyje. Saugokite kodo saugyklas, sekite problemas ir peržiūrėkite pakeitimus neprisijungę. Interneto nereikia. + Tik Git serveris. Savo saugyklas sukuriate įdiegę. diff --git a/controller/app/src/main/res/values-nl/strings.xml b/controller/app/src/main/res/values-nl/strings.xml index 9d42a8c8d..177e9940a 100644 --- a/controller/app/src/main/res/values-nl/strings.xml +++ b/controller/app/src/main/res/values-nl/strings.xml @@ -1341,4 +1341,8 @@ Nieuwe downloads gebruiken nu mobiele data. Dit kan kosten opleveren of je databundel opmaken. Waarschuwingen datakosten Handleiding + Code hosten + Codehosting + Een privé-Git-server op je box. Sla codeopslagplaatsen op, volg problemen en bekijk wijzigingen offline. Geen internet nodig. + Alleen de Git-server. Je maakt je eigen opslagplaatsen na de installatie. diff --git a/controller/app/src/main/res/values-no/strings.xml b/controller/app/src/main/res/values-no/strings.xml index d8b395f80..fb113d53a 100644 --- a/controller/app/src/main/res/values-no/strings.xml +++ b/controller/app/src/main/res/values-no/strings.xml @@ -1351,4 +1351,8 @@ Nye nedlastinger bruker nå mobildata. Det kan koste penger eller bruke opp datapakken din. Varsler om datakostnad Håndbok + Vert for kode + Kodehosting + En privat Git-server på boksen din. Lagre kodelagre, følg saker og se gjennom endringer offline. Ingen internett nødvendig. + Bare Git-serveren. Du oppretter dine egne lagre etter installasjonen. diff --git a/controller/app/src/main/res/values-pl/strings.xml b/controller/app/src/main/res/values-pl/strings.xml index 36ef3b2e6..7d2d8de3a 100644 --- a/controller/app/src/main/res/values-pl/strings.xml +++ b/controller/app/src/main/res/values-pl/strings.xml @@ -1351,4 +1351,8 @@ Nowe pobierania używają teraz danych komórkowych. Może to wiązać się z kosztami lub wyczerpać pakiet danych. Alerty o kosztach danych Podręcznik + Hostuj kod + Hosting kodu + Prywatny serwer Git na Twoim urządzeniu. Przechowuj repozytoria kodu, śledź zgłoszenia i przeglądaj zmiany offline. Internet nie jest potrzebny. + Tylko serwer Git. Własne repozytoria tworzysz po instalacji. diff --git a/controller/app/src/main/res/values-pt/strings.xml b/controller/app/src/main/res/values-pt/strings.xml index 5660d4baa..503b523dc 100644 --- a/controller/app/src/main/res/values-pt/strings.xml +++ b/controller/app/src/main/res/values-pt/strings.xml @@ -1420,4 +1420,8 @@ Os novos downloads agora usam dados móveis. Isso pode gerar custos ou esgotar seu plano de dados. Alertas de custo de dados Manual + Hospedar código + Hospedagem de código + Um servidor Git privado na sua caixa. Guarde repositórios de código, acompanhe problemas e reveja alterações offline. Não é preciso internet. + Apenas o servidor Git. Você cria os seus próprios repositórios após instalar. diff --git a/controller/app/src/main/res/values-ro/strings.xml b/controller/app/src/main/res/values-ro/strings.xml index 2b773b137..8fe326901 100644 --- a/controller/app/src/main/res/values-ro/strings.xml +++ b/controller/app/src/main/res/values-ro/strings.xml @@ -1341,4 +1341,8 @@ Descărcările noi folosesc acum date mobile. Acest lucru poate genera costuri sau îți poate epuiza planul de date. Alerte privind costul datelor Manual + Găzduiește cod + Găzduire de cod + Un server Git privat pe dispozitivul tău. Stochează depozite de cod, urmărește problemele și revizuiește modificările offline. Nu este nevoie de internet. + Doar serverul Git. Îți creezi propriile depozite după instalare. diff --git a/controller/app/src/main/res/values-ru-rRU/strings.xml b/controller/app/src/main/res/values-ru-rRU/strings.xml index 822eba8d9..d764d15a0 100644 --- a/controller/app/src/main/res/values-ru-rRU/strings.xml +++ b/controller/app/src/main/res/values-ru-rRU/strings.xml @@ -1417,4 +1417,8 @@ Новые загрузки теперь используют мобильные данные. Это может повлечь расходы или исчерпать пакет данных. Оповещения о расходе данных Руководство + Хостинг кода + Хостинг кода + Частный сервер Git на вашем устройстве. Храните репозитории кода, отслеживайте задачи и просматривайте изменения офлайн. Интернет не нужен. + Только сервер Git. Свои репозитории вы создаёте после установки. diff --git a/controller/app/src/main/res/values-sk/strings.xml b/controller/app/src/main/res/values-sk/strings.xml index e31a2df08..7c9a37ea2 100644 --- a/controller/app/src/main/res/values-sk/strings.xml +++ b/controller/app/src/main/res/values-sk/strings.xml @@ -1348,4 +1348,8 @@ Nové sťahovania teraz používajú mobilné dáta. Môže byť spoplatnené alebo vyčerpať váš dátový limit. Upozornenia na náklady za dáta Príručka + Hostovať kód + Hosting kódu + Súkromný server Git na vašom zariadení. Ukladajte úložiská kódu, sledujte problémy a kontrolujte zmeny offline. Internet nie je potrebný. + Len server Git. Vlastné úložiská si vytvoríte po inštalácii. diff --git a/controller/app/src/main/res/values-sr/strings.xml b/controller/app/src/main/res/values-sr/strings.xml index 92b668fbd..fa0f84427 100644 --- a/controller/app/src/main/res/values-sr/strings.xml +++ b/controller/app/src/main/res/values-sr/strings.xml @@ -1354,4 +1354,8 @@ Нова преузимања сада користе мобилне податке. Ово може да има трошак или да потроши ваш план за податке. Обавештења о трошку података Приручник + Хостуј код + Хостинг кода + Приватни Git сервер на вашем уређају. Чувајте спремишта кода, пратите проблеме и прегледајте измене офлајн. Интернет није потребан. + Само Git сервер. Сопствена спремишта правите након инсталације. diff --git a/controller/app/src/main/res/values-sw/strings.xml b/controller/app/src/main/res/values-sw/strings.xml index 0d17cf640..17a5b559c 100644 --- a/controller/app/src/main/res/values-sw/strings.xml +++ b/controller/app/src/main/res/values-sw/strings.xml @@ -1361,4 +1361,8 @@ Vipakuliwa vipya sasa vinatumia data ya simu. Hii inaweza kugharimu au kumaliza kifurushi chako cha data. Arifa za gharama ya data Mwongozo + Pangisha msimbo + Upangishaji wa msimbo + Seva ya Git ya faragha kwenye kifaa chako. Hifadhi hazina za msimbo, fuatilia masuala, na kagua mabadiliko nje ya mtandao. Hakuna intaneti inayohitajika. + Seva ya Git pekee. Unaunda hazina zako mwenyewe baada ya kuisakinisha. diff --git a/controller/app/src/main/res/values-ta/strings.xml b/controller/app/src/main/res/values-ta/strings.xml index 359b9c662..ed35ef885 100644 --- a/controller/app/src/main/res/values-ta/strings.xml +++ b/controller/app/src/main/res/values-ta/strings.xml @@ -1361,4 +1361,8 @@ புதிய பதிவிறக்கங்கள் இப்போது மொபைல் டேட்டாவைப் பயன்படுத்துகின்றன. இதனால் கட்டணம் ஏற்படலாம் அல்லது உங்கள் தரவுத் திட்டம் தீர்ந்துபோகலாம். டேட்டா செலவு எச்சரிக்கைகள் கையேடு + குறியீட்டை ஹோஸ்ட் செய் + குறியீடு ஹோஸ்டிங் + உங்கள் சாதனத்தில் தனிப்பட்ட Git சேவையகம். குறியீட்டுக் களஞ்சியங்களைச் சேமியுங்கள், சிக்கல்களைக் கண்காணியுங்கள், மாற்றங்களை ஆஃப்லைனில் மதிப்பாய்வு செய்யுங்கள். இணையம் தேவையில்லை. + Git சேவையகம் மட்டுமே. நிறுவிய பிறகு உங்கள் சொந்தக் களஞ்சியங்களை உருவாக்குகிறீர்கள். diff --git a/controller/app/src/main/res/values-tr/strings.xml b/controller/app/src/main/res/values-tr/strings.xml index 7930756e2..a4d761ab6 100644 --- a/controller/app/src/main/res/values-tr/strings.xml +++ b/controller/app/src/main/res/values-tr/strings.xml @@ -1341,4 +1341,8 @@ Yeni indirmeler artık mobil veri kullanıyor. Bu, ücretlendirilebilir veya veri paketinizi tüketebilir. Veri maliyeti uyarıları Kılavuz + Kodu barındır + Kod barındırma + Cihazınızda özel bir Git sunucusu. Kod depolarını saklayın, sorunları izleyin ve değişiklikleri çevrimdışı inceleyin. İnternet gerekmez. + Yalnızca Git sunucusu. Kendi depolarınızı kurduktan sonra oluşturursunuz. diff --git a/controller/app/src/main/res/values-uk/strings.xml b/controller/app/src/main/res/values-uk/strings.xml index 24a25c299..20d7d1987 100644 --- a/controller/app/src/main/res/values-uk/strings.xml +++ b/controller/app/src/main/res/values-uk/strings.xml @@ -1341,4 +1341,8 @@ Нові завантаження тепер використовують мобільні дані. Це може призвести до витрат або вичерпати пакет даних. Сповіщення про витрати даних Посібник + Хостинг коду + Хостинг коду + Приватний сервер Git на вашому пристрої. Зберігайте репозиторії коду, відстежуйте задачі та переглядайте зміни офлайн. Інтернет не потрібен. + Лише сервер Git. Власні репозиторії ви створюєте після встановлення. diff --git a/controller/app/src/main/res/values-vi/strings.xml b/controller/app/src/main/res/values-vi/strings.xml index ad3286b29..b29a8cb19 100644 --- a/controller/app/src/main/res/values-vi/strings.xml +++ b/controller/app/src/main/res/values-vi/strings.xml @@ -1341,4 +1341,8 @@ Các bản tải xuống mới hiện dùng dữ liệu di động. Điều này có thể phát sinh chi phí hoặc dùng hết gói dữ liệu của bạn. Cảnh báo chi phí dữ liệu Hướng dẫn + Lưu trữ mã + Lưu trữ mã + Máy chủ Git riêng trên thiết bị của bạn. Lưu kho mã, theo dõi vấn đề và xem lại thay đổi ngoại tuyến. Không cần internet. + Chỉ máy chủ Git. Bạn tạo kho của riêng mình sau khi cài đặt. diff --git a/controller/app/src/main/res/values-yo/strings.xml b/controller/app/src/main/res/values-yo/strings.xml index 0c61dfe11..22e541132 100644 --- a/controller/app/src/main/res/values-yo/strings.xml +++ b/controller/app/src/main/res/values-yo/strings.xml @@ -1361,4 +1361,8 @@ Awọn igbasilẹ tuntun n lo data alagbeka bayii. Eyi le san owo tabi lo package data rẹ tan. Awọn ikilọ iye owo data Ìwé Ìtọ́sọ́nà + Gbàlejò kóòdù + Ìgbàlejò kóòdù + Olùpín Git aládàáni lórí ẹ̀rọ rẹ. Fi àwọn ibi ìpamọ́ kóòdù pamọ́, tọpinpin àwọn ìṣòro, kí o sì ṣàyẹ̀wò àwọn ìyípadà láìsí Íńtánẹ́ẹ̀tì. A kò nílò Íńtánẹ́ẹ̀tì. + Olùpín Git nìkan. O máa ń ṣẹ̀dá àwọn ibi ìpamọ́ tìrẹ lẹ́yìn ìfìsórí-ẹ̀rọ. diff --git a/controller/app/src/main/res/values-zh-rCN/strings.xml b/controller/app/src/main/res/values-zh-rCN/strings.xml index a7595b7ea..a17cd20bf 100644 --- a/controller/app/src/main/res/values-zh-rCN/strings.xml +++ b/controller/app/src/main/res/values-zh-rCN/strings.xml @@ -1342,4 +1342,8 @@ 新的下载现在会使用移动数据。这可能产生费用或用尽您的套餐流量。 数据费用提醒 手册 + 托管代码 + 代码托管 + 设备上的私有 Git 服务器。离线存储代码仓库、跟踪问题并审查更改。无需联网。 + 仅提供 Git 服务器。安装后由你创建自己的仓库。 diff --git a/controller/app/src/main/res/values/strings.xml b/controller/app/src/main/res/values/strings.xml index f5383255b..7a7c2f551 100644 --- a/controller/app/src/main/res/values/strings.xml +++ b/controller/app/src/main/res/values/strings.xml @@ -58,6 +58,7 @@ Kolibri IIAB Maps Matomo + Forgejo System Code @@ -754,6 +755,9 @@ Analytics Matomo Private, self-hosted usage analytics for your library that helps you understand how content is being used. + Code hosting + Forgejo + A private Git server on your box. Store code repositories, track issues, and review changes offline. No internet is needed. Backups & recovery You can save your system to a file, restore your system from a backup file, or reinstall K2Go from scratch @@ -944,6 +948,7 @@ Explore Wikipedia Take courses Navigate maps + Host code Ready to explore Ready Connecting @@ -1345,6 +1350,7 @@ Reader only. Add books in Get more. Reader only. Add Wikipedia and ZIM content in Get more. This downloads the Code on the Go (CoGo) installer to your phone. CoGo runs outside K2Go. In your phone\'s Downloads folder, tap the file to install CoGo. + The Git server only. You create your own repositories after you install it. Analytics for this server — nothing to add. Base map — pick the layers and region when you install. diff --git a/controller/app/src/test/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicyTest.java b/controller/app/src/test/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicyTest.java index 9589f695d..26b3e9f68 100644 --- a/controller/app/src/test/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicyTest.java +++ b/controller/app/src/test/java/org/appdevforall/k2go/portal/domain/AutoLoginPolicyTest.java @@ -21,6 +21,12 @@ public class AutoLoginPolicyTest { assertEquals("kolibri", AutoLoginPolicy.serviceFor("http://127.0.0.1:8085/kolibri/learn#/home")); } + @Test public void forgejoPagesOpenAsForgejoAdmin() { // K2GO-212 + assertEquals("forgejo", AutoLoginPolicy.serviceFor("http://localhost:8085/forgejo/")); + assertEquals("forgejo", AutoLoginPolicy.serviceFor("http://127.0.0.1:8085/forgejo/AppDevForAll/KnowledgeToGo")); + assertEquals("/forgejo", AutoLoginPolicy.prefixFor("http://localhost:8085/forgejo/")); + } + @Test public void otherBoxPagesNeedNoSession() { assertNull(AutoLoginPolicy.serviceFor("http://localhost:8085/home")); assertNull(AutoLoginPolicy.serviceFor("http://localhost:8085/kiwix/")); diff --git a/iiab-android b/iiab-android index 7869362bc..bb8fee365 100644 --- a/iiab-android +++ b/iiab-android @@ -51,6 +51,7 @@ INSTALL_FALLBACK="https://raw.githubusercontent.com/iiab/iiab-factory/refs/heads ENABLE_INDEX_PAGE="${ENABLE_INDEX_PAGE:-1}" ENABLE_DEMO_CONTENTS="${ENABLE_DEMO_CONTENTS:-0}" +ENABLE_FORGEJO_SEED="${ENABLE_FORGEJO_SEED:-0}" # K2GO-212: seed Forgejo repos (bake only; needs internet) DEMO_REPO_URL="https://iiab.switnet.org/android/static_demo/" PG_CATALOG_URL="https://iiab.switnet.org/android/pg/catalog.db.gz" @@ -630,6 +631,19 @@ else sed -i -E '/^[[:space:]]*code_(install|enabled)[[:space:]]*:/d' "$LOCAL_VARS_DEST" echo "code_install: True" >> "$LOCAL_VARS_DEST" echo "code_enabled: True" >> "$LOCAL_VARS_DEST" + + # K2GO-212: the forgejo role ships install/enabled False in every vars template (carried via + # tools/upstream-patches until iiab#4505 merges), so enable it for Standard/Full here (not Basic). + case "$LOCAL_VARS_URL" in + *_small*) + log "Basic tier: Forgejo left off." + ;; + *) + sed -i -E '/^[[:space:]]*forgejo_(install|enabled)[[:space:]]*:/d' "$LOCAL_VARS_DEST" + echo "forgejo_install: True" >> "$LOCAL_VARS_DEST" + echo "forgejo_enabled: True" >> "$LOCAL_VARS_DEST" + ;; + esac fi #----------------------------- @@ -674,6 +688,30 @@ else log "Skipping index site installation (ENABLE_INDEX_PAGE=0)." fi +#----------------------------- +# K2GO-212: seed Forgejo repos (bake only, needs internet -> gated on ENABLE_FORGEJO_SEED). Repo set +# is tier-scoped (Standard: KnowledgeToGo; Full: + CodeOnTheGo@stage + plugin-examples); Basic has +# forgejo off so is_role_enabled skips it. See static/forgejo/orchestration. +#----------------------------- +if [ "${ENABLE_FORGEJO_SEED:-0}" -eq 1 ] && is_role_enabled forgejo; then + if [ -f "${K2GO_OPT_DIR}/static/forgejo/orchestration" ]; then + . "${K2GO_OPT_DIR}/static/forgejo/orchestration" + # Pick the tier's repo list by name; the URLs live only in the orchestration. + case "$LOCAL_VARS_URL" in + *_large*) FORGEJO_REPOS="$FORGEJO_REPOS_FULL" ;; + *) FORGEJO_REPOS="$FORGEJO_REPOS_STANDARD" ;; + esac + export FORGEJO_REPOS + log "Seeding Forgejo repos (tier vars: ${LOCAL_VARS_URL##*/})..." + # Best-effort: a seed failure must not abort the whole bake (mirrors install_welcome_zim). + seed_forgejo || warn "Forgejo seed failed (non-fatal)." + else + warn "static/forgejo/orchestration not found; skipping Forgejo seed." + fi +else + log "Skipping Forgejo seed (ENABLE_FORGEJO_SEED=${ENABLE_FORGEJO_SEED:-0})." +fi + #----------------------------- # K2Go docs (tier-3) static module. # Install the nginx conf, then deploy the committed manual (static/k2go-docs/content) into the diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index 1d9e78b01..bdf12d17d 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i (the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`. +- **1.3.4** - Forgejo admin auto-login (K2GO-212). New `/auth/forgejo/session` mints the box admin web session for the WebView, extending the auto-login family (Calibre-Web / Kolibri, 1.1.3) to the Git forge. Forgejo 15's login is CSRF-exempt: a POST of `user_name` + `password` returns 303 with a `session` cookie, verified by the redirect (a 200 means the form re-rendered, so wrong credentials). The returned cookie jar drops empty "clear" directives so a path-blind merge cannot inject the logged-out cookie. Localhost-only, like all of `/k2go-api`. (K2GO-212) - **1.3.3** - Base-map job takes a file id, composes the URL (K2GO-394). The `basemaps` runner now accepts a bare pmtiles file name per item (`POST /api/basemaps/download {ids:[.pmtiles]}`) and composes `https://iiab.switnet.org/maps/2/` itself, instead of taking a full URL. This matches the kiwix split: the app holds the catalog and sends a light id, the box owns the mirror host -- so the switnet host never enters the app. The id is validated as a plain `.pmtiles` file name (no path, no traversal); archives (search) are not delegated here. No other behavior changes (same aria2 flags, reconnect loop, cancel-cleanup). (K2GO-394) - **1.3.2** - Base-map downloads via the durable job engine (K2GO-394). New `basemaps` job type + runner (`sockets/maps-base.exec.ts`), reached through the generic surface (`POST /api/basemaps/download {items:[]}`, `GET /api/basemaps/jobs/:id`, `POST /api/basemaps/jobs/:id/{cancel,pause,resume,retry}`). It downloads the selected global map pmtiles (vector / satellite / terrain) with aria2 straight into `/library/www/maps`, reusing the EXACT kiwix mechanism -- the canonical aria2 flag set plus the `withRetry` OUTER reconnect loop -- so a full Wi-Fi drop (aria2 exits on DNS, code 19) recovers by re-running aria2 which resumes via `--continue`, surfaced as "Reconnecting n/5". This replaces the aria2c the maps runrole ran IN-PROOT, which could not recover a mobile-radio drop (it wedged with no exit): the app runs this job (server up) and the runrole then only post-processes, its download tasks SKIPPING via `creates:` (see the maps role's `is_proot` delegate patch). Two things learned the hard way and encoded here: it passes the DIRECT pmtiles URL, NOT a `.meta4` metalink (metalink downloads were the exact case aria2 could not recover), and it does NOT diverge the flags (an aggressive `--max-tries=1 --timeout=10` cut wedged worse; the kiwix values are load-bearing). Kept SEPARATE from the FQR `maps` type (tile-extract). Device-verified: cut Wi-Fi at 27% of a pmtiles -> "Reconnecting 5/5", partial kept -> restore -> resumed to done, file complete at dest_path. (K2GO-394) - **1.3.1** - Live firehose signal for the app-side backstop (K2GO-386, ADR-386 §6). New read-only `GET /system/disk-guard/firehose` returns `{ recurring, maxStreak, paths, lastTruncatedAtMs, now }`. The in-box guard (1.3.0) truncates a runaway `.log` every tick, so the disk may never go low -- but a recurring firehose means an off-proot orphan the box CANNOT stop; only an app-side reap can. This endpoint exposes the guard's LIVE in-memory streak state (never a parsed log line, so a restart-resolved firehose reports clean) as the app's SECOND reap trigger. `recurring` is `maxStreak >= 2` (a single `.log` refilled past the cap on at least two consecutive ticks); `lastTruncatedAtMs` (wall-clock, 0 if never) lets the app judge freshness. It is an ALERT only: the app re-probes live log growth before it reaps (confirm before acting). Localhost-only. (K2GO-386) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index f2c67742c..d6d65a3f9 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "dashboard-console", - "version": "1.3.3", + "version": "1.3.4", "description": "", "main": "index.js", "scripts": { diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts index 5557eac9c..1e09fb43e 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -17,6 +17,7 @@ import { verifyCredentials, ChannelNotInstalledError, } from './sockets/kolibri.query'; import { checkReadiness, KolibriAuthError, KolibriApiError, login as kolibriLogin } from './sockets/kolibri.session'; +import { login as forgejoLogin, ForgejoAuthError } from './sockets/forgejo.session'; import { describeCredential, setCredential, clearCredential, isServiceName, } from './sockets/credentials'; @@ -802,6 +803,11 @@ apiRouter.get('/auth/:service/session', async (req: Request, res: Response): Pro res.json({ service: 'calibre', cookie: s.cookie }); return; } + if (service === 'forgejo') { + const s = await forgejoLogin(undefined, consumerUa); + res.json({ service: 'forgejo', cookie: s.cookie }); + return; + } res.status(404).json({ error: 'unknown service' }); } catch (e: any) { // Keep the detail server-side; the app only needs the status + a generic reason. @@ -811,6 +817,11 @@ apiRouter.get('/auth/:service/session', async (req: Request, res: Response): Pro res.status(status).json({ error: 'sign-in failed' }); return; } + if (e instanceof ForgejoAuthError) { + const status = e.reason === 'credentials' ? 401 : 503; + res.status(status).json({ error: 'sign-in failed' }); + return; + } // Calibre login throws generic errors; treat a clear bad-credential signal as 401, else 503. const status = /invalid.*cred/i.test(e?.message || '') ? 401 : 503; res.status(status).json({ error: 'sign-in failed' }); diff --git a/static/dashboard/sockets/credentials.ts b/static/dashboard/sockets/credentials.ts index 9ab0e16be..d72151cc4 100644 --- a/static/dashboard/sockets/credentials.ts +++ b/static/dashboard/sockets/credentials.ts @@ -16,7 +16,7 @@ import fs from 'fs'; import path from 'path'; -export type ServiceName = 'kolibri' | 'calibre'; +export type ServiceName = 'kolibri' | 'calibre' | 'forgejo'; export interface Credential { username: string; @@ -37,14 +37,17 @@ const STORE_PATH = process.env.K2GO_CREDENTIALS_FILE const DEFAULTS: Record = { kolibri: { username: 'Admin', password: 'changeme' }, calibre: { username: 'Admin', password: 'changeme' }, + // K2GO-212: the seed creates this admin ('admin' is reserved by forgejo). + forgejo: { username: 'k2goadmin', password: 'changeme' }, }; const ENV_PREFIX: Record = { kolibri: 'K2GO_KOLIBRI', calibre: 'K2GO_CALIBRE', + forgejo: 'K2GO_FORGEJO', }; -const SERVICES: ServiceName[] = ['kolibri', 'calibre']; +const SERVICES: ServiceName[] = ['kolibri', 'calibre', 'forgejo']; export function isServiceName(s: string): s is ServiceName { return (SERVICES as string[]).includes(s); diff --git a/static/dashboard/sockets/forgejo.session.ts b/static/dashboard/sockets/forgejo.session.ts new file mode 100644 index 000000000..d8fa78da3 --- /dev/null +++ b/static/dashboard/sockets/forgejo.session.ts @@ -0,0 +1,115 @@ +// sockets/forgejo.session.ts — authenticated web session against Forgejo (K2GO-212) +// +// Forgejo's login is a form POST. Unlike older Gitea, Forgejo 15's login form has +// NO _csrf field and the login route is CSRF-exempt (verified on device: a POST of +// just user_name + password returns 303 and the session cookie). So we do not seed +// or send a CSRF token: +// POST /user/login (form-encoded: user_name, password) +// success -> 303/302 redirect to the dashboard, with a 'session' cookie; +// wrong password -> the form re-renders with HTTP 200. +// The box talks to Forgejo DIRECTLY on :3300 (nginx strips the /forgejo prefix via +// its trailing-slash proxy_pass), so the paths carry no prefix here. We return the +// whole Set-Cookie jar (the session cookie name is Forgejo's own) and verify by the +// redirect; the app re-homes the cookies to path=/ when it injects them (SessionCookies). +import { getCredential } from './credentials'; +import { mergeCookies } from './kolibri.session'; + +export const FORGEJO_BASE = process.env.K2GO_FORGEJO_URL || 'http://127.0.0.1:3300'; +const DEFAULT_TIMEOUT_MS = 8000; + +export interface ForgejoSession { + /** Cookie header, already assembled, to inject into the WebView. */ + cookie: string; + username: string; +} + +/** 'unreachable' -> 503 (service not ready), 'credentials' -> 401, 'protocol' -> 503. */ +export type ForgejoAuthReason = 'unreachable' | 'credentials' | 'protocol'; + +export class ForgejoAuthError extends Error { + readonly reason: ForgejoAuthReason; + constructor(reason: ForgejoAuthReason, message: string) { + super(message); + this.name = 'ForgejoAuthError'; + this.reason = reason; + } +} + +async function fetchWithTimeout( + url: string, + init: RequestInit = {}, + timeoutMs = DEFAULT_TIMEOUT_MS, +): Promise { + return fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); +} + +/** + * Drops "clear" directives (empty value, e.g. `session=; Max-Age=0`) from a Set-Cookie list. + * Forgejo rotates the session by clearing it at one path and setting it at another in the SAME + * response; mergeCookies keys by name only, so without this a last-wins merge could keep the empty + * clear and inject a logged-out cookie. Keeping only non-empty values makes the merge order-independent. + */ +function dropClears(setCookies: string[]): string[] { + return setCookies.filter((raw) => { + const first = raw.split(';')[0]; + const eq = first.indexOf('='); + return eq >= 0 && first.slice(eq + 1).trim() !== ''; + }); +} + +/** + * Authenticates against Forgejo and returns a reusable web session. + * + * @param override explicit credentials (used before persisting them); if omitted, + * they are taken from the store. + * @param userAgent the agent that will USE the session (the app's WebView), so the + * login is minted for it (mirrors the Kolibri/Calibre endpoints). + */ +export async function login( + override?: { username: string; password: string }, + userAgent?: string, +): Promise { + const cred = override ?? getCredential('forgejo'); + const agent: Record = userAgent ? { 'User-Agent': userAgent } : {}; + + // Seed any cookies the login page sets (harmless; login itself is CSRF-exempt). + let cookie = ''; + try { + const seed = await fetchWithTimeout(`${FORGEJO_BASE}/user/login`, { headers: { ...agent } }); + cookie = mergeCookies('', dropClears(seed.headers.getSetCookie())); + } catch (e) { + throw new ForgejoAuthError('unreachable', + `Forgejo did not respond at ${FORGEJO_BASE}: ${e instanceof Error ? e.message : String(e)}`); + } + + // POST the login form. Do NOT follow the redirect: a 302/303 is success, a 200 + // means the form re-rendered (wrong credentials). + let res: Response; + try { + const body = new URLSearchParams({ user_name: cred.username, password: cred.password }); + res = await fetchWithTimeout(`${FORGEJO_BASE}/user/login`, { + method: 'POST', + redirect: 'manual', + headers: { + ...agent, + 'Content-Type': 'application/x-www-form-urlencoded', + Cookie: cookie, + }, + body: body.toString(), + }); + } catch (e) { + throw new ForgejoAuthError('unreachable', + `Forgejo dropped the connection during login: ${e instanceof Error ? e.message : String(e)}`); + } + + if (res.status === 200) { + throw new ForgejoAuthError('credentials', + `Forgejo rejected the credentials for '${cred.username}'`); + } + if (res.status !== 302 && res.status !== 303) { + throw new ForgejoAuthError('protocol', `Forgejo login returned HTTP ${res.status}`); + } + + cookie = mergeCookies(cookie, dropClears(res.headers.getSetCookie())); + return { cookie, username: cred.username }; +} diff --git a/static/forgejo/orchestration b/static/forgejo/orchestration new file mode 100644 index 000000000..e04d1b9ba --- /dev/null +++ b/static/forgejo/orchestration @@ -0,0 +1,159 @@ +# ============================================================================ +# Name : static/forgejo/orchestration +# Author : AppDevForAll +# Copyright : Copyright (c) 2026 AppDevForAll +# Description : K2GO-212. Forgejo repo seeding for the K2Go bake. Sourced by the +# installer ONLY when ENABLE_FORGEJO_SEED=1. Holds the config +# (env-overridable) and the orchestration function seed_forgejo. +# Guard-based and idempotent: Forgejo is the single source of truth +# (it already knows which repos exist and whether they are empty), +# so re-running needs no local state file. +# +# The seeding method is "shallow": a shallow single-branch bare clone adopted +# into Forgejo. The migrate API does a FULL clone and cannot go shallow, so the +# bake clones the shallow dir and adopts it. This carries the full current tree +# (compiles to a working APK) and drops the dead git history: CoGo 1.2 GB -> ~150 MB. +# Study: Confluence "Code on the Go (CoGo) - repo size, subset strategy & +# offline-compile validation". +# ============================================================================ + +# ===== CONFIG (env overrides win) ========================================== +FORGEJO_BIN="${FORGEJO_BIN:-/library/forgejo/forgejo}" # absolute: 'forgejo' is NOT on the forgejo user's PATH under su +FORGEJO_CONFIG="${FORGEJO_CONFIG:-/etc/forgejo/app.ini}" +FORGEJO_RUN_USER="${FORGEJO_RUN_USER:-forgejo}" +FORGEJO_REPO_ROOT="${FORGEJO_REPO_ROOT:-/library/forgejo/data/repositories}" + +# Talk to forgejo DIRECTLY (bypass nginx). A synchronous migrate through nginx +# can hit proxy_read_timeout and make forgejo ROLL BACK the repo. forgejo serves +# its ROOT at :3300, so the API is :3300/api/v1 (nginx strips the /forgejo prefix). +FORGEJO_API="${FORGEJO_API:-http://127.0.0.1:3300/api/v1}" +# Health gate goes THROUGH nginx on purpose: a healthy K2Go needs nginx up too, +# not just forgejo. :8085 is the box nginx; /forgejo/ proxies to :3300. +FORGEJO_HEALTH="${FORGEJO_HEALTH:-http://127.0.0.1:8085/forgejo/}" + +FORGEJO_ADMIN_USER="${FORGEJO_ADMIN_USER:-k2goadmin}" # 'admin' is RESERVED by forgejo +FORGEJO_ADMIN_PASS="${FORGEJO_ADMIN_PASS:-changeme}" # override in the env for real deployments +FORGEJO_ADMIN_EMAIL="${FORGEJO_ADMIN_EMAIL:-k2go@box.lan}" + +# Repos live under an org (full-name mirrors of the originals); contributors fork. Admin owns the org. +FORGEJO_ORG="${FORGEJO_ORG:-AppDevForAll}" + +FORGEJO_PROOT="${FORGEJO_PROOT:-1}" # 1 on K2Go (proot): enables the l2s double-rm +FORGEJO_WAIT_TRIES="${FORGEJO_WAIT_TRIES:-60}" # 502 window tolerance (x 5s ~= 5 min) +# "shallow" (git clone --bare --depth 1 + adopt; recommended) or "migrate" +# (forgejo migrate API, full mirror). Shallow keeps the full current tree and +# drops history; the migrate API cannot go shallow. +FORGEJO_SEED_METHOD="${FORGEJO_SEED_METHOD:-shallow}" + +# Canonical repo lists (owner|name|clone_addr|branch; branch optional -> default). Single source +# for the repo URLs: the installer gate selects one by tier, it does not restate the URLs. +FORGEJO_REPOS_FULL="${FORGEJO_ORG}|CodeOnTheGo|https://github.com/appdevforall/CodeOnTheGo|stage +${FORGEJO_ORG}|KnowledgeToGo|https://github.com/appdevforall/KnowledgeToGo| +${FORGEJO_ORG}|plugin-examples|https://github.com/appdevforall/plugin-examples|" +FORGEJO_REPOS_STANDARD="${FORGEJO_ORG}|KnowledgeToGo|https://github.com/appdevforall/KnowledgeToGo|" +FORGEJO_REPOS="${FORGEJO_REPOS:-$FORGEJO_REPOS_FULL}" + +# ===== small helpers (reuse installer's log/ok/warn if present) ============ +command -v log >/dev/null 2>&1 || log(){ printf ' %s\n' "$*"; } +command -v ok >/dev/null 2>&1 || ok(){ printf ' OK: %s\n' "$*"; } +command -v warn >/dev/null 2>&1 || warn(){ printf ' WARN: %s\n' "$*" >&2; } + +_fj_su() { su -s /bin/sh "$FORGEJO_RUN_USER" -c "$1"; } # run as the forgejo user +_fj_api() { curl -fsS -u "$FORGEJO_ADMIN_USER:$FORGEJO_ADMIN_PASS" "$@"; } + +# Wait for forgejo to answer 200 THROUGH nginx (tolerate the post-restart 502 window). +_fj_wait_200() { + local i=0 + while [ "$i" -lt "$FORGEJO_WAIT_TRIES" ]; do + [ "$(curl -s -o /dev/null -w '%{http_code}' "$FORGEJO_HEALTH")" = "200" ] && { ok "forgejo is serving 200"; return 0; } + i=$((i+1)); sleep 5 + done + warn "forgejo did not reach 200 after $((FORGEJO_WAIT_TRIES*5))s"; return 1 +} + +# Admin (guard: create only if missing; run as forgejo user, absolute binary path). +_fj_ensure_admin() { + if _fj_su "$FORGEJO_BIN admin user list --config $FORGEJO_CONFIG" 2>/dev/null | awk '{print $2}' | grep -qx "$FORGEJO_ADMIN_USER"; then + log "admin '$FORGEJO_ADMIN_USER' already exists"; return 0 + fi + _fj_su "$FORGEJO_BIN admin user create --admin --username '$FORGEJO_ADMIN_USER' \ + --password '$FORGEJO_ADMIN_PASS' --email '$FORGEJO_ADMIN_EMAIL' \ + --must-change-password=false --config $FORGEJO_CONFIG" \ + && ok "admin '$FORGEJO_ADMIN_USER' created" || { warn "admin create failed"; return 1; } +} + +# Org (guard: create only if missing). Owned by the admin user; repos live under it. +_fj_ensure_org() { + if _fj_api "$FORGEJO_API/orgs/$FORGEJO_ORG" >/dev/null 2>&1; then + log "org '$FORGEJO_ORG' already exists"; return 0 + fi + if _fj_api -X POST "$FORGEJO_API/orgs" -H 'Content-Type: application/json' \ + -d "{\"username\":\"$FORGEJO_ORG\",\"visibility\":\"public\"}" >/dev/null 2>&1; then + ok "org '$FORGEJO_ORG' created" + else + warn "org '$FORGEJO_ORG' create failed"; return 1 + fi +} + +# Guard: repo exists AND is non-empty (a dangling/empty repo dir still 409s on re-seed). +_fj_repo_ready() { + _fj_api "$FORGEJO_API/repos/$1/$2" 2>/dev/null | grep -q '"empty":false' +} + +# Purge a broken/empty repo before retry. On proot, a single rm leaves dangling +# link2symlink (l2s) entries -> the dir survives -> next seed 409s. So rm TWICE (+ once more). +_fj_purge_repo() { + local owner="$1" name="$2" dir="$FORGEJO_REPO_ROOT/$1/$2.git" + _fj_api -X DELETE "$FORGEJO_API/repos/$owner/$name" >/dev/null 2>&1 || true + if [ "$FORGEJO_PROOT" = "1" ]; then + rm -rf "$dir" 2>/dev/null; rm -rf "$dir" 2>/dev/null; rm -rf "$dir" 2>/dev/null + else + rm -rf "$dir" 2>/dev/null + fi +} + +# Method A: full mirror via the migrate API (direct :3300, bypassing nginx). +# K2GO-212: keep the failure output for debugging instead of discarding it. +_fj_migrate() { + local owner="$1" name="$2" addr="$3" out + out="$(_fj_api -X POST "$FORGEJO_API/repos/migrate" -H 'Content-Type: application/json' \ + -d "{\"clone_addr\":\"$addr\",\"repo_owner\":\"$owner\",\"repo_name\":\"$name\",\"service\":\"git\",\"mirror\":false}" 2>&1)" \ + || { warn "migrate $owner/$name failed: $out"; return 1; } +} + +# Method B: shallow snapshot -> adopt (recommended; full current tree, compilable, no history). +# K2GO-212: keep the failure output for debugging. +_fj_shallow_adopt() { + local owner="$1" name="$2" addr="$3" branch="$4" dir="$FORGEJO_REPO_ROOT/$1/$2.git" out + local br=""; [ -n "$branch" ] && br="--branch $branch" + mkdir -p "$FORGEJO_REPO_ROOT/$owner" + # shellcheck disable=SC2086 + out="$(git clone --bare --depth 1 --single-branch $br "$addr" "$dir" 2>&1)" \ + || { warn "clone $owner/$name failed: $out"; return 1; } + chown -R "$FORGEJO_RUN_USER:$FORGEJO_RUN_USER" "$FORGEJO_REPO_ROOT/$owner" + out="$(_fj_api -X POST "$FORGEJO_API/admin/unadopted/$owner/$name" 2>&1)" \ + || { warn "adopt $owner/$name failed: $out"; return 1; } # HTTP 204 on success +} + +# Seed one repo (guard -> purge-if-broken -> seed -> verify). +_fj_seed_one() { + local owner="$1" name="$2" addr="$3" branch="$4" + if _fj_repo_ready "$owner" "$name"; then log "skip $owner/$name (already seeded)"; return 0; fi + log "seeding $owner/$name [$FORGEJO_SEED_METHOD]" + _fj_purge_repo "$owner" "$name" + if [ "$FORGEJO_SEED_METHOD" = "migrate" ]; then _fj_migrate "$owner" "$name" "$addr" + else _fj_shallow_adopt "$owner" "$name" "$addr" "$branch"; fi + if _fj_repo_ready "$owner" "$name"; then ok "seeded $owner/$name"; else warn "FAILED $owner/$name"; return 1; fi +} + +# ===== entry point (what the installer gate calls) ========================= +seed_forgejo() { + _fj_wait_200 || return 1 + _fj_ensure_admin || return 1 + _fj_ensure_org || return 1 + printf '%s\n' "$FORGEJO_REPOS" | while IFS='|' read -r owner name addr branch; do + [ -n "$owner" ] && [ -n "$addr" ] || continue + _fj_seed_one "$owner" "$name" "$addr" "$branch" || true # one repo must not abort the rest + done + ok "forgejo seeding done" +} diff --git a/static/site/index.html b/static/site/index.html index eb9821511..8ffb03d5d 100644 --- a/static/site/index.html +++ b/static/site/index.html @@ -45,6 +45,12 @@

Knowledge to Go

+ +