[PR #1055] [MERGED] strongly type ActivityPeriod #1212

Closed
opened 2026-02-27 20:01:35 +03:00 by kerem · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/librespot-org/librespot/pull/1055
Author: @eladyn
Created: 8/31/2022
Status: Merged
Merged: 9/3/2022
Merged by: @roderickvd

Base: devHead: strong_activity_periods


📝 Commits (3)

  • df0d50f strongly type ActivityPeriods
  • 0c5926d use fallible conversion for ActivityPeriod
  • 07336c2 switch fallibly to unsigned integers

📊 Changes

2 files changed (+44 additions, -14 deletions)

View changed files

📝 core/src/error.rs (+12 -1)
📝 metadata/src/artist.rs (+32 -13)

📄 Description

From my observations, ActivityPeriod always comes in one of the following three compositions:

  • decade
  • start_year (open timespan)
  • start_year + end_year (closed timespan)

Thus, it probably makes sense to strongly type those variants into ActivityPeriod.

I also added two debug_assert!s that make sure that the invariants that I assume are always held up. Alternatively, I could also turn them into normal assert!s or handle-able exceptions through TryFrom. I went for the current variants, since I think it makes most sense, but I'm open to different perspectives!

I've verified my assumptions with the help of the below program for probably around 1000 different artists, so it should be fine? Some example outputs:

  • for spotify:artist:5WUlDfRSoLAfcVSX1WnrxN: known good artists: 470 (decades: 203, closed: 4, open: 31)
  • for spotify:artist:3fMbdgg4jU18AjLCKBhRSm: known good artists: 333 (decades: 966, closed: 112, open: 216)
use std::{
    collections::{HashSet, VecDeque},
    env,
    io::Write,
    process::exit,
};

use librespot_core::{spotify_id::SpotifyItemType, Session, SessionConfig, SpotifyId};
use librespot_discovery::Credentials;
use librespot_metadata::{artist::ActivityPeriod, Artist, Metadata};

#[tokio::main]
async fn main() {
    env_logger::init();
    let session_config = SessionConfig::default();

    let args: Vec<_> = env::args().collect();
    if args.len() != 4 && args.len() != 5 {
        eprintln!("Usage: {} USERNAME PASSWORD ARTIST_URI", args[0]);
        return;
    }
    let credentials = Credentials::with_password(&args[1], &args[2]);

    let uri = SpotifyId::from_uri(&args[3]).unwrap_or_else(|_| {
        eprintln!(
            "URI should be a URI such as: \
                \"spotify:artist:5WUlDfRSoLAfcVSX1WnrxN\""
        );
        exit(1);
    });

    if uri.item_type != SpotifyItemType::Artist {
        eprintln!("URI must be of item type artist!");
        exit(1);
    }

    let session = Session::new(session_config, None);
    if let Err(e) = session.connect(credentials, false).await {
        eprintln!("Error connecting: {}", e);
        exit(1);
    }

    let mut decades = 0;
    let mut closed_timespans = 0;
    let mut open_timespans = 0;
    let mut known_artist_ids: HashSet<SpotifyId> = HashSet::new();
    let mut new_artist_ids: VecDeque<SpotifyId> = VecDeque::new();
    new_artist_ids.push_back(uri);
    while let Some(id) = new_artist_ids.pop_front() {
        known_artist_ids.insert(id);
        let artist = Artist::get(&session, &id).await.unwrap();
        for period in artist.activity_periods.0 {
            match period {
                ActivityPeriod::Decade(_) => decades += 1,
                ActivityPeriod::Timespan { end_year, .. } => match end_year {
                    Some(_) => closed_timespans += 1,
                    None => open_timespans += 1,
                },
            }
        }
        for artist in artist.related.0 {
            let id = artist.id;
            if !known_artist_ids.contains(&id) {
                new_artist_ids.push_back(artist.id);
            }
        }
        print!(
            "\rknown good artists: {} (decades: {decades}, \
            closed: {closed_timespans}, open: {open_timespans})",
            known_artist_ids.len()
        );
        std::io::stdout().flush().unwrap();
    }
}


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/librespot-org/librespot/pull/1055 **Author:** [@eladyn](https://github.com/eladyn) **Created:** 8/31/2022 **Status:** ✅ Merged **Merged:** 9/3/2022 **Merged by:** [@roderickvd](https://github.com/roderickvd) **Base:** `dev` ← **Head:** `strong_activity_periods` --- ### 📝 Commits (3) - [`df0d50f`](https://github.com/librespot-org/librespot/commit/df0d50fa647ba7af6e8ca0f58e16af4a1f4df119) strongly type ActivityPeriods - [`0c5926d`](https://github.com/librespot-org/librespot/commit/0c5926d5316a96a0d641b7ceff69e3ebf9df0556) use fallible conversion for ActivityPeriod - [`07336c2`](https://github.com/librespot-org/librespot/commit/07336c2e3113d713b2614c1a82601ae9c0779599) switch fallibly to unsigned integers ### 📊 Changes **2 files changed** (+44 additions, -14 deletions) <details> <summary>View changed files</summary> 📝 `core/src/error.rs` (+12 -1) 📝 `metadata/src/artist.rs` (+32 -13) </details> ### 📄 Description From my observations, `ActivityPeriod` **always** comes in one of the following three compositions: - `decade` - `start_year` (open timespan) - `start_year` + `end_year` (closed timespan) Thus, it probably makes sense to strongly type those variants into `ActivityPeriod`. I also added two `debug_assert!`s that make sure that the invariants that I assume are always held up. Alternatively, I could also turn them into normal `assert!`s or handle-able exceptions through `TryFrom`. I went for the current variants, since I think it makes most sense, but I'm open to different perspectives! I've verified my assumptions with the help of the below program for probably around 1000 different artists, so it should be fine? Some example outputs: - for `spotify:artist:5WUlDfRSoLAfcVSX1WnrxN`: `known good artists: 470 (decades: 203, closed: 4, open: 31)` - for `spotify:artist:3fMbdgg4jU18AjLCKBhRSm`: `known good artists: 333 (decades: 966, closed: 112, open: 216)` <details> ```rust use std::{ collections::{HashSet, VecDeque}, env, io::Write, process::exit, }; use librespot_core::{spotify_id::SpotifyItemType, Session, SessionConfig, SpotifyId}; use librespot_discovery::Credentials; use librespot_metadata::{artist::ActivityPeriod, Artist, Metadata}; #[tokio::main] async fn main() { env_logger::init(); let session_config = SessionConfig::default(); let args: Vec<_> = env::args().collect(); if args.len() != 4 && args.len() != 5 { eprintln!("Usage: {} USERNAME PASSWORD ARTIST_URI", args[0]); return; } let credentials = Credentials::with_password(&args[1], &args[2]); let uri = SpotifyId::from_uri(&args[3]).unwrap_or_else(|_| { eprintln!( "URI should be a URI such as: \ \"spotify:artist:5WUlDfRSoLAfcVSX1WnrxN\"" ); exit(1); }); if uri.item_type != SpotifyItemType::Artist { eprintln!("URI must be of item type artist!"); exit(1); } let session = Session::new(session_config, None); if let Err(e) = session.connect(credentials, false).await { eprintln!("Error connecting: {}", e); exit(1); } let mut decades = 0; let mut closed_timespans = 0; let mut open_timespans = 0; let mut known_artist_ids: HashSet<SpotifyId> = HashSet::new(); let mut new_artist_ids: VecDeque<SpotifyId> = VecDeque::new(); new_artist_ids.push_back(uri); while let Some(id) = new_artist_ids.pop_front() { known_artist_ids.insert(id); let artist = Artist::get(&session, &id).await.unwrap(); for period in artist.activity_periods.0 { match period { ActivityPeriod::Decade(_) => decades += 1, ActivityPeriod::Timespan { end_year, .. } => match end_year { Some(_) => closed_timespans += 1, None => open_timespans += 1, }, } } for artist in artist.related.0 { let id = artist.id; if !known_artist_ids.contains(&id) { new_artist_ids.push_back(artist.id); } } print!( "\rknown good artists: {} (decades: {decades}, \ closed: {closed_timespans}, open: {open_timespans})", known_artist_ids.len() ); std::io::stdout().flush().unwrap(); } } ``` </details> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
kerem 2026-02-27 20:01:35 +03:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/librespot#1212
No description provided.