Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic last.fm integration #1000

Merged
merged 8 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ const kRadioIndex = 'radioIndex';
const kPodcastIndex = 'podcastIndex';
const kNeverShowImportFails = 'neverShowImportFails';
const kEnableDiscordRPC = 'enableDiscordRPC';
const kEnableLastFmScrobbling = 'enableLastFmScrobbling';
const kLastFmApiKey = 'lastFmApiKey';
const klastFmSecret = 'lastFmSecret';
const kLastFmSessionKey = 'lastFmSessionKey';
const kLastFmUsername = 'lastFmUsername';
const kLastCountryCode = 'lastCountryCode';
const kLastLanguageCode = 'lastLanguageCode';
const kSearchResult = 'searchResult';
Expand Down
30 changes: 28 additions & 2 deletions lib/expose/expose_service.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import 'dart:async';

import 'package:flutter_discord_rpc/flutter_discord_rpc.dart';
import 'package:lastfm/lastfm.dart';

class ExposeService {
ExposeService({required FlutterDiscordRPC? discordRPC})
: _discordRPC = discordRPC;
ExposeService({
required FlutterDiscordRPC? discordRPC,
required LastFMAuthorized? lastFm,
}) : _discordRPC = discordRPC,
_lastFm = lastFm;

final FlutterDiscordRPC? _discordRPC;
final LastFMAuthorized? _lastFm;
final _errorController = StreamController<String?>.broadcast();
Stream<String?> get discordErrorStream => _errorController.stream;
Stream<bool> get isDiscordConnectedStream =>
Expand All @@ -24,6 +29,12 @@ class ExposeService {
additionalInfo: additionalInfo,
imageUrl: imageUrl,
);
if (_lastFm != null) {
await _exposeTitleToLastfm(
title: title,
artist: artist,
);
}
}

