Files
youtube_personal/lib/services/google_oauth_config_service.dart

132 lines
3.2 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
class GoogleOauthConfig {
const GoogleOauthConfig({
this.webClientId = '',
this.desktopClientId = '',
this.desktopClientSecret = '',
});
final String webClientId;
final String desktopClientId;
final String desktopClientSecret;
bool get hasAndroidConfig => webClientId.trim().isNotEmpty;
bool get hasWindowsConfig => desktopClientId.trim().isNotEmpty;
GoogleOauthConfig copyWith({
String? webClientId,
String? desktopClientId,
String? desktopClientSecret,
}) {
return GoogleOauthConfig(
webClientId: webClientId ?? this.webClientId,
desktopClientId:
desktopClientId ?? this.desktopClientId,
desktopClientSecret:
desktopClientSecret ?? this.desktopClientSecret,
);
}
}
class GoogleOauthConfigService {
GoogleOauthConfigService._();
static final GoogleOauthConfigService instance =
GoogleOauthConfigService._();
static const String _webClientIdKey =
'youtube_personal.google.web_client_id.v1';
static const String _desktopClientIdKey =
'youtube_personal.google.desktop_client_id.v1';
static const String _desktopClientSecretKey =
'youtube_personal.google.desktop_client_secret.v1';
final SharedPreferencesAsync _preferences =
SharedPreferencesAsync();
final ValueNotifier<GoogleOauthConfig> config =
ValueNotifier<GoogleOauthConfig>(
const GoogleOauthConfig(),
);
bool _initialized = false;
Future<void> initialize() async {
if (_initialized) {
return;
}
final webClientId =
await _preferences.getString(_webClientIdKey) ?? '';
final desktopClientId =
await _preferences.getString(_desktopClientIdKey) ?? '';
final desktopClientSecret =
await _preferences.getString(
_desktopClientSecretKey,
) ??
'';
config.value = GoogleOauthConfig(
webClientId: webClientId,
desktopClientId: desktopClientId,
desktopClientSecret: desktopClientSecret,
);
_initialized = true;
}
Future<void> saveAndroid({
required String webClientId,
}) async {
final value = webClientId.trim();
if (value.isEmpty) {
await _preferences.remove(_webClientIdKey);
} else {
await _preferences.setString(
_webClientIdKey,
value,
);
}
config.value = config.value.copyWith(
webClientId: value,
);
}
Future<void> saveWindows({
required String desktopClientId,
required String desktopClientSecret,
}) async {
final clientId = desktopClientId.trim();
final clientSecret = desktopClientSecret.trim();
if (clientId.isEmpty) {
await _preferences.remove(_desktopClientIdKey);
} else {
await _preferences.setString(
_desktopClientIdKey,
clientId,
);
}
if (clientSecret.isEmpty) {
await _preferences.remove(
_desktopClientSecretKey,
);
} else {
await _preferences.setString(
_desktopClientSecretKey,
clientSecret,
);
}
config.value = config.value.copyWith(
desktopClientId: clientId,
desktopClientSecret: clientSecret,
);
}
}