connectReddit method
Connect to Reddit using enhanced WebView
Implementation
Future<bool> connectReddit(BuildContext context) async {
try {
// Mirror the NPM modal flow:
// - POST /reddit/authorize with session { username, sdkType, returnUrl }
// - Open OAuthWebViewScreen (has Reddit-specific popup handling on iOS)
final storedUsername = (await getFromSecure('onairos_username'))?.trim();
final fallbackUsername = (await getFromSecure('username'))?.trim();
final username = (storedUsername != null && storedUsername.isNotEmpty)
? storedUsername
: (fallbackUsername ?? '');
debugPrint('🟠 Connecting to Reddit for user: $username');
const returnUrl = 'https://onairos.uk/home';
final apiKeyService = ApiKeyService();
final resp = await apiKeyService.authenticatedPost(
'reddit/authorize',
body: {
'session': {
'username': username,
'platform': 'reddit',
'timestamp': DateTime.now().toIso8601String(),
'sdkType': 'web',
'returnUrl': returnUrl,
},
// Backward compatibility: some routes read `returnUrl` at top-level
'returnUrl': returnUrl,
},
);
final authUrl = (resp['redditURL'] ??
resp['redditUrl'] ??
resp['reddit_url'] ??
resp['url'] ??
resp['authUrl'])
?.toString();
if (authUrl == null || !authUrl.startsWith('http')) {
debugPrint('❌ Reddit authorize did not return a valid URL: $resp');
return false;
}
final completer = Completer<bool>();
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => FractionallySizedBox(
heightFactor: 0.9,
child: OAuthWebViewScreen(
platform: 'reddit',
authUrl: authUrl,
callbackUrlPattern: 'onairos.uk',
onComplete: (success) {
if (!completer.isCompleted) completer.complete(success);
},
),
),
);
// If user dismisses manually, treat as failure.
return completer.isCompleted ? await completer.future : false;
} catch (e) {
debugPrint('❌ Error connecting to Reddit: $e');
return false;
}
}