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

Match Genius paths #29

Merged
merged 5 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 6 additions & 14 deletions src/album.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use crate::genius::{self, GeniusAlbumResponse};
use crate::settings::{settings_from_req, Settings};
use crate::utils;
use actix_web::HttpRequest;
use actix_web::{get, web, Responder, Result};
use actix_web::{get, Responder, Result};
use askama::Template;
use serde::Deserialize;

use crate::genius::GeniusAlbum;
use crate::templates::template;
Expand All @@ -16,18 +15,11 @@ struct AlbumTemplate {
album: GeniusAlbum,
}

#[derive(Debug, Deserialize)]
pub struct AlbumQuery {
path: String,
}

#[get("/album")]
pub async fn album(req: HttpRequest, info: web::Query<AlbumQuery>) -> Result<impl Responder> {
let album_res = genius::extract_data::<GeniusAlbumResponse>(&utils::ensure_path_prefix(
"albums", &info.path,
))
.await?;
let mut album = album_res.album;
#[get("/albums/{name:.*}")]
pub async fn album(req: HttpRequest) -> Result<impl Responder> {
let mut album = genius::extract_data::<GeniusAlbumResponse>(req.path())
.await?
.album;

album.tracks = Some(genius::get_album_tracks(album.id).await?);

Expand Down
26 changes: 7 additions & 19 deletions src/artist.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
use crate::settings::{settings_from_req, Settings};
use crate::utils;
use actix_web::{get, web, HttpRequest, Responder, Result};
use actix_web::{get, HttpRequest, Responder, Result};
use askama::Template;
use lazy_regex::*;
use regex::Regex;
use serde::Deserialize;

use crate::genius::{self, GeniusArtist};
use crate::genius::{GeniusArtistResponse, SortMode};
use crate::templates::template;

static GENIUS_IMAGE_URL: &str = "https://images.genius.com/";
static GENIUS_BASE_PATTERN: Lazy<Regex> = lazy_regex!(r#"https?://\w*.?genius\.com/"#);
static GENIUS_ALBUMS_PATTERN: Lazy<Regex> = lazy_regex!(r#"https?://\w*.?genius\.com/albums/"#);
static GENIUS_ARTIST_PATTERN: Lazy<Regex> = lazy_regex!(r#"https?://\w*.?genius\.com/artists/"#);

#[derive(Template)]
#[template(path = "artist.html")]
Expand All @@ -22,20 +19,13 @@ struct ArtistTemplate {
artist: GeniusArtist,
}

#[derive(Debug, Deserialize)]
pub struct ArtistQuery {
path: String,
}

const MAX_SONGS: u8 = 5;

#[get("/artist")]
pub async fn artist(req: HttpRequest, info: web::Query<ArtistQuery>) -> Result<impl Responder> {
let artist_res = genius::extract_data::<GeniusArtistResponse>(&utils::ensure_path_prefix(
"artists", &info.path,
))
.await?;
let mut artist = artist_res.artist;
#[get("/artists/{name}")]
pub async fn artist(req: HttpRequest) -> Result<impl Responder> {
let mut artist = genius::extract_data::<GeniusArtistResponse>(req.path())
.await?
.artist;

artist.popular_songs =
Some(genius::get_artist_songs(artist.id, SortMode::Popularity, MAX_SONGS).await?);
Expand All @@ -58,8 +48,6 @@ fn rewrite_links(html: &str) -> String {
GENIUS_IMAGE_URL,
&format!("/api/image?url={}", GENIUS_IMAGE_URL),
); // Images
let html = GENIUS_ALBUMS_PATTERN.replace_all(&html, "/album?path=albums/"); // Albums
let html = GENIUS_ARTIST_PATTERN.replace_all(&html, "/artist?path=artists/"); // Artists
let html = GENIUS_BASE_PATTERN.replace_all(&html, "/lyrics?path=/"); // Lyrics
let html = GENIUS_BASE_PATTERN.replace_all(&html, ""); // We follow Genius' schema
html.to_string()
}
20 changes: 13 additions & 7 deletions src/lyrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,34 +25,40 @@ struct Verse {

#[derive(Template)]
#[template(path = "lyrics.html")]
struct LyricsTemplate {
struct LyricsTemplate<'a> {
settings: Settings,
verses: Vec<Verse>,
query: LyricsQuery,
path: &'a str,
song: GeniusSong,
}

#[derive(Debug, Deserialize)]
pub struct LyricsQuery {
id: Option<u32>,
path: String,
}

#[get("/lyrics")]
#[get("/{path}-lyrics")]
pub async fn lyrics(req: HttpRequest, info: web::Query<LyricsQuery>) -> Result<impl Responder> {
let document: Html;
let song: GeniusSong;

// The '-lyrics' bit of the path gets cut off since we match for it explicitly,
// so we need to add it back here otherwise the path will be incorrect.
let path = &format!(
"{}-lyrics",
req.match_info().query("path").trim_end_matches('?')
);

if let Some(id) = info.id {
let responses = future::join(
genius::get_text(genius::SubDomain::Root, &info.path, None),
genius::get_text(genius::SubDomain::Root, path, None),
genius::get_song(id),
)
.await;
document = Html::parse_document(&responses.0?);
song = responses.1?;
} else {
let lyric_page = genius::get_text(genius::SubDomain::Root, &info.path, None).await?;
let lyric_page = genius::get_text(genius::SubDomain::Root, path, None).await?;
document = Html::parse_document(&lyric_page);
let id = get_song_id(&document)?;
song = genius::get_song(id).await?;
Expand All @@ -65,7 +71,7 @@ pub async fn lyrics(req: HttpRequest, info: web::Query<LyricsQuery>) -> Result<i
LyricsTemplate {
settings: settings_from_req(&req),
verses,
query: info.0,
path,
song,
},
))
Expand Down
2 changes: 1 addition & 1 deletion src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use include_dir::{include_dir, Dir};

const STATIC_RESOURCES: Dir = include_dir!("$CARGO_MANIFEST_DIR/static");

#[get("{resource}")]
#[get("{resource}.{ext}")]
pub async fn resource(path: web::Path<String>) -> impl Responder {
asset(path.as_str())
}
Expand Down
9 changes: 0 additions & 9 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,3 @@ pub fn borrowed_u8_eq(a: &u8, b: &u8) -> bool {
pub fn path_from_url(url: &str) -> String {
url.splitn(4, '/').last().unwrap().to_owned()
}

pub fn ensure_path_prefix(prefix: &'static str, path: &str) -> String {
let path = path.trim_start_matches('/');
if path.starts_with(prefix) {
path.to_string()
} else {
format!("{}/{}", prefix, path)
}
}
4 changes: 2 additions & 2 deletions templates/album.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<div class="song-info">
<p class="title">{{ album.name|e }}</p>
<p class="artist-name">By
<a href="artist?path={{ utils::path_from_url(album.artist.url)|urlencode }}">
<a href="/{{ utils::path_from_url(album.artist.url)|urlencode }}">
<cite>{{ album.artist.name|e }}</cite>
</a>
</p>
Expand All @@ -29,7 +29,7 @@
<p class="stats-release-date">Released on {{ album.release_date_for_display.as_ref().unwrap()|e }}</p>
{% endif %}
</div>
<img class="header-cover" src="api/image?url={{ album.cover_art_url|urlencode }}&size=500" alt="Thumbnail"/>
<img class="header-cover" src="/api/image?url={{ album.cover_art_url|urlencode }}&size=500" alt="Thumbnail"/>
</div>
<br/>
{% if album.tracks.is_some() %}
Expand Down
6 changes: 3 additions & 3 deletions templates/artist.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

{% block content %}
<div class="artist">
<img class="artist-image" src="api/image?url={{ artist.image_url|urlencode }}&size=500" alt="Thumbnail"/>
<img class="artist-image" src="/api/image?url={{ artist.image_url|urlencode }}&size=500" alt="Thumbnail"/>
<div class="artist-info">
<p class="artist-name">{{ artist.name|e }}</p>
{% if artist.alternate_names.is_some() && !artist.alternate_names.as_ref().unwrap().is_empty() %}
Expand All @@ -31,7 +31,7 @@
<div class="artist-socials">
{% for social in artist.socials() %}
<a class="social {{social.brand|e}}" href="https://{{social.brand}}.com/{{social.name_raw|urlencode}}">
<img class="social-icon" src="icon/{{social.brand}}.svg"/>
<img class="social-icon" src="/icon/{{social.brand}}.svg"/>
<p class="social-name">{{ social.name_formatted|e }}</p>
</a>
{% endfor %}
Expand All @@ -46,7 +46,7 @@ <h1 class="text-centered">Popular Songs</h1>
{% for song in artist.popular_songs.as_ref().unwrap() %}
{% include "song.html" %}
{% endfor %}
<a class="artist-search-songs text-centered" href="search?q={{ artist.name|urlencode }}">Search for songs</a>
<a class="artist-search-songs text-centered" href="/search?q={{ artist.name|urlencode }}">Search for songs</a>
</div>
{% endif %}
</div>
Expand Down
8 changes: 4 additions & 4 deletions templates/lyrics.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

{% block navright %}
<div class="nav-item.right">
<a class="external-link" href="https://genius.com{{ query.path|urlencode }}">View on Genius</a>
<a class="external-link" href="https://genius.com{{ path|urlencode }}">View on Genius</a>
</div>
{% endblock %}

Expand All @@ -16,13 +16,13 @@
<div class="song-info">
<p class="title">{{ song.title|e }}</p>
<p class="artist-name">By
<a href="artist?path={{ utils::path_from_url(song.primary_artist.url)|urlencode }}">
<a href="/{{ utils::path_from_url(song.primary_artist.url)|urlencode }}">
<cite>{{ song.primary_artist.name|e }}</cite>
</a>
</p>
{% if song.album.is_some() %}
<p class="album-name">On
<a href="album?path={{ utils::path_from_url(song.album.as_ref().unwrap().url)|urlencode }}">
<a href="/{{ utils::path_from_url(song.album.as_ref().unwrap().url)|urlencode }}">
<cite>{{ song.album.as_ref().unwrap().name|e }}</cite>
</a>
</p>
Expand All @@ -36,7 +36,7 @@
<p class="stats-views">{{ utils::pretty_format_num(song.stats.pageviews.unwrap())|e }} Views</p>
{% endif %}
</div>
<img class="header-cover" src="api/image?url={{ song.header_image_url|urlencode }}&size=500" alt="Thumbnail"/>
<img class="header-cover" src="/api/image?url={{ song.header_image_url|urlencode }}&size=500" alt="Thumbnail"/>
</div>
<br/>
{% for verse in verses %}
Expand Down
4 changes: 2 additions & 2 deletions templates/song.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<a class="song" href="lyrics?path={{ song.path|urlencode }}&id={{ song.id|urlencode }}">
<a class="song" href="{{ song.path|urlencode }}?id={{ song.id|urlencode }}">
<img class="song-thumbnail"
src="api/image?url={{ song.song_art_image_thumbnail_url|urlencode }}&size=150"
src="/api/image?url={{ song.song_art_image_thumbnail_url|urlencode }}&size=150"
alt="Thumbnail"
/>
<h2 class="song-title">{{ song.title|e }}</h2>
Expand Down
Loading