Future<void> _exposeTitleToDiscord({
Expand Down Expand Up @@ -54,6 +65,21 @@ class ExposeService {
}
}

Future<void> _exposeTitleToLastfm({
required String title,
required String artist,
}) async {
try {
await _lastFm?.scrobble(
track: title,
artist: artist,
startTime: DateTime.now(),
);
} on Exception catch (e) {
_errorController.add(e.toString());
}
}

Future<void> connect() async {
await connectToDiscord();
}
Expand Down
6 changes: 6 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,12 @@
"exposeOnlineHeadline": "Expose your listening activity online",
"exposeToDiscordTitle": "Discord",
"exposeToDiscordSubTitle": "The artist and title of the song/station/podcast you are currently listening to are shared.",
"exposeToLastfmTitle": "Last.fm",
"exposeToLastfmSubTitle": "The artist and title of the song/station/podcast you are currently listening to are shared.",
"lastfmApiKey": "Last.fm API key",
"lastfmSecret": "Last.fm secret",
"lastfmApiKeyEmpty": "Please enter an API key",
"lastfmSecretEmpty": "Please enter the shared secret",
"featureDisabledOnPlatform": "This feature is currently disabled for this operating system.",
"regionNone": "None",
"regionAfghanistan": "Afghanistan",
Expand Down
38 changes: 35 additions & 3 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_discord_rpc/flutter_discord_rpc.dart';
import 'package:github/github.dart';
import 'package:gtk/gtk.dart';
import 'package:lastfm/lastfm.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:package_info_plus/package_info_plus.dart';
Expand Down Expand Up @@ -107,10 +108,40 @@ void registerServicesAndViewModels({
),
dispose: (s) => s.dispose(),
)
..registerFactory<LastFM>(() {
final apiKey = sharedPreferences.getString(kLastFmApiKey) ?? '';
final apiSecret = sharedPreferences.getString(klastFmSecret) ?? '';
final sessionKey = sharedPreferences.getString(kLastFmSessionKey);
final username = sharedPreferences.getString(kLastFmUsername);

if (sessionKey != null && username != null) {
return LastFMAuthorized(
apiKey,
secret: apiSecret,
sessionKey: sessionKey,
username: username,
);
} else {
return LastFMUnauthorized(apiKey, apiSecret);
}
})
..registerLazySingleton<ExposeService>(
() => ExposeService(
discordRPC: allowDiscordRPC ? di<FlutterDiscordRPC>() : null,
),
() {
final sessionKey = sharedPreferences.getString(kLastFmSessionKey);
final lastFMEnabled =
sharedPreferences.getBool(kEnableLastFmScrobbling) ?? false;
if (sessionKey != null) {
return ExposeService(
discordRPC: allowDiscordRPC ? di<FlutterDiscordRPC>() : null,
lastFm: lastFMEnabled ? di<LastFM>() as LastFMAuthorized : null,
);
} else {
return ExposeService(
discordRPC: allowDiscordRPC ? di<FlutterDiscordRPC>() : null,
lastFm: null,
Feichtmeier marked this conversation as resolved.
Show resolved Hide resolved
);
}
},
dispose: (s) => s.dispose(),
)
..registerLazySingleton<PlayerService>(
Expand All @@ -129,6 +160,7 @@ void registerServicesAndViewModels({
() => SettingsService(
sharedPreferences: di<SharedPreferences>(),
downloadsDefaultDir: downloadsDefaultDir,
lastFm: di<LastFM>(),
),
dispose: (s) async => s.dispose(),
)
Expand Down
13 changes: 13 additions & 0 deletions lib/settings/settings_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ class SettingsModel extends SafeChangeNotifier {
bool get enableDiscordRPC => _service.enableDiscordRPC;
void setEnableDiscordRPC(bool value) => _service.setEnableDiscordRPC(value);

bool get enableLastFmScrobbling => _service.enableLastFmScrobbling;
String? get lastFmApiKey => _service.lastFmApiKey;
String? get lastFmSecret => _service.lastFmSecret;
String? get lastFmSessionKey => _service.lastFmSessionKey;
String? get lastFmUsername => _service.lastFmUsername;
void setEnableLastFmScrobbling(bool value) =>
_service.setEnableLastFmScrobbling(value);
void setLastFmApiKey(String value) => _service.setLastFmApiKey(value);
void setLastFmSecret(String value) => _service.setLastFmSecret(value);
void setLastFmSessionKey(String value) => _service.setLastFmSessionKey(value);
void setLastFmUsername(String value) => _service.setLastFmUsername(value);
Future<void> setLastFmAuth() async => _service.setLastFmAuth();

bool get useMoreAnimations => _service.useMoreAnimations;
void setUseMoreAnimations(bool value) => _service.setUseMoreAnimations(value);

Expand Down
64 changes: 63 additions & 1 deletion lib/settings/settings_service.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import 'dart:async';
import 'dart:io';

import 'package:lastfm/lastfm.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

import '../common/data/close_btn_action.dart';
import '../constants.dart';
Expand All @@ -10,11 +12,14 @@ class SettingsService {
SettingsService({
required String? downloadsDefaultDir,
required SharedPreferences sharedPreferences,
required LastFM lastFm,
}) : _preferences = sharedPreferences,
_downloadsDefaultDir = downloadsDefaultDir;
_downloadsDefaultDir = downloadsDefaultDir,
_lastFm = lastFm;

final String? _downloadsDefaultDir;
final SharedPreferences _preferences;
final LastFM _lastFm;
final _propertiesChangedController = StreamController<bool>.broadcast();
Stream<bool> get propertiesChanged => _propertiesChangedController.stream;

Expand All @@ -37,6 +42,63 @@ class SettingsService {
);
}

bool get enableLastFmScrobbling =>
_preferences.getBool(kEnableLastFmScrobbling) ?? false;
String? get lastFmApiKey => _preferences.getString(kLastFmApiKey);
String? get lastFmSecret => _preferences.getString(klastFmSecret);
String? get lastFmSessionKey => _preferences.getString(kLastFmSessionKey);
String? get lastFmUsername => _preferences.getString(kLastFmUsername);
void setEnableLastFmScrobbling(bool value) {
_preferences.setBool(kEnableLastFmScrobbling, value).then(
(saved) {
if (saved) _propertiesChangedController.add(true);
},
);
}

void setLastFmApiKey(String value) {
_preferences.setString(kLastFmApiKey, value).then(
(saved) {
if (saved) _propertiesChangedController.add(true);
},
);
}

void setLastFmSecret(String value) {
_preferences.setString(klastFmSecret, value).then(
(saved) {
if (saved) _propertiesChangedController.add(true);
},
);
}

void setLastFmSessionKey(String value) {
_preferences.setString(kLastFmSessionKey, value).then(
(saved) {
if (saved) _propertiesChangedController.add(true);
},
);
}

void setLastFmUsername(String value) {
_preferences.setString(kLastFmUsername, value).then(
(saved) {
if (saved) _propertiesChangedController.add(true);
},
);
}

Future<void> setLastFmAuth() async {
Feichtmeier marked this conversation as resolved.
Show resolved Hide resolved
final lastfmua = _lastFm as LastFMUnauthorized;
launchUrl(
Uri.parse(await lastfmua.authorizeDesktop()),
);
await Future.delayed(const Duration(seconds: 20));
final lastfm = await lastfmua.finishAuthorizeDesktop();
setLastFmSessionKey(lastfm.sessionKey);
setLastFmUsername(lastfm.username);
}

bool get enableDiscordRPC => _preferences.getBool(kEnableDiscordRPC) ?? false;
void setEnableDiscordRPC(bool value) {
_preferences.setBool(kEnableDiscordRPC, value).then(
Expand Down
103 changes: 103 additions & 0 deletions lib/settings/view/settings_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,23 @@ class _ExposeOnlineSection extends StatelessWidget with WatchItMixin {
? watchPropertyValue((SettingsModel m) => m.enableDiscordRPC)
: false;

final lastFmEnabled =
watchPropertyValue((SettingsModel m) => m.enableLastFmScrobbling);

final lastFmApiKey =
watchPropertyValue((SettingsModel m) => m.lastFmApiKey);

final lastFmSecret =
watchPropertyValue((SettingsModel m) => m.lastFmSecret);

final TextEditingController lastFmApiKeyController =
TextEditingController(text: lastFmApiKey);

final TextEditingController lastFmSecretController =
TextEditingController(text: lastFmSecret);

final formkey = GlobalKey<FormState>();

return YaruSection(
headline: Text(l10n.exposeOnlineHeadline),
margin: const EdgeInsets.only(
Expand Down Expand Up @@ -557,6 +574,92 @@ class _ExposeOnlineSection extends StatelessWidget with WatchItMixin {
: null,
),
),
YaruTile(
title: Row(
children: space(
children: [
const Icon(
TablerIcons.brand_lastfm,
),
Text(l10n.exposeToLastfmTitle),
],
),
),
subtitle: Column(
children: [
Text(l10n.exposeToLastfmSubTitle),
if (lastFmEnabled)
Form(
key: formkey,
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: TextFormField(
controller: lastFmApiKeyController,
decoration: InputDecoration(
hintText: l10n.lastfmApiKey,
),
validator: (value) {
if (value == null || value.isEmpty) {
return l10n.lastfmApiKeyEmpty;
}
return null;
},
onFieldSubmitted: (value) async {
if (formkey.currentState!.validate()) {
di<SettingsModel>().setLastFmApiKey(value);
}
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: TextFormField(
controller: lastFmSecretController,
decoration: InputDecoration(
hintText: l10n.lastfmSecret,
),
validator: (value) {
if (value == null || value.isEmpty) {
return l10n.lastfmSecretEmpty;
}
return null;
},
onFieldSubmitted: (value) async {
if (formkey.currentState!.validate()) {
di<SettingsModel>().setLastFmSecret(value);
}
},
),
),
],
),
),
],
),
trailing: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CommonSwitch(
value: lastFmEnabled,
onChanged: (v) {
di<SettingsModel>().setEnableLastFmScrobbling(v);
},
),
if (lastFmEnabled)
ImportantButton(
onPressed: () {
if (lastFmApiKeyController.text.isNotEmpty &&
lastFmSecretController.text.isNotEmpty) {
di<SettingsModel>().setLastFmAuth();
}
},
child: Text(l10n.save),
),
],
),
),
],
),
);
Expand Down
Loading