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)
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)
def bigscreen(request): with mpdConnection(): cursong = Song() cursong.now_playing() return render( request, 'music/bigscreen.html', { 'artist': cursong.artist if hasattr(cursong, 'artist') else '', 'title': cursong.title if hasattr(cursong, 'title') else '', 'album': cursong.album if hasattr(cursong, 'album') else '' })
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, )))
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'))
def index(request): with mpdConnection() as client: cursong = Song() cursong.now_playing() playlist = client.playlistinfo() artistList = client.list('Artist') return render( request, 'music/index.html', { 'artist': cursong.artist if hasattr(cursong, 'artist') else '', 'title': cursong.title if hasattr(cursong, 'title') else '', 'album': cursong.album if hasattr(cursong, 'album') else '', 'lUpcoming': playlist[1:11], 'iTotalTracks': len(playlist) - 1, 'artistList': artistList })
def sync(request, user_id): api, result = UserProfile.get_google_music_api(user_id) if(result): songs = api.get_all_songs() song_dicts = [Song.create_from_google_music(song, user_id).to_dict() for song in songs] return HttpResponse(json.dumps({'songs':song_dicts, 'id': user_id}), mimetype="application/json") else: logger.warn("Failed to log in!") return HttpResponse(json.dumps({'message':'Could not log in to Google Music'}), mimetype="application/json")
def artwork(request): client = MPDClient() client.connect("localhost", 6600) current = Song() current.now_playing() if current.file: file = mutagen.File(os.environ['HOME'] + "/Music/" + current.file) if type(file) is mutagen.mp4.MP4: if 'covr' in file.tags: return HttpResponse(file.tags['covr'][0], content_type="image/jpeg") if type(file) is mutagen.mp3.MP3: if 'APIC:' in file.tags: return HttpResponse(file.tags['APIC:'].data, content_type=file.tags['APIC:'].mime) with open(os.path.join(settings.BASE_DIR, "static/no-artwork.png"), "rb") as f: return HttpResponse(f.read(), content_type="image/jpeg")
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('/')
def post(self, request, **kwargs): form = SongModelForm(request.POST) if form.is_valid(): album = self.get_object() Song(album=album, name=form.cleaned_data.get('name'), artist=form.cleaned_data.get('artist')).save() return redirect('album_detail', album.id) else: self.object = self.get_object() context = self.get_context_data(**kwargs) context['form'] = form return render(request, self.get_template_names(), context)
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!"
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)
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)
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)
def add_track_to_database(track_info): """Add a track to the database. Arguments: track_info (dict): Specific track information to be entered into the database. """ track_path = track_info['track_path'] track_hash = track_info['track_hash'] with access_db() as db_conn: # Make sure the track doesn't already exist # First by checking the track path exists = db_conn.query(Song)\ .filter(Song.track_path==track_path)\ .first() if exists: return False else: # Then by checking the track hash exists = db_conn.query(Song)\ .filter(Song.track_hash==track_hash)\ .first() if exists and exists.file_missing: # If the track hash exists, and the file is missing, update its path exists.track_path = track_path exists.file_missing = False db_conn.commit() return False # Create and add ORM object to the database song = Song(track_name=track_info['title'], artist_name=track_info['artist'], album_name=track_info['album'], track_path=track_info['track_path'], track_length=track_info['track_length'], track_hash=track_info['track_hash']) db_conn.add(song) db_conn.commit() return True return False
def test_string_representation(self): song = Song(title="Song Title") self.assertEqual(str(song), song.title)
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
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
def CreateSong(): a = Album.objects.get(artist="Taylor swift") d = Song(song_title="red", album=a, file_type="mp3") d.save()
Album.objects.all() Album.objects.filter(id =1) #prints the first one Album.objects.filter(artist__startswith='Taylor') #adding songs to database In [1]: from music.models import Album,Song In [2]: album1 = Album.objects.get(pk = 1) In [3]: album1.artist Out[3]: 'Taylor Swift' In [4]: song = Song() In [5]: song.album = album1 In [7]: song.song_title = 'I hate my boyfriend' In [9]: song.file_type = 'mp3' In [10]: song.save() #using create to do all steps in one step album1.song_set.create(song_title = 'I love bacon' , file_type = 'mp3') album1.song_set.create(song_title = 'Icecream' , file_type = 'mp3')
import pusher pusher_client = pusher.Pusher( app_id='190359', key='18e076434d0479a10e71', secret='e9a5ea2bc88d8ffedf76', cluster='ap1', ssl=True ) print('Starting Monitor') client = MPDClient() client.connect("localhost",6600) cursong = Song() cursong.now_playing() while True: client.idle() nextsong = Song() nextsong.now_playing() if cursong != nextsong: cursong = nextsong backoff = 2 delay = 2 while True: try: pusher_client.trigger('play-py', 'now-playing', { 'artist': cursong.artist if hasattr(cursong,'artist') else '', 'title': cursong.title if hasattr(cursong,'title') else '', 'album': cursong.album if hasattr(cursong,'album') else '',
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
return render(request,'music/index.html',context) #if page is not present from django.http import Http404 def detail(request,album_id): try: ablum=Album.objects.get(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exits") return render(request, 'music/detail.html', {'ablum':ablum}) #put songs album1=Album.objects.filter(pk=1).get() album1.artist song = Song() from music.models import Album, Song song = Song() song.album=album1 song.file_type=="mp4" song.file_type=="mp3" song.song_title="I hate u" song.save() #This will create the new object album1.song_set.create(song_title='I love bacon',file_type='mp3') #count album1.song_set.count() #all the objects album1.song_set.all()
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()
song.year = year song.genre = genre song.album = album song.artist = artist song.user = user song.path_orig = path song.time_changed = timestamp song.time_added = datetime.datetime.now().replace(tzinfo=utc) else: song = Song( title = tags['title'], track = tags['track'], mime = tags['mime'], length = tags['length'], year = year, artist = artist, album = album, genre = genre, user = user, path_orig = path, time_changed = timestamp, time_added = datetime.datetime.now().replace(tzinfo=utc), ) return song @transaction.autocommit def update_song(song): """ re-reads tags of song and saves it """ timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(song.path_orig)).replace(tzinfo=utc)
from music.models import Album,Song album1 = Album.objects.get(pk=1) album1.artist song = Song() song.album = album1 song.file_type = "mp3" song.song_title = "I hate my boyfirend" song.save() %his -f AddSong.py %hist -f AddSong.py
def test_min_length_name(self): song = Song(name="T", url="https://www.example.com/", artist=self.artist) with self.assertValidationErrors(['name']): song.full_clean()