-
Notifications
You must be signed in to change notification settings - Fork 87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Collections #1810
Draft
quimmrc
wants to merge
31
commits into
master
Choose a base branch
from
collections
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,230
−15
Draft
Collections #1810
Changes from 19 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
813bd48
collections app creation and first basic implementations
quimmrc 52543c4
migration: add collection attributes
quimmrc 5f137eb
attempt to implement collection modals
quimmrc 51adc61
models reformulation
quimmrc 13a90da
Merge branch 'master' into collections
quimmrc 2780959
add sound modal behavior tbd
quimmrc 4c7c190
add sound modal collection selector
quimmrc 0f47090
add sound to col from sound url
quimmrc fc55074
delete sound from collection func.
quimmrc b2e0277
deletion for CollectionSound + restrict add duplicates
quimmrc 5ba088d
minor details correction
quimmrc ae9950b
delete and create collection functionalities
quimmrc d679849
Edit collection permissions
quimmrc 58d845f
add collection parameter to settings.py
quimmrc 3d7a668
add maintainer modal (fails)
quimmrc 5ffea0b
add maintainers interface
quimmrc d5fed09
adequate variable namings for collection modals
quimmrc 04ba23d
maintainers display in edit collection url
quimmrc e2bc70a
Merge branch 'master' into collections
quimmrc 18c9548
changes from github review
quimmrc 034528c
Merge branch 'master' into collections
quimmrc f62d388
db update + review + collect sound small player
quimmrc 81affae
add sound to collection for all sound displays
quimmrc 79787d1
remove maintainers from edit page
quimmrc 82b3e2a
add maintainers
quimmrc d8fe151
Initial tests + create collections from scratch
quimmrc 058d326
enable bookmark collection + public/private edition
quimmrc 8fd039a
add sounds from small player + display Json success msg
quimmrc cd609e0
download collections
quimmrc f64d1b2
tests and miscellanious
quimmrc ff18e6b
order paginator query
quimmrc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 110 additions & 0 deletions
110
freesound/static/bw-frontend/src/components/collectSound.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import {dismissModal, handleGenericModal} from "./modal"; | ||
import {showToast} from "./toast"; | ||
import {makePostRequest} from "../utils/postRequest"; | ||
|
||
const saveCollectionAttr = (collectionAttrUrl, data, modalType) => { | ||
|
||
let formData = {}; | ||
if (data === undefined){ | ||
formData.name = ""; | ||
formData.collection = ""; | ||
formData.new_collection_name = ""; | ||
formData.use_last_collection = true; | ||
} else { | ||
formData = data; | ||
} | ||
makePostRequest(collectionAttrUrl, formData, (responseText) => { | ||
// Collection attribute saved successfully. Close model and show feedback | ||
dismissModal(modalType); // TBC | ||
try { | ||
showToast(JSON.parse(responseText).message); | ||
} catch (error) { | ||
// If not logged in, the url will respond with a redirect and JSON parsing will fail | ||
showToast("You need to be logged in before using collections.") | ||
} | ||
}, () => { | ||
// Unexpected errors happened while processing request: close modal and show error in toast | ||
dismissModal(modalType); | ||
showToast('Some errors occurred while editing the collection.'); | ||
}); | ||
} | ||
|
||
|
||
const toggleNewCollectionNameDiv = (select, newCollectionNameDiv) => { | ||
if (select.value == '0'){ | ||
// No category is selected, show the new category name input | ||
newCollectionNameDiv.classList.remove('display-none'); | ||
} else { | ||
newCollectionNameDiv.classList.add('display-none'); | ||
} | ||
} | ||
|
||
|
||
const initCollectionFormModal = (objId, collectionAttrUrl, modalType) => { | ||
|
||
// Modify the form structure to add a "Category" label inline with the select dropdown | ||
const modalContainer = document.getElementById(modalType); | ||
const selectElement = modalContainer.getElementsByTagName('select')[0]; | ||
const wrapper = document.createElement('div'); | ||
wrapper.style = 'display:inline-block;'; | ||
if (selectElement === undefined){ | ||
// If no select element, the modal has probably loaded for an unauthenticated user | ||
return; | ||
} | ||
selectElement.parentNode.insertBefore(wrapper, selectElement.parentNode.firstChild); | ||
const label = document.createElement('div'); | ||
label.innerHTML = "Select a collection:" | ||
label.classList.add('text-grey'); | ||
wrapper.appendChild(label) | ||
wrapper.appendChild(selectElement) | ||
|
||
const formElement = modalContainer.getElementsByTagName('form')[0]; | ||
const buttonsInModalForm = formElement.getElementsByTagName('button'); | ||
const saveButtonElement = buttonsInModalForm[buttonsInModalForm.length - 1]; | ||
const categorySelectElement = document.getElementById(`id_${ objId.toString() }-collection`); | ||
// New collection is not allowed for addMaintainerModal | ||
if (modalType=='collectSoundModal'){ | ||
const newCategoryNameElement = document.getElementById(`id_${ objId.toString() }-new_collection_name`); | ||
toggleNewCollectionNameDiv(categorySelectElement, newCategoryNameElement); | ||
categorySelectElement.addEventListener('change', (event) => { | ||
toggleNewCollectionNameDiv(categorySelectElement, newCategoryNameElement); | ||
}); | ||
} | ||
|
||
|
||
// Bind action to save collection attribute and prevent default submit | ||
saveButtonElement.addEventListener('click', (e) => { | ||
e.preventDefault(); | ||
const data = {}; | ||
data.collection = document.getElementById(`id_${ objId.toString() }-collection`).value; | ||
if(modalType=='collectSoundModal'){ | ||
data.new_collection_name = document.getElementById(`id_${ objId.toString() }-new_collection_name`).value; | ||
} | ||
saveCollectionAttr(collectionAttrUrl, data, modalType); | ||
}); | ||
}; | ||
|
||
const bindCollectionModals = (container) => { | ||
const collectionButtons = [...container.querySelectorAll('[data-toggle="collect-modal"]')]; | ||
collectionButtons.forEach(element => { | ||
if (element.dataset.alreadyBinded !== undefined){ | ||
return; | ||
} | ||
element.dataset.alreadyBinded = true; | ||
element.addEventListener('click', (evt) => { | ||
evt.preventDefault(); | ||
const modalUrlSplitted = element.dataset.modalUrl.split('/'); | ||
const objId = parseInt(modalUrlSplitted[modalUrlSplitted.length - 2], 10); | ||
const modalType = element.dataset.modalType; | ||
if (!evt.altKey) { | ||
handleGenericModal(element.dataset.modalUrl, () => { | ||
initCollectionFormModal(objId, element.dataset.collectionAttrUrl, modalType); | ||
}, undefined, true, true); | ||
} else { | ||
saveCollectionAttr(element.dataset.collectionAttrUrl); | ||
} | ||
}); | ||
}); | ||
} | ||
|
||
export { bindCollectionModals }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from django.contrib import admin | ||
|
||
# Register your models here. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from django.apps import AppConfig | ||
|
||
|
||
class FscollectionsConfig(AppConfig): | ||
default_auto_field = 'django.db.models.BigAutoField' | ||
name = 'fscollections' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
# | ||
# Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA | ||
# | ||
# Freesound is free software: you can redistribute it and/or modify | ||
# it under the terms of the GNU Affero General Public License as | ||
# published by the Free Software Foundation, either version 3 of the | ||
# License, or (at your option) any later version. | ||
# | ||
# Freesound is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
# GNU Affero General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Affero General Public License | ||
# along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
# | ||
# Authors: | ||
# See AUTHORS file. | ||
# | ||
|
||
from django import forms | ||
from django.forms import ModelForm, Textarea, TextInput, SelectMultiple | ||
from fscollections.models import Collection, CollectionSound | ||
from utils.forms import HtmlCleaningCharField | ||
|
||
#this class was aimed to perform similarly to BookmarkSound, however, at first the method to add a sound to a collection | ||
#will be opening the search engine in a modal, looking for a sound in there and adding it to the actual collection page | ||
#this can be found in edit pack -> add sounds | ||
#class CollectSoundForm(forms.ModelForm): | ||
|
||
class CollectionSoundForm(forms.Form): | ||
#list of existing collections | ||
#add sound to collection from sound page | ||
collection = forms.ChoiceField( | ||
label=False, | ||
choices=[], | ||
required=True) | ||
|
||
new_collection_name = forms.CharField( | ||
label = False, | ||
help_text=None, | ||
max_length = 128, | ||
required = False) | ||
|
||
use_last_collection = forms.BooleanField(widget=forms.HiddenInput(), required=False, initial=False) | ||
user_collections = None | ||
user_available_collections = None | ||
|
||
NO_COLLECTION_CHOICE_VALUE = '-1' | ||
NEW_COLLECTION_CHOICE_VALUE = '0' | ||
|
||
def __init__(self, *args, **kwargs): | ||
self.user_collections = kwargs.pop('user_collections', False) | ||
self.user_saving_sound = kwargs.pop('user_saving_sound', False) | ||
self.sound_id = kwargs.pop('sound_id', False) | ||
|
||
if self.user_collections: | ||
self.user_available_collections = Collection.objects.filter(id__in=self.user_collections).exclude(collectionsound__sound__id=self.sound_id) | ||
|
||
# NOTE: as a provisional solution to avoid duplicate sounds in a collection, Collections already containing the sound are not selectable | ||
super().__init__(*args, **kwargs) | ||
self.fields['collection'].choices = [(self.NO_COLLECTION_CHOICE_VALUE, '--- No collection ---'),#in this case this goes to bookmarks collection (might have to be created) | ||
(self.NEW_COLLECTION_CHOICE_VALUE, 'Create a new collection...')] + \ | ||
([(collection.id, collection.name) for collection in self.user_available_collections ] | ||
if self.user_available_collections else[]) | ||
|
||
self.fields['new_collection_name'].widget.attrs['placeholder'] = "Fill in the name for the new collection" | ||
self.fields['collection'].widget.attrs = { | ||
'data-grey-items': f'{self.NO_COLLECTION_CHOICE_VALUE},{self.NEW_COLLECTION_CHOICE_VALUE}'} | ||
|
||
def save(self, *args, **kwargs): | ||
collection_to_use = None | ||
|
||
if not self.cleaned_data['use_last_collection']: | ||
if self.cleaned_data['collection'] == self.NO_COLLECTION_CHOICE_VALUE: | ||
pass | ||
elif self.cleaned_data['collection'] == self.NEW_COLLECTION_CHOICE_VALUE: | ||
if self.cleaned_data['new_collection_name'] != "": | ||
collection = \ | ||
Collection(user=self.user_saving_sound, name=self.cleaned_data['new_collection_name']) | ||
collection.save() | ||
collection_to_use = collection | ||
else: | ||
collection_to_use = Collection.objects.get(id=self.cleaned_data['collection']) | ||
else: | ||
try: | ||
last_user_collection = \ | ||
Collection.objects.filter(user=self.user_saving_sound).order_by('-created')[0] | ||
collection_to_use = last_user_collection | ||
except IndexError: | ||
pass | ||
# If collection already exists, don't save it and return the existing one | ||
collection, _ = Collection.objects.get_or_create( | ||
name = collection_to_use.name, user=self.user_saving_sound) | ||
return collection | ||
|
||
def clean(self): | ||
collection = self.cleaned_data['collection'] | ||
sound = self.sound_id | ||
if CollectionSound.objects.filter(collection=collection,sound=sound).exists(): | ||
raise forms.ValidationError("This sound already exists in the collection") | ||
|
||
return super().clean() | ||
|
||
class CollectionEditForm(forms.ModelForm): | ||
|
||
class Meta(): | ||
model = Collection | ||
fields = ('name', 'description','maintainers') | ||
widgets = { | ||
'name': TextInput(), | ||
'description': Textarea(attrs={'rows': 5, 'cols': 50}), | ||
'maintainers': forms.CheckboxSelectMultiple() | ||
} | ||
|
||
def __init__(self, *args, **kwargs): | ||
is_owner = kwargs.pop('is_owner', True) | ||
super().__init__(*args, **kwargs) | ||
self.fields['maintainers'].queryset = self.instance.maintainers.all().values_list('username', flat=True) | ||
|
||
if not is_owner: | ||
for field in self.fields: | ||
self.fields[field].widget.attrs['readonly'] = 'readonly' | ||
|
||
|
||
class CollectionMaintainerForm(forms.Form): | ||
collection = forms.ChoiceField( | ||
label=False, | ||
choices=[], | ||
required=True) | ||
|
||
use_last_collection = forms.BooleanField(widget=forms.HiddenInput(), required=False, initial=False) | ||
user_collections = None | ||
user_available_collections = None | ||
|
||
def __init__(self, *args, **kwargs): | ||
self.user_collections = kwargs.pop('user_collections', False) | ||
self.user_adding_maintainer = kwargs.pop('user_adding_maintainer', False) | ||
self.maintainer_id = kwargs.pop('maintainer_id', False) | ||
|
||
if self.user_collections: | ||
# the available collections are: from the user's collections, the ones in which the maintainer is not a maintaner still | ||
self.user_available_collections = Collection.objects.filter(id__in=self.user_collections).exclude(maintainers__id=self.maintainer_id) | ||
|
||
super().__init__(*args, **kwargs) | ||
self.fields['collection'].choices = ([(collection.id, collection.name) for collection in self.user_available_collections] | ||
if self.user_available_collections else []) | ||
|
||
|
||
def save(self, *args, **kwargs): | ||
# this function returns de selected collection | ||
collection_to_use = Collection.objects.get(id=self.cleaned_data['collection']) | ||
return collection_to_use |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Generated by Django 3.2.23 on 2025-01-07 12:44 | ||
|
||
from django.conf import settings | ||
from django.db import migrations, models | ||
import django.db.models.deletion | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
initial = True | ||
|
||
dependencies = [ | ||
migrations.swappable_dependency(settings.AUTH_USER_MODEL), | ||
('sounds', '0052_alter_sound_type'), | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='Collection', | ||
fields=[ | ||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||
('name', models.CharField(default='', max_length=128)), | ||
('created', models.DateTimeField(auto_now_add=True, db_index=True)), | ||
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), | ||
('sound', models.ManyToManyField(to='sounds.Sound')), | ||
], | ||
), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Generated by Django 3.2.23 on 2025-01-09 10:35 | ||
|
||
from django.db import migrations, models | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('sounds', '0052_alter_sound_type'), | ||
('fscollections', '0001_initial'), | ||
] | ||
|
||
operations = [ | ||
migrations.RemoveField( | ||
model_name='collection', | ||
name='sound', | ||
), | ||
migrations.AddField( | ||
model_name='collection', | ||
name='description', | ||
field=models.TextField(default='', max_length=500), | ||
), | ||
migrations.AddField( | ||
model_name='collection', | ||
name='sounds', | ||
field=models.ManyToManyField(related_name='collections', to='sounds.Sound'), | ||
), | ||
] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe rename this to
ENABLE COLLECTIONS
?