/** * 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, '&').replace(//g, '>'); const warnings = []; // Firebase-Dateien der Einrichtung übernehmen. Fehlt eine, wird die einer anderen // Einrichtung entfernt – sonst landeten Push-Anmeldungen im falschen Firebase-Projekt. if (env.kunde) { for (const [name, target] of [ ['google-services.json', p('android', 'app', 'google-services.json')], ['GoogleService-Info.plist', p('ios', 'App', 'App', 'GoogleService-Info.plist')] ]) { const src = path.join(env.dir, name); if (fs.existsSync(src)) fs.copyFileSync(src, target); else fs.rmSync(target, { force: true }); } } const assetsFor = fs.existsSync(p('assets', '.einrichtung')) ? read(p('assets', '.einrichtung')).trim() : ''; if (assetsFor && assetsFor !== env.appId) warnings.push(`Symbole stammen noch von ${assetsFor} – zuerst \`${env.kunde ? `KUNDE=${env.kunde} ` : ''}npm run assets\` ausführen.`); 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}`; const end = `${indent}`; const full = `${start}\n${content}\n${end}`; const re = new RegExp(`[ \\t]*[\\s\\S]*?`); 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'), ` ${xmlEsc(env.appName)}

Keine Verbindung

${xmlEsc(env.appName)} braucht Internet.
Bitte prüfe WLAN oder mobile Daten.

Noch einmal versuchen
` ); // ─── 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(`()[^<]*()`), `$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'), `\n\n ${env.brandColor}\n\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', ` `, ' ', ' ' ); // 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 ? ` \n` : '' } `, ' ', ' ' ); 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'), ` aps-environment development com.apple.developer.associated-domains applinks:${host} ` ); const plistFile = p('ios', 'App', 'App', 'Info.plist'); let pl = read(plistFile); pl = pl.replace(/(CFBundleDisplayName<\/key>\s*)[^<]*(<\/string>)/, `$1${xmlEsc(env.appName)}$2`); if (!pl.includes('UIBackgroundModes')) pl = pl.replace(//, '\n\tUIBackgroundModes\n\t\n\t\tremote-notification\n\t'); 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.kunde ? ` für „${env.kunde}“` : ''}: ${env.appName} (${env.appId}) → ${env.appUrl}`); for (const w of warnings) console.warn(`⚠ ${w}`);