Skip to content

Commit

Permalink
await result where applicable
Browse files Browse the repository at this point in the history
  • Loading branch information
jariz committed Nov 11, 2024
1 parent 83d2df2 commit 8332694
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 45 deletions.
10 changes: 10 additions & 0 deletions Speck/Speck/Extensions/CoreError+Error.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//
// CoreError.swift
// Speck
//
// Created by Jari on 11/11/2024.
//

extension CoreError: Error {

}
4 changes: 2 additions & 2 deletions Speck/Speck/Extensions/Lyrics+from.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
import SpotifyWebAPI

extension Lyrics {
static func from(_ track: Track) async -> Lyrics? {
static func from(_ track: Track) async throws -> Lyrics? {
guard let trackId = track.id else {
return nil
}

return await SpeckCore.shared.get_lyrics(trackId)
return try await SpeckCore.shared.get_lyrics(trackId)
}
}
22 changes: 16 additions & 6 deletions Speck/Speck/Models/Spotify.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ final class Spotify: ObservableObject {
*/
@Published var isAuthorized = false

@Published var isLoggingIn = false

/// The keychain to store the authorization information in.
private let keychain = Keychain(service: "io.jari.Speck").accessibility(.whenUnlocked)

Expand Down Expand Up @@ -222,14 +224,22 @@ final class Spotify: ObservableObject {
)
}

if self.isAuthorized && !isExpired && self.player == nil {
if self.isAuthorized && !isExpired && self.player == nil && !self.isLoggingIn {
Task {
// TODO do something with error!
await SpeckCore.shared.login(api.authorizationManager.accessToken!)
// TODO background thread updates ardgfr;dg[fd
DispatchQueue.main.async {
self.player = Player(api: self.api)
do {
self.isLoggingIn = true

// TODO do something with error!
try await SpeckCore.shared.login(api.authorizationManager.accessToken!)

DispatchQueue.main.async {
self.player = Player(api: self.api)
}
}
catch {
print("could not login to core: \(error)")
}
self.isLoggingIn = false
}
}
}
Expand Down
15 changes: 9 additions & 6 deletions Speck/Speck/Views/Player/LyricsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ struct LyricsView: View {
}
}
.padding(18)
.frame(maxWidth: .infinity)
.frame(minWidth: 300)
.opacity(showRight ? 1 : 0)
}
.frame(maxHeight: .infinity)
.frame(width: showRight ? 300 : 0)
Expand All @@ -51,12 +52,14 @@ struct LyricsView: View {
.onChange(of: player.track) { oldValue, newValue in
if let track = newValue {
Task {
let lyrics = await Lyrics.from(track)
withAnimation {
self.lyrics = lyrics
do {
let lyrics = try await Lyrics.from(track)
withAnimation {
self.lyrics = lyrics
}
} catch {
debugPrint("unable to fetch lyrics: \(error)")
}

debugPrint(lyrics)
}
}
}
Expand Down
63 changes: 32 additions & 31 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ use std::sync::Arc;
#[swift_bridge::bridge]
mod ffi {
#[swift_bridge(swift_repr = "struct")]
struct LoginResult {
ok: bool,
struct CoreError {
message: String,
}

Expand Down Expand Up @@ -163,7 +162,7 @@ mod ffi {
#[swift_bridge(init)]
fn new() -> SpeckCore;

async fn login(&mut self, access_token: String) -> LoginResult;
async fn login(&mut self, access_token: String) -> Result<(), CoreError>;

async fn get_player_event(&mut self) -> PlayerEventResult;

Expand All @@ -174,7 +173,7 @@ mod ffi {
fn player_play(&self);
fn player_seek(&self, position_ms: u32);

async fn get_lyrics(&self, track_id: String) -> Lyrics;
async fn get_lyrics(&self, track_id: String) -> Result<Lyrics, CoreError>;
}
}

Expand Down Expand Up @@ -358,22 +357,34 @@ impl SpeckCore {
// artist.portraits;
// }

async fn get_lyrics(&self, track_id: String) -> ffi::Lyrics {
let mut id = SpotifyId::from_base62(&track_id).unwrap();
async fn get_lyrics(&self, track_id: String) -> Result<ffi::Lyrics, ffi::CoreError> {
let mut id = SpotifyId::from_base62(&track_id).map_err(|_| ffi::CoreError {
message: "Invalid track id".to_string(),
})?;

id.item_type = SpotifyItemType::Track;
let metadata = Lyrics::get(self.session.as_ref().unwrap(), &id)
.await
.unwrap();
debug!("getting lyrics for track: {:?}", id);
let metadata = Lyrics::get(
self.session.as_ref().ok_or(ffi::CoreError {
message: "No session active".to_string(),
})?,
&id,
)
.await
.map_err(|err| ffi::CoreError {
message: format!("{:?}", err),
})?;
debug!("got metadata: {:?}", metadata);
let lyrics = metadata.lyrics;
return ffi::Lyrics {
Ok(ffi::Lyrics {
lines: lyrics.lines.iter().map(|line| line.words.clone()).collect(),
provider: lyrics.provider,
provider_display_name: lyrics.provider_display_name,
is_synced: lyrics.sync_type == SyncType::LineSynced,
color_background: metadata.colors.background,
color_highlight_text: metadata.colors.highlight_text,
color_text: metadata.colors.text,
};
})
}

fn player_load_track(&mut self, track_id: String) {
Expand All @@ -394,7 +405,7 @@ impl SpeckCore {
self.player.as_ref().unwrap().seek(position_ms);
}

async fn login(&mut self, access_token: String) -> ffi::LoginResult {
async fn login(&mut self, access_token: String) -> Result<(), ffi::CoreError> {
let session_config = SessionConfig::default();
// let mut cache_dir = env::temp_dir();
// cache_dir.push("spotty-cache");
Expand All @@ -406,25 +417,15 @@ impl SpeckCore {
// None => Credentials::with_access_token(access_token),
// };
let credentials = Credentials::with_access_token(access_token);
let session = Session::new(
session_config,
None, // Some(cache)
);
let res = session.connect(credentials, true).await;
let session = Session::new(session_config, None);
session
.connect(credentials, false)
.await
.map_err(|err| ffi::CoreError {
message: format!("{:?}", err),
})?;

match res {
Ok(_) => {
self.session = Some(session);
ffi::LoginResult {
ok: true,
message: "".to_string(),
}
}
// Err(err) => Err(format!("{:?}", err)),
Err(err) => ffi::LoginResult {
ok: false,
message: err.to_string(),
},
}
self.session = Some(session);
Ok(())
}
}

0 comments on commit 8332694

Please sign in to comment.