Compare commits

...

20 Commits
56.2 ... 58.2

Author SHA1 Message Date
5e0dffdc7a [release] Bump to version 58.2
Some checks failed
build / test (push) Successful in 2m5s
deploy / test (push) Successful in 2m3s
deploy / build-and-deploy (push) Failing after 25s
- Add more robust webpage scraping
- Time of Day Categories trend
2026-06-23 23:04:48 -04:00
2283a6c640 [webpages] Add more robust scraping 2026-06-23 23:04:30 -04:00
327ba94c63 [trends] Add new time of day trend
All checks were successful
build / test (push) Successful in 2m4s
2026-06-23 22:21:18 -04:00
ee59cde882 [release] Bump to version 58.1
All checks were successful
build / test (push) Successful in 2m7s
deploy / test (push) Successful in 2m8s
deploy / build-and-deploy (push) Successful in 1m5s
- Add auto genre tagging for papers
2026-06-23 16:19:06 -04:00
c7b4656679 [papers] Add genre tagging 2026-06-23 16:18:50 -04:00
04f9e00c9c [release] Bump to version 58.0
All checks were successful
deploy / test (push) Successful in 2m7s
build / test (push) Successful in 2m3s
deploy / build-and-deploy (push) Successful in 1m2s
- Add scrobbling of Papers via webpages with doi.org links in them
2026-06-23 14:28:40 -04:00
c2dabd1dac [papers] Fix scrobbling of academic papers 2026-06-23 14:28:16 -04:00
7a0cb8b9d0 [release] Bump to version 57.1
Some checks failed
build / test (push) Successful in 2m3s
deploy / test (push) Successful in 2m5s
deploy / build-and-deploy (push) Failing after 2m18s
- Write poetry lock file
2026-06-21 23:06:14 -04:00
1c2c570c4b [deps] Lock poetry 2026-06-21 23:05:58 -04:00
0671ab432f [release] Bump to version 57.0
Some checks failed
build / test (push) Failing after 35s
deploy / test (push) Failing after 37s
deploy / build-and-deploy (push) Has been skipped
- Scrobble button on some media list pages dont work
- Use HTMx to update the Now Playing widget
- Add a live page that updates the scrobble list via JS polling
- Turns out we cant cache the now playing widget
- What would it look like to add an MCP server to expose scrobbles and media items?
2026-06-21 23:04:23 -04:00
893867419a [templates] Shorten up naturalduration rep 2026-06-21 23:04:01 -04:00
d9dfec81aa [scrobbles] Fix bug where media list scrobble btns didnt work 2026-06-21 23:00:28 -04:00
948fbc19bf [templates] Add HTMX support to Now Playing 2026-06-21 23:00:09 -04:00
7d708ad8a6 [templates] Add polling live page for all scrobbles
Some checks failed
build / test (push) Failing after 35s
2026-06-21 22:39:46 -04:00
e0505cb82c [templates] Fix caching issue with Now Playing 2026-06-21 22:36:58 -04:00
ab6459e4b0 [mcp] Add a basic mcp service
Some checks failed
build / test (push) Failing after 31s
2026-06-21 01:26:16 -04:00
c001248d1b [release] Bump to version 56.4
All checks were successful
build / test (push) Successful in 2m0s
deploy / test (push) Successful in 1m59s
deploy / build-and-deploy (push) Successful in 49s
- Add ability to do reverse address lookup on lat-long pairs
- Add address fields to GeoLocation
- Add better detail template for Disc Golf Courses
2026-06-21 01:04:57 -04:00
f1c777d4ef [discgolf] Add trail maps and addresses
Some checks failed
build / test (push) Has been cancelled
2026-06-21 01:02:43 -04:00
931488c288 [release] Bump to version 56.3
Some checks failed
build / test (push) Has been cancelled
deploy / test (push) Successful in 1m58s
deploy / build-and-deploy (push) Successful in 32s
- Fix bug in importer script from discgolf being added
2026-06-20 01:12:33 -04:00
ab897fd848 [importers] Just fix a smol bug 2026-06-20 01:12:14 -04:00
53 changed files with 2952 additions and 244 deletions

View File

