eksplicit mapping af envs
Some checks failed
Backend CI / test (push) Has been cancelled
Flutter CI / analyze-and-test (push) Has been cancelled

This commit is contained in:
Henrik Jess Nielsen
2026-05-12 18:21:25 +02:00
parent b7a435f8b9
commit 99e9b509a0
67 changed files with 8060 additions and 9 deletions

View File

@@ -0,0 +1,268 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:sighej/screens/profile_screen.dart';
import 'package:sighej/services/api_service.dart';
import 'package:sighej/services/session_store.dart';
// BLE service UUID that identifies SigHej devices.
const String kSigHejServiceUuid = '1248f5a0-0000-1000-8000-00805f9b34fb';
// Manufacturer ID used in BLE advertising data (Android).
const int kManufacturerId = 0x4E58; // "NX"
final FlutterLocalNotificationsPlugin _notifications =
FlutterLocalNotificationsPlugin();
const _androidChannel = AndroidNotificationDetails(
'sighej_nudge',
'SigHej Nudges',
channelDescription: 'Notifies when a nearby person shares your interests',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
);
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool _openToTalk = false;
String? _lastNudge;
StreamSubscription? _bleSub;
// Track tokens we have already matched this session to avoid spam.
final Set<String> _matchedTokens = {};
@override
void initState() {
super.initState();
_initNotifications();
}
Future<void> _initNotifications() async {
const android = AndroidInitializationSettings('@mipmap/ic_launcher');
const ios = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
await _notifications.initialize(
const InitializationSettings(android: android, iOS: ios),
);
}
@override
void dispose() {
_stopScanning();
super.dispose();
}
Future<void> _toggle(SessionStore store) async {
if (_openToTalk) {
_stopScanning();
return;
}
final granted = await _requestPermissions();
if (!granted) return;
await registerSession(
store.bleToken,
store.interests,
name: store.name,
tagline: store.tagline,
);
await _startAdvertising(store.bleToken);
FlutterBluePlus.startScan(timeout: const Duration(minutes: 120));
_bleSub = FlutterBluePlus.onScanResults.listen((results) async {
for (final r in results) {
final detected = _parseSigHejToken(r);
if (detected == null ||
detected == store.bleToken ||
_matchedTokens.contains(detected)) {
continue;
}
_matchedTokens.add(detected);
await _handlePotentialMatch(store.bleToken, detected, store);
}
});
setState(() => _openToTalk = true);
}
Future<void> _startAdvertising(String token) async {
final tokenBytes = Uint8List.fromList(token.codeUnits);
try {
await FlutterBluePlus.startAdvertising(
AdvertiseData(
serviceUuids: [Guid(kSigHejServiceUuid)],
manufacturerData: [ManufacturerData(kManufacturerId, tokenBytes)],
),
);
} catch (e) {
debugPrint('BLE advertise error: $e');
}
}
void _stopScanning() {
FlutterBluePlus.stopScan();
FlutterBluePlus.stopAdvertising();
_bleSub?.cancel();
_bleSub = null;
_matchedTokens.clear();
setState(() {
_openToTalk = false;
_lastNudge = null;
});
}
Future<void> _handlePotentialMatch(
String own, String detected, SessionStore store) async {
try {
final result = await reportMatch(own, detected);
if (result == null || !result.match) return;
final interests = result.sharedInterests;
final body = interests.isEmpty
? '${store.displayName} — nogen i nærheden er åben for en snak!'
: 'Fælles interesser: ${interests.join(', ')}';
await _showNudgeNotification('SigHej — sig hej!', body);
setState(() => _lastNudge = body);
} catch (e) {
debugPrint('Match error: $e');
}
}
Future<void> _showNudgeNotification(String title, String body) async {
const details = NotificationDetails(android: _androidChannel);
await _notifications.show(
body.hashCode,
title,
body,
details,
);
}
/// Parses a SigHej BLE token from a scan result.
/// Android: reads manufacturer data with key [kManufacturerId].
/// iOS fallback: reads service data for [kSigHejServiceUuid].
String? _parseSigHejToken(ScanResult result) {
final ad = result.advertisementData;
// Filter: only process SigHej advertisers.
final hasSigHejUuid = ad.serviceUuids
.map((g) => g.toString().toLowerCase())
.contains(kSigHejServiceUuid.toLowerCase());
if (!hasSigHejUuid) return null;
// Android: manufacturer data.
final mfr = ad.manufacturerData[kManufacturerId];
if (mfr != null && mfr.isNotEmpty) {
try {
return String.fromCharCodes(mfr);
} catch (_) {}
}
// iOS fallback: service data.
final svcData = ad.serviceData[Guid(kSigHejServiceUuid)];
if (svcData != null && svcData.isNotEmpty) {
try {
return String.fromCharCodes(svcData);
} catch (_) {}
}
return null;
}
Future<bool> _requestPermissions() async {
final perms = [
Permission.bluetooth,
Permission.bluetoothScan,
Permission.bluetoothAdvertise,
Permission.bluetoothConnect,
Permission.location,
Permission.notification,
];
final statuses = await perms.request();
return statuses.values.every((s) => s.isGranted || s.isLimited);
}
@override
Widget build(BuildContext context) {
final store = context.watch<SessionStore>();
return Scaffold(
appBar: AppBar(
title: const Text('SigHej'),
actions: [
IconButton(
icon: const Icon(Icons.person_outline),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const ProfileScreen()),
),
tooltip: 'Rediger profil',
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_openToTalk ? 'You\'re open to talk' : 'Tap to open up',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 32),
GestureDetector(
onTap: () => _toggle(store),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
width: 150,
height: 150,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _openToTalk
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.surfaceContainerHighest,
),
child: Icon(
_openToTalk ? Icons.record_voice_over : Icons.mic_off,
size: 60,
color: _openToTalk
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
if (_lastNudge != null) ...[
const SizedBox(height: 40),
Card(
margin: const EdgeInsets.symmetric(horizontal: 24),
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(
_lastNudge!,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge,
),
),
),
],
],
),
),
);
}
}

