Netease cloud music login

This commit is contained in:
LittleSheep 2024-09-06 12:41:35 +08:00
parent 6cdc025c40
commit 6509cd2511
10 changed files with 602 additions and 170 deletions

View File

@ -9,15 +9,23 @@ import 'package:rhythm_box/providers/database.dart';
import 'package:rhythm_box/services/database/database.dart';
extension ExpirationAuthenticationTableData on AuthenticationTableData {
bool get isExpired => DateTime.now().isAfter(expiration);
bool get isExpired => DateTime.now().isAfter(spotifyExpiration);
String? getCookie(String key) => cookie.value
String? getCookie(String key) => spotifyCookie.value
.split('; ')
.firstWhereOrNull((c) => c.trim().startsWith('$key='))
?.trim()
.split('=')
.last
.replaceAll(';', '');
String? getNeteaseCookie(String key) => neteaseCookie?.value
.split(';')
.firstWhereOrNull((c) => c.trim().startsWith('$key='))
?.trim()
.split('=')
.last
.replaceAll(';', '');
}
class AuthenticationProvider extends GetxController {
@ -55,18 +63,18 @@ class AuthenticationProvider extends GetxController {
void _setRefreshTimer() {
refreshTimer?.cancel();
if (auth.value != null && auth.value!.isExpired) {
refreshCredentials();
refreshSpotifyCredentials();
}
refreshTimer = Timer(
auth.value!.expiration.difference(DateTime.now()),
() => refreshCredentials(),
auth.value!.spotifyExpiration.difference(DateTime.now()),
() => refreshSpotifyCredentials(),
);
}
Future<void> refreshCredentials() async {
Future<void> refreshSpotifyCredentials() async {
final database = Get.find<DatabaseProvider>().database;
final refreshedCredentials =
await credentialsFromCookie(auth.value!.cookie.value);
await credentialsFromCookie(auth.value!.spotifyCookie.value);
await database
.update(database.authenticationTable)
@ -112,9 +120,10 @@ class AuthenticationProvider extends GetxController {
return AuthenticationTableCompanion.insert(
id: const Value(0),
cookie: DecryptedText("${res.headers["set-cookie"]?.join(";")}; $spDc"),
accessToken: DecryptedText(body['accessToken']),
expiration: DateTime.fromMillisecondsSinceEpoch(
spotifyCookie:
DecryptedText("${res.headers["set-cookie"]?.join(";")}; $spDc"),
spotifyAccessToken: DecryptedText(body['accessToken']),
spotifyExpiration: DateTime.fromMillisecondsSinceEpoch(
body['accessTokenExpirationTimestampMs']),
);
} catch (e) {
@ -123,6 +132,21 @@ class AuthenticationProvider extends GetxController {
}
}
Future<void> setNeteaseCredentials(String cookie) async {
final database = Get.find<DatabaseProvider>().database;
await database.update(database.authenticationTable).replace(
AuthenticationTableCompanion.insert(
id: const Value(0),
spotifyCookie: auth.value!.spotifyCookie,
spotifyAccessToken: auth.value!.spotifyAccessToken,
spotifyExpiration: auth.value!.spotifyExpiration,
neteaseCookie: Value(DecryptedText(cookie)),
neteaseExpiration: const Value(null),
),
);
await loadAuthenticationData();
}
Future<void> logout() async {
auth.value = null;
final database = Get.find<DatabaseProvider>().database;
@ -132,6 +156,21 @@ class AuthenticationProvider extends GetxController {
// Additional cleanup if necessary
}
Future<void> logoutNetease() async {
final database = Get.find<DatabaseProvider>().database;
await database.update(database.authenticationTable).replace(
AuthenticationTableCompanion.insert(
id: const Value(0),
spotifyCookie: auth.value!.spotifyCookie,
spotifyAccessToken: auth.value!.spotifyAccessToken,
spotifyExpiration: auth.value!.spotifyExpiration,
neteaseCookie: const Value(null),
neteaseExpiration: const Value(null),
),
);
await loadAuthenticationData();
}
@override
void onClose() {
refreshTimer?.cancel();

View File

@ -44,7 +44,7 @@ class SpotifyProvider extends GetxController {
log('[SpotifyApi] Using user credentials...');
final AuthenticationProvider authenticate = Get.find();
return SpotifyApi.withAccessToken(
authenticate.auth.value!.accessToken.value);
authenticate.auth.value!.spotifyAccessToken.value);
}
@override

View File

@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:rhythm_box/screens/about.dart';
import 'package:rhythm_box/screens/album/view.dart';
import 'package:rhythm_box/screens/auth/login_netease.dart';
import 'package:rhythm_box/screens/auth/mobile_login.dart';
import 'package:rhythm_box/screens/explore.dart';
import 'package:rhythm_box/screens/library/view.dart';
@ -104,6 +105,11 @@ final router = GoRouter(routes: [
name: 'authMobileLogin',
builder: (context, state) => const MobileLogin(),
),
GoRoute(
path: '/auth/netease/login',
name: 'authMobileLoginNetease',
builder: (context, state) => const LoginNeteaseScreen(),
),
],
),
]);

View File

@ -0,0 +1,156 @@
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:get/get.dart';
import 'package:go_router/go_router.dart';
import 'package:rhythm_box/providers/auth.dart';
import 'package:rhythm_box/providers/error_notifier.dart';
import 'package:rhythm_box/services/sourced_track/sources/netease.dart';
import 'package:rhythm_box/widgets/sized_container.dart';
class LoginNeteaseScreen extends StatefulWidget {
const LoginNeteaseScreen({super.key});
@override
State<LoginNeteaseScreen> createState() => _LoginNeteaseScreenState();
}
class _LoginNeteaseScreenState extends State<LoginNeteaseScreen> {
final TextEditingController _phoneController = TextEditingController();
final TextEditingController _phoneRegionController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
late final AuthenticationProvider _auth = Get.find();
bool _isLogging = false;
Future<void> _sentCaptcha() async {
setState(() => _isLogging = true);
final phone = _phoneController.text;
var region = _phoneRegionController.text;
if (region.isEmpty) region = '86';
final client = NeteaseSourcedTrack.getClient();
final resp = await client.get(
'/captcha/sent?phone=$phone&ctcode=$region&timestamp=${DateTime.now().millisecondsSinceEpoch}',
);
if (resp.statusCode != 200 || resp.body?['code'] != 200) {
Get.find<ErrorNotifier>().showError(
resp.bodyString ?? resp.status.toString(),
);
}
setState(() => _isLogging = false);
}
Future<void> _performLogin() async {
setState(() => _isLogging = true);
final phone = _phoneController.text;
final password = _passwordController.text;
var region = _phoneRegionController.text;
if (region.isEmpty) region = '86';
final client = NeteaseSourcedTrack.getClient();
final resp = await client.get(
'/login/cellphone?phone=$phone&captcha=$password&countrycode=$region&timestamp=${DateTime.now().millisecondsSinceEpoch}',
);
if (resp.statusCode != 200 || resp.body?['code'] != 200) {
Get.find<ErrorNotifier>().showError(
resp.bodyString ?? resp.status.toString(),
);
setState(() => _isLogging = false);
return;
}
await _auth.setNeteaseCredentials(resp.body['cookie']);
setState(() => _isLogging = false);
GoRouter.of(context).goNamed('settings');
}
@override
void dispose() {
_phoneController.dispose();
_phoneRegionController.dispose();
_passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Connect with Netease Cloud Music'),
),
body: CenteredContainer(
maxWidth: 320,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
SizedBox(
width: 64,
child: TextField(
controller: _phoneRegionController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: '86',
isDense: true,
),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
),
),
const Gap(8),
Expanded(
child: TextField(
controller: _phoneController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
label: Text('Phone Number'),
isDense: true,
),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
),
),
],
),
const Gap(8),
Row(
children: [
Expanded(
child: TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
label: Text('Captcha Code'),
isDense: true,
),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
),
),
const Gap(8),
IconButton(
onPressed: _isLogging ? null : () => _sentCaptcha(),
icon: const Icon(Icons.sms),
tooltip: 'Get Captcha',
),
],
),
const Gap(8),
TextButton(
onPressed: _isLogging ? null : () => _performLogin(),
child: const Text('Login'),
)
],
),
),
);
}
}

