Compare commits

...

14 Commits

48 changed files with 783 additions and 210 deletions

View File

@ -1,6 +1,6 @@
[tool.poetry]
name = "vrobbler"
version = "0.10.0"
version = "0.11.0"
description = ""
authors = ["Colin Powell <colin@unbl.ink>"]

View File

@ -16,7 +16,7 @@ from scrobbles.models import Scrobble
def build_scrobbles(client, request_data, num=7, spacing=2):
url = reverse('scrobbles:mopidy-websocket')
url = reverse('scrobbles:mopidy-webhook')
user = get_user_model().objects.create(username='Test User')
UserProfile.objects.create(user=user, timezone='US/Eastern')
for i in range(num):

View File

@ -10,7 +10,7 @@ from podcasts.models import Episode
@pytest.mark.django_db
def test_get_not_allowed_from_mopidy(client, valid_auth_token):
url = reverse('scrobbles:mopidy-websocket')
url = reverse('scrobbles:mopidy-webhook')
headers = {'Authorization': f'Token {valid_auth_token}'}
response = client.get(url, headers=headers)
assert response.status_code == 405
@ -18,7 +18,7 @@ def test_get_not_allowed_from_mopidy(client, valid_auth_token):
@pytest.mark.django_db
def test_bad_mopidy_request_data(client, valid_auth_token):
url = reverse('scrobbles:mopidy-websocket')
url = reverse('scrobbles:mopidy-webhook')
headers = {'Authorization': f'Token {valid_auth_token}'}
response = client.post(url, headers)
assert response.status_code == 400
@ -32,7 +32,7 @@ def test_bad_mopidy_request_data(client, valid_auth_token):
def test_scrobble_mopidy_track(
client, mopidy_track_request_data, valid_auth_token
):
url = reverse('scrobbles:mopidy-websocket')
url = reverse('scrobbles:mopidy-webhook')
headers = {'Authorization': f'Token {valid_auth_token}'}
response = client.post(
url,
@ -55,7 +55,7 @@ def test_scrobble_mopidy_same_track_different_album(
mopidy_track_diff_album_request_data,
valid_auth_token,
):
url = reverse('scrobbles:mopidy-websocket')
url = reverse('scrobbles:mopidy-webhook')
headers = {'Authorization': f'Token {valid_auth_token}'}
response = client.post(
url,
@ -84,7 +84,7 @@ def test_scrobble_mopidy_same_track_different_album(
def test_scrobble_mopidy_podcast(
client, mopidy_podcast_request_data, valid_auth_token
):
url = reverse('scrobbles:mopidy-websocket')
url = reverse('scrobbles:mopidy-webhook')
headers = {'Authorization': f'Token {valid_auth_token}'}
response = client.post(
url,

View File

@ -0,0 +1,14 @@
from books.models import Author, Book
from rest_framework import serializers
class AuthorSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Author
fields = "__all__"
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = "__all__"

View File

@ -0,0 +1,19 @@
from rest_framework import permissions, viewsets
from books.api.serializers import (
AuthorSerializer,
BookSerializer,
)
from books.models import Author, Book
class AuthorViewSet(viewsets.ModelViewSet):
queryset = Author.objects.all().order_by('-created')
serializer_class = AuthorSerializer
permission_classes = [permissions.IsAuthenticated]
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all().order_by('-created')
serializer_class = BookSerializer
permission_classes = [permissions.IsAuthenticated]

View File

@ -8,7 +8,8 @@ from django.urls import reverse
from django_extensions.db.models import TimeStampedModel
from scrobbles.mixins import ScrobblableMixin
from vrobbler.apps.books.utils import lookup_book_from_openlibrary
from books.utils import lookup_book_from_openlibrary
from scrobbles.utils import get_scrobbles_for_media
logger = logging.getLogger(__name__)
User = get_user_model()
@ -66,3 +67,7 @@ class Book(ScrobblableMixin):
logger.warn(f"{self} has no pages, no completion percentage")
return 0
return int(self.pages * (self.COMPLETION_PERCENT / 100))
def progress_for_user(self, user: User) -> int:
last_scrobble = get_scrobbles_for_media(self, user).last()
return int((last_scrobble.book_pages_read / self.pages) * 100)

View File

@ -55,7 +55,9 @@ def scrobble_counts(user=None):
return data
def week_of_scrobbles(user=None, media: str = 'tracks') -> dict[str, int]:
def week_of_scrobbles(
user=None, start=None, media: str = 'tracks'
) -> dict[str, int]:
now = timezone.now()
user_filter = Q()
@ -63,9 +65,8 @@ def week_of_scrobbles(user=None, media: str = 'tracks') -> dict[str, int]:
now = now_user_timezone(user.profile)
user_filter = Q(user=user)
start_of_today = datetime.combine(
now.date(), datetime.min.time(), now.tzinfo
)
if not start:
start = datetime.combine(now.date(), datetime.min.time(), now.tzinfo)
scrobble_day_dict = {}
base_qs = Scrobble.objects.filter(user_filter, played_to_completion=True)
@ -77,7 +78,7 @@ def week_of_scrobbles(user=None, media: str = 'tracks') -> dict[str, int]:
media_filter = Q(video__video_type=Video.VideoType.TV_EPISODE)
for day in range(6, -1, -1):
start = start_of_today - timedelta(days=day)
start = start - timedelta(days=day)
end = datetime.combine(start, datetime.max.time(), now.tzinfo)
day_of_week = start.strftime('%A')

View File

View File

@ -0,0 +1,20 @@
from music.models import Album, Artist, Track
from rest_framework import serializers
class ArtistSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Artist
fields = "__all__"
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Album
fields = "__all__"
class TrackSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Track
fields = "__all__"

View File

@ -0,0 +1,26 @@
from rest_framework import permissions, viewsets
from music.api.serializers import (
TrackSerializer,
ArtistSerializer,
AlbumSerializer,
)
from music.models import Artist, Album, Track
class ArtistViewSet(viewsets.ModelViewSet):
queryset = Artist.objects.all().order_by('-created')
serializer_class = ArtistSerializer
permission_classes = [permissions.IsAuthenticated]
class AlbumViewSet(viewsets.ModelViewSet):
queryset = Album.objects.all().order_by('-created')
serializer_class = AlbumSerializer
permission_classes = [permissions.IsAuthenticated]
class TrackViewSet(viewsets.ModelViewSet):
queryset = Track.objects.all().order_by('-created')
serializer_class = TrackSerializer
permission_classes = [permissions.IsAuthenticated]

View File

@ -181,10 +181,18 @@ class Track(ScrobblableMixin):
def get_absolute_url(self):
return reverse('music:track_detail', kwargs={'slug': self.uuid})
@property
def subtitle(self):
return self.artist
@property
def mb_link(self):
return f"https://musicbrainz.org/recording/{self.musicbrainz_id}"
@property
def info_link(self):
return self.mb_link
@classmethod
def find_or_create(
cls, artist_dict: Dict, album_dict: Dict, track_dict: Dict

View File

@ -0,0 +1 @@
#!/usr/bin/env python3

View File

@ -4,6 +4,7 @@ import re
from scrobbles.musicbrainz import (
lookup_album_dict_from_mb,
lookup_artist_from_mb,
lookup_track_from_mb,
)
logger = logging.getLogger(__name__)
@ -93,7 +94,11 @@ def get_or_create_track(
title=title, artist=artist, album=album
).first()
# TODO Can we look up mbid for tracks?
if not mbid:
mbid = lookup_track_from_mb(
title, artist.musicbrainz_id, album.musicbrainz_id
)['id']
if not track:
track = Track.objects.create(
title=title,

View File

@ -1,3 +1,4 @@
from django.db.models import Count
from django.views import generic
from music.models import Track, Artist, Album
from scrobbles.stats import get_scrobble_count_qs

View File

@ -45,6 +45,14 @@ class Episode(ScrobblableMixin):
def __str__(self):
return f"{self.title}"
@property
def subtitle(self):
return self.podcast
@property
def info_link(self):
return ""
@classmethod
def find_or_create(
cls, podcast_dict: Dict, producer_dict: Dict, episode_dict: Dict

View File

@ -0,0 +1 @@
#!/usr/bin/env python3

View File

@ -0,0 +1,18 @@
from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()
from profiles.models import UserProfile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
exclude = ('password',)
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UserProfile
exclude = ('lastfm_password',)

View File

@ -0,0 +1,28 @@
from django.contrib.auth import get_user_model
from rest_framework import permissions, viewsets
from profiles.api.serializers import UserSerializer, UserProfileSerializer
from profiles.models import UserProfile
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class UserProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = UserProfile.objects.all().order_by('-created')
serializer_class = UserProfileSerializer
permission_classes = [permissions.IsAuthenticated]

View File

View File

@ -0,0 +1,33 @@
from rest_framework import serializers
from scrobbles.models import (
AudioScrobblerTSVImport,
KoReaderImport,
LastFmImport,
Scrobble,
)
class ScrobbleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Scrobble
fields = "__all__"
class KoReaderImportSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = KoReaderImport
fields = "__all__"
class AudioScrobblerTSVImportSerializer(
serializers.HyperlinkedModelSerializer
):
class Meta:
model = AudioScrobblerTSVImport
fields = "__all__"
class LastFmImportSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = LastFmImport
fields = "__all__"

View File

@ -0,0 +1,49 @@
from rest_framework import permissions, viewsets
from scrobbles.api.serializers import (
AudioScrobblerTSVImportSerializer,
KoReaderImportSerializer,
LastFmImportSerializer,
ScrobbleSerializer,
)
from scrobbles.models import (
AudioScrobblerTSVImport,
KoReaderImport,
Scrobble,
LastFmImport,
)
class ScrobbleViewSet(viewsets.ModelViewSet):
queryset = Scrobble.objects.all().order_by('-timestamp')
serializer_class = ScrobbleSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return super().get_queryset().filter(user=self.request.user)
class KoReaderImportViewSet(viewsets.ModelViewSet):
queryset = KoReaderImport.objects.all().order_by('-created')
serializer_class = KoReaderImportSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return super().get_queryset().filter(user=self.request.user)
class AudioScrobblerTSVImportViewSet(viewsets.ModelViewSet):
queryset = AudioScrobblerTSVImport.objects.all().order_by('-created')
serializer_class = AudioScrobblerTSVImportSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return super().get_queryset().filter(user=self.request.user)
class LastFmImportViewSet(viewsets.ModelViewSet):
queryset = LastFmImport.objects.all().order_by('-created')
serializer_class = LastFmImportSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return super().get_queryset().filter(user=self.request.user)

View File

@ -0,0 +1,30 @@
# Generated by Django 4.1.5 on 2023-02-25 00:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scrobbles', '0022_scrobble_book_pages_read'),
]
operations = [
migrations.AlterModelOptions(
name='audioscrobblertsvimport',
options={'verbose_name': 'AudioScrobbler TSV Import'},
),
migrations.AlterModelOptions(
name='koreaderimport',
options={'verbose_name': 'KOReader Import'},
),
migrations.AlterModelOptions(
name='lastfmimport',
options={'verbose_name': 'Last.FM Import'},
),
migrations.AddField(
model_name='chartrecord',
name='count',
field=models.IntegerField(default=0),
),
]

View File

@ -14,6 +14,7 @@ from scrobbles.lastfm import LastFM
from scrobbles.utils import check_scrobble_for_finish
from sports.models import SportEvent
from videos.models import Series, Video
from vrobbler.apps.scrobbles.stats import build_charts
logger = logging.getLogger(__name__)
User = get_user_model()
@ -203,6 +204,7 @@ class ChartRecord(TimeStampedModel):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, **BNULL)
rank = models.IntegerField()
count = models.IntegerField(default=0)
year = models.IntegerField(default=timezone.now().year)
month = models.IntegerField(**BNULL)
week = models.IntegerField(**BNULL)
@ -219,6 +221,8 @@ class ChartRecord(TimeStampedModel):
media_obj = self.video
if self.track:
media_obj = self.track
if self.artist:
media_obj = self.artist
return media_obj
@property
@ -267,6 +271,26 @@ class ChartRecord(TimeStampedModel):
def __str__(self):
return f"#{self.rank} in {self.period} - {self.media_obj}"
@classmethod
def build(cls, user, **kwargs):
build_charts(user=user, **kwargs)
@classmethod
def for_year(cls, user, year):
return cls.objects.filter(year=year, user=user)
@classmethod
def for_month(cls, user, year, month):
return cls.objects.filter(year=year, month=month, user=user)
@classmethod
def for_day(cls, user, year, day, month):
return cls.objects.filter(year=year, month=month, day=day, user=user)
@classmethod
def for_week(cls, user, year, week):
return cls.objects.filter(year=year, week=week, user=user)
class Scrobble(TimeStampedModel):
"""A scrobble tracks played media items by a user."""

View File

@ -90,16 +90,18 @@ def lookup_artist_from_mb(artist_name: str) -> str:
return top_result
def lookup_track_from_mb(artist_name: str) -> str:
def lookup_track_from_mb(
track_name: str, artist_mbid: str, album_mbid: str
) -> str:
musicbrainzngs.set_useragent('vrobbler', '0.3.0')
top_result = musicbrainzngs.search_recordings(artist=artist_name)[
'artist-list'
][0]
top_result = musicbrainzngs.search_recordings(
query=track_name, artist=artist_mbid, release=album_mbid
)['recording-list'][0]
score = int(top_result.get('ext:score'))
if score < 85:
logger.debug(
"Artist lookup score below 85 threshold",
"Track lookup score below 85 threshold",
extra={"result": top_result},
)
return ""

View File

@ -1,14 +0,0 @@
from rest_framework import serializers
from scrobbles.models import Scrobble, AudioScrobblerTSVImport
class AudioScrobblerTSVImportSerializer(serializers.ModelSerializer):
class Meta:
model = AudioScrobblerTSVImport
fields = ('tsv_file',)
class ScrobbleSerializer(serializers.ModelSerializer):
class Meta:
model = Scrobble
fields = "__all__"

View File

@ -6,7 +6,7 @@ from typing import Optional
import pytz
from django.apps import apps
from django.conf import settings
from django.db.models import Count, Q
from django.db.models import Count, Q, ExpressionWrapper, OuterRef, Subquery
logger = logging.getLogger(__name__)
@ -30,12 +30,14 @@ def get_scrobble_count_qs(
user=None,
model_str="Track",
) -> dict[str, int]:
tz = settings.TIME_ZONE
if user and user.is_authenticated:
tz = pytz.timezone(user.profile.timezone)
tz = pytz.utc
data_model = apps.get_model(app_label='music', model_name='Track')
if model_str == "Artist":
data_model = apps.get_model(app_label='music', model_name='Artist')
if model_str == "Video":
data_model = apps.get_model(app_label='videos', model_name='Video')
if model_str == "SportEvent":
@ -43,10 +45,16 @@ def get_scrobble_count_qs(
app_label='sports', model_name='SportEvent'
)
base_qs = data_model.objects.filter(
scrobble__user=user,
scrobble__played_to_completion=True,
)
if model_str == "Artist":
base_qs = data_model.objects.filter(
track__scrobble__user=user,
track__scrobble__played_to_completion=True,
)
else:
base_qs = data_model.objects.filter(
scrobble__user=user,
scrobble__played_to_completion=True,
)
# Returna all media items with scrobble count annotated
if not year:
@ -56,29 +64,41 @@ def get_scrobble_count_qs(
start = datetime(year, 1, 1, tzinfo=tz)
end = datetime(year, 12, 31, tzinfo=tz)
if month:
if year and day and month:
logger.debug('Filtering by year, month and day')
start = datetime(year, month, day, 0, 0, tzinfo=tz)
end = datetime(year, month, day, 23, 59, tzinfo=tz)
elif year and week:
logger.debug('Filtering by year and week')
start, end = get_start_end_dates_by_week(year, week, tz)
elif month:
logger.debug('Filtering by month')
end_day = calendar.monthrange(year, month)[1]
start = datetime(year, month, 1, tzinfo=tz)
end = datetime(year, month, end_day, tzinfo=tz)
elif week:
start, end = get_start_end_dates_by_week(year, week, tz)
elif day and month:
start = datetime(year, month, day, 0, 0, tzinfo=tz)
end = datetime(year, month, day, 23, 59, tzinfo=tz)
elif day and not month:
logger.warning('Day provided with month, defaulting ot all-time')
date_filter = Q(
scrobble__timestamp__gte=start, scrobble__timestamp__lte=end
)
return (
base_qs.annotate(
scrobble_count=Count("scrobble", filter=Q(date_filter))
if model_str == "Artist":
scrobble_date_filter = Q(
track__scrobble__timestamp__gte=start,
track__scrobble__timestamp__lte=end,
)
.filter(date_filter)
.order_by("-scrobble_count")
)
qs = (
base_qs.filter(scrobble_date_filter)
.annotate(scrobble_count=Count("track__scrobble", distinct=True))
.order_by("-scrobble_count")
)
else:
scrobble_date_filter = Q(
scrobble__timestamp__gte=start, scrobble__timestamp__lte=end
)
qs = (
base_qs.filter(scrobble_date_filter)
.annotate(scrobble_count=Count("scrobble", distinct=True))
.order_by("-scrobble_count")
)
return qs
def build_charts(
@ -109,7 +129,12 @@ def build_charts(
'user': user,
}
chart_record['rank'] = ranks[result.scrobble_count]
chart_record['count'] = result.scrobble_count
if model_str == 'Track':
chart_record['track'] = result
if model_str == 'Video':
chart_record['video'] = result
if model_str == 'Artist':
chart_record['artist'] = result
chart_records.append(ChartRecord(**chart_record))
ChartRecord.objects.bulk_create(chart_records, ignore_conflicts=True)

View File

@ -24,6 +24,7 @@ def lookup_event_from_thesportsdb(event_id: str) -> dict:
)
data_dict = {
"EventId": event_id,
"ItemType": sport.default_event_type,
"Name": event.get('strEvent'),
"AltName": event.get('strEventAlternate'),

View File

@ -4,7 +4,21 @@ from scrobbles import views
app_name = 'scrobbles'
urlpatterns = [
path('', views.scrobble_endpoint, name='api-list'),
path(
'manual/imdb/',
views.ManualScrobbleView.as_view(),
name='imdb-manual-scrobble',
),
path(
'manual/audioscrobbler/',
views.AudioScrobblerImportCreateView.as_view(),
name='audioscrobbler-file-upload',
),
path(
'manual/koreader/',
views.KoReaderImportCreateView.as_view(),
name='koreader-file-upload',
),
path('finish/<slug:uuid>', views.scrobble_finish, name='finish'),
path('cancel/<slug:uuid>', views.scrobble_cancel, name='cancel'),
path(
@ -12,8 +26,25 @@ urlpatterns = [
views.AudioScrobblerImportCreateView.as_view(),
name='audioscrobbler-file-upload',
),
path('lastfm-import/', views.lastfm_import, name='lastfm-import'),
path('jellyfin/', views.jellyfin_websocket, name='jellyfin-websocket'),
path('mopidy/', views.mopidy_websocket, name='mopidy-websocket'),
path(
'lastfm-import/',
views.lastfm_import,
name='lastfm-import',
),
path(
'webhook/jellyfin/',
views.jellyfin_webhook,
name='jellyfin-webhook',
),
path(
'webhook/mopidy/',
views.mopidy_webhook,
name='mopidy-webhook',
),
path('export/', views.export, name='export'),
path(
'charts/',
views.ChartRecordView.as_view(),
name='charts-home',
),
]

View File

@ -1,10 +1,14 @@
import logging
from urllib.parse import unquote
from django.contrib.auth import get_user_model
from dateutil.parser import ParserError, parse
from django.conf import settings
from django.db import models
logger = logging.getLogger(__name__)
User = get_user_model()
def convert_to_seconds(run_time: str) -> int:
@ -103,3 +107,11 @@ def check_scrobble_for_finish(
if getattr(settings, "KEEP_DETAILED_SCROBBLE_LOGS", False):
scrobble.scrobble_log += f"\n{str(scrobble.timestamp)} - {scrobble.playback_position} - {str(scrobble.playback_position_ticks)} - {str(scrobble.percent_played)}%"
scrobble.save(update_fields=['scrobble_log'])
def get_scrobbles_for_media(media_obj, user: User) -> models.QuerySet:
from scrobbles.models import Scrobble
if media_obj.__class__.__name__ == 'Book':
media_query = models.Q(book=media_obj)
return Scrobble.objects.filter(media_query, user=user)

View File

@ -1,16 +1,19 @@
import calendar
import json
import logging
from datetime import datetime
import pytz
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.db.models.fields import timezone
from django.http import FileResponse, HttpResponseRedirect, JsonResponse
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import FormView
from django.views.generic import FormView, TemplateView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from music.aggregators import (
@ -28,6 +31,7 @@ from rest_framework.decorators import (
from rest_framework.parsers import MultiPartParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from scrobbles.api import serializers
from scrobbles.constants import (
JELLYFIN_AUDIO_ITEM_TYPES,
JELLYFIN_VIDEO_ITEM_TYPES,
@ -37,6 +41,7 @@ from scrobbles.forms import ExportScrobbleForm, ScrobbleForm
from scrobbles.imdb import lookup_video_from_imdb
from scrobbles.models import (
AudioScrobblerTSVImport,
ChartRecord,
KoReaderImport,
LastFmImport,
Scrobble,
@ -49,10 +54,6 @@ from scrobbles.scrobblers import (
mopidy_scrobble_podcast,
mopidy_scrobble_track,
)
from scrobbles.serializers import (
AudioScrobblerTSVImportSerializer,
ScrobbleSerializer,
)
from scrobbles.tasks import (
process_koreader_import,
process_lastfm_import,
@ -215,19 +216,10 @@ def lastfm_import(request):
return HttpResponseRedirect(success_url)
@csrf_exempt
@api_view(['GET'])
def scrobble_endpoint(request):
"""List all Scrobbles, or create a new Scrobble"""
scrobble = Scrobble.objects.all()
serializer = ScrobbleSerializer(scrobble, many=True)
return Response(serializer.data)
@csrf_exempt
@permission_classes([IsAuthenticated])
@api_view(['POST'])
def jellyfin_websocket(request):
def jellyfin_webhook(request):
data_dict = request.data
if (
@ -259,7 +251,7 @@ def jellyfin_websocket(request):
@csrf_exempt
@permission_classes([IsAuthenticated])
@api_view(['POST'])
def mopidy_websocket(request):
def mopidy_webhook(request):
try:
data_dict = json.loads(request.data)
except TypeError:
@ -293,7 +285,9 @@ def import_audioscrobbler_file(request):
scrobbles_created = []
# tsv_file = request.FILES[0]
file_serializer = AudioScrobblerTSVImportSerializer(data=request.data)
file_serializer = serializers.AudioScrobblerTSVImportSerializer(
data=request.data
)
if file_serializer.is_valid():
import_file = file_serializer.save()
return Response(
@ -305,39 +299,48 @@ def import_audioscrobbler_file(request):
)
@csrf_exempt
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def scrobble_finish(request, uuid):
user = request.user
success_url = reverse_lazy('vrobbler-home')
if not user.is_authenticated:
return Response({}, status=status.HTTP_403_FORBIDDEN)
return HttpResponseRedirect(success_url)
scrobble = Scrobble.objects.filter(user=user, uuid=uuid).first()
if not scrobble:
return Response({}, status=status.HTTP_404_NOT_FOUND)
scrobble.stop(force_finish=True)
return Response(
{'id': scrobble.id, 'status': scrobble.status},
status=status.HTTP_200_OK,
)
if scrobble:
scrobble.stop(force_finish=True)
messages.add_message(
request,
messages.SUCCESS,
f"Scrobble of {scrobble.media_obj} finished.",
)
else:
messages.add_message(request, messages.ERROR, "Scrobble not found.")
return HttpResponseRedirect(success_url)
@csrf_exempt
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def scrobble_cancel(request, uuid):
user = request.user
success_url = reverse_lazy('vrobbler-home')
if not user.is_authenticated:
return Response({}, status=status.HTTP_403_FORBIDDEN)
return HttpResponseRedirect(success_url)
scrobble = Scrobble.objects.filter(user=user, uuid=uuid).first()
if not scrobble:
return Response({}, status=status.HTTP_404_NOT_FOUND)
scrobble.cancel()
return Response(
{'id': scrobble.id, 'status': 'cancelled'}, status=status.HTTP_200_OK
)
if scrobble:
scrobble.cancel()
messages.add_message(
request,
messages.SUCCESS,
f"Scrobble of {scrobble.media_obj} cancelled.",
)
else:
messages.add_message(request, messages.ERROR, "Scrobble not found.")
return HttpResponseRedirect(success_url)
@permission_classes([IsAuthenticated])
@ -358,3 +361,69 @@ def export(request):
response["Content-Disposition"] = f'attachment; filename="{filename}"'
return response
class ChartRecordView(TemplateView):
template_name = 'scrobbles/chart_index.html'
def get_context_data(self, **kwargs):
context_data = super().get_context_data(**kwargs)
date = self.request.GET.get('date')
media_type = self.request.GET.get('media')
params = {}
if not media_type:
media_type = 'Track'
context_data['media_type'] = media_type
media_filter = Q(track__isnull=False)
if media_type == 'Video':
media_filter = Q(video__isnull=False)
if media_type == 'Artist':
media_filter = Q(artist__isnull=False)
year = timezone.now().year
params = {'year': year}
name = f"Chart for {year}"
if not date:
date = timezone.now().strftime("%Y-%m-%d")
date_params = date.split('-')
year = int(date_params[0])
if len(date_params) == 2:
if 'W' in date_params[1]:
week = int(date_params[1].strip('W"'))
params['week'] = week
r = datetime.strptime(date + '-1', "%Y-W%W-%w").strftime(
'Week of %B %d, %Y'
)
name = f"Chart for {r}"
else:
month = int(date_params[1])
params['month'] = month
month_str = calendar.month_name[month]
name = f"Chart for {month_str} {year}"
if len(date_params) == 3:
month = int(date_params[1])
day = int(date_params[2])
params['month'] = month
params['day'] = day
month_str = calendar.month_name[month]
name = f"Chart for {month_str} {day}, {year}"
charts = ChartRecord.objects.filter(
media_filter, user=self.request.user, **params
).order_by("rank")
if charts.count() == 0:
ChartRecord.build(
user=self.request.user, model_str=media_type, **params
)
charts = ChartRecord.objects.filter(
media_filter, user=self.request.user, **params
).order_by("rank")
context_data['object_list'] = charts
context_data['name'] = name
return context_data

View File

@ -0,0 +1,18 @@
# Generated by Django 4.1.5 on 2023-02-23 15:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sports', '0007_sport_default_event_type'),
]
operations = [
migrations.AddField(
model_name='sportevent',
name='thesportsdb_id',
field=models.CharField(blank=True, max_length=255, null=True),
),
]

View File

@ -15,8 +15,9 @@ BNULL = {"blank": True, "null": True}
class SportEventType(models.TextChoices):
UNKNOWN = 'UK', _('Unknown')
UNKNOWN = 'UK', _('Event')
GAME = 'GA', _('Game')
RACE = 'RA', _('Race')
MATCH = 'MA', _('Match')
@ -89,6 +90,7 @@ class Round(TheSportsDbMixin):
class SportEvent(ScrobblableMixin):
COMPLETION_PERCENT = getattr(settings, 'SPORT_COMPLETION_PERCENT', 90)
thesportsdb_id = models.CharField(max_length=255, **BNULL)
event_type = models.CharField(
max_length=2,
choices=SportEventType.choices,
@ -127,6 +129,18 @@ class SportEvent(ScrobblableMixin):
def get_absolute_url(self):
return reverse("sports:event_detail", kwargs={'slug': self.uuid})
@property
def subtitle(self):
return self.round.season.league
@property
def sportsdb_link(self):
return f"https://thesportsdb.com/event/{self.thesportsdb_id}"
@property
def info_link(self):
return self.sportsdb_link
@classmethod
def find_or_create(cls, data_dict: Dict) -> "Event":
"""Given a data dict from Jellyfin, does the heavy lifting of looking up
@ -208,6 +222,7 @@ class SportEvent(ScrobblableMixin):
away_team, _created = Team.objects.get_or_create(**away_team_dict)
event_dict = {
"thesportsdb_id": data_dict.get("EventId"),
"title": data_dict.get("Name"),
"event_type": sport.default_event_type,
"home_team": home_team,

View File

View File

@ -0,0 +1,14 @@
from videos.models import Series, Video
from rest_framework import serializers
class SeriesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Series
fields = "__all__"
class VideoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Video
fields = "__all__"

View File

@ -0,0 +1,19 @@
from rest_framework import permissions, viewsets
from videos.api.serializers import (
SeriesSerializer,
VideoSerializer,
)
from videos.models import Series, Video
class SeriesViewSet(viewsets.ModelViewSet):
queryset = Series.objects.all().order_by('-created')
serializer_class = SeriesSerializer
permission_classes = [permissions.IsAuthenticated]
class VideoViewSet(viewsets.ModelViewSet):
queryset = Video.objects.all().order_by('-created')
serializer_class = VideoSerializer
permission_classes = [permissions.IsAuthenticated]

View File

@ -69,10 +69,24 @@ class Video(ScrobblableMixin):
def get_absolute_url(self):
return reverse("videos:video_detail", kwargs={'slug': self.uuid})
@property
def subtitle(self):
if self.tv_series:
return self.tv_series
return ""
@property
def imdb_link(self):
return f"https://www.imdb.com/title/{self.imdb_id}"
@property
def info_link(self):
return self.imdb_link
@property
def link(self):
return self.imdb_link
@classmethod
def find_or_create(cls, data_dict: Dict) -> "Video":
"""Given a data dict from Jellyfin, does the heavy lifting of looking up

View File

@ -6,6 +6,7 @@ from videos.models import Series, Video
class MovieListView(generic.ListView):
model = Video
template_name = "videos/movie_list.html"
def get_queryset(self):
return Video.objects.filter(video_type=Video.VideoType.MOVIE)

View File

@ -140,6 +140,8 @@ TEMPLATES = [
},
]
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
WSGI_APPLICATION = "vrobbler.wsgi.application"
DATABASES = {
@ -171,22 +173,19 @@ AUTHENTICATION_BACKENDS = [
"allauth.account.auth_backends.AuthenticationBackend",
]
# We have to ignore content negotiation because Jellyfin is a bad actor
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'vrobbler.negotiation.IgnoreClientContentNegotiation',
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend"
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
],
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'vrobbler.negotiation.IgnoreClientContentNegotiation',
"PAGE_SIZE": 100,
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 200,
}
LOGIN_REDIRECT_URL = "/"

View File

@ -177,7 +177,7 @@
</button>
{% if user.is_authenticated %}
<form id="scrobble-form" action="{% url 'imdb-manual-scrobble' %}" method="post">
<form id="scrobble-form" action="{% url 'scrobbles:imdb-manual-scrobble' %}" method="post">
{% csrf_token %}
{{ imdb_form }}
</form>
@ -197,16 +197,20 @@
<div class="row">
<nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
<div class="position-sticky pt-3">
{% if messages %}
<ul style="padding-right:10px;">
{% for message in messages %}
<li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% if now_playing_list and user.is_authenticated %}
<ul style="padding-right:10px;">
<b>Now playing</b>
{% for scrobble in now_playing_list %}
<div>
{{scrobble.media_obj.title}}<br/>
{% if scrobble.track %}<em>{{scrobble.track.artist}}</em><br/>{% endif %}
{% if scrobble.podcast_episode%}<em>{{scrobble.podcast_episode.podcast}}</em><br/>{% endif %}
{% if scrobble.video.tv_series %}<em>{{scrobble.video.tv_series }}</em><br/>{% endif %}
{% if scrobble.sport_event %}<em>{{scrobble.sport_event.round.season.league}}</em><br/>{% endif %}
{% if scrobble.media_obj.subtitle %}<em>{{scrobble.media_obj.subtitle}}</em><br/>{% endif %}
<small>{{scrobble.timestamp|naturaltime}}<br/>
from {{scrobble.source}}</small>
<div class="progress-bar" style="margin-right:5px;">
@ -219,8 +223,6 @@
{% endfor %}
</ul>
{% endif %}
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">
@ -228,6 +230,12 @@
Dashboard
</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/charts/">
<span data-feather="bar-chart"></span>
Charts
</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/tracks/">
<span data-feather="music"></span>
@ -249,7 +257,7 @@
<li class="nav-item">
<a class="nav-link" href="/series/">
<span data-feather="tv"></span>
Series
TV Shows
</a>
</li>
{% if user.is_authenticated %}
@ -271,6 +279,7 @@
{% endblock %}
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/feather-icons@4.28.0/dist/feather.min.js" integrity="sha384-uO3SXW5IuS1ZpFPKugNNWqTZRRglnUJK6UAZ/gxOX80nxEkN9NcGZTftn6RzhGWE" crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js" integrity="sha384-zNy6FEbO50N+Cg5wap8IKA4M/ZnLJgzc6w2NqACZaK0u0FXfOWRRJOnQtpZun8ha" crossorigin="anonymous"></script>
<script><!-- comment ------------------------------------------------->
/* globals Chart:false, feather:false */

View File

@ -1,8 +1,9 @@
{% extends "base.html" %}
{% block content %}
<main class="col-md-4 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">
<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">
<h1 class="h2">{% block title %}{% endblock %} </h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group me-2">
@ -15,4 +16,4 @@
{% block lists %}{% endblock %}
</div>
</main>
{% endblock %}
{% endblock %}

View File

@ -0,0 +1,30 @@
{% extends "base_list.html" %}
{% block lists %}
<h2>{{name}}</h2>
<div class="row">
<div class="col-md">
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Rank</th>
<th scope="col">{{media_type}}</th>
<th scope="col">Scrobbles</th>
</tr>
</thead>
<tbody>
{% for chartrecord in object_list %}
<tr>
<td>{{chartrecord.rank}}</td>
<td><a href="{{chartrecord.media_obj.get_absolute_url}}">{{chartrecord.media_obj}}</a></td>
<td>{{chartrecord.count}}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}

View File

@ -3,7 +3,7 @@
{% block content %}
<main class="col-md-4 ms-sm-auto col-lg-10 px-md-4">
<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">
<h1 class="h2">Dashboard</h1>
@ -316,7 +316,7 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<form action="{% url 'audioscrobbler-file-upload' %}" method="post" enctype="multipart/form-data">
<form action="{% url 'scrobbles:audioscrobbler-file-upload' %}" method="post" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
<div class="form-group">
@ -328,7 +328,7 @@
<button type="submit" class="btn btn-primary">Import</button>
</div>
</form>
<form action="{% url 'koreader-file-upload' %}" method="post" enctype="multipart/form-data">
<form action="{% url 'scrobbles:koreader-file-upload' %}" method="post" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
<div class="form-group">

View File

@ -1,13 +1,14 @@
{% extends "base.html" %}
{% block content %}
<main class="col-md-4 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
class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Manual scrobble</h1>
<form action="{% url 'audioscrobbler-file-upload' %}" method="post">
<form action="{% url 'scrobbles:audioscrobbler-file-upload' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</div>
</main>
{% endblock %}
{% endblock %}

View File

@ -1,28 +1,28 @@
{% extends "base.html" %}
{% extends "base_list.html" %}
{% block content %}
<main class="col-md-4 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">
<h1 class="h2">Movies</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group me-2">
<button type="button" class="btn btn-sm btn-outline-secondary">Share</button>
<button type="button" class="btn btn-sm btn-outline-secondary">Export</button>
</div>
<button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle">
<span data-feather="calendar"></span>
This week
</button>
{% block lists %}
<div class="row">
<div class="col-md">
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Scrobbles</th>
<th scope="col">All time</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
<tr>
<td><a href="{{obj.get_absolute_url}}">{{obj}}</a></td>
<td>{{obj.scrobble_set.count}}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="container">
<ul>
{% for movie in object_list %}
<li>{{movie}}</li>
{% endfor %}
</ul>
</div>
</main>
{% endblock %}
</div>
{% endblock %}

View File

@ -1,22 +1,32 @@
{% extends "base.html" %}
{% extends "base_list.html" %}
{% block content %}
<main class="col-md-4 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">
<h1 class="h2">Series</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group me-2">
<button type="button" class="btn btn-sm btn-outline-secondary">Export</button>
</div>
{% block lists %}
<div class="row">
<div class="col-md">
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Series</th>
<th scope="col">Episode</th>
<th scope="col">Scrobbles</th>
<th scope="col">All time</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
{% for video in obj.video_set.all %}
<tr>
<td><a href="{{video.get_absolute_url}}">{{video}}</a></td>
<td><a href="{{obj.get_absolute_url}}">{{obj}}</a></td>
<td>{{video.scrobble_set.count}}</td>
<td></td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="container">
<ul>
{% for movie in object_list %}
<li>{{movie}}</li>
{% endfor %}
</ul>
</div>
</main>
{% endblock %}
</div>
{% endblock %}

View File

@ -1,14 +1,37 @@
{% extends "base.html" %}
{% extends "base_detail.html" %}
{% block title %}Videos{% endblock %}
{% block title %}{{object.name}}{% endblock %}
{% block content %}
{{object}}
{% block details %}
{% for scrobble in object.scrobble_set.all %}
<ul>
<li>{{scrobble}}</li>
</ul>
{% endfor %}
{% endblock %}
<div class="row">
<h2>{{object.tv_series}}</h2>
<div class="col-md">
<h3>Last scrobbles</h3>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Title</th>
<th scope="col">Series</th>
<th scope="col">Season</th>
<th scope="col">Episode</th>
</tr>
</thead>
<tbody>
{% for scrobble in object.scrobble_set.all %}
<tr>
<td>{{scrobble.timestamp}}</td>
<td>{{scrobble.video.title}}</td>
<td>{{scrobble.video.tv_series}}</td>
<td>{{scrobble.video.season_number}}</td>
<td>{{scrobble.video.episode_number}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}

View File

@ -1,13 +0,0 @@
{% extends "base.html" %}
{% block title %}Movies{% endblock %}
{% block content %}
{% for movie in object_list %}
<dl>
<dt>{{movie}}</dt>
{% for scrobble in movie.scrobble_set.all %}
<dd>{{scrobble}}</dd>
{% endfor %}
</dl>
{% endfor %}
{% endblock %}

View File

@ -3,34 +3,49 @@ from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from scrobbles import urls as scrobble_urls
from music import urls as music_urls
from videos import urls as video_urls
from rest_framework import routers
from vrobbler.apps.books.api.views import AuthorViewSet, BookViewSet
from vrobbler.apps.music import urls as music_urls
from vrobbler.apps.music.api.views import (
AlbumViewSet,
ArtistViewSet,
TrackViewSet,
)
from vrobbler.apps.profiles.api.views import UserProfileViewSet, UserViewSet
from vrobbler.apps.scrobbles import urls as scrobble_urls
from vrobbler.apps.scrobbles.api.views import (
AudioScrobblerTSVImportViewSet,
KoReaderImportViewSet,
LastFmImportViewSet,
ScrobbleViewSet,
)
from vrobbler.apps.videos import urls as video_urls
from vrobbler.apps.videos.api.views import SeriesViewSet, VideoViewSet
router = routers.DefaultRouter()
router.register(r'scrobbles', ScrobbleViewSet)
router.register(r'lastfm-imports', LastFmImportViewSet)
router.register(r'tsv-imports', AudioScrobblerTSVImportViewSet)
router.register(r'koreader-imports', KoReaderImportViewSet)
router.register(r'artist', ArtistViewSet)
router.register(r'album', AlbumViewSet)
router.register(r'tracks', TrackViewSet)
router.register(r'series', SeriesViewSet)
router.register(r'videos', VideoViewSet)
router.register(r'authors', AuthorViewSet)
router.register(r'books', BookViewSet)
router.register(r'users', UserViewSet)
router.register(r'user_profiles', UserProfileViewSet)
urlpatterns = [
path('api/v1/', include(router.urls)),
path('api/v1/auth', include("rest_framework.urls")),
path("admin/", admin.site.urls),
path("accounts/", include("allauth.urls")),
# path("api-auth/", include("rest_framework.urls")),
# path("movies/", include(movies, namespace="movies")),
# path("shows/", include(shows, namespace="shows")),
path("api/v1/scrobbles/", include(scrobble_urls, namespace="scrobbles")),
path(
'manual/imdb/',
scrobbles_views.ManualScrobbleView.as_view(),
name='imdb-manual-scrobble',
),
path(
'manual/audioscrobbler/',
scrobbles_views.AudioScrobblerImportCreateView.as_view(),
name='audioscrobbler-file-upload',
),
path(
'manual/koreader/',
scrobbles_views.KoReaderImportCreateView.as_view(),
name='koreader-file-upload',
),
path("", include(music_urls, namespace="music")),
path("", include(video_urls, namespace="videos")),
path("", include(scrobble_urls, namespace="scrobbles")),
path(
"", scrobbles_views.RecentScrobbleList.as_view(), name="vrobbler-home"
),