Commit 7876e77a authored by Eliot Berriot's avatar Eliot Berriot 💬

Merge branch '551-display-libraries' into 'develop'

Resolve "Display available libraries containing a track / album / artist"

Closes #551

See merge request funkwhale/funkwhale!433
parents d7b6e546 c2a2321b
......@@ -3,7 +3,7 @@ import urllib
from django.conf import settings
from django.db import transaction
from django.db.models import Count, Prefetch, Sum, F
from django.db.models import Count, Prefetch, Sum, F, Q
from django.db.models.functions import Length
from django.utils import timezone
......@@ -26,6 +26,28 @@ from . import filters, models, serializers, tasks, utils
logger = logging.getLogger(__name__)
def get_libraries(filter_uploads):
def view(self, request, *args, **kwargs):
obj = self.get_object()
actor = utils.get_actor_from_request(request)
uploads = models.Upload.objects.all()
uploads = filter_uploads(obj, uploads)
uploads = uploads.playable_by(actor)
libraries = models.Library.objects.filter(
pk__in=uploads.values_list("library", flat=True)
)
libraries = libraries.select_related("actor")
page = self.paginate_queryset(libraries)
if page is not None:
serializer = federation_api_serializers.LibrarySerializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = federation_api_serializers.LibrarySerializer(libraries, many=True)
return Response(serializer.data)
return view
class TagViewSetMixin(object):
def get_queryset(self):
queryset = super().get_queryset()
......@@ -50,6 +72,14 @@ class ArtistViewSet(viewsets.ReadOnlyModelViewSet):
)
return queryset.prefetch_related(Prefetch("albums", queryset=albums)).distinct()
libraries = detail_route(methods=["get"])(
get_libraries(
filter_uploads=lambda o, uploads: uploads.filter(
Q(track__artist=o) | Q(track__album__artist=o)
)
)
)
class AlbumViewSet(viewsets.ReadOnlyModelViewSet):
queryset = (
......@@ -76,6 +106,10 @@ class AlbumViewSet(viewsets.ReadOnlyModelViewSet):
qs = queryset.prefetch_related(Prefetch("tracks", queryset=tracks))
return qs.distinct()
libraries = detail_route(methods=["get"])(
get_libraries(filter_uploads=lambda o, uploads: uploads.filter(track__album=o))
)
class LibraryViewSet(
mixins.CreateModelMixin,
......@@ -197,6 +231,10 @@ class TrackViewSet(TagViewSetMixin, viewsets.ReadOnlyModelViewSet):
serializer = serializers.LyricsSerializer(lyrics)
return Response(serializer.data)
libraries = detail_route(methods=["get"])(
get_libraries(filter_uploads=lambda o, uploads: uploads.filter(track=o))
)
def get_file_path(audio_file):
serve_path = settings.MUSIC_DIRECTORY_SERVE_PATH
......
......@@ -449,3 +449,34 @@ def test_user_can_list_own_library_follows(factories, logged_in_api_client):
"previous": None,
"results": [federation_api_serializers.LibraryFollowSerializer(follow).data],
}
@pytest.mark.parametrize("entity", ["artist", "album", "track"])
def test_can_get_libraries_for_music_entities(
factories, api_client, entity, preferences
):
preferences["common__api_authentication_required"] = False
upload = factories["music.Upload"](playable=True)
# another private library that should not appear
factories["music.Upload"](
import_status="finished", library__privacy_level="me", track=upload.track
).library
library = upload.library
data = {
"artist": upload.track.artist,
"album": upload.track.album,
"track": upload.track,
}
url = reverse("api:v1:{}s-libraries".format(entity), kwargs={"pk": data[entity].pk})
response = api_client.get(url)
expected = federation_api_serializers.LibrarySerializer(library).data
assert response.status_code == 200
assert response.data == {
"count": 1,
"next": None,
"previous": None,
"results": [expected],
}
Added a library widget to display libraries associated with a track, album and artist (#551)
......@@ -38,7 +38,7 @@
</table>
<div class="center aligned segment" v-if="album.tracks.length > initialTracks">
<em v-if="!showAllTracks" @click="showAllTracks = true" class="expand">
<translate :translate-params="{count: album.tracks.length - initialTracks}" :translate-n="album.tracks.length - initialTracks" translate-plural="Show %{ count } more tracks">Show 1 more track</translate>
<translate :translate-params="{count: album.tracks.length - initialTracks}" :translate-n="album.tracks.length - initialTracks" translate-plural="Show %{ count } more tracks">Show %{ count } more track</translate>
</em>
<em v-else @click="showAllTracks = false" class="expand">
<translate>Collapse</translate>
......@@ -52,7 +52,7 @@
</play-button>
<span>
<i class="music icon"></i>
<translate :translate-params="{count: album.tracks.length}" :translate-n="album.tracks.length" translate-plural="%{ count } tracks">1 track</translate>
<translate :translate-params="{count: album.tracks.length}" :translate-n="album.tracks.length" translate-plural="%{ count } tracks">%{ count } track</translate>
</span>
</div>
</div>
......
......@@ -4,7 +4,7 @@
<translate>Text copied to clipboard!</translate>
</p>
<input ref="input" :value="value" type="text">
<button @click="copy" class="ui teal right labeled icon button">
<button @click="copy" :class="['ui', buttonClasses, 'right', 'labeled', 'icon', 'button']">
<i class="copy icon"></i>
<translate>Copy</translate>
</button>
......@@ -12,7 +12,10 @@
</template>
<script>
export default {
props: ['value'],
props: {
value: {type: String},
buttonClasses: {type: String, default: 'teal'}
},
data () {
return {
copied: false,
......
<template>
<div class="ui card">
<div class="content">
<div class="header ellipsis">
<router-link
v-if="library"
:title="displayName"
:to="{name: 'federation.libraries.detail', params: {id: library.uuid }}">
{{ displayName }}
</router-link>
<span :title="displayName" v-else>{{ displayName }}</span>
</div>
</div>
<div class="content">
<span class="right floated" v-if="following">
<i class="check icon"></i><translate>Following</translate>
</span>
<span class="right floated" v-else-if="manuallyApprovesFollowers">
<i class="lock icon"></i><translate>Followers only</translate>
</span>
<span class="right floated" v-else>
<i class="open lock icon"></i><translate>Open</translate>
</span>
<span v-if="totalItems">
<i class="music icon"></i>
<translate
translate-plural="%{ count } tracks"
:translate-n="totalItems"
:translate-params="{count: totalItems}">
1 track
</translate>
</span>
</div>
<div class="extra content">
<template v-if="awaitingApproval">
<i class="clock icon"></i>
<translate>Follow request pending approval</translate>
</template>
<div
v-if="!library"
@click="follow"
:disabled="isLoading"
:class="['ui', 'basic', {loading: isLoading}, 'green', 'button']">
<translate v-if="manuallyApprovesFollowers">Send a follow request</translate>
<translate v-else>Follow</translate>
</div>
<router-link
v-else
class="ui basic button"
:to="{name: 'federation.libraries.detail', params: {id: library.uuid }}">
<translate>Detail</translate>
</router-link>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: ['libraryData', 'libraryInstance'],
data () {
return {
library: this.libraryInstance,
isLoading: false,
data: null,
errors: []
}
},
methods: {
follow () {
let params = {
'actor': this.libraryData['actor']['id'],
'autoimport': false,
'download_files': false,
'federation_enabled': true
}
let self = this
self.isLoading = true
axios.post('/federation/libraries/', params).then((response) => {
self.$emit('follow', {data: self.libraryData, library: response.data})
self.library = response.data
self.isLoading = false
}, error => {
self.isLoading = false
self.errors = error.backendErrors
})
}
},
computed: {
displayName () {
if (this.libraryData) {
return this.libraryData.display_name
} else {
return `${this.library.actor.preferred_username}@${this.library.actor.domain}`
}
},
manuallyApprovesFollowers () {
if (this.libraryData) {
return this.libraryData.actor.manuallyApprovesFollowers
} else {
return this.library.actor.manually_approves_followers
}
},
totalItems () {
if (this.libraryData) {
return this.libraryData.library.totalItems
} else {
return this.library.tracks_count
}
},
awaitingApproval () {
if (this.libraryData) {
return this.libraryData.local.awaiting_approval
} else {
return this.library.follow.approved === null
}
},
following () {
if (this.libraryData) {
return this.libraryData.local.following
} else {
return this.library.follow.approved
}
}
}
}
</script>
<template>
<div>
<div class="ui form">
<div class="fields">
<div class="ui six wide field">
<input type="text" v-model="search" :placeholder="labels.searchPlaceholder" />
</div>
<div class="ui four wide inline field">
<div class="ui checkbox">
<input v-model="pending" type="checkbox">
<label>
<translate>Pending approval</translate>
</label>
</div>
</div>
</div>
</div>
<div class="ui hidden divider"></div>
<table v-if="result" class="ui very basic single line unstackable table">
<thead>
<tr>
<th><translate>Actor</translate></th>
<th><translate>Creation date</translate></th>
<th><translate>Status</translate></th>
<th><translate>Actions</translate></th>
</tr>
</thead>
<tbody>
<tr v-for="follow in result.results">
<td>
{{ follow.actor.preferred_username }}@{{ follow.actor.domain }}
</td>
<td>
<human-date :date="follow.creation_date"></human-date>
</td>
<td>
<template v-if="follow.approved === true">
<i class="check icon"></i>
<translate>Approved</translate>
</template>
<template v-else-if="follow.approved === false">
<i class="x icon"></i>
<translate>Refused</translate>
</template>
<template v-else>
<i class="clock icon"></i>
<translate>Pending</translate>
</template>
</td>
<td>
<dangerous-button v-if="follow.approved !== false" class="tiny basic labeled icon" color='red' @confirm="updateFollow(follow, false)">
<i class="x icon"></i>
<translate>Deny</translate>
<p slot="modal-header">
<translate>Deny access?</translate>
</p>
<p slot="modal-content">
<translate
:translate-params="{username: follow.actor.preferred_username + '@' + follow.actor.domain}">
By confirming, %{ username } will be denied access to your library.
</translate>
</p>
<p slot="modal-confirm">
<translate>Deny</translate>
</p>
</dangerous-button>
<dangerous-button v-if="follow.approved !== true" class="tiny basic labeled icon" color='green' @confirm="updateFollow(follow, true)">
<i class="check icon"></i>
<translate>Approve</translate>
<p slot="modal-header">
<translate>Approve access?</translate>
</p>
<p slot="modal-content">
<translate
:translate-params="{username: follow.actor.preferred_username + '@' + follow.actor.domain}">
By confirming, %{ username } will be granted access to your library.
</translate>
<p slot="modal-confirm">
<translate>Approve</translate>
</p>
</dangerous-button>
</td>
</tr>
</tbody>
<tfoot class="full-width">
<tr>
<th>
<pagination
v-if="result && result.count > paginateBy"
@page-changed="selectPage"
:compact="true"
:current="page"
:paginate-by="paginateBy"
:total="result.count"
></pagination>
</th>
<th v-if="result && result.results.length > 0">
<translate
:translate-params="{start: ((page-1) * paginateBy) + 1, end: ((page-1) * paginateBy) + result.results.length, total: result.count}">
Showing results %{ start }-%{ end } on %{ total }
</translate>
</th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</template>
<script>
import axios from 'axios'
import _ from 'lodash'
import Pagination from '@/components/Pagination'
export default {
props: {
filters: {type: Object, required: false, default: () => {}}
},
components: {
Pagination
},
data () {
return {
isLoading: false,
result: null,
page: 1,
paginateBy: 25,
search: '',
pending: false
}
},
created () {
this.fetchData()
},
computed: {
labels () {
return {
searchPlaceholder: this.$gettext('Search by username, domain...')
}
}
},
methods: {
fetchData () {
let params = _.merge({
'page': this.page,
'page_size': this.paginateBy,
'q': this.search
}, this.filters)
if (this.pending) {
params.pending = true
}
let self = this
self.isLoading = true
axios.get('/federation/libraries/followers/', {params: params}).then((response) => {
self.result = response.data
self.isLoading = false
}, error => {
self.isLoading = false
self.errors = error.backendErrors
})
},
selectPage: function (page) {
this.page = page
},
updateFollow (follow, approved) {
let payload = {
follow: follow.id,
approved: approved
}
let self = this
axios.patch('/federation/libraries/followers/', payload).then((response) => {
follow.approved = response.data.approved
self.isLoading = false
}, error => {
self.isLoading = false
self.errors = error.backendErrors
})
}
},
watch: {
search (newValue) {
if (newValue.length > 0) {
this.fetchData()
}
},
page () {
this.fetchData()
},
pending () {
this.fetchData()
}
}
}
</script>
<template>
<form class="ui form" @submit.prevent="fetchInstanceInfo">
<h3 class="ui header">
<translate>Federate with a new instance</translate>
</h3>
<p>
<translate>Use this form to scan an instance and setup federation.</translate>
</p>
<div v-if="errors.length > 0 || scanErrors.length > 0" class="ui negative message">
<div class="header">
<translate>Error while scanning library</translate>
</div>
<ul class="list">
<li v-for="error in errors">{{ error }}</li>
<li v-for="error in scanErrors">{{ error }}</li>
</ul>
</div>
<div class="ui two fields">
<div class="ui field">
<label>
<translate>Library name</translate>
</label>
<input v-model="libraryUsername" type="text" :placeholder="labels.namePlaceholder" />
</div>
<div class="ui field">
<label>&nbsp;</label>
<button
type="submit"
:disabled="isLoading"
:class="['ui', 'icon', {loading: isLoading}, 'button']">
<i class="search icon"></i>
<translate>Launch scan</translate>
</button>
</div>
</div>
</form>
</template>
<script>
import axios from 'axios'
import TrackTable from '@/components/audio/track/Table'
import RadioButton from '@/components/radios/Button'
import Pagination from '@/components/Pagination'
export default {
components: {
TrackTable,
RadioButton,
Pagination
},
data () {
return {
isLoading: false,
libraryUsername: '',
result: null,
errors: []
}
},
methods: {
follow () {
let params = {
'actor': this.result['actor']['id'],
'autoimport': false,
'download_files': false,
'federation_enabled': true
}
let self = this
self.isFollowing = false
axios.post('/federation/libraries/', params).then((response) => {
self.$emit('follow', {data: self.result, library: response.data})
self.result = response.data
self.isFollowing = false
}, error => {
self.isFollowing = false
self.errors = error.backendErrors
})
},
fetchInstanceInfo () {
let self = this
this.isLoading = true
self.errors = []
self.result = null
axios.get('/federation/libraries/fetch/', {params: {account: this.libraryUsername.trim()}}).then((response) => {
self.result = response.data
self.result.display_name = self.libraryUsername
self.isLoading = false
}, error => {
self.isLoading = false
self.errors = error.backendErrors
})
}
},
computed: {
labels () {
return {
namePlaceholder: this.$gettext('library@demo.funkwhale.audio')
}
},
scanErrors () {
let errors = []
if (!this.result) {
return errors
}
let keys = ['webfinger', 'actor', 'library']
keys.forEach(k => {
if (this.result[k]) {
if (this.result[k].errors) {
this.result[k].errors.forEach(e => {
errors.push(e)
})
}
}
})
return errors
}
},
watch: {
result (newValue, oldValue) {
this.$emit('scanned', newValue)
}
}
}
</script>
<template>
<div>
<div class="ui inline form">
<div class="fields">
<div class="ui six wide field">
<label><translate>Search</translate></label>
<input type="text" v-model="search" :placeholder="labels.searchPlaceholder" />
</div>
<div class="ui field">
<label><translate>Import status</translate></label>
<select class="ui dropdown" v-model="importedFilter">
<option :value="null"><translate>Any</translate></option>
<option :value="'imported'"><translate>Imported</translate></option>
<option :value="'not_imported'"><translate>Not imported</translate></option>
<option :value="'import_pending'"><translate>Import pending</translate></option>
</select>
</div>
<div class="field">
<label><translate>Ordering</translate></label>
<select class="ui dropdown" v-model="ordering">
<option v-for="option in orderingOptions" :value="option[0]">
{{ option[1] }}
</option>
</select>
</div>
<div class="field">
<label><translate>Ordering direction</translate></label>
<select class="ui dropdown" v-model="orderingDirection">
<option value="+"><translate>Ascending</translate></option>
<option value="-"><translate>Descending</translate></option>
</select>
</div>
</div>
</div>
<div class="dimmable">
<div v-if="isLoading" class="ui active inverted dimmer">
<div class="ui loader"></div>
</div>
<action-table
v-if="result"
@action-launched="fetchData"
:objects-data="result"
:actions="actions"
:action-url="'federation/library-tracks/action/'"
:filters="actionFilters">
<template slot="header-cells">
<th><translate>Status</translate></th>
<th><translate>Title</translate></th>
<th><translate>Artist</translate></th>
<th><translate>Album</translate></th>
<th><translate>Published date</translate></th>
<th v-if="showLibrary"><translate>Library</translate></th>
</template>
<template slot="action-success-footer" slot-scope="scope">
<router-link
v-if="scope.result.action === 'import'"
:to="{name: 'library.import.batches.detail', params: {id: scope.result.result.batch.id }}">
<translate
:translate-params="{id: scope.result.result.batch.id}">
Import #%{ id } launched
</translate>
</router-link>
</template>
<template slot="row-cells" slot-scope="scope">
<td>
<span v-if="scope.obj.status === 'imported'" class="ui basic green label"><translate>In library</translate></span>
<span v-else-if="scope.obj.status === 'import_pending'" class="ui basic yellow label"><translate>Import pending</translate></span>
<span v-else class="ui basic label"><translate>Not imported</translate></span>
</td>
<td>
<span :title="scope.obj.title">{{ scope.obj.title|truncate(30) }}</span>
</td>
<td>
<span class="discrete link" @click="updateSearch({key: 'artist', value: scope.obj.artist_name})" :title="scope.obj.artist_name">{{ scope.obj.artist_name|truncate(30) }}</span>
</td>
<td>
<span class="discrete link" @click="updateSearch({key: 'album', value: scope.obj.album_title})" :title="scope.obj.album_title">{{ scope.obj.album_title|truncate(20) }}</span>
</td>
<td>
<human-date :date="scope.obj.published_date"></human-date>
</td>
<td v-if="showLibrary">
<span class="discrete link" @click="updateSearch({key: 'domain', value: scope.obj.library.actor.domain})">{{ scope.obj.library.actor.domain }}</span>
</td>
</template>
</action-table>
</div>
<div>
<pagination
v-if="result && result.count > paginateBy"
@page-changed="selectPage"
:compact="true"
:current="page"
:paginate-by="paginateBy"
:total="result.count"
></pagination>
<span v-if="result && result.results.length > 0">
<translate
:translate-params="{start: ((page-1) * paginateBy) + 1, end: ((page-1) * paginateBy) + result.results.length, total: result.count}">
Showing results %{ start }-%{ end } on %{ total }
</translate>
</span>
</div>