@ -604,6 +604,83 @@ independent of the email flow it was originally creatdd for
** TODO [#B] Is there way to create unique slugs for media instances :media_types:
* Version 58.2 [2/2]
** DONE [#B] Add more robust webpage scraping :webpages:metadata:
:PROPERTIES:
:ID: 84d9bfa5-75c0-0718-764e-379f7456602a
:END:
** DONE [#B] Time of Day Categories trend :trends:
:PROPERTIES:
:ID: 6598074f-2290-46db-967b-29f45d30be29
:END:
*** Description
Added a "Time of Day Categories" trend that groups scrobbles for Books, Trails,
Birding Locations, and Board Games into Early Bird (5-10:59am), Day Jay (11am-6:59pm),
and Night Owl (7pm-4:59am) buckets. Shows both overall and per-media-type breakdowns.
* Version 58.1 [1/1]
** DONE [#B] Add auto genre tagging for papers :books:papers:metadata:
:PROPERTIES:
:ID: e6b5c3a5-7fc6-b530-96c2-b5962a716db6
:END:
* Version 58.0 [1/1]
** DONE [#B] Add scrobbling of Papers via webpages with doi.org links in them :feature:papers:
:PROPERTIES:
:ID: d30bb8aa-eefd-002c-38d5-3f2fcef345f2
:END:
* Version 57.1 [1/1]
** DONE [#A] Write poetry lock file :bug:deps:
:PROPERTIES:
:ID: 0f5a6f4b-a486-ba7e-bbce-f7581274398c
:END:
* Version 57.0 [5/5]
** DONE [#A] Scrobble button on some media list pages dont work :bug:scrobbles:
:PROPERTIES:
:ID: a3a5c707-2e3d-a6b1-0f7f-4c6f7433aa1f
:END:
** DONE [#B] Use HTMx to update the Now Playing widget :feature:templates:
:PROPERTIES:
:ID: 5f5631fc-9ee1-d5a5-d0f8-94fea6fbbfa4
:END:
** DONE [#B] Add a live page that updates the scrobble list via JS polling :feature:templates:
:PROPERTIES:
:ID: 58790d76-dc6e-8aa5-2dc0-e64fe786fbf1
:END:
** DONE [#A] Turns out we cant cache the now playing widget :bug:templates:
:PROPERTIES:
:ID: 9ce669ea-c000-cdfe-a634-ad5cdaeae81c
:END:
** DONE [#C] What would it look like to add an MCP server to expose scrobbles and media items? :mcpserver:feature:
:PROPERTIES:
:ID: c5fca159-c7e0-5795-7c05-bbc48f539650
:END:
* Version 56.4 [3/3]
** DONE [#B] Add ability to do reverse address lookup on lat-long pairs :geolocations:feature:
:PROPERTIES:
:ID: 86c071ff-7638-41ba-6b65-1382df1cb5aa
:END:
** DONE [#B] Add address fields to GeoLocation :addresses:geolocation:
:PROPERTIES:
:ID: a55ae508-07ab-ccdd-e453-846bd3fca6fb
:END:
** DONE [#B] Add better detail template for Disc Golf Courses :discgolf:templates:
:PROPERTIES:
:ID: 12cee67c-f723-0fa3-848a-cbc6e4d65fc3
:END:
* Version 56.3 [1/1]
** DONE [#A] Fix bug in importer script from discgolf being added :bug:
:PROPERTIES:
:ID: c3733f96-18f1-eef8-f5d9-edaf97e35623
:END:
* Version 56.2 [1/1]
** DONE [#A] Fix bug in creating people when importing course plays :discgolf:bug:
:PROPERTIES:

835
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[tool.poetry]
name = "vrobbler"
version = "56.2"
version = "58.2"
description = ""
authors = ["Colin Powell <colin@unbl.ink>"]
@ -9,8 +9,10 @@ python = ">=3.11,<3.15"
Django = "^4.0.3"
django-extensions = "^3.1.5"
python-dateutil = "^2.8.2"
python-dotenv = "^0.20.0"
python-dotenv = ">=0.20.0,<2"
python-json-logger = "^2.0.2"
cloudscraper = "^1.2.71"
curl-cffi = "^0.15.0"
colorlog = "^6.6.0"
httpx = "<=0.27.2"
djangorestframework = "^3.13.1"
@ -43,6 +45,7 @@ ipython = "^8.14.0"
pendulum = "^3"
trafilatura = "^1.6.3"
django-imagekit = "^5.0.0"
django-mcp-server = "^0.5.7"
thefuzz = "^0.22.1"
dataclass-wizard = "^0.35.0"
webdavclient3 = "^3.14.6"
@ -65,6 +68,7 @@ lxml = ">=5.5.0"
vaderSentiment = "^3.3.2"
sqids = "^0.5.2"
python-amazon-paapi = "^6.3.0"
yake = "^0.7.3"
[tool.poetry.group.test]
optional = true

View File

@ -1,8 +1,19 @@
from books.models import Author, Book, Paper
from books.models import Author, Book, Journal, Paper
from django.contrib import admin
from scrobbles.admin import ScrobbleInline
@admin.register(Journal)
class JournalAdmin(admin.ModelAdmin):
date_hierarchy = "created"
list_display = (
"title",
"website_url",
)
search_fields = ("title",)
ordering = ("-created",)
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
date_hierarchy = "created"

View File

@ -0,0 +1,18 @@
# Generated by Django 4.2.29 on 2026-06-23 14:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("books", "0037_book_volume_book_volume_comicvine_id"),
]
operations = [
migrations.AddField(
model_name="paper",
name="pdf_file",
field=models.FileField(blank=True, null=True, upload_to="papers/pdf/"),
),
]

View File

@ -0,0 +1,92 @@
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import uuid
def migrate_journal_data(apps, schema_editor):
Paper = apps.get_model("books", "Paper")
Journal = apps.get_model("books", "Journal")
for paper in Paper.objects.all():
old_journal = getattr(paper, "journal", None)
if old_journal:
journal, _ = Journal.objects.get_or_create(title=str(old_journal))
paper._journal_tmp = journal
paper.save(update_fields=["_journal_tmp"])
def reverse_migrate_journal_data(apps, schema_editor):
Paper = apps.get_model("books", "Paper")
for paper in Paper.objects.all():
if paper._journal_tmp:
paper.journal = paper._journal_tmp.title
paper.save(update_fields=["journal"])
class Migration(migrations.Migration):
dependencies = [
("books", "0038_paper_pdf_file"),
]
operations = [
migrations.CreateModel(
name="Journal",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"created",
django_extensions.db.fields.CreationDateTimeField(
auto_now_add=True, verbose_name="created"
),
),
(
"modified",
django_extensions.db.fields.ModificationDateTimeField(
auto_now=True, verbose_name="modified"
),
),
(
"uuid",
models.UUIDField(
blank=True, default=uuid.uuid4, editable=False, null=True
),
),
("title", models.CharField(max_length=255)),
("description", models.TextField(blank=True, null=True)),
("website_url", models.URLField(blank=True, max_length=500, null=True)),
],
options={
"get_latest_by": "modified",
"abstract": False,
},
),
migrations.AddField(
model_name="paper",
name="_journal_tmp",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
to="books.journal",
),
),
migrations.RunPython(migrate_journal_data, reverse_migrate_journal_data),
migrations.RemoveField(
model_name="paper",
name="journal",
),
migrations.RenameField(
model_name="paper",
old_name="_journal_tmp",
new_name="journal",
),
]

View File

@ -27,7 +27,11 @@ from books.sources.amazon import lookup_book_from_amazon
from books.sources.openlibrary import (
lookup_book_from_openlibrary as lookup_book_from_ol,
)
from books.sources.semantic import lookup_paper_from_semantic
from books.sources.semantic import (
lookup_paper_from_semantic,
lookup_paper_from_semantic_by_doi,
)
from books.sources.scihub import SciHubService
from books.utils import get_comic_issue_url
from django.conf import settings
from django.contrib.auth import get_user_model
@ -82,6 +86,16 @@ class BookLogData(BaseLogData, LongPlayLogData):
return int(total_duration / len(self.page_data))
class Journal(TimeStampedModel):
uuid = models.UUIDField(default=uuid4, editable=False, **BNULL)
title = models.CharField(max_length=255)
description = models.TextField(**BNULL)
website_url = models.URLField(max_length=500, **BNULL)
def __str__(self):
return self.title
class Author(TimeStampedModel):
name = models.CharField(max_length=255)
uuid = models.UUIDField(default=uuid4, editable=False, **BNULL)
@ -540,6 +554,21 @@ class Book(LongPlayScrobblableMixin):
return progress
@dataclass
class PaperLogData(BaseLogData):
@classmethod
def override_fields(cls) -> dict:
from scrobbles.forms import NotesDictField
fields = {}
for base in cls.mro()[1:]:
if hasattr(base, "override_fields"):
base_fields = base.override_fields()
fields.update(base_fields)
fields["notes"] = NotesDictField(required=False)
return fields
class Paper(LongPlayScrobblableMixin):
"""Keeps track of Academic Papers"""
@ -559,14 +588,29 @@ class Paper(LongPlayScrobblableMixin):
language = models.CharField(max_length=4, **BNULL)
first_publish_year = models.IntegerField(**BNULL)
publish_date = models.DateField(**BNULL)
journal = models.CharField(max_length=255, **BNULL)
journal = models.ForeignKey(Journal, on_delete=models.DO_NOTHING, **BNULL)
journal_volume = models.CharField(max_length=50, **BNULL)
abstract = models.TextField(**BNULL)
tldr = models.CharField(max_length=255, **BNULL)
openaccess_pdf_url = models.CharField(max_length=255, **BNULL)
pdf_file = models.FileField(upload_to="papers/pdf/", **BNULL)
genre = TaggableManager(through=ObjectWithGenres, blank=True, verbose_name="Genre")
@property
def logdata_cls(self):
return PaperLogData
@property
def scihub_url(self):
if not self.doi_id:
return None
domain = getattr(settings, "SCIHUB_DOMAIN", "sci-hub.st")
return f"https://{domain}/{self.doi_id}"
def get_absolute_url(self):
return reverse("books:paper_detail", kwargs={"slug": self.uuid})
@classmethod
def get_from_semantic(cls, title: str, overwrite: bool = False) -> "Paper":
paper, created = cls.objects.get_or_create(title=title)
@ -577,7 +621,7 @@ class Paper(LongPlayScrobblableMixin):
if created or overwrite:
author_list = []
author_dicts = paper_dict.pop("author_dicts")
author_dicts = paper_dict.pop("author_dicts", None)
if author_dicts:
for author_dict in author_dicts:
if author_dict.get("authorId"):
@ -588,8 +632,11 @@ class Paper(LongPlayScrobblableMixin):
if a_created:
author.name = author_dict.get("name")
author.save()
# TODO enrich author?
...
journal_name = paper_dict.pop("journal_name", None)
if journal_name:
journal, _ = Journal.objects.get_or_create(title=journal_name)
paper.journal = journal
for k, v in paper_dict.items():
setattr(paper, k, v)
@ -601,3 +648,78 @@ class Paper(LongPlayScrobblableMixin):
if genres:
paper.genre.add(*genres)
return paper
@classmethod
def find_or_create_by_doi(cls, doi_url: str) -> "Paper":
doi = doi_url.replace("https://doi.org/", "").split("?")[0].rstrip("/")
paper = cls.objects.filter(doi_id=doi).first()
if paper:
return paper
paper = cls(doi_id=doi, title=f"Paper {doi}")
paper.save()
from books.sources.crossref import lookup_paper_from_crossref
paper_dict = lookup_paper_from_semantic_by_doi(doi)
if not paper_dict or not paper_dict.get("abstract"):
paper_dict = lookup_paper_from_crossref(doi)
if paper_dict:
author_list = []
author_dicts = paper_dict.pop("author_dicts", None)
if author_dicts:
for author_dict in author_dicts:
author_id = author_dict.get("authorId")
if author_id:
author, a_created = Author.objects.get_or_create(
semantic_id=author_id
)
author_list.append(author)
if a_created:
author.name = author_dict.get("name")
author.save()
else:
author_name = author_dict.get("name")
if author_name:
author, a_created = Author.objects.get_or_create(
name=author_name
)
author_list.append(author)
journal_name = paper_dict.pop("journal_name", None)
if journal_name:
journal, _ = Journal.objects.get_or_create(title=journal_name)
paper.journal = journal
for k, v in paper_dict.items():
if v is not None:
setattr(paper, k, v)
paper.save()
if author_list:
paper.authors.add(*author_list)
genres = paper_dict.pop("genres", [])
if genres:
paper.genre.add(*genres)
if not paper.pdf_file:
service = SciHubService()
if paper.openaccess_pdf_url:
pdf_content = service.fetch_from_url(paper.openaccess_pdf_url)
if pdf_content:
filename = f"{doi.replace('/', '_')}.pdf"
paper.pdf_file.save(filename, ContentFile(pdf_content))
if not paper.pdf_file:
try:
pdf_content = service.fetch_pdf(doi)
if pdf_content:
filename = f"{doi.replace('/', '_')}.pdf"
paper.pdf_file.save(filename, ContentFile(pdf_content))
except Exception as e:
logger.error(
"[paper] sci-hub PDF download failed",
extra={"doi": doi, "error": str(e)},
)
return paper

View File

@ -0,0 +1,149 @@
import json
import logging
import re
import requests
import yake
CROSSREF_WORK_URL = "https://api.crossref.org/works/{}"
logger = logging.getLogger(__name__)
_STOPWORDS = {
"this", "that", "these", "those", "the", "a", "an", "in", "on", "at",
"to", "for", "of", "and", "or", "is", "are", "was", "were", "be",
"been", "being", "have", "has", "had", "do", "does", "did", "will",
"would", "can", "could", "may", "might", "shall", "should", "not",
"no", "nor", "with", "from", "by", "as", "at", "but", "if", "because",
"while", "although", "however", "we", "our", "their", "its", "it",
"they", "them", "also", "more", "most", "new", "such", "into",
"across", "between", "through", "about", "after", "before", "during",
"within", "without", "other", "many", "some", "each", "every", "both",
"few", "own", "via",
}
_DROP_PHRASES = {
"paper", "study", "studies", "research", "introduction", "conclusion",
"conclusions", "background", "methods", "results", "findings",
"analysis", "approach", "approaches", "framework", "theory",
"theories", "concept", "concepts", "model", "models", "process",
"processes", "role", "roles", "factor", "factors", "effect",
"effects", "impact", "implication", "implications", "actor", "actors",
"article", "chapter", "section", "discussion", "review", "overview",
"summary", "methodology", "special issue", "implications",
"limitations", "findings", "purpose", "objective", "objectives",
"design", "setting", "participants", "sample", "data",
"contemporary", "little", "empirical", "theoretical",
"organizations", "dissent",
}
def _strip_jats(text: str) -> str:
if not text:
return ""
text = re.sub(r"</?jats:[^>]*>", "", text)
text = re.sub(r"^\s*Abstract\s*", "", text)
return text.strip()
def _extract_genres_from_abstract(abstract: str, max_keywords: int = 8) -> list[str]:
if not abstract or len(abstract) < 50:
return []
kw_extractor = yake.KeywordExtractor(lan="en", n=2, top=max_keywords)
keywords = kw_extractor.extract_keywords(abstract)
genres = []
seen = set()
for kw, score in keywords:
kw_lower = kw.lower().strip()
if kw_lower in seen or kw_lower in _DROP_PHRASES:
continue
words = [w for w in kw_lower.split() if w not in _STOPWORDS]
cleaned = " ".join(words)
if not cleaned or len(cleaned) < 3 or cleaned in seen:
continue
if cleaned in _DROP_PHRASES:
continue
seen.add(cleaned)
genres.append(cleaned)
return genres
def lookup_paper_from_crossref(doi: str) -> dict:
url = CROSSREF_WORK_URL.format(doi)
headers = {"User-Agent": "Vrobbler/1.0 (mailto:hello@example.com)"}
response = requests.get(url, headers=headers)
if response.status_code != 200:
logger.warning(
"Bad response from Crossref",
extra={"doi": doi, "status": response.status_code},
)
return {"doi_id": doi}
try:
data = response.json()
except json.JSONDecodeError:
return {"doi_id": doi}
msg = data.get("message", {})
if not msg:
return {"doi_id": doi}
paper_dict = {"doi_id": doi}
titles = msg.get("title", [])
if titles:
paper_dict["title"] = titles[0]
abstract = msg.get("abstract", "")
if abstract:
stripped = _strip_jats(abstract)
paper_dict["abstract"] = stripped
genres = _extract_genres_from_abstract(stripped)
if genres:
paper_dict["genres"] = genres
author_dicts = []
for author in msg.get("author", []):
given = author.get("given", "")
family = author.get("family", "")
name = f"{given} {family}".strip()
if not name:
continue
entry = {"name": name}
orcid = author.get("ORCID", "")
if orcid:
orcid_id = orcid.replace("https://orcid.org/", "")
entry["authorId"] = orcid_id
author_dicts.append(entry)
if author_dicts:
paper_dict["author_dicts"] = author_dicts
container = msg.get("container-title", [])
if container:
paper_dict["journal_name"] = container[0]
volume = msg.get("volume")
if volume:
paper_dict["journal_volume"] = volume
page = msg.get("page")
if page:
try:
parts = page.split("-")
if len(parts) == 2:
paper_dict["pages"] = int(parts[1]) - int(parts[0])
except (ValueError, IndexError):
pass
for date_field in ("published-print", "published-online", "created"):
date_data = msg.get(date_field)
if date_data and date_data.get("date-parts"):
parts = date_data["date-parts"][0]
if len(parts) >= 1:
paper_dict["first_publish_year"] = int(parts[0])
if len(parts) >= 3:
paper_dict["publish_date"] = f"{parts[0]:04d}-{parts[1]:02d}-{parts[2]:02d}"
break
return paper_dict

View File

@ -0,0 +1,142 @@
import logging
from typing import Optional
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
from django.conf import settings
logger = logging.getLogger(__name__)
SCIHUB_DOMAINS = [
"sci-hub.ru",
"sci-hub.ee",
"sci-hub.st",
"sci-hub.do",
]
class SciHubService:
def __init__(self):
self.session = requests.Session()
self.session.headers.update(
{
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
)
def fetch_from_url(self, url: str) -> Optional[bytes]:
try:
resp = self.session.get(url, timeout=60)
if resp.status_code != 200:
logger.warning(
"[pdf] URL download failed",
extra={"status": resp.status_code, "url": url},
)
return None
if not self._looks_like_pdf(resp):
return None
return resp.content
except requests.RequestException as e:
logger.error(
"[pdf] URL download request failed",
extra={"url": url, "error": str(e)},
)
return None
def fetch_pdf(self, doi: str) -> Optional[bytes]:
configured_domain = getattr(settings, "SCIHUB_DOMAIN", None)
domains_to_try = (
[configured_domain] + SCIHUB_DOMAINS
if configured_domain and configured_domain not in SCIHUB_DOMAINS
else SCIHUB_DOMAINS
)
for domain in domains_to_try:
url = f"https://{domain}/{doi}"
logger.info(
"[scihub] trying domain",
extra={"domain": domain, "doi": doi},
)
try:
response = self.session.get(url, timeout=30)
if response.status_code != 200:
continue
pdf_url = self._extract_pdf_url(response.text, url)
if not pdf_url:
continue
pdf_response = self.session.get(pdf_url, timeout=60)
if pdf_response.status_code != 200:
continue
if not self._looks_like_pdf(pdf_response):
continue
logger.info(
"[scihub] PDF downloaded successfully",
extra={
"domain": domain,
"doi": doi,
"size": len(pdf_response.content),
},
)
return pdf_response.content
except requests.RequestException as e:
logger.debug(
"[scihub] domain failed",
extra={"domain": domain, "doi": doi, "error": str(e)},
)
continue
logger.warning(
"[scihub] all domains failed",
extra={"doi": doi, "tried": domains_to_try},
)
return None
def _looks_like_pdf(self, response: requests.Response) -> bool:
content_type = response.headers.get("Content-Type", "")
if "application/pdf" in content_type:
return True
if content_type.startswith("application/octet"):
return True
if response.url.endswith(".pdf"):
return True
return False
def _extract_pdf_url(self, html: str, page_url: str) -> Optional[str]:
soup = BeautifulSoup(html, "html.parser")
iframe = soup.find("iframe", {"id": "pdf"})
if iframe and iframe.get("src"):
src = iframe["src"]
if src.startswith("http"):
return src
return urljoin(page_url, src)
embed = soup.find("embed", {"type": "application/pdf"})
if embed and embed.get("src"):
src = embed["src"]
if src.startswith("http"):
return src
return urljoin(page_url, src)
download_div = soup.find("div", {"id": "download"})
if download_div:
link = download_div.find("a")
if link and link.get("href"):
href = link["href"]
if href.startswith("http"):
return href
return urljoin(page_url, href)
for link in soup.find_all("a", href=True):
href = link["href"]
if ".pdf" in href:
if href.startswith("http"):
return href
return urljoin(page_url, href)
return None

View File

@ -9,6 +9,7 @@ PAPER_SEARCH_URL = (
"https://api.semanticscholar.org/graph/v1/paper/search/match?query={}"
)
PAPER_DETAIL_URL = "https://api.semanticscholar.org/graph/v1/paper/{}?fields=title,authors,url,year,abstract,externalIds,citationCount,referenceCount,journal,fieldsOfStudy,publicationDate,openAccessPdf"
PAPER_DOI_URL = "https://api.semanticscholar.org/graph/v1/paper/DOI:{}?fields=title,authors,url,year,abstract,externalIds,citationCount,referenceCount,journal,fieldsOfStudy,publicationDate,openAccessPdf"
logger = logging.getLogger(__name__)
@ -39,6 +40,18 @@ def lookup_paper_from_semantic(title: str) -> dict:
if not result:
return paper_dict
paper_dict.update(_parse_semantic_result(result))
paper_dict.setdefault("title", title)
if paper_dict.get("publish_date"):
paper_dict["publish_date"] = datetime.strptime(
paper_dict["publish_date"], "%Y-%m-%d"
)
return paper_dict
def _parse_semantic_result(result: dict) -> dict:
paper_dict = {}
page_str = result.get("journal", {}).get("pages")
if page_str:
try:
@ -55,12 +68,10 @@ def lookup_paper_from_semantic(title: str) -> dict:
paper_dict["corpus_id"] = result.get("externalIds", {}).get("CorpusId")
paper_dict["semantic_title"] = result.get("title")
paper_dict["first_publish_year"] = result.get("year")
paper_dict["publish_date"] = datetime.strptime(
result.get("publicationDate", "1950-01-01"), "%Y-%m-%d"
)
paper_dict["publish_date"] = result.get("publicationDate")
paper_dict["abstract"] = result.get("abstract")
paper_dict["tldr"] = result.get("bib", {}).get("abstract")
paper_dict["journal"] = result.get("journal", {}).get("name")
paper_dict["journal_name"] = result.get("journal", {}).get("name")
paper_dict["journal_volume"] = result.get("journal", {}).get("volume")
paper_dict["openaccess_pdf_url"] = result.get("openAccessPdf", {}).get("url")
paper_dict["base_run_time_seconds"] = paper_dict.get("pages", 10) * getattr(
@ -68,5 +79,19 @@ def lookup_paper_from_semantic(title: str) -> dict:
)
paper_dict["author_dicts"] = result.get("authors")
paper_dict["genres"] = result.get("fieldsOfStudy")
return paper_dict
def lookup_paper_from_semantic_by_doi(doi: str) -> dict:
response = get_api_result(PAPER_DOI_URL.format(doi))
if not response:
return {"doi_id": doi}
result = json.loads(response.content)
if not result:
return {"doi_id": doi}
paper_dict = _parse_semantic_result(result)
if not paper_dict.get("title"):
paper_dict["title"] = result.get("title", f"Paper {doi}")
return paper_dict

View File

@ -16,4 +16,15 @@ urlpatterns = [
views.AuthorDetailView.as_view(),
name="author_detail",
),
path("papers/", views.PaperListView.as_view(), name="paper_list"),
path(
"papers/<slug:slug>/",
views.PaperDetailView.as_view(),
name="paper_detail",
),
path(
"papers/<slug:slug>/upload_pdf/",
views.PaperUploadPdfView.as_view(),
name="paper_upload_pdf",
),
]

View File

@ -1,5 +1,8 @@
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import View
from django.views import generic
from books.models import Book, Author
from books.models import Book, Author, Paper
from scrobbles.views import ScrobbleableListView, ScrobbleableDetailView
@ -15,3 +18,24 @@ class BookDetailView(ScrobbleableDetailView):
class AuthorDetailView(generic.DetailView):
model = Author
slug_field = "uuid"
class PaperListView(ScrobbleableListView):
model = Paper
class PaperDetailView(ScrobbleableDetailView):
model = Paper
class PaperUploadPdfView(View):
def post(self, request, slug):
paper = Paper.objects.filter(uuid=slug).first()
if not paper or not request.user.is_authenticated:
return HttpResponseRedirect(reverse("books:paper_detail", args=[slug]))
pdf_file = request.FILES.get("pdf_file")
if pdf_file:
paper.pdf_file.save(pdf_file.name, pdf_file)
return HttpResponseRedirect(reverse("books:paper_detail", args=[slug]))

View File

@ -6,7 +6,7 @@ from scrobbles.admin import ScrobbleInline
@admin.register(DiscGolfCourse)
class DiscGolfCourseAdmin(admin.ModelAdmin):
date_hierarchy = "created"
list_display = ("title", "layout_name", "number_of_holes", "par_total")
list_display = ("title", "layout_name", "number_of_holes", "par_total", "pdga_slug", "udisc_id")
raw_id_fields = ("trail",)
search_fields = ("title", "layout_name")
inlines = [

View File

@ -3,6 +3,9 @@ from rest_framework import serializers
class DiscGolfCourseSerializer(serializers.HyperlinkedModelSerializer):
pdga_link = serializers.ReadOnlyField()
udisc_link = serializers.ReadOnlyField()
class Meta:
model = models.DiscGolfCourse
fields = "__all__"

View File

@ -0,0 +1,23 @@
# Generated by Django 4.2.29 on 2026-06-21 04:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("discgolf", "0003_discgolfcourse_par_per_hole"),
]
operations = [
migrations.AddField(
model_name="discgolfcourse",
name="pdga_slug",
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name="discgolfcourse",
name="udisc_id",
field=models.CharField(blank=True, max_length=255, null=True),
),
]

View File

@ -39,6 +39,20 @@ class DiscGolfCourse(ScrobblableMixin):
trail = models.ForeignKey(
"trails.Trail", on_delete=models.DO_NOTHING, **BNULL
)
pdga_slug = models.CharField(max_length=255, **BNULL)
udisc_id = models.CharField(max_length=255, **BNULL)
@property
def pdga_link(self) -> str:
if self.pdga_slug:
return f"https://www.pdga.com/course-directory/course/{self.pdga_slug}/"
return ""
@property
def udisc_link(self) -> str:
if self.udisc_id:
return f"https://udisc.com/courses/{self.udisc_id}/"
return ""
def get_absolute_url(self) -> str:
return reverse("discgolf:course_detail", kwargs={"slug": self.uuid})

View File

@ -1,3 +1,5 @@
from django.apps import apps
from discgolf.models import DiscGolfCourse
from scrobbles.views import (
@ -13,3 +15,18 @@ class DiscGolfCourseListView(ScrobbleableListView):
class DiscGolfCourseDetailView(ScrobbleableDetailView, ChartContextMixin):
model = DiscGolfCourse
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
Scrobble = apps.get_model("scrobbles", "Scrobble")
context["trail_gpx_url"] = None
latest = (
Scrobble.objects.filter(
trail=self.object.trail, gpx_file__isnull=False
)
.order_by("-timestamp")
.first()
)
if latest and latest.gpx_file:
context["trail_gpx_url"] = latest.gpx_file.url
return context

View File

@ -1,4 +1,7 @@
import time
from django.contrib import admin
from django.http import HttpRequest
from locations.models import GeoLocation
@ -14,9 +17,29 @@ class GeoLocationAdmin(admin.ModelAdmin):
"lon",
"title",
"altitude",
"city",
"state_province",
"country",
)
ordering = ("-created",)
search_fields = ("title",)
actions = ["reverse_geocode_selected"]
inlines = [
ScrobbleInline,
]
@admin.action(description="Reverse geocode selected locations")
def reverse_geocode_selected(self, request: HttpRequest, queryset):
updated = 0
errors = 0
for i, location in enumerate(queryset.iterator()):
if location.reverse_geocode():
updated += 1
else:
errors += 1
if i < queryset.count() - 1:
time.sleep(1.1)
msg = f"Reverse geocoded {updated} locations"
if errors:
msg += f", {errors} failed"
self.message_user(request, msg)

View File

@ -0,0 +1,38 @@
# Generated by Django 4.2.29 on 2026-06-21 04:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("locations", "0010_clean_start"),
]
operations = [
migrations.AddField(
model_name="geolocation",
name="city",
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name="geolocation",
name="country",
field=models.CharField(blank=True, max_length=100, null=True),
),
migrations.AddField(
model_name="geolocation",
name="postal_code",
field=models.CharField(blank=True, max_length=20, null=True),
),
migrations.AddField(
model_name="geolocation",
name="state_province",
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name="geolocation",
name="street",
field=models.TextField(blank=True, null=True),
),
]

View File

@ -45,6 +45,11 @@ class GeoLocation(ScrobblableMixin):
truncated_lat = models.FloatField(**BNULL)
truncated_lon = models.FloatField(**BNULL)
altitude = models.FloatField(**BNULL)
street = models.TextField(**BNULL)
city = models.CharField(max_length=255, **BNULL)
state_province = models.CharField(max_length=255, **BNULL)
postal_code = models.CharField(max_length=20, **BNULL)
country = models.CharField(max_length=100, **BNULL)
class Meta:
unique_together = [["lat", "lon", "altitude"]]
@ -55,6 +60,11 @@ class GeoLocation(ScrobblableMixin):
return f"{self.lat} x {self.lon}"
@property
def display_address(self) -> str:
parts = [self.street, self.city, self.state_province, self.postal_code, self.country]
return ", ".join(p for p in parts if p)
def get_absolute_url(self):
return reverse("locations:geolocation_detail", kwargs={"slug": self.uuid})
@ -121,6 +131,17 @@ class GeoLocation(ScrobblableMixin):
return fetch_current_weather(self.lat, self.lon)
def reverse_geocode(self) -> bool:
from locations.utils import reverse_geocode
result = reverse_geocode(self.lat, self.lon)
if result is None:
return False
for field, value in result.items():
setattr(self, field, value)
self.save(update_fields=list(result.keys()))
return True
def loc_diff(self, old_lat_lon: tuple) -> tuple:
return (
abs(Decimal(old_lat_lon[0]) - Decimal(self.lat)),

View File

@ -201,6 +201,50 @@ def detect_movement(
return result
NOMINATIM_URL = "https://nominatim.openstreetmap.org/reverse"
USER_AGENT = "Vrobbler/1.0 (https://github.com/secstate/vrobbler)"
def reverse_geocode(lat: float, lon: float) -> Optional[dict]:
"""Reverse geocode lat/lon to an address using Nominatim.
Returns a dict with address fields, or None on failure.
Nominatim usage policy: max 1 request per second.
"""
params = {
"lat": lat,
"lon": lon,
"format": "json",
}
headers = {"User-Agent": USER_AGENT}
try:
resp = requests.get(NOMINATIM_URL, params=params, headers=headers, timeout=10)
resp.raise_for_status()
except requests.RequestException as e:
logger.warning("Failed to reverse geocode %s,%s: %s", lat, lon, e)
return None
data = resp.json()
if "error" in data:
logger.warning("Nominatim error for %s,%s: %s", lat, lon, data["error"])
return None
address = data.get("address", {})
return {
"street": address.get("road")
or address.get("pedestrian")
or address.get("footway"),
"city": address.get("city")
or address.get("town")
or address.get("village")
or address.get("hamlet"),
"state_province": address.get("state"),
"postal_code": address.get("postcode"),
"country": address.get("country"),
}
NWS_URL = "https://forecast.weather.gov/MapClick.php"

View File

@ -40,6 +40,7 @@ class UserProfileForm(forms.ModelForm):
"enable_public_widgets",
"widget_custom_css",
"home_scrobble_limit",
"live_now_playing",
"weigh_in_units",
]
widgets = {

View File

@ -0,0 +1,18 @@
# Generated by Django 4.2.29 on 2026-06-22 02:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("profiles", "0038_userprofile_media_type_visibility"),
]
operations = [
migrations.AddField(
model_name="userprofile",
name="live_now_playing",
field=models.BooleanField(default=False),
),
]

View File

@ -98,6 +98,8 @@ class UserProfile(TimeStampedModel):
home_scrobble_limit = models.IntegerField(default=20)
live_now_playing = models.BooleanField(default=False)
weigh_in_units = models.CharField(
max_length=16,
choices=WeighUnit.choices,

View File

@ -14,6 +14,7 @@ LONG_PLAY_MEDIA = {
"books": "Book",
"bricksets": "BrickSet",
"tasks": "Task",
"papers": "Paper",
}
# Media types that should just be finished if they go over time
@ -25,16 +26,24 @@ AUTO_FINISH_MEDIA = {
}
PLAY_AGAIN_MEDIA = {
"videogames": "VideoGame",
"videos": "Video",
"music": "Track",
"podcasts": "PodcastEpisode",
"sports": "SportEvent",
"books": "Book",
"videogames": "VideoGame",
"boardgames": "BoardGame",
"moods": "Mood",
"bricksets": "BrickSet",
"locations": "GeoLocation",
"trails": "Trail",
"beers": "Beer",
"puzzles": "Puzzle",
"foods": "Food",
"locations": "GeoLocation",
"videos": "Video",
"tasks": "Task",
"webpages": "WebPage",
"lifeevents": "LifeEvent",
"moods": "Mood",
"bricksets": "BrickSet",
"channels": "Channel",
"birds": "BirdingLocation",
"discgolf": "DiscGolfCourse",
}
@ -53,6 +62,7 @@ SCROBBLE_CONTENT_URLS = {
"-b": ["https://www.amazon.com/"],
"-t": ["https://app.todoist.com/app/task/{id}"],
"-p": ["https://www.ipdb.plus/IPDb/puzzle.php?id="],
"-pp": ["https://doi.org/"],
"-l": ["https://brickset.com/sets/"],
"-c": ["https://readcomicsonline.ru"],
"-h": ["https://www.twitch.tv/"],
@ -75,6 +85,7 @@ MANUAL_SCROBBLE_FNS = {
"-f": "manual_scrobble_food",
"-h": "manual_scrobble_twitch_channel",
"-dg": "manual_scrobble_discgolf",
"-pp": "manual_scrobble_paper",
}

View File

@ -1,5 +1,4 @@
import pytz
from django.core.cache import cache
from django.utils import timezone
from scrobbles.constants import EXCLUDE_FROM_NOW_PLAYING
@ -20,8 +19,6 @@ MONTH_COLORS = [
"#db7a7a", # Dec
]
CACHE_TTL = 60
def month_color(request):
from datetime import date
@ -33,10 +30,8 @@ def now_playing(request):
if not user.is_authenticated:
return {}
cache_key = f"now_playing_list_{user.id}"
now_playing_list = cache.get(cache_key)
if now_playing_list is None:
now_playing_list = list(
return {
"now_playing_list": list(
Scrobble.objects.filter(
in_progress=True,
is_paused=False,
@ -46,9 +41,5 @@ def now_playing(request):
media_type__in=EXCLUDE_FROM_NOW_PLAYING,
)
.select_related("track", "video", "podcast_episode")
)
cache.set(cache_key, now_playing_list, CACHE_TTL)
return {
"now_playing_list": now_playing_list,
),
}

View File

@ -93,6 +93,7 @@ def import_from_webdav_for_all_users(
bgstats_count,
ebird_count,
scale_count,
udisc_count,
extra={
"koreader": ko_count,
"trail_gpx": gpx_count,

View File

@ -0,0 +1,518 @@
from mcp_server import MCPToolset
from scrobbles.models import Scrobble
from scrobbles.constants import LONG_PLAY_MEDIA
class ScrobbleToolset(MCPToolset):
def list_recent_scrobbles(
self,
days: int = 7,
media_type: str | None = None,
limit: int = 50,
) -> list[dict]:
"""List scrobbles from the last N days, optionally filtered by media type.
Valid media_type values: Video, Track, PodcastEpisode, SportEvent, Book,
Paper, VideoGame, BoardGame, GeoLocation, Trail, Beer, Puzzle, Food, Task,
WebPage, LifeEvent, Mood, BrickSet, Channel, BirdingLocation, DiscGolfCourse
"""
qs = (
Scrobble.objects.filter(user=self.request.user)
.select_related(
"video", "track", "book", "video_game", "board_game",
"beer", "puzzle", "food", "trail", "task", "web_page",
"life_event", "mood", "brick_set", "podcast_episode",
"sport_event", "geo_location", "birding_location",
"disc_golf_course", "channel",
)
.order_by("-timestamp")
)
from django.utils import timezone
import datetime
qs = qs.filter(timestamp__gte=timezone.now() - datetime.timedelta(days=days))
if media_type:
qs = qs.filter(media_type=media_type)
qs = qs[:limit]
return [_scrobble_to_dict(s) for s in qs]
def get_scrobble(self, uuid: str) -> dict | None:
"""Get a single scrobble by its UUID."""
try:
s = Scrobble.objects.filter(user=self.request.user).get(uuid=uuid)
except Scrobble.DoesNotExist:
return None
return _scrobble_to_dict(s)
def search_scrobbles(
self, query: str, media_type: str | None = None, limit: int = 20
) -> list[dict]:
"""Search scrobbles by text in their log data or related media titles."""
from django.db.models import Q
qs = Scrobble.objects.filter(user=self.request.user).order_by("-timestamp")
if media_type:
qs = qs.filter(media_type=media_type)
qs = qs.filter(
Q(log__icontains=query)
| Q(video__title__icontains=query)
| Q(track__title__icontains=query)
| Q(book__title__icontains=query)
| Q(video_game__title__icontains=query)
| Q(board_game__title__icontains=query)
| Q(beer__title__icontains=query)
| Q(food__title__icontains=query)
| Q(trail__title__icontains=query)
| Q(task__title__icontains=query)
| Q(web_page__title__icontains=query)
| Q(life_event__title__icontains=query)
| Q(puzzle__title__icontains=query)
| Q(brick_set__title__icontains=query)
| Q(podcast_episode__title__icontains=query)
)[:limit]
return [_scrobble_to_dict(s) for s in qs]
def get_scrobbles_by_date(
self, date: str, media_type: str | None = None
) -> list[dict]:
"""Get scrobbles for a specific date (YYYY-MM-DD format)."""
import datetime
try:
dt = datetime.datetime.strptime(date, "%Y-%m-%d").date()
except ValueError:
return []
qs = Scrobble.objects.filter(
user=self.request.user,
timestamp__date=dt,
).order_by("-timestamp")
if media_type:
qs = qs.filter(media_type=media_type)
return [_scrobble_to_dict(s) for s in qs]
def get_in_progress_scrobbles(
self, media_type: str | None = None
) -> list[dict]:
"""Get scrobbles currently in progress (started but not finished).
These are long-play items like books, video games, brick sets, or tasks."""
qs = Scrobble.objects.filter(
user=self.request.user,
in_progress=True,
).order_by("-timestamp")
if media_type:
qs = qs.filter(media_type=media_type)
return [_scrobble_to_dict(s) for s in qs]
def get_long_play_scrobbles(
self, status: str = "in_progress", media_type: str | None = None
) -> list[dict]:
"""Get long-play scrobbles (books, video games, brick sets, tasks).
Status can be 'in_progress' or 'completed'."""
types = list(LONG_PLAY_MEDIA.values())
qs = Scrobble.objects.filter(
user=self.request.user,
media_type__in=types,
).order_by("-timestamp")
if media_type:
qs = qs.filter(media_type=media_type)
if status == "in_progress":
qs = qs.filter(in_progress=True)
elif status == "completed":
qs = qs.filter(in_progress=False)
return [_scrobble_to_dict(s) for s in qs]
class MediaToolset(MCPToolset):
def get_book(self, uuid: str) -> dict | None:
"""Get a book by UUID."""
from books.models import Book
try:
b = Book.objects.get(uuid=uuid)
except Book.DoesNotExist:
return None
return _media_to_dict(b, fields=["title", "pages", "language",
"first_publish_year", "isbn_13",
"publisher", "summary"])
def list_books(self, author: str | None = None, limit: int = 20) -> list[dict]:
"""List books, optionally filtered by author name."""
from books.models import Book
qs = Book.objects.all().order_by("title")
if author:
qs = qs.filter(authors__name__icontains=author)
return [_media_to_dict(b, fields=["title", "pages", "language",
"first_publish_year", "isbn_13",
"publisher"]) for b in qs[:limit]]
def get_track(self, uuid: str) -> dict | None:
"""Get a music track by UUID."""
from music.models import Track
try:
t = Track.objects.select_related("artist_fk").get(uuid=uuid)
except Track.DoesNotExist:
return None
return _media_to_dict(t, fields=["title", "base_run_time_seconds",
"artist_fk__name", "genre"])
def list_tracks(self, artist: str | None = None, limit: int = 20) -> list[dict]:
"""List music tracks, optionally filtered by artist name."""
from music.models import Track
qs = Track.objects.select_related("artist_fk").all().order_by("title")
if artist:
qs = qs.filter(artist_fk__name__icontains=artist)
return [_media_to_dict(t, fields=["title", "base_run_time_seconds",
"artist_fk__name", "genre"])
for t in qs[:limit]]
def get_video(self, uuid: str) -> dict | None:
"""Get a video by UUID."""
from videos.models import Video
try:
v = Video.objects.select_related("tv_series", "channel").get(uuid=uuid)
except Video.DoesNotExist:
return None
return _media_to_dict(v, fields=["title", "year", "overview",
"imdb_id", "imdb_rating",
"tv_series__name", "channel__title",
"season_number", "episode_number"])
def list_videos(self, series: str | None = None, limit: int = 20) -> list[dict]:
"""List videos, optionally filtered by series name."""
from videos.models import Video
qs = Video.objects.select_related("tv_series", "channel").all().order_by("title")
if series:
qs = qs.filter(tv_series__name__icontains=series)
return [_media_to_dict(v, fields=["title", "year", "overview",
"tv_series__name", "channel__title",
"season_number", "episode_number"])
for v in qs[:limit]]
def get_board_game(self, uuid: str) -> dict | None:
"""Get a board game by UUID."""
from boardgames.models import BoardGame
try:
bg = BoardGame.objects.get(uuid=uuid)
except BoardGame.DoesNotExist:
return None
return _media_to_dict(bg, fields=["title", "genre"])
def list_board_games(self, limit: int = 20) -> list[dict]:
"""List board games."""
from boardgames.models import BoardGame
qs = BoardGame.objects.all().order_by("title")[:limit]
return [_media_to_dict(bg, fields=["title", "genre"]) for bg in qs]
def get_podcast_episode(self, uuid: str) -> dict | None:
"""Get a podcast episode by UUID."""
from podcasts.models import PodcastEpisode
try:
pe = PodcastEpisode.objects.select_related("podcast", "producer").get(
uuid=uuid
)
except PodcastEpisode.DoesNotExist:
return None
return _media_to_dict(pe, fields=["title", "podcast__title",
"producer__name", "base_run_time_seconds"])
def get_beer(self, uuid: str) -> dict | None:
"""Get a beer by UUID."""
from beers.models import Beer
try:
b = Beer.objects.select_related("style", "producer").get(uuid=uuid)
except Beer.DoesNotExist:
return None
return _media_to_dict(b, fields=["title", "style__name",
"producer__name", "abv"])
def get_brick_set(self, uuid: str) -> dict | None:
"""Get a brick set (LEGO) by UUID."""
from bricksets.models import BrickSet
try:
bs = BrickSet.objects.get(uuid=uuid)
except BrickSet.DoesNotExist:
return None
return _media_to_dict(bs, fields=["title", "piece_count", "set_number"])
def get_video_game(self, uuid: str) -> dict | None:
"""Get a video game by UUID."""
from videogames.models import VideoGame
try:
vg = VideoGame.objects.get(uuid=uuid)
except VideoGame.DoesNotExist:
return None
return _media_to_dict(vg, fields=["title", "genre",
"base_run_time_seconds"])
def get_puzzle(self, uuid: str) -> dict | None:
"""Get a puzzle by UUID."""
from puzzles.models import Puzzle
try:
p = Puzzle.objects.select_related("manufacturer").get(uuid=uuid)
except Puzzle.DoesNotExist:
return None
return _media_to_dict(p, fields=["title", "piece_count",
"manufacturer__name"])
def get_web_page(self, uuid: str) -> dict | None:
"""Get a web page by UUID."""
from webpages.models import WebPage
try:
wp = WebPage.objects.select_related("domain").get(uuid=uuid)
except WebPage.DoesNotExist:
return None
return _media_to_dict(wp, fields=["title", "url", "domain__name"])
def get_task(self, uuid: str) -> dict | None:
"""Get a task by UUID."""
from tasks.models import Task
try:
t = Task.objects.get(uuid=uuid)
except Task.DoesNotExist:
return None
return _media_to_dict(t, fields=["title", "completed"])
def get_trail(self, uuid: str) -> dict | None:
"""Get a trail by UUID."""
from trails.models import Trail
try:
t = Trail.objects.get(uuid=uuid)
except Trail.DoesNotExist:
return None
return _media_to_dict(t, fields=["title", "genre", "base_run_time_seconds"])
def get_geo_location(self, uuid: str) -> dict | None:
"""Get a geo location by UUID."""
from locations.models import GeoLocation
try:
gl = GeoLocation.objects.get(uuid=uuid)
except GeoLocation.DoesNotExist:
return None
return _media_to_dict(gl, fields=["title", "latitude", "longitude"])
def get_life_event(self, uuid: str) -> dict | None:
"""Get a life event by UUID."""
from lifeevents.models import LifeEvent
try:
le = LifeEvent.objects.get(uuid=uuid)
except LifeEvent.DoesNotExist:
return None
return _media_to_dict(le, fields=["title", "event_date", "genre"])
def get_mood(self, uuid: str) -> dict | None:
"""Get a mood entry by UUID."""
from moods.models import Mood
try:
m = Mood.objects.get(uuid=uuid)
except Mood.DoesNotExist:
return None
return _media_to_dict(m, fields=["title", "mood_type", "mood_quality"])
def get_food(self, uuid: str) -> dict | None:
"""Get a food entry by UUID."""
from foods.models import Food
try:
f = Food.objects.select_related("category").get(uuid=uuid)
except Food.DoesNotExist:
return None
return _media_to_dict(f, fields=["title", "category__name"])
def get_bird_sighting(self, uuid: str) -> dict | None:
"""Get a bird sighting by UUID."""
from birds.models import BirdSighting
try:
bs = BirdSighting.objects.select_related("bird").get(uuid=uuid)
except BirdSighting.DoesNotExist:
return None
return _media_to_dict(bs, fields=["title", "bird__common_name",
"bird__scientific_name", "location"])
def get_disc_golf_course(self, uuid: str) -> dict | None:
"""Get a disc golf course by UUID."""
from discgolf.models import DiscGolfCourse
try:
dg = DiscGolfCourse.objects.get(uuid=uuid)
except DiscGolfCourse.DoesNotExist:
return None
return _media_to_dict(dg, fields=["title", "holes", "location"])
class StatsToolset(MCPToolset):
def get_scrobble_counts(self, days: int = 30) -> list[dict]:
"""Get scrobble counts grouped by media type for the last N days."""
from django.utils import timezone
import datetime
from django.db.models import Count
cutoff = timezone.now() - datetime.timedelta(days=days)
qs = (
Scrobble.objects.filter(user=self.request.user, timestamp__gte=cutoff)
.values("media_type")
.annotate(count=Count("id"))
.order_by("-count")
)
return list(qs)
def get_top_media(
self, media_type: str, days: int = 30, limit: int = 10
) -> list[dict]:
"""Get the most-scrobbled items of a given media type in the last N days.
Valid media_type values: Video, Track, Book, BoardGame, Beer, etc."""
from django.utils import timezone
import datetime
from django.db.models import Count
cutoff = timezone.now() - datetime.timedelta(days=days)
rel_field = _media_type_to_rel_field(media_type)
if not rel_field:
return []
qs = (
Scrobble.objects.filter(
user=self.request.user,
media_type=media_type,
timestamp__gte=cutoff,
)
.values(rel_field)
.annotate(count=Count("id"))
.order_by("-count")
)[:limit]
results = []
for row in qs:
obj_id = row[rel_field]
if obj_id is None:
continue
results.append({"id": obj_id, "count": row["count"]})
return results
def _media_type_to_rel_field(media_type: str) -> str | None:
mapping = {
"Video": "video",
"Track": "track",
"PodcastEpisode": "podcast_episode",
"SportEvent": "sport_event",
"Book": "book",
"Paper": "paper",
"VideoGame": "video_game",
"BoardGame": "board_game",
"GeoLocation": "geo_location",
"Trail": "trail",
"Beer": "beer",
"Puzzle": "puzzle",
"Food": "food",
"Task": "task",
"WebPage": "web_page",
"LifeEvent": "life_event",
"Mood": "mood",
"BrickSet": "brick_set",
"Channel": "channel",
"BirdingLocation": "birding_location",
"DiscGolfCourse": "disc_golf_course",
}
return mapping.get(media_type)
def _scrobble_to_dict(s: Scrobble) -> dict:
result = {
"uuid": str(s.uuid),
"media_type": s.media_type,
"timestamp": s.timestamp.isoformat() if s.timestamp else None,
"stop_timestamp": s.stop_timestamp.isoformat() if s.stop_timestamp else None,
"in_progress": s.in_progress,
"played_to_completion": s.played_to_completion,
"source": s.source,
"visibility": s.visibility,
"timezone": s.timezone,
}
if s.log:
result["log"] = s.log
rel = _scrobble_related_to_dict(s)
if rel:
result["media"] = rel
return result
def _scrobble_related_to_dict(s: Scrobble) -> dict | None:
if s.video:
return _media_to_dict(s.video, fields=["title", "year", "imdb_id",
"imdb_rating"])
if s.track:
return _media_to_dict(s.track, fields=["title",
"base_run_time_seconds"])
if s.book:
return _media_to_dict(s.book, fields=["title", "pages"])
if s.video_game:
return _media_to_dict(s.video_game, fields=["title",
"base_run_time_seconds"])
if s.board_game:
return _media_to_dict(s.board_game, fields=["title"])
if s.beer:
return _media_to_dict(s.beer, fields=["title"])
if s.puzzle:
return _media_to_dict(s.puzzle, fields=["title", "piece_count"])
if s.food:
return _media_to_dict(s.food, fields=["title"])
if s.trail:
return _media_to_dict(s.trail, fields=["title",
"base_run_time_seconds"])
if s.task:
return _media_to_dict(s.task, fields=["title"])
if s.web_page:
return _media_to_dict(s.web_page, fields=["title", "url"])
if s.life_event:
return _media_to_dict(s.life_event, fields=["title", "event_date"])
if s.mood:
return _media_to_dict(s.mood, fields=["title"])
if s.brick_set:
return _media_to_dict(s.brick_set, fields=["title", "set_number"])
if s.podcast_episode:
return _media_to_dict(s.podcast_episode, fields=["title"])
if s.sport_event:
return {"title": str(s.sport_event)}
if s.geo_location:
return _media_to_dict(s.geo_location, fields=["title", "latitude",
"longitude"])
if s.birding_location:
return _media_to_dict(s.birding_location, fields=["title"])
if s.disc_golf_course:
return _media_to_dict(s.disc_golf_course, fields=["title", "holes"])
if s.channel:
return _media_to_dict(s.channel, fields=["title"])
return None
def _media_to_dict(obj, fields: list[str] | None = None) -> dict:
if obj is None:
return {}
result = {}
if hasattr(obj, "uuid"):
result["uuid"] = str(obj.uuid)
if hasattr(obj, "title"):
result["title"] = obj.title
if fields is None:
return result
resolved = _resolve_fields(obj, fields)
for k, v in resolved.items():
if k not in result:
result[k] = v
return result
def _resolve_fields(obj, fields: list[str]) -> dict:
result = {}
for field in fields:
parts = field.split("__")
val = obj
try:
for part in parts:
val = getattr(val, part)
except AttributeError:
continue
if val is not None:
if hasattr(val, "all"):
val = [str(v) for v in val.all()]
result[field] = val
return result

View File

@ -1377,6 +1377,8 @@ class Scrobble(TimeStampedModel):
media_obj = self.channel
if self.birding_location:
media_obj = self.birding_location
if self.paper:
media_obj = self.paper
if self.disc_golf_course:
media_obj = self.disc_golf_course
return media_obj

View File

@ -9,7 +9,7 @@ import requests
from beers.models import Beer
from boardgames.models import BoardGame, BoardGameDesigner, BoardGameLocation
from books.constants import READCOMICSONLINE_URL
from books.models import Book, BookLogData, BookPageLogData
from books.models import Book, BookLogData, BookPageLogData, Paper
from books.utils import parse_readcomicsonline_uri
from bricksets.models import BrickSet
from dateutil.parser import parse
@ -641,6 +641,8 @@ def manual_scrobble_from_url(
item_id = "tt" + str(item_id)
elif content_key == "-h" and "twitch.tv" in url:
item_id = url
elif content_key == "-pp" and "doi.org" in url:
item_id = url
scrobble_fn = MANUAL_SCROBBLE_FNS[content_key]
return eval(scrobble_fn)(item_id, user_id, source=source, action=action)
@ -995,6 +997,38 @@ def manual_scrobble_task(
return scrobble
def manual_scrobble_paper(
doi_url: str,
user_id: int,
source: str = "Bookmarklet",
action: Optional[str] = None,
):
paper = Paper.find_or_create_by_doi(doi_url)
scrobble_dict = {
"user_id": user_id,
"timestamp": timezone.now(),
"playback_position_seconds": 0,
"source": source,
}
logger.info(
"[vrobbler-scrobble] paper scrobble request received",
extra={
"paper_id": paper.id,
"user_id": user_id,
"scrobble_dict": scrobble_dict,
"media_type": Scrobble.MediaType.PAPER,
},
)
scrobble = Scrobble.create_or_update(paper, user_id, scrobble_dict)
if action == "stop":
scrobble.stop(force_finish=True)
return scrobble
def manual_scrobble_webpage(
url: str,
user_id: int,

View File

@ -10,6 +10,7 @@ from scrobbles.tasks import (
add_favorite_to_mopidy_playlist,
CHARTABLE_MEDIA_TYPES,
remove_favorite_from_mopidy_playlist,
reverse_geocode_geolocation,
SCROBBLES_WITHOUT_CHARTS,
update_charts_for_timestamp,
)
@ -86,6 +87,31 @@ def add_tags_from_task_title(sender, instance, **kwargs):
instance.tags.add(tag)
@receiver(post_save, sender=Scrobble)
def reverse_geocode_on_scrobble_creation(sender, instance, created, **kwargs):
if not created:
return
if not instance.geo_location_id:
logger.info(
"Skipping reverse geocode: scrobble %s has no geo_location",
instance.id,
)
return
if instance.geo_location.postal_code:
logger.info(
"Skipping reverse geocode: geo_location %s already has postal_code %s",
instance.geo_location_id,
instance.geo_location.postal_code,
)
return
logger.info(
"Enqueuing reverse geocode for geo_location %s",
instance.geo_location_id,
)
reverse_geocode_geolocation.delay(instance.geo_location_id)
@receiver(post_save, sender=FavoriteMedia)
def add_to_mopidy_playlist_on_favorite(sender, instance, created, **kwargs):
if not created:

View File

@ -726,3 +726,41 @@ def add_scrobble_to_mopidy_monthly_playlist(scrobble_id):
break
add_track_to_mopidy_monthly_playlist(scrobble)
@shared_task
def reverse_geocode_geolocation(geo_location_id):
from locations.models import GeoLocation
location = GeoLocation.objects.filter(id=geo_location_id).first()
if not location:
logger.info(
"Skipping reverse geocode: geo_location %s not found",
geo_location_id,
)
return
if location.postal_code:
logger.info(
"Skipping reverse geocode: geo_location %s already has postal_code %s",
geo_location_id,
location.postal_code,
)
return
logger.info(
"Reverse geocoding geo_location %s (%s, %s)",
geo_location_id,
location.lat,
location.lon,
)
if location.reverse_geocode():
logger.info(
"Reverse geocode succeeded for geo_location %s: %s",
geo_location_id,
location.display_address,
)
else:
logger.warning(
"Reverse geocode failed for geo_location %s",
geo_location_id,
)

View File

@ -5,6 +5,7 @@ from tasks.webhooks import EmacsWebhookView, TodoistWebhookView
app_name = "scrobbles"
urlpatterns = [
path("now-playing/", views.NowPlayingPartialView.as_view(), name="now-playing-partial"),
path("calendar/", views.ScrobbleCalendarView.as_view(), name="calendar"),
path("search/", views.ScrobbleSearchView.as_view(), name="search"),
path("status/", views.ScrobbleStatusView.as_view(), name="status"),

View File

@ -361,11 +361,35 @@ class RecentScrobbleList(ListView):
return Scrobble.objects.all().order_by("-timestamp")
class NowPlayingPartialView(LoginRequiredMixin, TemplateView):
template_name = "scrobbles/_now_playing.html"
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
from scrobbles.constants import EXCLUDE_FROM_NOW_PLAYING
ctx["now_playing_list"] = list(
Scrobble.objects.filter(
in_progress=True,
is_paused=False,
user=self.request.user,
)
.exclude(media_type__in=EXCLUDE_FROM_NOW_PLAYING)
.select_related("track", "video", "podcast_episode")
)
return ctx
class ScrobbleListView(LoginRequiredMixin, ListView):
model = Scrobble
paginate_by = 100
template_name = "scrobbles/scrobble_all_list.html"
def get_template_names(self):
if self.request.headers.get("HX-Request"):
return ["scrobbles/_scrobble_all_content.html"]
return ["scrobbles/scrobble_all_list.html"]
def get_queryset(self):
qs = Scrobble.objects.filter(user=self.request.user).order_by("-timestamp")
tags_param = self.request.GET.get("tags", "")
@ -586,7 +610,12 @@ class ManualScrobbleView(FormView):
item_str = form.cleaned_data.get("item_id")
logger.debug(f"Looking for scrobblable media with input {item_str}")
key, item_id = item_str[:2], item_str[3:]
if len(item_str) > 2 and item_str[:3] in MANUAL_SCROBBLE_FNS:
key = item_str[:3]
item_id = item_str[4:]
else:
key = item_str[:2]
item_id = item_str[3:]
scrobble_fn = MANUAL_SCROBBLE_FNS[key]
scrobble = eval(scrobble_fn)(item_id, self.request.user.id)
@ -894,7 +923,7 @@ def scrobble_start(request, media_uuid):
if last_scrobble and last_scrobble.logdata:
next_page = last_scrobble.logdata.page_end + 1
log_data = {"page_start": next_page}
media_obj.scrobble_for_user(user_id, log=log_data)
scrobble = media_obj.scrobble_for_user(user_id, log=log_data)
if scrobble:
messages.add_message(

View File

@ -0,0 +1,29 @@
# Generated by Django 4.2.29 on 2026-06-22 02:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
(
"trends",
"0002_alter_trendresult_unique_together_trendresult_period_and_more",
),
]
operations = [
migrations.AlterField(
model_name="trendresult",
name="period",
field=models.CharField(
choices=[
("last_30", "Last 30 days"),
("last_90", "Last 90 days"),
("last_year", "Last year"),
],
default="last_30",
max_length=20,
),
),
]

View File

@ -0,0 +1,65 @@
<div class="row">
<div class="col-12">
{% if data.total and data.total > 0 %}
<h5>Overall</h5>
<div class="table-responsive mb-4">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Category</th>
<th class="text-end">Scrobbles</th>
<th class="text-end">%</th>
</tr>
</thead>
<tbody>
{% for slug, info in data.categories.items %}
<tr>
<td>{{ info.label }}</td>
<td class="text-end">{{ info.count }}</td>
<td class="text-end">{{ info.pct }}%</td>
</tr>
{% endfor %}
<tr class="table-secondary">
<td><strong>Total</strong></td>
<td class="text-end"><strong>{{ data.total }}</strong></td>
<td class="text-end"></td>
</tr>
</tbody>
</table>
</div>
<h5>By Media Type</h5>
{% for mt, mt_data in data.by_media_type.items %}
<h6 class="mt-3">{{ mt }}</h6>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Category</th>
<th class="text-end">Scrobbles</th>
<th class="text-end">%</th>
</tr>
</thead>
<tbody>
{% for slug, info in mt_data.categories.items %}
<tr>
<td>{{ info.label }}</td>
<td class="text-end">{{ info.count }}</td>
<td class="text-end">{{ info.pct }}%</td>
</tr>
{% endfor %}
<tr class="table-secondary">
<td><strong>Total</strong></td>
<td class="text-end"><strong>{{ mt_data.total }}</strong></td>
<td class="text-end"></td>
</tr>
</tbody>
</table>
</div>
{% endfor %}
{% else %}
<p class="text-muted">No data found for Books, Trails, Birding Locations, or Board Games in this period.</p>
{% endif %}
</div>
</div>

View File

@ -55,6 +55,9 @@
{% elif trend.slug == "reading-pace-vs-activity" %}
{% include "trends/_reading_pace.html" %}
{% elif trend.slug == "time-of-day-categories" %}
{% include "trends/_time_of_day_categories.html" %}
{% elif trend.slug == "trending-up" %}
{% include "trends/_trending_up.html" %}

View File

@ -15,6 +15,7 @@ from trends.trends.mood import (
compute_mood_weather,
)
from trends.trends.reading import compute_reading_pace_vs_activity
from trends.trends.time_of_day import compute_time_of_day_categories
from trends.trends.trending import compute_trending_up
TREND_REGISTRY = {}
@ -44,5 +45,8 @@ compute_peak_hours = register("peak-hours")(compute_peak_hours)
compute_reading_pace_vs_activity = register("reading-pace-vs-activity")(
compute_reading_pace_vs_activity
)
compute_time_of_day_categories = register("time-of-day-categories")(
compute_time_of_day_categories
)
compute_trending_up = register("trending-up")(compute_trending_up)
compute_weekly_rhythm = register("weekly-rhythm")(compute_weekly_rhythm)

View File

@ -0,0 +1,89 @@
from collections import OrderedDict
from django.db.models import Count, Q
from django.db.models.functions import Extract
from scrobbles.models import Scrobble
TARGET_MEDIA_TYPES = ["Book", "Trail", "BirdingLocation", "BoardGame"]
CATEGORIES = OrderedDict(
[
("early_bird", {"label": "Early Bird", "hours": {5, 6, 7, 8, 9, 10}}),
("day_jay", {"label": "Day Jay", "hours": {11, 12, 13, 14, 15, 16, 17, 18}}),
("night_owl", {"label": "Night Owl", "hours": {19, 20, 21, 22, 23, 0, 1, 2, 3, 4}}),
]
)
def _categorize_hour(hour):
for slug, cat in CATEGORIES.items():
if hour in cat["hours"]:
return slug
return None
def compute_time_of_day_categories(user, period="last_30"):
from trends.utils import get_date_range
start, end = get_date_range(period)
filters = Q(user=user, media_type__in=TARGET_MEDIA_TYPES, timestamp__isnull=False)
if start:
filters &= Q(timestamp__gte=start)
if end:
filters &= Q(timestamp__lte=end)
qs = (
Scrobble.objects.filter(filters)
.annotate(hour=Extract("timestamp", "hour"))
.values("media_type", "hour")
.annotate(count=Count("id"))
.order_by("media_type", "hour")
)
raw = {}
for row in qs:
mt = row["media_type"]
raw.setdefault(mt, {})[row["hour"]] = row["count"]
by_media_type = {}
grand_totals = {"early_bird": 0, "day_jay": 0, "night_owl": 0}
grand_total = 0
for mt in TARGET_MEDIA_TYPES:
mt_data = raw.get(mt, {})
cat_counts = {"early_bird": 0, "day_jay": 0, "night_owl": 0}
mt_total = 0
for hour, count in mt_data.items():
slug = _categorize_hour(hour)
if slug:
cat_counts[slug] += count
mt_total += count
by_media_type[mt] = {
"total": mt_total,
"categories": {},
}
for slug in CATEGORIES:
c = cat_counts[slug]
by_media_type[mt]["categories"][slug] = {
"count": c,
"pct": round((c / mt_total * 100), 1) if mt_total else 0,
"label": CATEGORIES[slug]["label"],
}
grand_totals[slug] += c
grand_total += mt_total
categories = {}
for slug in CATEGORIES:
c = grand_totals[slug]
categories[slug] = {
"count": c,
"pct": round((c / grand_total * 100), 1) if grand_total else 0,
"label": CATEGORIES[slug]["label"],
}
return {
"categories": categories,
"total": grand_total,
"by_media_type": by_media_type,
}

View File

@ -25,6 +25,7 @@ TIME_BOUND_TRENDS = {
"mood-weather",
"peak-hours",
"reading-pace-vs-activity",
"time-of-day-categories",
"trending-up",
"weekly-rhythm",
}

View File

@ -55,6 +55,11 @@ TREND_METADATA = {
"description": "Compare how long you read per session with and without concurrent music.",
"icon": "📊",
},
"time-of-day-categories": {
"title": "Time of Day Categories",
"description": "Are you an early bird, day jay, or night owl? Categorized by Books, Trails, Birding Locations, and Board Games.",
"icon": "🦉",
},
"trending-up": {
"title": "Trending Media Types",
"description": "Which media types have you been consuming more or less of recently?",

View File

@ -15,13 +15,11 @@ def natural_duration(value):
seconds = remainder % 60
parts = []
if days:
parts.append(f"{days} day{'s' if days != 1 else ''}")
parts.append(f"{days} d")
if hours:
parts.append(f"{hours} hour{'s' if hours != 1 else ''}")
parts.append(f"{hours} hr")
if minutes:
parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")
parts.append(f"{minutes} min")
if seconds or not parts:
parts.append(f"{seconds} second{'s' if seconds != 1 else ''}")
if len(parts) == 1:
return parts[0]
return ", ".join(parts[:-1]) + " and " + parts[-1]
parts.append(f"{seconds} sec")
return ", ".join(parts)

View File

@ -2,6 +2,8 @@ import logging
from typing import Dict, Optional
from uuid import uuid4
import cloudscraper
from curl_cffi import requests as curl_requests
import pendulum
import requests
import trafilatura
@ -45,6 +47,37 @@ class Domain(TimeStampedModel):
)
def _fetch_url_raw(url: str) -> Optional[str]:
"""Fetch raw HTML for a URL.
Tries three strategies in order:
1. trafilatura (standard, works for most sites)
2. cloudscraper (handles basic Cloudflare JS challenges)
3. curl_cffi (impersonates browser TLS fingerprint for aggressive
Cloudflare / bot detection)
"""
raw = trafilatura.fetch_url(url)
if raw:
return raw
logger.debug("trafilatura returned nothing for %s, trying cloudscraper", url)
try:
scraper = cloudscraper.create_scraper()
resp = scraper.get(url, timeout=30)
resp.raise_for_status()
return resp.text
except Exception as exc:
logger.debug("cloudscraper failed for %s: %s, trying curl_cffi", url, exc)
try:
resp = curl_requests.get(
url, impersonate="chrome124", timeout=30
)
resp.raise_for_status()
return resp.text
except Exception as e:
logger.warning("curl_cffi also failed for %s: %s", url, e)
return None
class WebPage(ScrobblableMixin):
COMPLETION_PERCENT = getattr(settings, "WEBSITE_COMPLETION_PERCENT", 100)
@ -80,7 +113,7 @@ class WebPage(ScrobblableMixin):
def _update_extract_from_web(self, raw_text: str = "", force=True):
if not raw_text:
raw_text = requests.get(self.url, headers=headers).text
raw_text = _fetch_url_raw(self.url)
if not self.extract or force:
self.extract = trafilatura.extract(raw_text)
self.save(update_fields=["extract"])
@ -259,7 +292,7 @@ class WebPage(ScrobblableMixin):
return False
def fetch_data_from_web(self, save=True, force=True):
raw_text = trafilatura.fetch_url(self.url)
raw_text = _fetch_url_raw(self.url)
if not self.extract or force:
self.extract = trafilatura.extract(
raw_text,

View File

@ -236,6 +236,7 @@ INSTALLED_APPS = [
"allauth.account",
"allauth.socialaccount",
"django_celery_results",
"mcp_server",
]
SITE_ID = 1
@ -329,6 +330,13 @@ REST_FRAMEWORK = {
"PAGE_SIZE": 200,
}
DJANGO_MCP_AUTHENTICATION_CLASSES = [
"oauth2_provider.contrib.rest_framework.OAuth2Authentication",
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
]
DJANGO_MCP_GET_SERVER_INSTRUCTIONS_TOOL = True
LOGIN_REDIRECT_URL = "/"
AUTH_PASSWORD_VALIDATORS = [
@ -389,6 +397,8 @@ else:
MEDIA_URL = os.getenv("VROBBLER_MEDIA_URL", "/media/")
SCIHUB_DOMAIN = os.getenv("VROBBLER_SCIHUB_DOMAIN", "sci-hub.st")
JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", "false").lower() in TRUTHY
LOG_TYPE = "json" if JSON_LOGGING else "log"

View File

@ -13,6 +13,7 @@
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.10/clipboard.min.js"></script>
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
<style type="text/css">
dl {
display: flex;
@ -310,26 +311,13 @@
{% endblock %}
{% if now_playing_list and user.is_authenticated %}
<ul>
<b>Now playing</b>
{% for scrobble in now_playing_list %}
<div class="now-playing">
{% if scrobble.media_obj.primary_image_url %}<div style="float:left;padding-right:10px;padding-bottom:10px;"><img src="{{scrobble.media_obj.primary_image_url}}" /></div>{% endif %}
<p><a href="{{scrobble.get_absolute_url}}">{{scrobble.media_obj}}</a></p>
{% if scrobble.logdata %}{% if scrobble.logdata.title%}<p><em>{{scrobble.logdata.title}}</em></p>{% endif %}{% endif %}
<p><small>{{scrobble.local_timestamp|naturaltime}} from {{scrobble.source}}</small></p>
<div class="progress-bar" style="margin-right:5px;">
<span class="progress-bar-fill" style="width: {{scrobble.percent_played}}%;"></span>
</div>
<p class="action-buttons">
<a href="{% url "scrobbles:cancel" scrobble.id %}">Cancel</a>
<a class="right" href="{% url "scrobbles:finish" scrobble.id %}">Finish</a>
</p>
{% if not forloop.last %}<hr/>{% endif %}
</div>
{% endfor %}
</ul>
{% if now_playing_list|length > 1 %}<hr/>{% endif %}
{% if user.profile.live_now_playing %}
<div id="now-playing-container" hx-get="{% url 'scrobbles:now-playing-partial' %}" hx-trigger="every 7s" hx-swap="innerHTML">
{% include "scrobbles/_now_playing.html" %}
</div>
{% else %}
{% include "scrobbles/_now_playing.html" %}
{% endif %}
{% endif %}
{% if active_imports %}

View File

@ -0,0 +1,62 @@
{% extends "base_list.html" %}
{% block title %}{{object.title}}{% endblock %}
{% block lists %}
<div class="row">
<div class="col">
<h1>{{object.title}}</h1>
{% if object.authors.all %}
<p>{{object.authors.all|join:", "}}</p>
{% endif %}
{% if object.journal %}
<p><em>{{object.journal.title}}{% if object.journal_volume %}, vol. {{object.journal_volume}}{% endif %}</em></p>
{% endif %}
{% if object.doi_id %}
<p><a href="https://doi.org/{{object.doi_id}}">doi: {{object.doi_id}}</a></p>
{% endif %}
{% if object.abstract %}
<p>{{object.abstract|linebreaks|truncatewords:200}}</p>
{% endif %}
{% if object.pdf_file %}
<button class="btn btn-outline-secondary btn-sm" onclick="togglePdf()">Show/Hide PDF</button>
<div id="pdf-embed" style="display:none; margin-top:0.5rem;">
<iframe src="{{object.pdf_file.url}}" style="width:100%;height:600px;border:1px solid #ccc;"></iframe>
</div>
<script>
function togglePdf() {
var el = document.getElementById('pdf-embed');
el.style.display = el.style.display === 'none' ? 'block' : 'none';
}
</script>
{% endif %}
{% if object.openaccess_pdf_url %}
<p><a href="{{object.openaccess_pdf_url}}">Open Access PDF</a></p>
{% endif %}
{% if object.pdf_file %}
<a href="{{object.pdf_file.url}}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="text-danger" viewBox="0 0 16 16">
<path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"/>
<path d="M4.603 14.087a.81.81 0 0 1-.438-.42c-.195-.388-.13-.776.08-1.102.197-.307.526-.568.897-.707.07-.024.15-.023.222 0l.044.014a.27.27 0 0 1 .152.295.7.7 0 0 1-.128.416c-.159.206-.344.388-.544.555-.357.299-.592.527-.406.623.08.04.272.045.578-.057a.93.93 0 0 0 .363-.226.8.8 0 0 0 .194-.277.28.28 0 0 1 .414-.112.3.3 0 0 1 .065.422 1.3 1.3 0 0 1-.67.522c-.38.147-.746.103-1.04.02zM7.12 11.5c.16-.186.34-.34.486-.514.294-.35.628-.617.947-.786.204-.108.546-.206.715-.153.087.027.135.068.16.126a.6.6 0 0 1-.003.27 1 1 0 0 1-.158.354c-.163.242-.349.47-.7.769-.332.283-.598.483-.793.607a1.1 1.1 0 0 1-.582.214c-.136 0-.234-.038-.298-.11-.05-.056-.076-.134-.07-.236a.99.99 0 0 1 .098-.45c.08-.17.21-.35.378-.57zm5.09 2.013c-.135.06-.277.104-.428.116-.205.015-.39-.048-.553-.177-.104-.082-.226-.196-.317-.325a1 1 0 0 1-.17-.572c0-.15.035-.27.095-.36.04-.063.089-.098.153-.112.138-.028.316.04.477.174.074.061.145.136.228.232.174.2.302.37.397.515.108.164.153.285.121.345a.25.25 0 0 1-.003.053c0 .079-.05.147-.198.262z"/>
</svg>
</a>
{% endif %}
{% if object.scihub_url %}
<p><a href="{{object.scihub_url}}">View on Sci-Hub</a></p>
{% endif %}
</div>
</div>
<hr>
<div class="row">
<div class="col">
<form method="post" enctype="multipart/form-data" action="{% url 'books:paper_upload_pdf' slug=object.uuid %}">
{% csrf_token %}
<div class="form-group">
<label for="pdf_file">Upload PDF</label>
<input type="file" class="form-control-file" id="pdf_file" name="pdf_file" accept=".pdf,application/pdf">
</div>
<button type="submit" class="btn btn-primary btn-sm">Upload</button>
</form>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,13 @@
{% extends "base_list.html" %}
{% block title %}Papers{% endblock %}
{% block lists %}
<div class="row">
<div class="col-md">
<div class="table-responsive">
{% include "_longplay_scrobblable_list.html" %}
</div>
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,15 @@
{% block title %}{{object.title}}{% endblock %}
{% block head_extra %}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
#map {
height: 400px;
}
</style>
{% endblock %}
{% block lists %}
{% if object.description %}
<div class="row">
@ -11,6 +20,30 @@
</div>
</div>
{% endif %}
{% if trail_gpx_url %}
<div class="row">
<div class="col-md mb-3">
<div id="map"></div>
</div>
</div>
{% endif %}
<div class="row">
<div class="col-md">
{% if object.trail.trailhead_location.display_address %}
<p>{{ object.trail.trailhead_location.display_address }}</p>
{% endif %}
{% if object.pdga_link or object.udisc_link %}
<p>
{% if object.pdga_link %}
<a href="{{ object.pdga_link }}" target="_blank">PDGA</a>
{% endif %}
{% if object.udisc_link %}
<a href="{{ object.udisc_link }}" target="_blank">uDisc</a>
{% endif %}
</p>
{% endif %}
</div>
</div>
{% if charts %}
<div class="row">
<div class="col-md">
@ -42,3 +75,27 @@
</div>
</div>
{% endblock %}
{% block extra_js %}
{{ block.super }}
{% if trail_gpx_url %}
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-gpx@2.2.0/gpx.min.js"></script>
<script>
var map = L.map('map');
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
referrerPolicy: 'origin'
}).addTo(map);
var gpx = new L.GPX("{{ trail_gpx_url|escapejs }}", {
async: true,
polyline_options: { color: '#e74c3c' }
});
gpx.on('loaded', function(e) {
map.fitBounds(e.target.getBounds());
});
gpx.addTo(map);
</script>
{% endif %}
{% endblock %}

View File

@ -0,0 +1,21 @@
{% load humanize %}
<ul>
<b>Now playing</b>
{% for scrobble in now_playing_list %}
<div class="now-playing">
{% if scrobble.media_obj.primary_image_url %}<div style="float:left;padding-right:10px;padding-bottom:10px;"><img src="{{scrobble.media_obj.primary_image_url}}" /></div>{% endif %}
<p><a href="{{scrobble.get_absolute_url}}">{{scrobble.media_obj}}</a></p>
{% if scrobble.logdata %}{% if scrobble.logdata.title%}<p><em>{{scrobble.logdata.title}}</em></p>{% endif %}{% endif %}
<p><small>{{scrobble.local_timestamp|naturaltime}} from {{scrobble.source}}</small></p>
<div class="progress-bar" style="margin-right:5px;">
<span class="progress-bar-fill" style="width: {{scrobble.percent_played}}%;"></span>
</div>
<p class="action-buttons">
<a href="{% url "scrobbles:cancel" scrobble.id %}">Cancel</a>
<a class="right" href="{% url "scrobbles:finish" scrobble.id %}">Finish</a>
</p>
{% if not forloop.last %}<hr/>{% endif %}
</div>
{% endfor %}
</ul>
{% if now_playing_list|length > 1 %}<hr/>{% endif %}

View File

@ -0,0 +1,146 @@
{% load humanize %}
{% load naturalduration %}
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4" hx-get="{% url 'scrobbles:scrobble-list' %}{% if request.META.QUERY_STRING %}?{{ request.META.QUERY_STRING }}{% endif %}" hx-trigger="every 7s" hx-swap="outerHTML">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<div>
<h1 class="h2">All Scrobbles</h1>
{% if tag_list %}
<h6 class="text-muted">Tagged {{ tag_list|join:", " }}</h6>
{% if total_time_seconds %}
<p class="text-muted small mb-0">Total time: {{ total_time_seconds|natural_duration }}</p>
{% endif %}
{% endif %}
{% if request.GET.visibility %}
<h6 class="text-muted">Filter: {{ request.GET.visibility|title }} scrobbles only</h6>
{% endif %}
</div>
</div>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Type</th>
<th scope="col">Title</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{% for scrobble in object_list %}
<tr class="{% if scrobble.id in overlap_map %}{{ overlap_map.scrobble.id }}{% endif %}">
<td>
{% if scrobble.id in overlap_map %}⏱ {% endif %}
<a href="{{scrobble.get_absolute_url}}">{{ scrobble.timestamp|naturaltime }}</a>
</td>
<td>
{% if scrobble.video %}
🎬 Video
{% elif scrobble.track %}
🎵 Track
{% elif scrobble.podcast_episode %}
🎙️ Podcast episode
{% elif scrobble.sport_event %}
⚽ Sport event
{% elif scrobble.book %}
📖 Book
{% elif scrobble.paper %}
📄 Paper
{% elif scrobble.video_game %}
🎮 Video game
{% elif scrobble.board_game %}
🎲 Board game
{% elif scrobble.geo_location %}
📍 GeoLocation
{% elif scrobble.trail %}
🥾 Trail
{% elif scrobble.beer %}
🍺 Beer
{% elif scrobble.puzzle %}
🧩 Puzzle
{% elif scrobble.food %}
🍔 Food
{% elif scrobble.task %}
✅ Task
{% elif scrobble.web_page %}
🌐 Web Page
{% elif scrobble.life_event %}
🎉 Life event
{% elif scrobble.mood %}
😊 Mood
{% elif scrobble.brick_set %}
🧱 Brick set
{% elif scrobble.channel %}
📺 Channel
{% else %}
Unknown
{% endif %}
</td>
<td>
{% if scrobble.video %}
<a href="{% url 'videos:video_detail' scrobble.video.uuid %}">{{ scrobble.video.title }}</a>
{% elif scrobble.track %}
<a href="{% url 'music:track_detail' scrobble.track.uuid %}">{{ scrobble.track.title }}</a>
{% elif scrobble.video_game %}
<a href="{% url 'videogames:videogame_detail' scrobble.video_game.uuid %}">{{ scrobble.video_game.title }}</a>
{% elif scrobble.book %}
<a href="{% url 'books:book_detail' scrobble.book.uuid %}">{{ scrobble.book.title }}</a>
{% elif scrobble.food %}
<a href="{% url 'foods:food_detail' scrobble.food.uuid %}">{{ scrobble.food.title }}</a>
{% elif scrobble.beer %}
<a href="{% url 'beers:beer_detail' scrobble.beer.uuid %}">{{ scrobble.beer.title }}</a>
{% elif scrobble.web_page %}
<a href="{% url 'webpages:webpage_detail' scrobble.web_page.uuid %}">{{ scrobble.web_page.title }}</a>
{% elif scrobble.podcast_episode %}
<a href="{% url 'podcasts:podcast_detail' scrobble.podcast_episode.podcast.id %}">{{ scrobble.podcast_episode.title }}</a>
{% elif scrobble.board_game %}
<a href="{% url 'boardgames:boardgame_detail' scrobble.board_game.uuid %}">{{ scrobble.board_game.title }}</a>
{% elif scrobble.trail %}
<a href="{% url 'trails:trail_detail' scrobble.trail.uuid %}">{{ scrobble.trail.title }}</a>
{% elif scrobble.puzzle %}
<a href="{% url 'puzzles:puzzle_detail' scrobble.puzzle.uuid %}">{{ scrobble.puzzle.title }}</a>
{% elif scrobble.brick_set %}
<a href="{% url 'bricksets:brickset_detail' scrobble.brick_set.uuid %}">{{ scrobble.brick_set.title }}</a>
{% elif scrobble.task %}
<a href="{% url 'tasks:task_detail' scrobble.task.uuid %}">{{scrobble.media_obj}}{% if scrobble.log.title %} - {{ scrobble.log.title }}{% endif %}</a>
{% elif scrobble.life_event %}
<a href="{% url 'lifeevents:lifeevent_detail' scrobble.life_event.uuid %}">{{ scrobble.life_event.title }}</a>
{% elif scrobble.mood %}
<a href="{% url 'moods:mood_detail' scrobble.mood.uuid %}">{{ scrobble.mood.title}}</a>
{% elif scrobble.geo_location %}
<a href="{% url 'locations:geolocation_detail' scrobble.geo_location.uuid %}">{{ scrobble.geo_location.title }}</a>
{% else %}
Unknown
{% endif %}
</td>
<td>
{% if scrobble.in_progress and not scrobble.played_to_completion %}
In progress ...
{% elif scrobble.playback_position_seconds %}
{{ scrobble.playback_position_seconds|natural_duration }}
{% endif %}
</td>
</tr>
{% empty %}
<tr>
<td colspan="4">No scrobbles found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if page_obj.has_previous or page_obj.has_next %}
<nav>
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if tags_param %}&tags={{ tags_param }}{% endif %}">Previous</a></li>
{% endif %}
<li class="page-item"><span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span></li>
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}{% if tags_param %}&tags={{ tags_param }}{% endif %}">Next</a></li>
{% endif %}
</ul>
</nav>
{% endif %}
</main>

View File

@ -1,148 +1,4 @@
{% extends "base.html" %}
{% load humanize %}
{% load naturalduration %}
{% block content %}
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<div>
<h1 class="h2">All Scrobbles</h1>
{% if tag_list %}
<h6 class="text-muted">Tagged {{ tag_list|join:", " }}</h6>
{% if total_time_seconds %}
<p class="text-muted small mb-0">Total time: {{ total_time_seconds|natural_duration }}</p>
{% endif %}
{% endif %}
{% if request.GET.visibility %}
<h6 class="text-muted">Filter: {{ request.GET.visibility|title }} scrobbles only</h6>
{% endif %}
</div>
</div>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Type</th>
<th scope="col">Title</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{% for scrobble in object_list %}
<tr class="{% if scrobble.id in overlap_map %}{{ overlap_map.scrobble.id }}{% endif %}">
<td>
{% if scrobble.id in overlap_map %}⏱ {% endif %}
<a href="{{scrobble.get_absolute_url}}">{{ scrobble.timestamp|naturaltime }}</a>
</td>
<td>
{% if scrobble.video %}
🎬 Video
{% elif scrobble.track %}
🎵 Track
{% elif scrobble.podcast_episode %}
🎙️ Podcast episode
{% elif scrobble.sport_event %}
⚽ Sport event
{% elif scrobble.book %}
📖 Book
{% elif scrobble.paper %}
📄 Paper
{% elif scrobble.video_game %}
🎮 Video game
{% elif scrobble.board_game %}
🎲 Board game
{% elif scrobble.geo_location %}
📍 GeoLocation
{% elif scrobble.trail %}
🥾 Trail
{% elif scrobble.beer %}
🍺 Beer
{% elif scrobble.puzzle %}
🧩 Puzzle
{% elif scrobble.food %}
🍔 Food
{% elif scrobble.task %}
✅ Task
{% elif scrobble.web_page %}
🌐 Web Page
{% elif scrobble.life_event %}
🎉 Life event
{% elif scrobble.mood %}
😊 Mood
{% elif scrobble.brick_set %}
🧱 Brick set
{% elif scrobble.channel %}
📺 Channel
{% else %}
Unknown
{% endif %}
</td>
<td>
{% if scrobble.video %}
<a href="{% url 'videos:video_detail' scrobble.video.uuid %}">{{ scrobble.video.title }}</a>
{% elif scrobble.track %}
<a href="{% url 'music:track_detail' scrobble.track.uuid %}">{{ scrobble.track.title }}</a>
{% elif scrobble.video_game %}
<a href="{% url 'videogames:videogame_detail' scrobble.video_game.uuid %}">{{ scrobble.video_game.title }}</a>
{% elif scrobble.book %}
<a href="{% url 'books:book_detail' scrobble.book.uuid %}">{{ scrobble.book.title }}</a>
{% elif scrobble.food %}
<a href="{% url 'foods:food_detail' scrobble.food.uuid %}">{{ scrobble.food.title }}</a>
{% elif scrobble.beer %}
<a href="{% url 'beers:beer_detail' scrobble.beer.uuid %}">{{ scrobble.beer.title }}</a>
{% elif scrobble.web_page %}
<a href="{% url 'webpages:webpage_detail' scrobble.web_page.uuid %}">{{ scrobble.web_page.title }}</a>
{% elif scrobble.podcast_episode %}
<a href="{% url 'podcasts:podcast_detail' scrobble.podcast_episode.podcast.id %}">{{ scrobble.podcast_episode.title }}</a>
{% elif scrobble.board_game %}
<a href="{% url 'boardgames:boardgame_detail' scrobble.board_game.uuid %}">{{ scrobble.board_game.title }}</a>
{% elif scrobble.trail %}
<a href="{% url 'trails:trail_detail' scrobble.trail.uuid %}">{{ scrobble.trail.title }}</a>
{% elif scrobble.puzzle %}
<a href="{% url 'puzzles:puzzle_detail' scrobble.puzzle.uuid %}">{{ scrobble.puzzle.title }}</a>
{% elif scrobble.brick_set %}
<a href="{% url 'bricksets:brickset_detail' scrobble.brick_set.uuid %}">{{ scrobble.brick_set.title }}</a>
{% elif scrobble.task %}
<a href="{% url 'tasks:task_detail' scrobble.task.uuid %}">{{scrobble.media_obj}}{% if scrobble.log.title %} - {{ scrobble.log.title }}{% endif %}</a>
{% elif scrobble.life_event %}
<a href="{% url 'lifeevents:lifeevent_detail' scrobble.life_event.uuid %}">{{ scrobble.life_event.title }}</a>
{% elif scrobble.mood %}
<a href="{% url 'moods:mood_detail' scrobble.mood.uuid %}">{{ scrobble.mood.title}}</a>
{% elif scrobble.geo_location %}
<a href="{% url 'locations:geolocation_detail' scrobble.geo_location.uuid %}">{{ scrobble.geo_location.title }}</a>
{% else %}
Unknown
{% endif %}
</td>
<td>
{% if scrobble.playback_position_seconds %}
{{ scrobble.playback_position_seconds|natural_duration }}
{% endif %}
</td>
</tr>
{% empty %}
<tr>
<td colspan="4">No scrobbles found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if page_obj.has_previous or page_obj.has_next %}
<nav>
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if tags_param %}&tags={{ tags_param }}{% endif %}">Previous</a></li>
{% endif %}
<li class="page-item"><span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span></li>
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}{% if tags_param %}&tags={{ tags_param }}{% endif %}">Next</a></li>
{% endif %}
</ul>
</nav>
{% endif %}
</main>
{% include "scrobbles/_scrobble_all_content.html" %}
{% endblock %}

View File

@ -73,24 +73,19 @@
<div class="btn-group me-2">
<a href="{% url 'charts:charts-home' %}" class="btn btn-sm btn-outline-secondary">Charts</a>
</div>
<div class="btn-group me-2">
<a href="{% url 'scrobbles:scrobble-list' %}" class="btn btn-sm btn-outline-secondary">Live</a>
</div>
<div class="btn-group me-2">
<a href="{% url 'trends:trends-home' %}" class="btn btn-sm btn-outline-secondary">Trends</a>
</div>
<div class="btn-group me-2">
{% if user.profile.lastfm_username and not user.profile.lastfm_auto_import %}
<form action="{% url 'scrobbles:lastfm-import' %}" method="get">
<button type="submit" class="btn btn-sm btn-outline-secondary">Last.fm Sync</button>
</form>
{% endif %}
{% if prev_link %}
<a type="button" class="btn btn-sm btn-outline-secondary" href="{{prev_link}}"
data-bs-target="#">Previous</a>
{% endif %}
{% if today_link %}
<a type="button" class="btn btn-sm btn-outline-secondary" href="{{today_link}}"
data-bs-target="#">Today</a>
{% endif %}
{% if next_link %}
<a type="button" class="btn btn-sm btn-outline-secondary" href="{{next_link}}"
data-bs-target="#">Next</a>
{% endif %}
</div>
<div class="btn-group me-2">
{% if user.profile.lastfm_username and not user.profile.lastfm_auto_import %}
@ -105,19 +100,6 @@
data-bs-target="#exportModal">Export</button>
</div>
{% endif %}
<div class="dropdown">
<button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" id="graphDateButton"
data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div data-feather="calendar"></div>
{{title}}
</button>
<div class="dropdown-menu" data-bs-toggle="#graphDataChange" aria-labelledby="graphDateButton">
<a class="dropdown-item" href="?date=today">Today</a>
<a class="dropdown-item" href="?date=this_week">This week</a>
<a class="dropdown-item" href="?date=this_month">This month</a>
<a class="dropdown-item" href="?date=this_year">This year</a>
</div>
</div>
</div>
</div>

View File

@ -188,6 +188,7 @@ urlpatterns = [
path("", include(people_urls, namespace="people")),
path("", include(charts_urls, namespace="charts")),
path("", include(trends_urls, namespace="trends")),
path("", include("mcp_server.urls")),
path("", scrobbles_views.RecentScrobbleList.as_view(), name="vrobbler-home"),
]
if settings.DEBUG: