Example #1
0
 def post(self, request , *args, **kwargs):
     name = request.POST['album_name']
     artist = request.POST['album_artist']
     album = Album.objects.get(id=self.kwargs['pk'])
     song = Song(name=name, artist = artist, album= album)
     song.save()
     return redirect('album_detail', album.id)
Example #2
0
def collect_song(dirname, filename):
    """
    Collect a single song.

    dirname  -- name of the containing directory
    filename -- name of the song file

    Throws ValueError if the file doesn't exist, isn't a song,
    or lacks metadata information 'name' and 'artist'.
    """
    filepath = os.path.join(dirname, filename)

    # TODO check if song must be updated instead of added
    try:
        raw = mutagen.File(filepath)
        song = Song(original=filename,
                    name=raw.get('title')[0],
                    artist=raw.get('artist')[0],
                    genre=raw.get('genre', [''])[0],
                    album=raw.get('album', [''])[0],
                    mime='audio/ogg')
        song.save()
    except Exception as e:
        raise ValueError('Could not collect file %s' % filepath)

    target_url = os.path.join(TARGET_DIR, song.filename())
    shutil.copy(filepath, target_url)
Example #3
0
def make_song(request, album_id):
    from ..views import album_details
    from ..models import Album
    is_form_valid = True
    audio_file = None
    error_msg = []
    if request.method == 'POST':
        song_title = request.POST['song_title']
        if not song_title:
            error_msg.append('Title required')
            is_form_valid = False
        if not request.FILES:
            error_msg.append('Upload a file')
            is_form_valid = False
        else:
            if not (request.FILES['song_file'].content_type
                    ).__contains__('audio/'):
                error_msg.append('Upload an audio file')
                is_form_valid = False
            else:
                audio_file = request.FILES['song_file']

        #print(error_msg)
        if (is_form_valid):
            current_album = Album.objects.get(pk=album_id)
            audio_file = save_file_to_firebase(
                file=audio_file,
                type='audio',
                album_name=current_album.album_title + str(album_id))
            file_url = audio_file[0]
            file_path = audio_file[1]
            song = Song(song_title=song_title,
                        album=current_album,
                        file_url=file_url,
                        file_path=file_path)
            song.save()
            return HttpResponseRedirect(
                reverse('music:album-details', args=(album_id, )))
        album = get_object_or_404(Album, pk=album_id)
        songs = album.song_set.all()
        context = {
            'title': album.album_title,
            'album': album,
            'songs': songs,
            'error_msg': error_msg,
        }
        return album_details(request, album_id, context=context)
        #return render(request, 'music/album/details.html', context)
    else:
        #return album_details(request, album_id)
        return HttpResponseRedirect(
            reverse('music:album-details', args=(album_id, )))
Example #4
0
def reload(request):
    if request.method != 'POST':
        return HttpResponseForbidden("Access page through POST only")
    Song.objects.all().delete()
    Album.objects.all().delete()
    for root, dirs, files in walk("/home/chris/Music"):
        for f in (f for f in files if splitext(f)[1] == ".m4a"):
            filename = join(root, f)
            s = Song(file_name = filename)
            s.read_metadata_from_file()
            s.save()

    return HttpResponseRedirect(reverse('music.views.index'))
Example #5
0
 def setUp(self):
   song = Song()
   song.title = "Basket Case"
   song.file_path = "burgle/data/pandora/Basket Case.mp3"
   artist = Artist()
   artist.name = 'Green Day'
   artist.save()
   song.artist = artist
   album = Album()
   album.title = 'Dookie'
   album.save()
   song.album = album
   song.station_id = int('21312')
   song.save()
   genre = Genre()
   genre.name = 'Rock'
   genre.save()
   song.genres.add(genre) 
Example #6
0
 def setUp(self):
   seed = str(random.randint(1, 100000))
   song = Song()
   song.title = 'Basket Case'
   pandora_url = 'http://audio-dc6-t1-1.pandora.com/access/6394738923373318898?version=4&lid=55475035&token=ltvKtTCJqaVK0%2FRsqx6FVl92LrWl3riBZtqhXMaoAQGBaZ5CflwAEnJO%2B7CSl%2FFyxIkYLmsL31krBpS3lnPj0PBX0UkSU0BFmh6BBO2wsUwUWvwFu2hyUHpWaJLcL7eJtEl08SKzQswNULEPr3V0R5JD64rB0ANyYc4YeDVSMs9m%2Fo5PITxWQlermntRbN1B2cGg4mi%2BOxQEHWnbwwoRKeQG6c0mv1qHasdMQXJrXc%2FxoUJM7az1yklTPW8LUnmaRho%2BxYBWhmJ5XBjMQtBt89moJVNfi9Cx08fUBf2GU369d63N1HACf86Nt1rcKRgS6NhaBngwjBPeJY0XBR76JesF%2BBQJHUKR'
   song.audio_url = pandora_url
   artist = Artist()
   artist.name = 'Green Day'
   artist.save()
   song.artist = artist
   album = Album()
   album.title = 'TestAlbum-' + str(seed)
   album.save()
   song.album = album
   song.station_id = int(seed)
   song.save()
   genre = Genre()
   genre.name = 'Rock'
   genre.save()
   song.genres.add(genre) 
Example #7
0
 def setUp(self):
   for i in range(10):
     seed = str(random.randint(1, 100000))
     song = Song()
     song.title = 'Demo'
     song.audio_url = 'test/music/demo.mp3'
     artist = Artist()
     artist.name = 'TestArtist-' + seed
     artist.save()
     song.artist = artist
     album = Album()
     album.title = 'TestAlbum-' + seed
     album.save()
     song.album = album
     song.station_id = int(seed)
     song.save()
     genre = Genre()
     genre.name = 'TestGenre-' + seed
     genre.save()
     song.genres.add(genre) 
     self.test_songs.append(song)
Example #8
0
def UploadSong(request):
	user = request.user
	username = user.username
	if request.user.is_authenticated():
		if request.method == 'POST':
			form = SongForm(request.POST, request.FILES)
			if form.is_valid():
				name = form.cleaned_data['name']
				artist = form.cleaned_data['artist']
				art = form.cleaned_data['art']
				song = request.FILES['song']
				newSong = Song(name=name,slug=slugify(name),artist=artist,art=art,song=song)
				newSong.save()
				return HttpResponseRedirect('/music-player/?song=' + name)
				
			context = {'form':form}
			return render_to_response('uploadsong.html', context, context_instance=RequestContext(request))
		form = SongForm()
		context = {'form':form}
		return render_to_response('uploadsong.html', context, context_instance=RequestContext(request))
	return HttpResponseRedirect('/')
Example #9
0
        def load_music_dir(music_root):
            print "searching in music_root=%s" % music_root
            for letter_dir in list_subdirs(music_root):
                print "  searching in letter_dir=%s" % letter_dir
                for artist_dir in list_subdirs(os.path.join(music_root, letter_dir)):
                    print "    searching artist_dir=%s" % artist_dir
                    for album_dir in list_subdirs(os.path.join(music_root, letter_dir, artist_dir)):
                        print "      searching album_dir=%s" % album_dir

                        for f in list_subfiles(os.path.join(music_root, letter_dir, artist_dir, album_dir)):
                            name = os.path.splitext(f)[0]
                            extension = os.path.splitext(f)[1][1:]
                            print "        adding song at %s with format=%s" %(f, extension)
                            song = Song(
                                path=os.path.join(letter_dir, artist_dir, album_dir, f),
                                name=name,
                                artist=artist_dir,
                                album=album_dir,
                                format=extension,autoloaded=True,
                            )
                            song.save()
                            print "        saving song..."

            print "-- Done with music!"
