werkstaetten-app/mobile/scripts/prepare.mjs
Friederich Loheide 856559f830 Native Apps für iOS und Android (Capacitor) mit Push über Firebase
Apps (mobile/):
- Capacitor-8-Hülle, lädt die Web-App von APP_URL – Inhalte ohne App-Update
- Android- und iOS-Projekt (Swift Package Manager) mit Firebase Messaging,
  nativer Sprachausgabe, Teilen, App, Statusleiste, Startbildschirm
- `npm run sync` überträgt APP_ID, Name, Adresse und Farbe aus mobile/.env
  in beide Projekte und richtet ein: App-Links (Android intent-filter,
  iOS Associated Domains), Push (Entitlements, Background Mode,
  AppDelegate, Benachrichtigungssymbol/-farbe), Offline-Seite;
  idempotent, prüft Eingaben, warnt bei fehlenden Firebase-Dateien
- `npm run assets` erzeugt Symbole und Startbildschirme aus Logo und
  Markenfarbe der Redaktion, dazu das Android-Benachrichtigungssymbol
- Schritt-für-Schritt-Anleitung für den Mac (mobile/README.md)

Server:
- Versand an App-Geräte über FCM HTTP v1 (signiertes JWT, ohne
  firebase-admin), eingebunden in alle Benachrichtigungen; abgemeldete
  Geräte werden entfernt (nur bei UNREGISTERED, nicht bei anderen Fehlern)
- Firebase-Dienstkonto in den Einstellungen hochladen (verschlüsselt),
  App-ID, Team-ID, SHA-256, Store-Links; /.well-known/apple-app-site-
  association und assetlinks.json; Smart-App-Banner, Store-Hinweis
- Server erkennt die App am User-Agent (kein Aufblitzen von
  „Als App installieren“); Datenschutz-Vorlage um Firebase ergänzt

Web-App in der App: Push über Firebase statt Web-Push, Vorlesen nativ,
Teilen nativ, Zurück-Taste (schließt erst Dialoge), Antippen einer
Benachrichtigung und App-Links öffnen die Seite (nur eigene Adressen).

Getestet mit nachgebauter Capacitor-Brücke und nachgebautem Firebase-Dienst.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 07:03:26 +00:00

