mirror of
https://github.com/block/buzz.git
synced 2026-11-30 05:02:57 +00:00
Address connection code checks
This commit is contained in:
@@ -266,8 +266,8 @@ async fn wait_for_oauth_callback(
|
||||
|
||||
let (title, body) = if result.is_ok() {
|
||||
(
|
||||
"Google Calendar connected",
|
||||
"You can close this browser tab and return to Buzz.",
|
||||
"Google Calendar authorization received",
|
||||
"Return to Buzz to finish connecting Google Calendar.",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
|
||||
@@ -16,9 +16,6 @@ use crate::secret_store::SecretStore;
|
||||
const SPOTIFY_CREDENTIAL_KEY: &str = "spotify-oauth";
|
||||
const SPOTIFY_AUTH_URL: &str = "https://accounts.spotify.com/authorize";
|
||||
const SPOTIFY_TOKEN_URL: &str = "https://accounts.spotify.com/api/token";
|
||||
const SPOTIFY_API_BASE_URL: &str = "https://api.spotify.com/v1";
|
||||
const SPOTIFY_SCOPES: &str =
|
||||
"user-read-playback-state user-read-currently-playing user-modify-playback-state";
|
||||
const OAUTH_CALLBACK_PATH: &str = "/oauth/spotify/callback";
|
||||
const OAUTH_CALLBACK_TIMEOUT: Duration = Duration::from_secs(180);
|
||||
const DEFAULT_SPOTIFY_REDIRECT_PORT: u16 = 18202;
|
||||
@@ -41,36 +38,6 @@ pub struct SpotifyStatus {
|
||||
scopes: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SpotifyDevice {
|
||||
id: Option<String>,
|
||||
name: String,
|
||||
device_type: String,
|
||||
is_active: bool,
|
||||
is_restricted: bool,
|
||||
volume_percent: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SpotifyPlaybackState {
|
||||
context_uri: Option<String>,
|
||||
device: Option<SpotifyDevice>,
|
||||
is_playing: bool,
|
||||
item: Option<SpotifyPlaybackItem>,
|
||||
progress_ms: Option<i64>,
|
||||
timestamp: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SpotifyPlaybackItem {
|
||||
artists: Vec<String>,
|
||||
duration_ms: Option<i64>,
|
||||
image_url: Option<String>,
|
||||
item_type: Option<String>,
|
||||
name: String,
|
||||
uri: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyTokenResponse {
|
||||
access_token: Option<String>,
|
||||
@@ -80,99 +47,6 @@ struct SpotifyTokenResponse {
|
||||
token_type: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyDevicesResponse {
|
||||
devices: Vec<SpotifyRawDevice>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawDevice {
|
||||
id: Option<String>,
|
||||
#[serde(default)]
|
||||
is_active: bool,
|
||||
#[serde(default)]
|
||||
is_restricted: bool,
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default, rename = "type")]
|
||||
device_type: String,
|
||||
volume_percent: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawPlaybackState {
|
||||
context: Option<SpotifyRawContext>,
|
||||
device: Option<SpotifyRawDevice>,
|
||||
#[serde(default)]
|
||||
is_playing: bool,
|
||||
item: Option<SpotifyRawPlaybackItem>,
|
||||
progress_ms: Option<i64>,
|
||||
timestamp: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawContext {
|
||||
uri: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawPlaybackItem {
|
||||
album: Option<SpotifyRawAlbum>,
|
||||
artists: Option<Vec<SpotifyRawArtist>>,
|
||||
duration_ms: Option<i64>,
|
||||
name: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
item_type: Option<String>,
|
||||
uri: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawAlbum {
|
||||
images: Option<Vec<SpotifyRawImage>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawArtist {
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SpotifyRawImage {
|
||||
url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SpotifyPlaybackInput {
|
||||
context_uri: Option<String>,
|
||||
device_id: Option<String>,
|
||||
position_ms: Option<u32>,
|
||||
uris: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SpotifyDeviceInput {
|
||||
device_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SpotifySeekInput {
|
||||
device_id: Option<String>,
|
||||
position_ms: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct SpotifyPlaybackBody<'a> {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
context_uri: Option<&'a str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
position_ms: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
uris: Option<&'a [String]>,
|
||||
}
|
||||
|
||||
fn spotify_client_id() -> Option<String> {
|
||||
std::env::var("BUZZ_SPOTIFY_CLIENT_ID")
|
||||
.ok()
|
||||
@@ -266,7 +140,6 @@ fn oauth_authorization_url(
|
||||
.append_pair("client_id", client_id)
|
||||
.append_pair("redirect_uri", redirect_uri)
|
||||
.append_pair("response_type", "code")
|
||||
.append_pair("scope", SPOTIFY_SCOPES)
|
||||
.append_pair("state", state)
|
||||
.append_pair("code_challenge", code_challenge)
|
||||
.append_pair("code_challenge_method", "S256");
|
||||
@@ -333,8 +206,8 @@ async fn wait_for_oauth_callback(
|
||||
|
||||
let (title, body) = if result.is_ok() {
|
||||
(
|
||||
"Spotify connected",
|
||||
"You can close this browser tab and return to Buzz.",
|
||||
"Spotify authorization received",
|
||||
"Return to Buzz to finish connecting Spotify.",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
@@ -388,131 +261,6 @@ async fn exchange_code_for_token(
|
||||
parse_spotify_token_response(response).await
|
||||
}
|
||||
|
||||
async fn refresh_access_token(
|
||||
credential: &SpotifyCredential,
|
||||
client_id: &str,
|
||||
state: &AppState,
|
||||
) -> Result<SpotifyTokenResponse, String> {
|
||||
let form = vec![
|
||||
("client_id", client_id.to_string()),
|
||||
("refresh_token", credential.refresh_token.clone()),
|
||||
("grant_type", "refresh_token".to_string()),
|
||||
];
|
||||
|
||||
let response = state
|
||||
.http_client
|
||||
.post(SPOTIFY_TOKEN_URL)
|
||||
.form(&form)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify token refresh couldn't complete: {e}"))?;
|
||||
parse_spotify_token_response(response).await
|
||||
}
|
||||
|
||||
async fn access_token(state: &AppState) -> Result<String, String> {
|
||||
let client_id = spotify_client_id()
|
||||
.ok_or_else(|| "Set BUZZ_SPOTIFY_CLIENT_ID to enable Spotify.".to_string())?;
|
||||
let mut credential = load_credential()?
|
||||
.ok_or_else(|| "Connect Spotify before controlling playback.".to_string())?;
|
||||
|
||||
if let (Some(token), Some(expires_at)) = (&credential.access_token, credential.expires_at) {
|
||||
if expires_at > now_ts() + 60 {
|
||||
return Ok(token.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let token = refresh_access_token(&credential, &client_id, state).await?;
|
||||
let access_token = token
|
||||
.access_token
|
||||
.ok_or_else(|| "Spotify token refresh returned no access token.".to_string())?;
|
||||
credential.access_token = Some(access_token.clone());
|
||||
credential.expires_at = token.expires_in.map(|seconds| now_ts() + seconds);
|
||||
if let Some(refresh_token) = token.refresh_token {
|
||||
credential.refresh_token = refresh_token;
|
||||
}
|
||||
credential.scope = token.scope.or(credential.scope);
|
||||
credential.token_type = token.token_type.or(credential.token_type);
|
||||
save_credential(&credential)?;
|
||||
Ok(access_token)
|
||||
}
|
||||
|
||||
fn convert_device(device: SpotifyRawDevice) -> SpotifyDevice {
|
||||
SpotifyDevice {
|
||||
id: device.id,
|
||||
name: device.name,
|
||||
device_type: device.device_type,
|
||||
is_active: device.is_active,
|
||||
is_restricted: device.is_restricted,
|
||||
volume_percent: device.volume_percent,
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_playback_item(item: SpotifyRawPlaybackItem) -> Option<SpotifyPlaybackItem> {
|
||||
let uri = item.uri?;
|
||||
let name = item.name.unwrap_or_else(|| "Untitled".to_string());
|
||||
let artists = item
|
||||
.artists
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|artist| artist.name)
|
||||
.collect();
|
||||
let image_url = item
|
||||
.album
|
||||
.and_then(|album| album.images)
|
||||
.and_then(|images| images.into_iter().find_map(|image| image.url));
|
||||
|
||||
Some(SpotifyPlaybackItem {
|
||||
artists,
|
||||
duration_ms: item.duration_ms,
|
||||
image_url,
|
||||
item_type: item.item_type,
|
||||
name,
|
||||
uri,
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_playback_state(state: SpotifyRawPlaybackState) -> SpotifyPlaybackState {
|
||||
SpotifyPlaybackState {
|
||||
context_uri: state.context.and_then(|context| context.uri),
|
||||
device: state.device.map(convert_device),
|
||||
is_playing: state.is_playing,
|
||||
item: state.item.and_then(convert_playback_item),
|
||||
progress_ms: state.progress_ms,
|
||||
timestamp: state.timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
async fn spotify_json<T: for<'de> Deserialize<'de>>(
|
||||
response: reqwest::Response,
|
||||
context: &str,
|
||||
) -> Result<T, String> {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("read Spotify {context} response: {e}"))?;
|
||||
if !status.is_success() {
|
||||
return Err(format!(
|
||||
"Spotify {context} request returned {status}: {body}"
|
||||
));
|
||||
}
|
||||
serde_json::from_str(&body).map_err(|e| format!("parse Spotify {context} response: {e}"))
|
||||
}
|
||||
|
||||
async fn spotify_empty(response: reqwest::Response, context: &str) -> Result<(), String> {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("read Spotify {context} response: {e}"))?;
|
||||
if !status.is_success() {
|
||||
return Err(format!(
|
||||
"Spotify {context} request returned {status}: {body}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_spotify_status() -> Result<SpotifyStatus, String> {
|
||||
if spotify_client_id().is_none() {
|
||||
@@ -567,192 +315,3 @@ pub fn disconnect_spotify() -> Result<SpotifyStatus, String> {
|
||||
credential_store().delete(SPOTIFY_CREDENTIAL_KEY)?;
|
||||
Ok(status_from_credential(None))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_spotify_devices(state: State<'_, AppState>) -> Result<Vec<SpotifyDevice>, String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let url = format!("{SPOTIFY_API_BASE_URL}/me/player/devices");
|
||||
let response = state
|
||||
.http_client
|
||||
.get(url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify devices request couldn't complete: {e}"))?;
|
||||
let raw: SpotifyDevicesResponse = spotify_json(response, "devices").await?;
|
||||
Ok(raw.devices.into_iter().map(convert_device).collect())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_spotify_playback_state(
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<SpotifyPlaybackState>, String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let url = format!("{SPOTIFY_API_BASE_URL}/me/player");
|
||||
let response = state
|
||||
.http_client
|
||||
.get(url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify playback state request couldn't complete: {e}"))?;
|
||||
|
||||
if response.status().as_u16() == 204 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let raw: SpotifyRawPlaybackState = spotify_json(response, "playback state").await?;
|
||||
Ok(Some(convert_playback_state(raw)))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn start_spotify_playback(
|
||||
input: Option<SpotifyPlaybackInput>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let input = input.unwrap_or_default();
|
||||
let mut url =
|
||||
Url::parse(&format!("{SPOTIFY_API_BASE_URL}/me/player/play")).map_err(|e| e.to_string())?;
|
||||
if let Some(device_id) = input.device_id.as_deref().filter(|value| !value.is_empty()) {
|
||||
url.query_pairs_mut().append_pair("device_id", device_id);
|
||||
}
|
||||
|
||||
let uris = input.uris.as_ref().filter(|values| !values.is_empty());
|
||||
let body = SpotifyPlaybackBody {
|
||||
context_uri: input
|
||||
.context_uri
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty()),
|
||||
position_ms: input.position_ms,
|
||||
uris: uris.map(Vec::as_slice),
|
||||
};
|
||||
let has_body = body.context_uri.is_some() || body.position_ms.is_some() || body.uris.is_some();
|
||||
let request = state.http_client.put(url).bearer_auth(access_token);
|
||||
let response = if has_body {
|
||||
request.json(&body).send().await
|
||||
} else {
|
||||
request.send().await
|
||||
}
|
||||
.map_err(|e| format!("Spotify playback request couldn't complete: {e}"))?;
|
||||
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("read Spotify playback response: {e}"))?;
|
||||
if !status.is_success() {
|
||||
return Err(format!(
|
||||
"Spotify playback request returned {status}: {body}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn pause_spotify_playback(
|
||||
input: Option<SpotifyDeviceInput>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let mut url = Url::parse(&format!("{SPOTIFY_API_BASE_URL}/me/player/pause"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
if let Some(device_id) = input
|
||||
.and_then(|input| input.device_id)
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
url.query_pairs_mut().append_pair("device_id", &device_id);
|
||||
}
|
||||
|
||||
let response = state
|
||||
.http_client
|
||||
.put(url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify pause request couldn't complete: {e}"))?;
|
||||
spotify_empty(response, "pause").await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn skip_spotify_next(
|
||||
input: Option<SpotifyDeviceInput>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let mut url =
|
||||
Url::parse(&format!("{SPOTIFY_API_BASE_URL}/me/player/next")).map_err(|e| e.to_string())?;
|
||||
if let Some(device_id) = input
|
||||
.and_then(|input| input.device_id)
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
url.query_pairs_mut().append_pair("device_id", &device_id);
|
||||
}
|
||||
|
||||
let response = state
|
||||
.http_client
|
||||
.post(url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify next track request couldn't complete: {e}"))?;
|
||||
spotify_empty(response, "next track").await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn skip_spotify_previous(
|
||||
input: Option<SpotifyDeviceInput>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let mut url = Url::parse(&format!("{SPOTIFY_API_BASE_URL}/me/player/previous"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
if let Some(device_id) = input
|
||||
.and_then(|input| input.device_id)
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
url.query_pairs_mut().append_pair("device_id", &device_id);
|
||||
}
|
||||
|
||||
let response = state
|
||||
.http_client
|
||||
.post(url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify previous track request couldn't complete: {e}"))?;
|
||||
spotify_empty(response, "previous track").await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn seek_spotify_playback(
|
||||
input: SpotifySeekInput,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let access_token = access_token(&state).await?;
|
||||
let mut url =
|
||||
Url::parse(&format!("{SPOTIFY_API_BASE_URL}/me/player/seek")).map_err(|e| e.to_string())?;
|
||||
url.query_pairs_mut()
|
||||
.append_pair("position_ms", &input.position_ms.to_string());
|
||||
if let Some(device_id) = input
|
||||
.device_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
url.query_pairs_mut().append_pair("device_id", device_id);
|
||||
}
|
||||
|
||||
let response = state
|
||||
.http_client
|
||||
.put(url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Spotify seek request couldn't complete: {e}"))?;
|
||||
spotify_empty(response, "seek").await
|
||||
}
|
||||
|
||||
@@ -452,13 +452,6 @@ pub fn run() {
|
||||
get_spotify_status,
|
||||
connect_spotify,
|
||||
disconnect_spotify,
|
||||
get_spotify_devices,
|
||||
get_spotify_playback_state,
|
||||
start_spotify_playback,
|
||||
pause_spotify_playback,
|
||||
skip_spotify_next,
|
||||
skip_spotify_previous,
|
||||
seek_spotify_playback,
|
||||
fetch_link_preview_title,
|
||||
discover_acp_providers,
|
||||
install_acp_runtime,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
getGoogleCalendarStatus,
|
||||
type GoogleCalendarEvent,
|
||||
} from "@/features/calendar/api";
|
||||
import { useNow } from "@/shared/lib/useNow";
|
||||
|
||||
export const googleCalendarStatusQueryKey = ["google-calendar-status"] as const;
|
||||
|
||||
@@ -22,6 +21,20 @@ const calendarBusyTimeFormatter = new Intl.DateTimeFormat(undefined, {
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
function useCalendarNow(enabled: boolean): number {
|
||||
const [now, setNow] = React.useState(() => Date.now());
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
setNow(Date.now());
|
||||
const interval = window.setInterval(() => setNow(Date.now()), 60_000);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [enabled]);
|
||||
|
||||
return now;
|
||||
}
|
||||
|
||||
export function useGoogleCalendarStatusQuery({
|
||||
enabled = true,
|
||||
}: {
|
||||
@@ -150,7 +163,7 @@ export function useCurrentGoogleCalendarEvent({
|
||||
}: {
|
||||
enabled?: boolean;
|
||||
} = {}) {
|
||||
const now = useNow(60_000);
|
||||
const now = useCalendarNow(enabled);
|
||||
const statusQuery = useGoogleCalendarStatusQuery({ enabled });
|
||||
const window = React.useMemo(() => todayCalendarWindow(now), [now]);
|
||||
const eventsQuery = useGoogleCalendarEventsQuery({
|
||||
|
||||
@@ -59,6 +59,37 @@ function CalendarMenuItem({
|
||||
const showJoin = Boolean(isOngoing && joinUrl);
|
||||
const canOpenJoinUrl = Boolean(showJoin && joinUrl);
|
||||
const meta = event ? formatCalendarStart(event, now) : null;
|
||||
const content = (
|
||||
<>
|
||||
<CalendarDays className="h-4 w-4" />
|
||||
<span className="min-w-0 flex-1 truncate pr-2">{title}</span>
|
||||
{showJoin ? (
|
||||
<>
|
||||
<span className="shrink-0 text-2xs font-medium text-sidebar-foreground/60 group-hover/calendar:hidden group-focus-visible/calendar:hidden">
|
||||
Now
|
||||
</span>
|
||||
<span className="hidden shrink-0 items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-2xs font-medium text-primary group-hover/calendar:inline-flex group-focus-visible/calendar:inline-flex">
|
||||
<Video className="h-3 w-3" />
|
||||
Join
|
||||
</span>
|
||||
</>
|
||||
) : meta ? (
|
||||
<span className="shrink-0 text-2xs font-medium text-sidebar-foreground/60">
|
||||
{meta}
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
if (!canOpenJoinUrl) {
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild className="group/calendar" tooltip={title}>
|
||||
<div data-testid="sidebar-calendar-status">{content}</div>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
@@ -73,23 +104,7 @@ function CalendarMenuItem({
|
||||
tooltip={title}
|
||||
type="button"
|
||||
>
|
||||
<CalendarDays className="h-4 w-4" />
|
||||
<span className="min-w-0 flex-1 truncate pr-2">{title}</span>
|
||||
{showJoin ? (
|
||||
<>
|
||||
<span className="shrink-0 text-2xs font-medium text-sidebar-foreground/60 group-hover/calendar:hidden group-focus-visible/calendar:hidden">
|
||||
Now
|
||||
</span>
|
||||
<span className="hidden shrink-0 items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-2xs font-medium text-primary group-hover/calendar:inline-flex group-focus-visible/calendar:inline-flex">
|
||||
<Video className="h-3 w-3" />
|
||||
Join
|
||||
</span>
|
||||
</>
|
||||
) : meta ? (
|
||||
<span className="shrink-0 text-2xs font-medium text-sidebar-foreground/60">
|
||||
{meta}
|
||||
</span>
|
||||
) : null}
|
||||
{content}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
|
||||
@@ -7,48 +7,6 @@ export type SpotifyStatus = {
|
||||
scopes: string[];
|
||||
};
|
||||
|
||||
export type SpotifyDevice = {
|
||||
id: string | null;
|
||||
name: string;
|
||||
deviceType: string;
|
||||
isActive: boolean;
|
||||
isRestricted: boolean;
|
||||
volumePercent: number | null;
|
||||
};
|
||||
|
||||
export type SpotifyPlaybackInput = {
|
||||
contextUri?: string;
|
||||
deviceId?: string;
|
||||
positionMs?: number;
|
||||
uris?: string[];
|
||||
};
|
||||
|
||||
export type SpotifyPlaybackState = {
|
||||
contextUri: string | null;
|
||||
device: SpotifyDevice | null;
|
||||
isPlaying: boolean;
|
||||
item: SpotifyPlaybackItem | null;
|
||||
progressMs: number | null;
|
||||
timestamp: number | null;
|
||||
};
|
||||
|
||||
export type SpotifyPlaybackItem = {
|
||||
artists: string[];
|
||||
durationMs: number | null;
|
||||
imageUrl: string | null;
|
||||
itemType: string | null;
|
||||
name: string;
|
||||
uri: string;
|
||||
};
|
||||
|
||||
export type SpotifyDeviceInput = {
|
||||
deviceId?: string;
|
||||
};
|
||||
|
||||
export type SpotifySeekInput = SpotifyDeviceInput & {
|
||||
positionMs: number;
|
||||
};
|
||||
|
||||
type RawSpotifyStatus = {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
@@ -56,33 +14,6 @@ type RawSpotifyStatus = {
|
||||
scopes: string[];
|
||||
};
|
||||
|
||||
type RawSpotifyDevice = {
|
||||
id: string | null;
|
||||
name: string;
|
||||
device_type: string;
|
||||
is_active: boolean;
|
||||
is_restricted: boolean;
|
||||
volume_percent: number | null;
|
||||
};
|
||||
|
||||
type RawSpotifyPlaybackState = {
|
||||
context_uri: string | null;
|
||||
device: RawSpotifyDevice | null;
|
||||
is_playing: boolean;
|
||||
item: RawSpotifyPlaybackItem | null;
|
||||
progress_ms: number | null;
|
||||
timestamp: number | null;
|
||||
};
|
||||
|
||||
type RawSpotifyPlaybackItem = {
|
||||
artists: string[];
|
||||
duration_ms: number | null;
|
||||
image_url: string | null;
|
||||
item_type: string | null;
|
||||
name: string;
|
||||
uri: string;
|
||||
};
|
||||
|
||||
function fromRawStatus(raw: RawSpotifyStatus): SpotifyStatus {
|
||||
return {
|
||||
configured: raw.configured,
|
||||
@@ -92,41 +23,6 @@ function fromRawStatus(raw: RawSpotifyStatus): SpotifyStatus {
|
||||
};
|
||||
}
|
||||
|
||||
function fromRawDevice(raw: RawSpotifyDevice): SpotifyDevice {
|
||||
return {
|
||||
id: raw.id,
|
||||
name: raw.name,
|
||||
deviceType: raw.device_type,
|
||||
isActive: raw.is_active,
|
||||
isRestricted: raw.is_restricted,
|
||||
volumePercent: raw.volume_percent,
|
||||
};
|
||||
}
|
||||
|
||||
function fromRawPlaybackItem(raw: RawSpotifyPlaybackItem): SpotifyPlaybackItem {
|
||||
return {
|
||||
artists: raw.artists,
|
||||
durationMs: raw.duration_ms,
|
||||
imageUrl: raw.image_url,
|
||||
itemType: raw.item_type,
|
||||
name: raw.name,
|
||||
uri: raw.uri,
|
||||
};
|
||||
}
|
||||
|
||||
function fromRawPlaybackState(
|
||||
raw: RawSpotifyPlaybackState,
|
||||
): SpotifyPlaybackState {
|
||||
return {
|
||||
contextUri: raw.context_uri,
|
||||
device: raw.device ? fromRawDevice(raw.device) : null,
|
||||
isPlaying: raw.is_playing,
|
||||
item: raw.item ? fromRawPlaybackItem(raw.item) : null,
|
||||
progressMs: raw.progress_ms,
|
||||
timestamp: raw.timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getSpotifyStatus(): Promise<SpotifyStatus> {
|
||||
return fromRawStatus(
|
||||
await invokeTauri<RawSpotifyStatus>("get_spotify_status"),
|
||||
@@ -142,45 +38,3 @@ export async function disconnectSpotify(): Promise<SpotifyStatus> {
|
||||
await invokeTauri<RawSpotifyStatus>("disconnect_spotify"),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSpotifyDevices(): Promise<SpotifyDevice[]> {
|
||||
const raw = await invokeTauri<RawSpotifyDevice[]>("get_spotify_devices");
|
||||
return raw.map(fromRawDevice);
|
||||
}
|
||||
|
||||
export async function getSpotifyPlaybackState(): Promise<SpotifyPlaybackState | null> {
|
||||
const raw = await invokeTauri<RawSpotifyPlaybackState | null>(
|
||||
"get_spotify_playback_state",
|
||||
);
|
||||
return raw ? fromRawPlaybackState(raw) : null;
|
||||
}
|
||||
|
||||
export async function startSpotifyPlayback(
|
||||
input: SpotifyPlaybackInput = {},
|
||||
): Promise<void> {
|
||||
await invokeTauri("start_spotify_playback", { input });
|
||||
}
|
||||
|
||||
export async function pauseSpotifyPlayback(
|
||||
input: SpotifyDeviceInput = {},
|
||||
): Promise<void> {
|
||||
await invokeTauri("pause_spotify_playback", { input });
|
||||
}
|
||||
|
||||
export async function skipSpotifyNext(
|
||||
input: SpotifyDeviceInput = {},
|
||||
): Promise<void> {
|
||||
await invokeTauri("skip_spotify_next", { input });
|
||||
}
|
||||
|
||||
export async function skipSpotifyPrevious(
|
||||
input: SpotifyDeviceInput = {},
|
||||
): Promise<void> {
|
||||
await invokeTauri("skip_spotify_previous", { input });
|
||||
}
|
||||
|
||||
export async function seekSpotifyPlayback(
|
||||
input: SpotifySeekInput,
|
||||
): Promise<void> {
|
||||
await invokeTauri("seek_spotify_playback", { input });
|
||||
}
|
||||
|
||||
@@ -3,22 +3,10 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
connectSpotify,
|
||||
disconnectSpotify,
|
||||
getSpotifyDevices,
|
||||
getSpotifyPlaybackState,
|
||||
getSpotifyStatus,
|
||||
pauseSpotifyPlayback,
|
||||
seekSpotifyPlayback,
|
||||
skipSpotifyNext,
|
||||
skipSpotifyPrevious,
|
||||
startSpotifyPlayback,
|
||||
type SpotifyDeviceInput,
|
||||
type SpotifyPlaybackInput,
|
||||
type SpotifySeekInput,
|
||||
} from "@/features/spotify/api";
|
||||
|
||||
export const spotifyStatusQueryKey = ["spotify-status"] as const;
|
||||
export const spotifyDevicesQueryKey = ["spotify-devices"] as const;
|
||||
export const spotifyPlaybackStateQueryKey = ["spotify-playback-state"] as const;
|
||||
|
||||
export function useSpotifyStatusQuery() {
|
||||
return useQuery({
|
||||
@@ -28,38 +16,10 @@ export function useSpotifyStatusQuery() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useSpotifyDevicesQuery({ enabled }: { enabled: boolean }) {
|
||||
return useQuery({
|
||||
enabled,
|
||||
queryKey: spotifyDevicesQueryKey,
|
||||
queryFn: getSpotifyDevices,
|
||||
refetchInterval: enabled ? 30_000 : false,
|
||||
staleTime: 20_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSpotifyPlaybackStateQuery({
|
||||
enabled,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
}) {
|
||||
return useQuery({
|
||||
enabled,
|
||||
queryKey: spotifyPlaybackStateQueryKey,
|
||||
queryFn: getSpotifyPlaybackState,
|
||||
refetchInterval: enabled ? 10_000 : false,
|
||||
staleTime: 5_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSpotifyConnectionMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: spotifyStatusQueryKey });
|
||||
void queryClient.invalidateQueries({ queryKey: spotifyDevicesQueryKey });
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: spotifyPlaybackStateQueryKey,
|
||||
});
|
||||
};
|
||||
|
||||
const connect = useMutation({
|
||||
@@ -73,51 +33,3 @@ export function useSpotifyConnectionMutations() {
|
||||
|
||||
return { connect, disconnect };
|
||||
}
|
||||
|
||||
export function useSpotifyPlaybackMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: spotifyDevicesQueryKey });
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: spotifyPlaybackStateQueryKey,
|
||||
});
|
||||
};
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input?: SpotifyPlaybackInput) =>
|
||||
startSpotifyPlayback(input ?? {}),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSpotifyPlaybackControlMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: spotifyDevicesQueryKey });
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: spotifyPlaybackStateQueryKey,
|
||||
});
|
||||
};
|
||||
|
||||
const pause = useMutation({
|
||||
mutationFn: (input?: SpotifyDeviceInput) =>
|
||||
pauseSpotifyPlayback(input ?? {}),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
const next = useMutation({
|
||||
mutationFn: (input?: SpotifyDeviceInput) => skipSpotifyNext(input ?? {}),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
const previous = useMutation({
|
||||
mutationFn: (input?: SpotifyDeviceInput) =>
|
||||
skipSpotifyPrevious(input ?? {}),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
const seek = useMutation({
|
||||
mutationFn: (input: SpotifySeekInput) => seekSpotifyPlayback(input),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
|
||||
return { pause, next, previous, seek };
|
||||
}
|
||||
|
||||
@@ -7522,16 +7522,6 @@ export function maybeInstallE2eTauriMocks() {
|
||||
return mockSpotifyStatus();
|
||||
case "disconnect_spotify":
|
||||
return mockSpotifyStatus();
|
||||
case "get_spotify_devices":
|
||||
return [];
|
||||
case "get_spotify_playback_state":
|
||||
return null;
|
||||
case "start_spotify_playback":
|
||||
case "pause_spotify_playback":
|
||||
case "skip_spotify_next":
|
||||
case "skip_spotify_previous":
|
||||
case "seek_spotify_playback":
|
||||
return;
|
||||
case "pick_and_upload_media":
|
||||
return await resolveMockUploadDescriptors(activeConfig);
|
||||
case "upload_media_bytes":
|
||||
|
||||
Reference in New Issue
Block a user