Example #10
0
from music.models import Album,Song
album1.song_set.all()
album1 = Album.objects.get(pk=1)
album1.artist
song = Song()
song.album = album1
song.file_type = 'mp3'
song.song_title = 'I love my boyfirend'
song.save()
album1.song_set.all()
album1.song_set.create(song_title = 'I love bacon',file_type = 'mp3')
album1.song_set.create(song_title = 'Bucky is Lucky',file_type = 'mp3')
album1.song_set.create(song_title = 'Ice Cream',file_type = 'mp3')
song = album1.song_set.create(song_title = 'Ice Cream',file_type = 'mp3')
song.album
song.song_title
album1.song_set.all()
album1.song_set.count()
%hist -f CreateSong2.py
Example #11
0
from django.conf import settings
from music.models import Song
from people.models import Band
from django.core.files import File
import random

for b in Band.objects.all():
  if not b.song_set.all():
    for i in range(2):
      s = random.choice(Song.objects.filter(band__isnull=True).filter(dummy=True))
      s = Song(
        name=s.name,
        src=str(s.src),
        band=b)
      s.save()
    print "2 songs created for %s"%b
    album_title="Ignite the night",
    genre="Rock",
    album_logo=
    "http://schmoesknow.com/wp-content/uploads/2017/05/Wonder-Woman-Movie-Artwork.jpg"
)
# above code is all on one line
##
a.save()  # writes into the database
##
a.id  # show the ID (primary key)

# Add "Albums" and "Song" table entries: Rick Astley
#
from music.models import Album, Song
a = Album(
    artist="Rick Astley",
    album_title="Whenever You Need Somebody",
    genre="rock",
    album_logo=
    "https://www.cs.allegheny.edu/sites/obonhamcarter/cs312/graphics/rick.jpg"
)  #Above line: all on one line
a.save()
#
# add a song for the album
s = Song()
s.album_id = 2
s.Album = "Whenever You Need Somebody"
s.song_title = "Never Gonna Give You Up"
s.file_type = "mp3"
s.save()
Example #13
0
    timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(song.path_orig)).replace(tzinfo=utc)

    if song.time_changed == timestamp:
        return

    try:
        tags = get_tags(song.path_orig)
    except Exception, e:
        dbgprint("update_song: error reading tags on file", song.path_orig, ":", e)
        return

    set_song(tags, timestamp, song.user, song.path_orig, song)

    try:
        song.save()
    except Exception, e:
        dbgprint("update_song: error saving entry", song, ":", e)
        raise e

@transaction.commit_manually
def add_song(dirname, files, user, force=False):
    """
    Takes a directory and one or more file names in that directory, reads tag information
    and adds the songs to the database for the given user.
    Invalid files or unsupported files are ignored.
    dirname must be string or os.path
    files must be array []

    If the given file path(s) are already in the database, it compares their timestamps
    and if they are not equal, the tags are read out again (->Performance)
Example #14
0
        artist_obj = Artist.objects.get(stage_name=artist)
    else:
        artist_obj = Artist(stage_name=artist)
        artist_obj.save()

    # Lookup if the album exists
    album_match = Album.objects.filter(album_name=album, artist=artist_obj)
    album_obj = ""
    if album_match:
        album_obj = Album.objects.get(album_name=album, artist=artist_obj)
    else:
        album_obj = Album(album_name=album, artist=artist_obj, uploader_id=1)
        album_obj.save()

    # Lookup if the song exists
    song_match = Song.objects.filter(song_name=title, artist=artist_obj)
    song_obj = ""
    if song_match:
        song_obj = Song.objects.get(song_name=title, artist=artist_obj)
        song_obj.save()
    else:
        # save the peaks file
        song_obj = Song(peaks_file="../media/peaks/" + genId + ".json", song_duration_seconds=file.info.length,song_file=song_file, track_art=art_file,track_art_dominant_color=dominant_color_hex, uploader_id=1, song_name=title, artist=artist_obj, album=album_obj)
        song_obj.save()

    index = index + 1

    
    

Example #15
0
def CreateSong():
    a = Album.objects.get(artist="Taylor swift")
    d = Song(song_title="red", album=a, file_type="mp3")
    d.save()