188 lines
8.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Bereitet die nativen Projekte vor – wird von `npm run sync` vor `cap sync` ausgeführt.
* Überträgt App-ID, Name, Adresse und Farbe aus mobile/.env in Android und iOS und
* richtet Push-Nachrichten und App-Links ein. Mehrfaches Ausführen ist unbedenklich.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadEnv } from '../env.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const env = loadEnv();
const host = new URL(env.appUrl).host;
const p = (...parts) => path.join(root, ...parts);
const read = (f) => fs.readFileSync(f, 'utf8');
const write = (f, s) => fs.writeFileSync(f, s);
const xmlEsc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const warnings = [];
if (!env.appUrl.startsWith('https://')) warnings.push('APP_URL muss mit https:// beginnen (Apple und Google verlangen HTTPS).');
if (env.appUrl.includes('example.org')) warnings.push('APP_URL ist noch der Platzhalter – bitte in mobile/.env eintragen.');
if (env.appId.startsWith('org.example')) warnings.push('APP_ID ist noch der Platzhalter – vor dem ersten Hochladen in die Stores festlegen (später nicht mehr änderbar).');
if (!/^[a-zA-Z][\w]*(\.[a-zA-Z][\w]*)+$/.test(env.appId)) throw new Error(`APP_ID „${env.appId}“ ist ungültig (Beispiel: org.lindenhof.app).`);
if (!/^#[0-9a-f]{6}$/i.test(env.brandColor)) throw new Error(`BRAND_COLOR „${env.brandColor}“ ist ungültig (Beispiel: #2e2672).`);
/** Bereich zwischen zwei Markierungen ersetzen oder einfügen */
function block(text, name, content, insertBefore, indent = '') {
const start = `${indent}<!-- werkstatt:${name}:start -->`;
const end = `${indent}<!-- werkstatt:${name}:end -->`;
const full = `${start}\n${content}\n${end}`;
const re = new RegExp(`[ \\t]*<!-- werkstatt:${name}:start -->[\\s\\S]*?<!-- werkstatt:${name}:end -->`);
if (re.test(text)) return text.replace(re, full);
if (!text.includes(insertBefore)) throw new Error(`Einfügestelle „${insertBefore}“ nicht gefunden`);
return text.replace(insertBefore, `${full}\n${insertBefore}`);
}
// ─── Offline-Seite ───────────────────────────────────────────────────────────
write(
p('www', 'offline.html'),
`<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>${xmlEsc(env.appName)}</title>
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: ${env.brandColor}; color: #fff;
font: 500 18px/1.6 system-ui, -apple-system, 'Segoe UI', sans-serif; text-align: center; padding: 24px; box-sizing: border-box; }
h1 { font-size: 26px; margin: 0 0 8px; }
p { margin: 0 0 28px; opacity: .9; }
a { display: inline-block; background: #fff; color: ${env.brandColor}; font-weight: 700; text-decoration: none;
padding: 14px 28px; border-radius: 999px; }
</style>
</head>
<body>
<main>
<h1>Keine Verbindung</h1>
<p>${xmlEsc(env.appName)} braucht Internet.<br>Bitte prüfe WLAN oder mobile Daten.</p>
<a href="${env.appUrl}/">Noch einmal versuchen</a>
</main>
</body>
</html>
`
);
// ─── Android ─────────────────────────────────────────────────────────────────
if (fs.existsSync(p('android'))) {
const gradle = p('android', 'app', 'build.gradle');
write(gradle, read(gradle).replace(/applicationId "[^"]*"/, `applicationId "${env.appId}"`));
const strings = p('android', 'app', 'src', 'main', 'res', 'values', 'strings.xml');
let s = read(strings);
for (const [key, value] of [
['app_name', env.appName],
['title_activity_main', env.appName],
['package_name', env.appId],
['custom_url_scheme', env.appId]
])
s = s.replace(new RegExp(`(<string name="${key}">)[^<]*(</string>)`), `$1${xmlEsc(value)}$2`);
write(strings, s);
// Farbe für das Benachrichtigungssymbol und den Symbol-Hintergrund
write(
p('android', 'app', 'src', 'main', 'res', 'values', 'werkstatt_colors.xml'),
`<?xml version="1.0" encoding="utf-8"?>\n<resources>\n <color name="werkstatt_brand">${env.brandColor}</color>\n</resources>\n`
);
const manifestFile = p('android', 'app', 'src', 'main', 'AndroidManifest.xml');
let m = read(manifestFile);
// App-Links: Links zur Website öffnen direkt die App (Nachweis: /.well-known/assetlinks.json)
m = block(
m,
'applinks',
` <intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="${host}" />
</intent-filter>`,
' </activity>',
' '
);
// Symbol und Farbe für Push-Nachrichten (Symbol erzeugt `npm run assets`)
const hasIcon = fs.existsSync(p('android', 'app', 'src', 'main', 'res', 'drawable-xxhdpi', 'ic_stat_notify.png'));
m = block(
m,
'push',
`${
hasIcon
? ` <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_notify" />\n`
: ''
} <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/werkstatt_brand" />`,
' </application>',
' '
);
write(manifestFile, m);
if (!hasIcon) warnings.push('Android: kein Benachrichtigungssymbol – `npm run assets` ausführen.');
if (!fs.existsSync(p('android', 'app', 'google-services.json')))
warnings.push('Android: android/app/google-services.json fehlt – ohne sie gibt es keine Push-Nachrichten (siehe README).');
}
// ─── iOS ─────────────────────────────────────────────────────────────────────
if (fs.existsSync(p('ios'))) {
const pbx = p('ios', 'App', 'App.xcodeproj', 'project.pbxproj');
let x = read(pbx).replace(/PRODUCT_BUNDLE_IDENTIFIER = [^;]+;/g, `PRODUCT_BUNDLE_IDENTIFIER = ${env.appId};`);
// Entitlements (Push + Associated Domains) dem App-Ziel zuordnen
if (!x.includes('CODE_SIGN_ENTITLEMENTS'))
x = x.replace(/(\n(\t+)INFOPLIST_FILE = App\/Info\.plist;)/g, '\n$2CODE_SIGN_ENTITLEMENTS = App/App.entitlements;$1');
write(pbx, x);
write(
p('ios', 'App', 'App', 'App.entitlements'),
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:${host}</string>
</array>
</dict>
</plist>
`
);
const plistFile = p('ios', 'App', 'App', 'Info.plist');
let pl = read(plistFile);
pl = pl.replace(/(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/, `$1${xmlEsc(env.appName)}$2`);
if (!pl.includes('<key>UIBackgroundModes</key>'))
pl = pl.replace(/<dict>/, '<dict>\n\t<key>UIBackgroundModes</key>\n\t<array>\n\t\t<string>remote-notification</string>\n\t</array>');
write(plistFile, pl);
// Push: Gerätekennung an das Firebase-Plugin weiterreichen (laut Plugin-Anleitung)
const delegate = p('ios', 'App', 'App', 'AppDelegate.swift');
let d = read(delegate);
if (!d.includes('capacitorDidRegisterForRemoteNotifications')) {
d = d.replace(
/\n}\s*$/,
`
// werkstatt:push – Push-Nachrichten (@capacitor-firebase/messaging)
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NotificationCenter.default.post(name: Notification.Name.init("didReceiveRemoteNotification"), object: completionHandler, userInfo: userInfo)
}
}
`
);
write(delegate, d);
}
if (!fs.existsSync(p('ios', 'App', 'App', 'GoogleService-Info.plist')))
warnings.push('iOS: ios/App/App/GoogleService-Info.plist fehlt – ohne sie gibt es keine Push-Nachrichten (siehe README).');
}
console.log(`✔ Vorbereitet: ${env.appName} (${env.appId}) → ${env.appUrl}`);
for (const w of warnings) console.warn(`⚠ ${w}`);