View File

@ -72,8 +72,8 @@ class _ExploreScreenState extends State<ExploreScreen> {
}
if (_auth.auth.value != null) {
final customEndpoint =
CustomSpotifyEndpoints(_auth.auth.value?.accessToken.value ?? '');
final customEndpoint = CustomSpotifyEndpoints(
_auth.auth.value?.spotifyAccessToken.value ?? '');
final forYouView = await customEndpoint.getView(
'made-for-x-hub',
market: market,

View File

@ -7,6 +7,7 @@ import 'package:rhythm_box/providers/spotify.dart';
import 'package:rhythm_box/providers/user_preferences.dart';
import 'package:rhythm_box/screens/auth/login.dart';
import 'package:rhythm_box/services/database/database.dart';
import 'package:rhythm_box/services/sourced_track/sources/netease.dart';
import 'package:rhythm_box/widgets/auto_cache_image.dart';
import 'package:rhythm_box/widgets/sized_container.dart';
@ -86,6 +87,75 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
);
}),
Obx(() {
if (_authenticate.auth.value == null) {
return const SizedBox();
}
if (_authenticate.auth.value?.neteaseCookie == null) {
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 24),
leading: const Icon(Icons.cloud_outlined),
title: const Text('Connect with Netease Cloud Music'),
subtitle: const Text(
'Make us able to play more music from Netease Cloud Music'),
trailing: const Icon(Icons.chevron_right),
enabled: !_isLoggingIn,
onTap: () async {
setState(() => _isLoggingIn = true);
await GoRouter.of(context)
.pushNamed('authMobileLoginNetease');
setState(() => _isLoggingIn = false);
},
);
}
return FutureBuilder(
future: NeteaseSourcedTrack.getClient().get('/user/account'),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 24),
leading: const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 3,
),
),
title: const Text('Loading...'),
trailing: IconButton(
onPressed: () {
_authenticate.logoutNetease();
},
icon: const Icon(Icons.link_off),
),
);
}
return ListTile(
leading:
snapshot.data!.body['profile']['avatarUrl'] != null
? CircleAvatar(
backgroundImage: AutoCacheImage.provider(
snapshot.data!.body['profile']['avatarUrl'],
),
)
: const Icon(Icons.account_circle),
title: Text(snapshot.data!.body['profile']['nickname']),
subtitle: const Text(
'Connected with your Netease Cloud Music account',
),
trailing: IconButton(
onPressed: () {
_authenticate.logoutNetease();
},
icon: const Icon(Icons.link_off),
),
);
},
);
}),
Obx(() {
if (_authenticate.auth.value == null) {
return const SizedBox();
@ -95,7 +165,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
contentPadding: const EdgeInsets.symmetric(horizontal: 24),
leading: const Icon(Icons.logout),
title: const Text('Log out'),
subtitle: const Text('Disconnect with this Spotify account'),
subtitle: const Text('Disconnect with every account'),
trailing: const Icon(Icons.chevron_right),
onTap: () async {
_authenticate.logout();

View File

@ -55,7 +55,7 @@ class AppDatabase extends _$AppDatabase {
AppDatabase() : super(_openConnection());
@override
int get schemaVersion => 3;
int get schemaVersion => 1;
@override
MigrationStrategy get migration {
@ -63,18 +63,7 @@ class AppDatabase extends _$AppDatabase {
onCreate: (Migrator m) async {
await m.createAll();
},
onUpgrade: (Migrator m, int from, int to) async {
if (from < 2) {
await m.addColumn(preferencesTable, preferencesTable.playerWakelock);
}
if (from > 3) {
await m.addColumn(
preferencesTable, preferencesTable.neteaseApiInstance);
await m.dropColumn(
preferencesTable, preferencesTable.audioSource.name);
await m.addColumn(preferencesTable, preferencesTable.audioSource);
}
},
onUpgrade: (Migrator m, int from, int to) async {},
);
}
}

View File

@ -18,29 +18,54 @@ class $AuthenticationTableTable extends AuthenticationTable
requiredDuringInsert: false,
defaultConstraints:
GeneratedColumn.constraintIsAlways('PRIMARY KEY AUTOINCREMENT'));
static const VerificationMeta _cookieMeta = const VerificationMeta('cookie');
@override
late final GeneratedColumnWithTypeConverter<DecryptedText, String> cookie =
GeneratedColumn<String>('cookie', aliasedName, false,
type: DriftSqlType.string, requiredDuringInsert: true)
.withConverter<DecryptedText>(
$AuthenticationTableTable.$convertercookie);
static const VerificationMeta _accessTokenMeta =
const VerificationMeta('accessToken');
static const VerificationMeta _spotifyCookieMeta =
const VerificationMeta('spotifyCookie');
@override
late final GeneratedColumnWithTypeConverter<DecryptedText, String>
accessToken = GeneratedColumn<String>('access_token', aliasedName, false,
spotifyCookie = GeneratedColumn<String>(
'spotify_cookie', aliasedName, false,
type: DriftSqlType.string, requiredDuringInsert: true)
.withConverter<DecryptedText>(
$AuthenticationTableTable.$converteraccessToken);
static const VerificationMeta _expirationMeta =
const VerificationMeta('expiration');
$AuthenticationTableTable.$converterspotifyCookie);
static const VerificationMeta _spotifyAccessTokenMeta =
const VerificationMeta('spotifyAccessToken');
@override
late final GeneratedColumn<DateTime> expiration = GeneratedColumn<DateTime>(
'expiration', aliasedName, false,
late final GeneratedColumnWithTypeConverter<DecryptedText, String>
spotifyAccessToken = GeneratedColumn<String>(
'spotify_access_token', aliasedName, false,
type: DriftSqlType.string, requiredDuringInsert: true)
.withConverter<DecryptedText>(
$AuthenticationTableTable.$converterspotifyAccessToken);
static const VerificationMeta _spotifyExpirationMeta =
const VerificationMeta('spotifyExpiration');
@override
late final GeneratedColumn<DateTime> spotifyExpiration =
GeneratedColumn<DateTime>('spotify_expiration', aliasedName, false,
type: DriftSqlType.dateTime, requiredDuringInsert: true);
static const VerificationMeta _neteaseCookieMeta =
const VerificationMeta('neteaseCookie');
@override
List<GeneratedColumn> get $columns => [id, cookie, accessToken, expiration];
late final GeneratedColumnWithTypeConverter<DecryptedText?, String>
neteaseCookie = GeneratedColumn<String>(
'netease_cookie', aliasedName, true,
type: DriftSqlType.string, requiredDuringInsert: false)
.withConverter<DecryptedText?>(
$AuthenticationTableTable.$converterneteaseCookien);
static const VerificationMeta _neteaseExpirationMeta =
const VerificationMeta('neteaseExpiration');
@override
late final GeneratedColumn<DateTime> neteaseExpiration =
GeneratedColumn<DateTime>('netease_expiration', aliasedName, true,
type: DriftSqlType.dateTime, requiredDuringInsert: false);
@override
List<GeneratedColumn> get $columns => [
id,
spotifyCookie,
spotifyAccessToken,
spotifyExpiration,
neteaseCookie,
neteaseExpiration
];
@override
String get aliasedName => _alias ?? actualTableName;
@override
@ -55,15 +80,22 @@ class $AuthenticationTableTable extends AuthenticationTable
if (data.containsKey('id')) {
context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta));
}
context.handle(_cookieMeta, const VerificationResult.success());
context.handle(_accessTokenMeta, const VerificationResult.success());
if (data.containsKey('expiration')) {
context.handle(_spotifyCookieMeta, const VerificationResult.success());
context.handle(_spotifyAccessTokenMeta, const VerificationResult.success());
if (data.containsKey('spotify_expiration')) {
context.handle(
_expirationMeta,
expiration.isAcceptableOrUnknown(
data['expiration']!, _expirationMeta));
_spotifyExpirationMeta,
spotifyExpiration.isAcceptableOrUnknown(
data['spotify_expiration']!, _spotifyExpirationMeta));
} else if (isInserting) {
context.missing(_expirationMeta);
context.missing(_spotifyExpirationMeta);
}
context.handle(_neteaseCookieMeta, const VerificationResult.success());
if (data.containsKey('netease_expiration')) {
context.handle(
_neteaseExpirationMeta,
neteaseExpiration.isAcceptableOrUnknown(
data['netease_expiration']!, _neteaseExpirationMeta));
}
return context;
}
@ -77,14 +109,19 @@ class $AuthenticationTableTable extends AuthenticationTable
return AuthenticationTableData(
id: attachedDatabase.typeMapping
.read(DriftSqlType.int, data['${effectivePrefix}id'])!,
cookie: $AuthenticationTableTable.$convertercookie.fromSql(
attachedDatabase.typeMapping
.read(DriftSqlType.string, data['${effectivePrefix}cookie'])!),
accessToken: $AuthenticationTableTable.$converteraccessToken.fromSql(
spotifyCookie: $AuthenticationTableTable.$converterspotifyCookie.fromSql(
attachedDatabase.typeMapping.read(
DriftSqlType.string, data['${effectivePrefix}access_token'])!),
expiration: attachedDatabase.typeMapping
.read(DriftSqlType.dateTime, data['${effectivePrefix}expiration'])!,
DriftSqlType.string, data['${effectivePrefix}spotify_cookie'])!),
spotifyAccessToken: $AuthenticationTableTable.$converterspotifyAccessToken
.fromSql(attachedDatabase.typeMapping.read(DriftSqlType.string,
data['${effectivePrefix}spotify_access_token'])!),
spotifyExpiration: attachedDatabase.typeMapping.read(
DriftSqlType.dateTime, data['${effectivePrefix}spotify_expiration'])!,
neteaseCookie: $AuthenticationTableTable.$converterneteaseCookien.fromSql(
attachedDatabase.typeMapping.read(
DriftSqlType.string, data['${effectivePrefix}netease_cookie'])),
neteaseExpiration: attachedDatabase.typeMapping.read(
DriftSqlType.dateTime, data['${effectivePrefix}netease_expiration']),
);
}
@ -93,45 +130,69 @@ class $AuthenticationTableTable extends AuthenticationTable
return $AuthenticationTableTable(attachedDatabase, alias);
}
static TypeConverter<DecryptedText, String> $convertercookie =
static TypeConverter<DecryptedText, String> $converterspotifyCookie =
EncryptedTextConverter();
static TypeConverter<DecryptedText, String> $converteraccessToken =
static TypeConverter<DecryptedText, String> $converterspotifyAccessToken =
EncryptedTextConverter();
static TypeConverter<DecryptedText, String> $converterneteaseCookie =
EncryptedTextConverter();
static TypeConverter<DecryptedText?, String?> $converterneteaseCookien =
NullAwareTypeConverter.wrap($converterneteaseCookie);
}
class AuthenticationTableData extends DataClass
implements Insertable<AuthenticationTableData> {
final int id;
final DecryptedText cookie;
final DecryptedText accessToken;
final DateTime expiration;
final DecryptedText spotifyCookie;
final DecryptedText spotifyAccessToken;
final DateTime spotifyExpiration;
final DecryptedText? neteaseCookie;
final DateTime? neteaseExpiration;
const AuthenticationTableData(
{required this.id,
required this.cookie,
required this.accessToken,
required this.expiration});
required this.spotifyCookie,
required this.spotifyAccessToken,
required this.spotifyExpiration,
this.neteaseCookie,
this.neteaseExpiration});
@override
Map<String, Expression> toColumns(bool nullToAbsent) {
final map = <String, Expression>{};
map['id'] = Variable<int>(id);
{
map['cookie'] = Variable<String>(
$AuthenticationTableTable.$convertercookie.toSql(cookie));
map['spotify_cookie'] = Variable<String>($AuthenticationTableTable
.$converterspotifyCookie
.toSql(spotifyCookie));
}
{
map['access_token'] = Variable<String>(
$AuthenticationTableTable.$converteraccessToken.toSql(accessToken));
map['spotify_access_token'] = Variable<String>($AuthenticationTableTable
.$converterspotifyAccessToken
.toSql(spotifyAccessToken));
}
map['spotify_expiration'] = Variable<DateTime>(spotifyExpiration);
if (!nullToAbsent || neteaseCookie != null) {
map['netease_cookie'] = Variable<String>($AuthenticationTableTable
.$converterneteaseCookien
.toSql(neteaseCookie));
}
if (!nullToAbsent || neteaseExpiration != null) {
map['netease_expiration'] = Variable<DateTime>(neteaseExpiration);
}
map['expiration'] = Variable<DateTime>(expiration);
return map;
}
AuthenticationTableCompanion toCompanion(bool nullToAbsent) {
return AuthenticationTableCompanion(
id: Value(id),
cookie: Value(cookie),
accessToken: Value(accessToken),
expiration: Value(expiration),
spotifyCookie: Value(spotifyCookie),
spotifyAccessToken: Value(spotifyAccessToken),
spotifyExpiration: Value(spotifyExpiration),
neteaseCookie: neteaseCookie == null && nullToAbsent
? const Value.absent()
: Value(neteaseCookie),
neteaseExpiration: neteaseExpiration == null && nullToAbsent
? const Value.absent()
: Value(neteaseExpiration),
);
}
@ -140,9 +201,14 @@ class AuthenticationTableData extends DataClass
serializer ??= driftRuntimeOptions.defaultSerializer;
return AuthenticationTableData(
id: serializer.fromJson<int>(json['id']),
cookie: serializer.fromJson<DecryptedText>(json['cookie']),
accessToken: serializer.fromJson<DecryptedText>(json['accessToken']),
expiration: serializer.fromJson<DateTime>(json['expiration']),
spotifyCookie: serializer.fromJson<DecryptedText>(json['spotifyCookie']),
spotifyAccessToken:
serializer.fromJson<DecryptedText>(json['spotifyAccessToken']),
spotifyExpiration:
serializer.fromJson<DateTime>(json['spotifyExpiration']),
neteaseCookie: serializer.fromJson<DecryptedText?>(json['neteaseCookie']),
neteaseExpiration:
serializer.fromJson<DateTime?>(json['neteaseExpiration']),
);
}
@override
@ -150,31 +216,51 @@ class AuthenticationTableData extends DataClass
serializer ??= driftRuntimeOptions.defaultSerializer;
return <String, dynamic>{
'id': serializer.toJson<int>(id),
'cookie': serializer.toJson<DecryptedText>(cookie),
'accessToken': serializer.toJson<DecryptedText>(accessToken),
'expiration': serializer.toJson<DateTime>(expiration),
'spotifyCookie': serializer.toJson<DecryptedText>(spotifyCookie),
'spotifyAccessToken':
serializer.toJson<DecryptedText>(spotifyAccessToken),
'spotifyExpiration': serializer.toJson<DateTime>(spotifyExpiration),
'neteaseCookie': serializer.toJson<DecryptedText?>(neteaseCookie),
'neteaseExpiration': serializer.toJson<DateTime?>(neteaseExpiration),
};
}
AuthenticationTableData copyWith(
{int? id,
DecryptedText? cookie,
DecryptedText? accessToken,
DateTime? expiration}) =>
DecryptedText? spotifyCookie,
DecryptedText? spotifyAccessToken,
DateTime? spotifyExpiration,
Value<DecryptedText?> neteaseCookie = const Value.absent(),
Value<DateTime?> neteaseExpiration = const Value.absent()}) =>
AuthenticationTableData(
id: id ?? this.id,
cookie: cookie ?? this.cookie,
accessToken: accessToken ?? this.accessToken,
expiration: expiration ?? this.expiration,
spotifyCookie: spotifyCookie ?? this.spotifyCookie,
spotifyAccessToken: spotifyAccessToken ?? this.spotifyAccessToken,
spotifyExpiration: spotifyExpiration ?? this.spotifyExpiration,
neteaseCookie:
neteaseCookie.present ? neteaseCookie.value : this.neteaseCookie,
neteaseExpiration: neteaseExpiration.present
? neteaseExpiration.value
: this.neteaseExpiration,
);
AuthenticationTableData copyWithCompanion(AuthenticationTableCompanion data) {
return AuthenticationTableData(
id: data.id.present ? data.id.value : this.id,
cookie: data.cookie.present ? data.cookie.value : this.cookie,
accessToken:
data.accessToken.present ? data.accessToken.value : this.accessToken,
expiration:
data.expiration.present ? data.expiration.value : this.expiration,
spotifyCookie: data.spotifyCookie.present
? data.spotifyCookie.value
: this.spotifyCookie,
spotifyAccessToken: data.spotifyAccessToken.present
? data.spotifyAccessToken.value
: this.spotifyAccessToken,
spotifyExpiration: data.spotifyExpiration.present
? data.spotifyExpiration.value
: this.spotifyExpiration,
neteaseCookie: data.neteaseCookie.present
? data.neteaseCookie.value
: this.neteaseCookie,
neteaseExpiration: data.neteaseExpiration.present
? data.neteaseExpiration.value
: this.neteaseExpiration,
);
}
@ -182,69 +268,89 @@ class AuthenticationTableData extends DataClass
String toString() {
return (StringBuffer('AuthenticationTableData(')
..write('id: $id, ')
..write('cookie: $cookie, ')
..write('accessToken: $accessToken, ')
..write('expiration: $expiration')
..write('spotifyCookie: $spotifyCookie, ')
..write('spotifyAccessToken: $spotifyAccessToken, ')
..write('spotifyExpiration: $spotifyExpiration, ')
..write('neteaseCookie: $neteaseCookie, ')
..write('neteaseExpiration: $neteaseExpiration')
..write(')'))
.toString();
}
@override
int get hashCode => Object.hash(id, cookie, accessToken, expiration);
int get hashCode => Object.hash(id, spotifyCookie, spotifyAccessToken,
spotifyExpiration, neteaseCookie, neteaseExpiration);
@override
bool operator ==(Object other) =>
identical(this, other) ||
(other is AuthenticationTableData &&
other.id == this.id &&
other.cookie == this.cookie &&
other.accessToken == this.accessToken &&
other.expiration == this.expiration);
other.spotifyCookie == this.spotifyCookie &&
other.spotifyAccessToken == this.spotifyAccessToken &&
other.spotifyExpiration == this.spotifyExpiration &&
other.neteaseCookie == this.neteaseCookie &&
other.neteaseExpiration == this.neteaseExpiration);
}
class AuthenticationTableCompanion
extends UpdateCompanion<AuthenticationTableData> {
final Value<int> id;
final Value<DecryptedText> cookie;
final Value<DecryptedText> accessToken;
final Value<DateTime> expiration;
final Value<DecryptedText> spotifyCookie;
final Value<DecryptedText> spotifyAccessToken;
final Value<DateTime> spotifyExpiration;
final Value<DecryptedText?> neteaseCookie;
final Value<DateTime?> neteaseExpiration;
const AuthenticationTableCompanion({
this.id = const Value.absent(),
this.cookie = const Value.absent(),
this.accessToken = const Value.absent(),
this.expiration = const Value.absent(),
this.spotifyCookie = const Value.absent(),
this.spotifyAccessToken = const Value.absent(),
this.spotifyExpiration = const Value.absent(),
this.neteaseCookie = const Value.absent(),
this.neteaseExpiration = const Value.absent(),
});
AuthenticationTableCompanion.insert({
this.id = const Value.absent(),
required DecryptedText cookie,
required DecryptedText accessToken,
required DateTime expiration,
}) : cookie = Value(cookie),
accessToken = Value(accessToken),
expiration = Value(expiration);
required DecryptedText spotifyCookie,
required DecryptedText spotifyAccessToken,
required DateTime spotifyExpiration,
this.neteaseCookie = const Value.absent(),
this.neteaseExpiration = const Value.absent(),
}) : spotifyCookie = Value(spotifyCookie),
spotifyAccessToken = Value(spotifyAccessToken),
spotifyExpiration = Value(spotifyExpiration);
static Insertable<AuthenticationTableData> custom({
Expression<int>? id,
Expression<String>? cookie,
Expression<String>? accessToken,
Expression<DateTime>? expiration,
Expression<String>? spotifyCookie,
Expression<String>? spotifyAccessToken,
Expression<DateTime>? spotifyExpiration,
Expression<String>? neteaseCookie,
Expression<DateTime>? neteaseExpiration,
}) {
return RawValuesInsertable({
if (id != null) 'id': id,
if (cookie != null) 'cookie': cookie,
if (accessToken != null) 'access_token': accessToken,
if (expiration != null) 'expiration': expiration,
if (spotifyCookie != null) 'spotify_cookie': spotifyCookie,
if (spotifyAccessToken != null)
'spotify_access_token': spotifyAccessToken,
if (spotifyExpiration != null) 'spotify_expiration': spotifyExpiration,
if (neteaseCookie != null) 'netease_cookie': neteaseCookie,
if (neteaseExpiration != null) 'netease_expiration': neteaseExpiration,
});
}
AuthenticationTableCompanion copyWith(
{Value<int>? id,
Value<DecryptedText>? cookie,
Value<DecryptedText>? accessToken,
Value<DateTime>? expiration}) {
Value<DecryptedText>? spotifyCookie,
Value<DecryptedText>? spotifyAccessToken,
Value<DateTime>? spotifyExpiration,
Value<DecryptedText?>? neteaseCookie,
Value<DateTime?>? neteaseExpiration}) {
return AuthenticationTableCompanion(
id: id ?? this.id,
cookie: cookie ?? this.cookie,
accessToken: accessToken ?? this.accessToken,
expiration: expiration ?? this.expiration,
spotifyCookie: spotifyCookie ?? this.spotifyCookie,
spotifyAccessToken: spotifyAccessToken ?? this.spotifyAccessToken,
spotifyExpiration: spotifyExpiration ?? this.spotifyExpiration,
neteaseCookie: neteaseCookie ?? this.neteaseCookie,
neteaseExpiration: neteaseExpiration ?? this.neteaseExpiration,
);
}
@ -254,17 +360,26 @@ class AuthenticationTableCompanion
if (id.present) {
map['id'] = Variable<int>(id.value);
}
if (cookie.present) {
map['cookie'] = Variable<String>(
$AuthenticationTableTable.$convertercookie.toSql(cookie.value));
if (spotifyCookie.present) {
map['spotify_cookie'] = Variable<String>($AuthenticationTableTable
.$converterspotifyCookie
.toSql(spotifyCookie.value));
}
if (accessToken.present) {
map['access_token'] = Variable<String>($AuthenticationTableTable
.$converteraccessToken
.toSql(accessToken.value));
if (spotifyAccessToken.present) {
map['spotify_access_token'] = Variable<String>($AuthenticationTableTable
.$converterspotifyAccessToken
.toSql(spotifyAccessToken.value));
}
if (expiration.present) {
map['expiration'] = Variable<DateTime>(expiration.value);
if (spotifyExpiration.present) {
map['spotify_expiration'] = Variable<DateTime>(spotifyExpiration.value);
}
if (neteaseCookie.present) {
map['netease_cookie'] = Variable<String>($AuthenticationTableTable
.$converterneteaseCookien
.toSql(neteaseCookie.value));
}
if (neteaseExpiration.present) {
map['netease_expiration'] = Variable<DateTime>(neteaseExpiration.value);
}
return map;
}
@ -273,9 +388,11 @@ class AuthenticationTableCompanion
String toString() {
return (StringBuffer('AuthenticationTableCompanion(')
..write('id: $id, ')
..write('cookie: $cookie, ')
..write('accessToken: $accessToken, ')
..write('expiration: $expiration')
..write('spotifyCookie: $spotifyCookie, ')
..write('spotifyAccessToken: $spotifyAccessToken, ')
..write('spotifyExpiration: $spotifyExpiration, ')
..write('neteaseCookie: $neteaseCookie, ')
..write('neteaseExpiration: $neteaseExpiration')
..write(')'))
.toString();
}
@ -3824,16 +3941,20 @@ abstract class _$AppDatabase extends GeneratedDatabase {
typedef $$AuthenticationTableTableCreateCompanionBuilder
= AuthenticationTableCompanion Function({
Value<int> id,
required DecryptedText cookie,
required DecryptedText accessToken,
required DateTime expiration,
required DecryptedText spotifyCookie,
required DecryptedText spotifyAccessToken,
required DateTime spotifyExpiration,
Value<DecryptedText?> neteaseCookie,
Value<DateTime?> neteaseExpiration,
});
typedef $$AuthenticationTableTableUpdateCompanionBuilder
= AuthenticationTableCompanion Function({
Value<int> id,
Value<DecryptedText> cookie,
Value<DecryptedText> accessToken,
Value<DateTime> expiration,
Value<DecryptedText> spotifyCookie,
Value<DecryptedText> spotifyAccessToken,
Value<DateTime> spotifyExpiration,
Value<DecryptedText?> neteaseCookie,
Value<DateTime?> neteaseExpiration,
});
class $$AuthenticationTableTableTableManager extends RootTableManager<
@ -3855,27 +3976,35 @@ class $$AuthenticationTableTableTableManager extends RootTableManager<
ComposerState(db, table)),
updateCompanionCallback: ({
Value<int> id = const Value.absent(),
Value<DecryptedText> cookie = const Value.absent(),
Value<DecryptedText> accessToken = const Value.absent(),
Value<DateTime> expiration = const Value.absent(),
Value<DecryptedText> spotifyCookie = const Value.absent(),
Value<DecryptedText> spotifyAccessToken = const Value.absent(),
Value<DateTime> spotifyExpiration = const Value.absent(),
Value<DecryptedText?> neteaseCookie = const Value.absent(),
Value<DateTime?> neteaseExpiration = const Value.absent(),
}) =>
AuthenticationTableCompanion(
id: id,
cookie: cookie,
accessToken: accessToken,
expiration: expiration,
spotifyCookie: spotifyCookie,
spotifyAccessToken: spotifyAccessToken,
spotifyExpiration: spotifyExpiration,
neteaseCookie: neteaseCookie,
neteaseExpiration: neteaseExpiration,
),
createCompanionCallback: ({
Value<int> id = const Value.absent(),
required DecryptedText cookie,
required DecryptedText accessToken,
required DateTime expiration,
required DecryptedText spotifyCookie,
required DecryptedText spotifyAccessToken,
required DateTime spotifyExpiration,
Value<DecryptedText?> neteaseCookie = const Value.absent(),
Value<DateTime?> neteaseExpiration = const Value.absent(),
}) =>
AuthenticationTableCompanion.insert(
id: id,
cookie: cookie,
accessToken: accessToken,
expiration: expiration,
spotifyCookie: spotifyCookie,
spotifyAccessToken: spotifyAccessToken,
spotifyExpiration: spotifyExpiration,
neteaseCookie: neteaseCookie,
neteaseExpiration: neteaseExpiration,
),
));
}
@ -3889,21 +4018,33 @@ class $$AuthenticationTableTableFilterComposer
ColumnFilters(column, joinBuilders: joinBuilders));
ColumnWithTypeConverterFilters<DecryptedText, DecryptedText, String>
get cookie => $state.composableBuilder(
column: $state.table.cookie,
get spotifyCookie => $state.composableBuilder(
column: $state.table.spotifyCookie,
builder: (column, joinBuilders) => ColumnWithTypeConverterFilters(
column,
joinBuilders: joinBuilders));
ColumnWithTypeConverterFilters<DecryptedText, DecryptedText, String>
get accessToken => $state.composableBuilder(
column: $state.table.accessToken,
get spotifyAccessToken => $state.composableBuilder(
column: $state.table.spotifyAccessToken,
builder: (column, joinBuilders) => ColumnWithTypeConverterFilters(
column,
joinBuilders: joinBuilders));
ColumnFilters<DateTime> get expiration => $state.composableBuilder(
column: $state.table.expiration,
ColumnFilters<DateTime> get spotifyExpiration => $state.composableBuilder(
column: $state.table.spotifyExpiration,
builder: (column, joinBuilders) =>
ColumnFilters(column, joinBuilders: joinBuilders));
ColumnWithTypeConverterFilters<DecryptedText?, DecryptedText, String>
get neteaseCookie => $state.composableBuilder(
column: $state.table.neteaseCookie,
builder: (column, joinBuilders) => ColumnWithTypeConverterFilters(
column,
joinBuilders: joinBuilders));
ColumnFilters<DateTime> get neteaseExpiration => $state.composableBuilder(
column: $state.table.neteaseExpiration,
builder: (column, joinBuilders) =>
ColumnFilters(column, joinBuilders: joinBuilders));
}
@ -3916,18 +4057,28 @@ class $$AuthenticationTableTableOrderingComposer
builder: (column, joinBuilders) =>
ColumnOrderings(column, joinBuilders: joinBuilders));
ColumnOrderings<String> get cookie => $state.composableBuilder(
column: $state.table.cookie,
ColumnOrderings<String> get spotifyCookie => $state.composableBuilder(
column: $state.table.spotifyCookie,
builder: (column, joinBuilders) =>
ColumnOrderings(column, joinBuilders: joinBuilders));
ColumnOrderings<String> get accessToken => $state.composableBuilder(
column: $state.table.accessToken,
ColumnOrderings<String> get spotifyAccessToken => $state.composableBuilder(
column: $state.table.spotifyAccessToken,
builder: (column, joinBuilders) =>
ColumnOrderings(column, joinBuilders: joinBuilders));
ColumnOrderings<DateTime> get expiration => $state.composableBuilder(
column: $state.table.expiration,
ColumnOrderings<DateTime> get spotifyExpiration => $state.composableBuilder(
column: $state.table.spotifyExpiration,
builder: (column, joinBuilders) =>
ColumnOrderings(column, joinBuilders: joinBuilders));
ColumnOrderings<String> get neteaseCookie => $state.composableBuilder(
column: $state.table.neteaseCookie,
builder: (column, joinBuilders) =>
ColumnOrderings(column, joinBuilders: joinBuilders));
ColumnOrderings<DateTime> get neteaseExpiration => $state.composableBuilder(
column: $state.table.neteaseExpiration,
builder: (column, joinBuilders) =>
ColumnOrderings(column, joinBuilders: joinBuilders));
}

View File

@ -2,7 +2,10 @@ part of '../database.dart';
class AuthenticationTable extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get cookie => text().map(EncryptedTextConverter())();
TextColumn get accessToken => text().map(EncryptedTextConverter())();
DateTimeColumn get expiration => dateTime()();
TextColumn get spotifyCookie => text().map(EncryptedTextConverter())();
TextColumn get spotifyAccessToken => text().map(EncryptedTextConverter())();
DateTimeColumn get spotifyExpiration => dateTime()();
TextColumn get neteaseCookie =>
text().map(EncryptedTextConverter()).nullable()();
DateTimeColumn get neteaseExpiration => dateTime().nullable()();
}

View File

@ -1,6 +1,8 @@
import 'package:collection/collection.dart';
import 'package:drift/drift.dart';
import 'package:get/get.dart' hide Value;
import 'package:get/get_connect/http/src/request/request.dart';
import 'package:rhythm_box/providers/auth.dart';
import 'package:rhythm_box/providers/database.dart';
import 'package:rhythm_box/providers/user_preferences.dart';
import 'package:rhythm_box/services/database/database.dart';
@ -38,9 +40,25 @@ class NeteaseSourcedTrack extends SourcedTrack {
}
static GetConnect getClient() {
final client = GetConnect();
final client = GetConnect(
withCredentials: true,
timeout: const Duration(seconds: 30),
);
client.baseUrl = getBaseUrl();
client.timeout = const Duration(seconds: 30);
client.httpClient.addRequestModifier((Request request) async {
final AuthenticationProvider auth = Get.find();
if (auth.auth.value!.neteaseCookie != null) {
final cookie =
'MUSIC_U=${auth.auth.value!.getNeteaseCookie('MUSIC_U')}';
if (request.headers['Cookie'] == null) {
request.headers['Cookie'] = cookie;
} else {
request.headers['Cookie'] = request.headers['Cookie']! + cookie;
}
}
return request;
});
return client;
}
@ -80,7 +98,7 @@ class NeteaseSourcedTrack extends SourcedTrack {
await client.get('/check/music?id=${siblings.first.info.id}');
if (checkResp.body['success'] != true) throw TrackNotFoundError(track);
await await db.database.into(db.database.sourceMatchTable).insert(
await db.database.into(db.database.sourceMatchTable).insert(
SourceMatchTableCompanion.insert(
trackId: track.id!,
sourceId: siblings.first.info.id,