View File

@@ -0,0 +1,201 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sighej/services/session_store.dart';
const List<String> kAvailableInterests = [
'Tech',
'Musik',
'Filosofi',
'Design',
'DevOps',
'Bøger',
'Gaming',
'Fitness',
'Kunst',
'Mad',
'Rejser',
'Videnskab',
'Iværksætteri',
'Film',
'Natur',
'Kodning',
'Podcast',
'Arkitektur',
'Klima',
'Sport',
];
class ProfileScreen extends StatefulWidget {
/// If [isSetup] is true, the screen is shown as first-run onboarding.
/// If false, it's opened from the home screen as "rediger profil".
final bool isSetup;
const ProfileScreen({super.key, this.isSetup = false});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
late final TextEditingController _nameCtrl;
late final TextEditingController _taglineCtrl;
late final Set<String> _selected;
@override
void initState() {
super.initState();
final store = context.read<SessionStore>();
_nameCtrl = TextEditingController(text: store.name);
_taglineCtrl = TextEditingController(text: store.tagline);
_selected = Set<String>.from(store.interests);
}
@override
void dispose() {
_nameCtrl.dispose();
_taglineCtrl.dispose();
super.dispose();
}
Future<void> _save() async {
await context.read<SessionStore>().saveProfile(
name: _nameCtrl.text.trim(),
tagline: _taglineCtrl.text.trim(),
interests: _selected.toList(),
);
if (mounted) Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
final isSetup = widget.isSetup;
return Scaffold(
appBar: AppBar(
title: Text(isSetup ? 'Hvem er du?' : 'Din profil'),
automaticallyImplyLeading: !isSetup,
),
body: SafeArea(
child: Column(
children: [
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isSetup) ...[
Text(
'SigHej sender en diskret notifikation, når nogen i nærheden deler dine interesser. '
'Ingen profiler at swipe — bare et lille vink om at starte en samtale.',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 28),
],
_SectionLabel('Kaldenavn', hint: 'Valgfrit — hvad vil du kaldes?'),
const SizedBox(height: 8),
TextField(
controller: _nameCtrl,
maxLength: 40,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
hintText: 'F.eks. "Henrik" eller "Tech-nerd"',
border: OutlineInputBorder(),
counterText: '',
),
),
const SizedBox(height: 24),
_SectionLabel(
'Hvad er du op til i dag?',
hint: 'Valgfrit — sæt tonen',
),
const SizedBox(height: 8),
TextField(
controller: _taglineCtrl,
maxLength: 80,
textCapitalization: TextCapitalization.sentences,
decoration: const InputDecoration(
hintText: 'F.eks. "Åben for en kaffesnak" eller "Op til at netværke"',
border: OutlineInputBorder(),
counterText: '',
),
),
const SizedBox(height: 24),
_SectionLabel(
'Hvad interesserer dig?',
hint: 'Vi finder folk med fælles interesser i nærheden',
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: kAvailableInterests.map((interest) {
final selected = _selected.contains(interest);
return FilterChip(
label: Text(interest),
selected: selected,
onSelected: (val) => setState(
() => val
? _selected.add(interest)
: _selected.remove(interest),
),
);
}).toList(),
),
const SizedBox(height: 16),
if (_selected.isEmpty)
Text(
'Vælg mindst ét emne for at bruge SigHej.',
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: 13,
),
),
],
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 24),
child: FilledButton(
onPressed: _selected.isEmpty ? null : _save,
style: FilledButton.styleFrom(
minimumSize: const Size.fromHeight(52),
),
child: Text(isSetup ? 'Kom i gang' : 'Gem'),
),
),
],
),
),
);
}
}
class _SectionLabel extends StatelessWidget {
final String label;
final String? hint;
const _SectionLabel(this.label, {this.hint});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: Theme.of(context).textTheme.titleSmall),
if (hint != null) ...[
const SizedBox(height: 2),
Text(
hint!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
],
);
}
}