def upload_file(request): logging.debug('Upload file 1') if request.method == 'POST': logging.debug('Upload file 2') form = UploadMp3FileForm(request.POST, request.FILES) logging.debug('upload'+str(form.errors)) if form.is_valid(): file_path = handle_upload_mp3file(request.FILES['mp3_file']) # Determen the play time of the uploaded mp3 import eyeD3 if eyeD3.isMp3File(file_path): logging.debug('eyeD3 %s' % file_path) audio_file = eyeD3.Mp3AudioFile(file_path) duration = audio_file.getPlayTime() song = Song( title=form.cleaned_data['title'], duration=duration, file_path=file_path) song.save() return HttpResponseRedirect(reverse('player-index')) else: # return error: The uploaded file is not a mp3 return HttpResponseRedirect(reverse('player-index')) else: form = UploadMp3FileForm() return HttpResponseRedirect(reverse('player-index'))
def upload(request): context = {"status": "norm"} if request.method == "POST": rb = xlrd.open_workbook(settings.BASE_DIR + '/Orders/cat.xls', formatting_info=True) sheet = rb.sheet_by_index(0) base = {} for rownum in range(sheet.nrows): row = sheet.row_values(rownum) row[0] = int(row[0]) if sheet.cell(rownum, 1).ctype == 3: row[1] = xlrd.xldate_as_tuple(row[1], 0) tmp = str(row[1][4]) if tmp == "0": tmp = "00" row[1] = str(row[1][3]) + ":" + tmp if sheet.cell(rownum, 1).ctype == 2: row[1] = int(row[1]) b1 = Artist(name=row[2]) try: b1.save() except: b1 = Artist.objects.filter(name=row[2])[0] s = Song(number=row[0], tittle=row[1], minus_quality=row[4], back_vocal=row[3], karaoke_system="test", artist=b1) s.save() return render(request, 'Orders/upload.html', context) return render(request, 'Orders/upload.html', context)
def songs(request): if request.method == 'PUT': s = Song(name=request.REQUEST['name'], author=request.REQUEST['author']) s.save() return HttpResponse(s.json(), content_type="application/json") if request.method == 'GET': records = Song.objects.all() p = Paginator([rec.dict() for rec in records], 5) if 'page' in request.GET: page = request.GET.get('page') else: page = 1 try: records_json = p.page(page).object_list except PageNotAnInteger: page = 1 records_json = p.page(page).object_list except EmptyPage: page = p.num_pages records_json = p.page(page).object_list c = json.dumps(records_json) return HttpResponse('{ "page" : ' + str(page) + ', "pages" : ' + str(p.num_pages) + ', "content" : ' + c + '}', content_type="application/json")
def post(self): notes = [] for i in self.request.get("notes"): notes.append(i.upper()) # Get next whole square root type = int(math.ceil(math.sqrt(len(notes)))) name = self.request.get("name") artist = self.request.get("artist") image = self.request.get("song_image") current_song = Song(name=name, artist=artist, note_progression=notes, type=type, image=image) current_song.put() variables = { 'song_name': current_song.name, 'song_artist': current_song.artist, 'song_notes': current_song.note_progression, 'song_type': current_song.type, 'song_image': current_song.image, } start_template = jinja_current_directory.get_template( "templates/home_page.html") self.response.write(start_template.render(variables))
def add_song_to_db(code,name,producer_farsi,album_farsi,category_farsi): # get or create producer try: producer,created = Producer.objects.get_or_create(name=producer_farsi) except Producer.MultipleObjectsReturned: producer = Producer.objects.filter(name=producer_farsi)[0] # get or create cateogory category,created = Category.objects.get_or_create(farsi_name=category_farsi) # get or create the album album,created = Album.objects.get_or_create(farsi_name=album_farsi,category=category) # audio download link audio_link = "http://rbt.mci.ir/wave/%s.wav" % code # save the song song = Song(activation_code=code, download_link=audio_link, song_name=name, producer=producer, album = album, confirmed = False, ) song.save()
def setUp(self): Song.query.delete() Album.query.delete() Artist.query.delete() artist = Artist(name="Nick Danger", logo_url="nickdanger.jpg") db.session.add(artist) db.session.commit() db_artist = Artist.query.filter_by(name="Nick Danger").first() artist_id = db_artist.id album = Album(title="bigh", year=2019, artist_id=artist_id) db.session.add(album) db.session.commit() db_album = Album.query.filter_by(title="bigh").first() album_id = db_album.id song_1 = Song(title="Eessennet", artist_id=artist_id, album_id=album_id) song_2 = Song(title="bigh", artist_id=artist_id, album_id=album_id) db.session.add(song_1) db.session.add(song_2) db.session.commit() self.song_1 = song_1 self.song_2 = song_2 self.client = app.test_client()
def do(self): apiKey = "AIzaSyCWDfJdQfcOeDGjvL4Rs0sNnaTY0CcBMRY" getChannelID = "https://www.googleapis.com/youtube/v3/channels?key=AIzaSyCWDfJdQfcOeDGjvL4Rs0sNnaTY0CcBMRY&forUsername=allrapnation&part=id" channelRequest = urllib2.urlopen(getChannelID) channel = channelRequest.read() channelJson = json.loads(channel) channelID = channelJson['items'][0]['id'] getPlaylistID = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=" + channelID + "&key=AIzaSyCWDfJdQfcOeDGjvL4Rs0sNnaTY0CcBMRY" playlistRequest = urllib2.urlopen(getPlaylistID) playlist = playlistRequest.read() playlistJson = json.loads(playlist) for item in playlistJson['items']: getVideosID = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" + str(item['id']) +"&maxResults=50&key=AIzaSyCWDfJdQfcOeDGjvL4Rs0sNnaTY0CcBMRY" videosRequest = urllib2.urlopen(getVideosID) videos = videosRequest.read() videosJson = json.loads(videos) for songItem in videosJson['items']: print songItem['snippet']['title'] print "Hello" song = Song() song.song_name = songItem['snippet']['title'] song.url = songItem['snippet']['resourceId']['videoId'] Song.save(song)
def test_new_song_has_played_at(self): with gillard.app.app_context(): song = Song() song = test_utils.save_and_refresh( gillard.db.session, song ) # played_at starts empty assert song.played_at is None song.artist = 'fake_ass_bullshit' song = test_utils.save_and_refresh( gillard.db.session, song ) # played_at doesn't update unless 'played' changes assert song.played_at is None song.played = True song = test_utils.save_and_refresh( gillard.db.session, song ) # on update played field, played_at gets set to now-ish assert (datetime.datetime.now() - song.played_at).\ total_seconds() < 2
def add_song(): if not request.json: abort(Response('Request not in JSON format', 400)) artist_name = request.json.get('artist_name', 'Unknown Artist') artist = Artist.query.filter_by(name=artist_name).first() if not artist: artist = Artist(name=artist_name) db.session.add(artist) g.redis.incr('artists') album_name = request.json.get('album_name', 'Unknown Album') album = Album.query.filter_by(name=album_name, artist_id=artist.id).first() if not album: album = Album(name=album_name, year=request.json.get('year'), artist=artist) db.session.add(album) g.redis.incr('albums') song = Song(track=request.json.get('track'), name=request.json.get('name'), album=album) db.session.add(song) db.session.commit() g.redis.incr('songs') return song.to_dict(), 200
def put(body): for song in body: try: Song.add_entry(song) except IntegrityError: orm.rollback() return { "message": "song of id {} already exists, aborting insert".format( song.get('id')) }, 400 except TransactionIntegrityError: orm.rollback() return { "message": "song of id {} already exists, aborting insert".format( song.get('id')) }, 400 except Exception as e: orm.rollback() logger.error(e) return { "message": "failed to insert the song of id {}, unknown error, check log for more info." " TIMESTAMP {}".format(song.get('id'), time.asctime()) }, 400 return {"message": "Successfully inserted {} songs".format(len(body))}, 200
def seed(): Song(title='Love You', genre='Blue', release_date='2012-1-1').insert() Song(title='The World', genre='Jazz', release_date='2019-8-12').insert() Song(title='Frozen', genre='Blue', release_date='2011-12-12').insert() Artist(name='Edward', age=36, gender='male').insert() Artist(name='Mike', age=25, gender='male').insert() Artist(name='Jeff', age=35, gender='female').insert()
def drop_users(): print "Dropping" User.objects().delete() SongRoom.objects().delete() Song.objects().delete() SongQueue.objects().delete() Vote.objects().delete() return "OK"
def add_song(): form = SongForm() if form.validate_on_submit(): Song.create_song(form=form) return redirect('/songs') return render_template('new_song.html', form=form)
def __init__(self, path=None, output_path=None, debug=False): self.file = FileUtils(path) self.output_path = output_path self.debug = debug rate, data = self.file.get_file_data() self.song = Song(samples=data, sample_rate=rate, debug=self.debug) print "song is {}".format(str(self.song))
def song_collection(audio_path=audio_commands, cb=audio_transcribe): talk = cb song = Song() song_list = song.list_song() print(song_list) songss = ', '.join(song_list) talk("Here are the songs available in your collection: " + songss) print(songss)
def song(url, text): if url[-4:] == '.mp3': try: s = AppSong(url=url, title=text, count=0) s.save() logging.debug('song saved') except: logging.debug('song found, could not be saved') return (url, text)
def create_file(audiofiletype): audiofiletype = audiofiletype.lower() if audiofiletype == 'song': try: name = request.args.getlist('name')[0] duration = request.args.getlist('duration')[0] song = Song(name, duration) if not song.save(): return server_error return success except IndexError as e: print(e) print(request.args) return bad_request except Exception as e: print(e) return server_error elif audiofiletype == 'podcast': try: name = request.args.getlist('name')[0] duration = request.args.getlist('duration')[0] host = request.args.getlist('host')[0] participants = request.args.getlist('participants')[0] podcast = Podcast(name, duration, host, participants) if not podcast.save(): return server_error return success except IndexError as e: print(request.args) print(e) return bad_request except Exception as e: print(e) return server_error elif audiofiletype == 'audiobook': try: name = request.args.getlist('name')[0] duration = request.args.getlist('duration')[0] author = request.args.getlist('author')[0] narrator = request.args.getlist('narrator')[0] print(name, duration, author, narrator) audiobook = Audiobook(name, duration, author, narrator) if not audiobook.save(): return server_error return success except IndexError as e: print(e) print(request.args) return bad_request except Exception as e: print(e) return server_error else: return bad_request
def post(self): user = users.get_current_user() if self.request.get("action") == "Add to Music": title_string = self.request.get("title_string") artist_string = self.request.get("artist_string") subject_string = self.request.get("subject-type") song_link = self.request.get("link_string") song = Song(link=song_link, title=title_string, artist=artist_string, owner=user.user_id(), subject=subject_string) song.put() self.get()
def get_json_queue(self): client = MongoClient() db = client.concert queue = [] cur_queue = db.Queue.find().sort('date', pymongo.ASCENDING) for item in cur_queue: song = Song(item['mrl'], item['title'], item['duration'], item['thumbnail'], item['playedby']) queue.append(song.dictify()) return json.dumps(queue)
def process_item(self, item, spider): if item.get('song_name') is None: # 分页完 raise DropItem('ajax page over.') singer = db.query( Singer.pk).filter_by(face=item['singer_face']).first() if singer is None: singer = Singer(name=item['singer'], face=item['singer_face']) db.add(singer) album_name = item.get('album_name') if album_name is not None: cover = item.get('album_cover') album = db.query(Album.pk).filter_by(cover=cover).first() if album is None: album = Album( name=album_name, intro=item.get('album_intro'), rdt=item['release_date'], cover=cover) db.add(album) else: album = Empty() db.commit() lrc = item.get('lrc') song = db.query(Song).filter_by( name=item['song_name'], singer=singer.pk).first() if song is None: song = Song( name=item['song_name'], singer=singer.pk, album=album.pk, lrc=lrc) db.add(song) db.commit() elif None not in (lrc, song.lrc): song.lrc = lrc tag_objs = [] for tag in item['tags']: t = db.query(Tag.pk).filter_by(name=tag).first() if t is None: t = Tag(name=tag) db.add(t) tag_objs.append(t) db.commit() for tag in tag_objs: db.merge(SongTag(sid=song.pk, tid=tag.pk)) db.commit() return item
def test_add_song(self): """Test the add_song route""" with self.client as client: # Test without user logged in. Should redirect and flash message: resp = client.post('/playlists/1/add/1', follow_redirects=True) html = resp.get_data(as_text=True) self.assertIn('Log in to add songs', html) # Log in user, create some sample playlists and songs to work with: data = {'username': '******', 'password': '******'} client.post('/login', data=data) playlist = Playlist(id=100, name='playlist1', user_id=100, description='description') song1 = Song(id=100, post_id=100, post_title='test1', title='song1', artist='artist1', link='https://youtu.be/DLzxrzFCyOs') song2 = Song(id=200, post_id=200, post_title='test2', title='song2', artist='artist2', link='https://youtu.be/DLzxrzFCyOs') song3 = Song(id=300, post_id=300, post_title='test3', title='song3', artist='artist3', link='https://youtu.be/DLzxrzFCyOs') db.session.add(playlist) db.session.add(song1) db.session.add(song2) db.session.add(song3) db.session.commit() # Now test adding these songs to the playlist client.post('/playlists/100/add/100') client.post('/playlists/100/add/200') client.post('/playlists/100/add/300') songs = [song.id for song in Playlist.query.get(100).songs] song1 = Song.query.get(100) song2 = Song.query.get(200) song3 = Song.query.get(300) self.assertIn(song1.id, songs) self.assertIn(song2.id, songs) self.assertIn(song3.id, songs)
def submit_vote(): user = get_user(request) is_up = parse_bool(request, "isUp") print get_song(request).to_json() vote = Vote(user=user, song=get_song(request), isUp=is_up) try: vote.save() Song.objects(id=request.values["songId"]).update_one(push__votes=vote) except NotUniqueError: pass return mk_json(get_song(request).votes)
def test_dictify_artist(self): expected = { 'artist_id': 'abcd', 'name': 'Drake', 'num_followers': 12345, 'image_url': "www.drake.com", 'popularity': 100, 'charted_songs': ['One Dance', 'Take Care'], 'genres': ['Rap', 'Hip-Hop'] } drake = Artist(artist_id="abcd", name="Drake", num_followers=12345, image_url="www.drake.com", popularity=100) one_dance = Song(song_name="One Dance", song_id="od") take_care = Song(song_name="Take Care", song_id="tc") rap = Genre(name="Rap", description="Rap music.") hip_hop = Genre(name="Hip-Hop", description="Hip hop music.") drake.charted_songs.append(one_dance) drake.charted_songs.append(take_care) drake.genres.append(rap) drake.genres.append(hip_hop) self.session.add_all([drake, one_dance, take_care, rap, hip_hop]) self.session.commit() returned_drake = self.session.query(Artist).filter_by( name="Drake").first() actual_dict = returned_drake.dictify() # The lists in the dictionary can be in any order, so # we have to compare the values line by line or it will fail. self.assertEqual(expected['artist_id'], actual_dict['artist_id']) self.assertEqual(expected['name'], actual_dict['name']) self.assertEqual(expected['num_followers'], actual_dict['num_followers']) self.assertEqual(expected['image_url'], actual_dict['image_url']) self.assertEqual(expected['popularity'], actual_dict['popularity']) self.assertEqual(len(actual_dict['genres']), 2) self.assertTrue("Rap" in actual_dict['genres']) self.assertTrue("Hip-Hop" in actual_dict['genres']) self.assertEqual(len(actual_dict['charted_songs']), 2) self.assertTrue("One Dance" in actual_dict['charted_songs']) self.assertTrue("Take Care" in actual_dict['charted_songs'])
def setUp(self): b = Band(name='Aerosmith', bio='', rank=3) b.save() self.b = b s1 = Song(band=b, name='Pink', duration=235) s1.save() s2 = Song(band=b, name='Dude (Looks Like a Lady)', duration=264) s2.save() s3 = Song(band=b, name='Jaded', duration=214) s3.save()
def new_song(): name = request.json.get('name') singer = request.json.get('singer_name') url = request.json.get('url') print name, singer, url song = Song(name=name, singer=singer, url=url) session = db_session() session.add(song) try: session.commit() finally: session.close() song = session.merge(song) return jsonify(song.to_json())
def add_random_song(): import random from faker import Faker fake = Faker() insert_data = dict( artist=' '.join(fake.words(nb=4)), title=' '.join(fake.words(nb=4)), difficulty=random.uniform(1, 20), level=random.randint(1, 15), released=str(fake.date()), ) Song.insert(insert_data) return jsonify(Song.Schemas.Get().dump(insert_data))
def _fetch_data(self, url): ''' Actual fetching of song information from remote server pased on the url provided Returns True or False depending on whether the request/parsing succeeded ''' resp = requests.get(url) if not resp.ok: print "Failed to get %s [%s]" % (resp.url, resp.status_code) return False try: data = resp.json() except ValueError as e: print e return False if not data: return False count = 0 while count < 100: if str(count) not in data: break track = data[str(count)] song = self._check_id(track['mediaid']) if not song: song = Song(track['mediaid']) song.title = track['title'] song.artist = track['artist'] song.url = track['stream_url_raw'] db.session.add(song) else: song.downloaded += 1 song.url = track['stream_url_raw'] db.session.add(song) db.session.commit() self.songs.append(song) count += 1 return True
def bulk_enq(): uris = request.values.getlist('spotifyURIs') names = request.values.getlist('names') print uris print names queue = get_queue(request) # Ugly, sorry sr = SongRoom.objects(queue=get_queue(request)).first() for uri, name in zip(uris, names): s = Song(spotifyURI=uri, songRoom=sr, name=name) s.save() update_queue(request)(push__songs=s) return "OK"
def test_dictify_year(self): expected = { 'year': "2000", 'top_album_name': 'Top Album', 'top_album_id': 'tgvjs', 'top_genre_name': 'Top Genre', 'top_album_artist_id': 'sadsd', 'top_songs': ['Top Song 1', 'Top Song 2'] } year = Year(year="2000", top_album_name='Top Album', top_album_id='tgvjs', top_genre_name='Top Genre', top_album_artist_id='sadsd') song1 = Song(song_id='abcd', song_name='Top Song 1') assoc_s1 = YearsSongsAssociation(year_num="2000", rank=2, song_id="abcd") assoc_s1.song = song1 song2 = Song(song_id='efgh', song_name='Top Song 2') assoc_s2 = YearsSongsAssociation(year_num="2000", rank=1, song_id="efgh") assoc_s2.song = song2 year.top_songs.append(assoc_s1) year.top_songs.append(assoc_s2) self.session.add_all([year, song1, song2, assoc_s1, assoc_s2]) self.session.commit() returned_year = self.session.query(Year) \ .filter_by(year="2000").first() actual_dict = returned_year.dictify() self.assertEqual(actual_dict['year'], expected['year']) self.assertEqual(actual_dict['top_album_name'], expected['top_album_name']) self.assertEqual(actual_dict['top_album_id'], expected['top_album_id']) self.assertEqual(actual_dict['top_genre_name'], expected['top_genre_name']) self.assertEqual(actual_dict['top_album_artist_id'], expected['top_album_artist_id']) self.assertTrue('Top Song 1' in actual_dict['top_songs']) self.assertTrue('Top Song 2' in actual_dict['top_songs'])
def search(query): query = query.replace('+', ' ') # songs = list(Song.objects(Q(title__icontains=query) | Q(album__icontains=query) | Q(artist__icontains=query)).order_by('listeners')) songs = list(Song.objects(Q(title__icontains=query) | Q(album__icontains=query) | Q(artist__icontains=query)).order_by('-listeners')[:20]) #fix this albums = list(Album.objects.order_by('-listeners').filter(Q(title__icontains=query) | Q(artist__icontains=query))[:25]) artists = list(Artist.objects.order_by('-listeners').filter(name__icontains=query)[:5]) #make response response = { 'songs': [{ 'title': song.title, 'artist': song.artist, 'album': song.album, 'img': song.img, 'id': str(song.id), 'album_index': song.album_index, 'duration': song.duration, 'youtube_url': song.youtube_url, 'album_id': str(song.album_id), 'artist_id': str(song.artist_id) } for song in songs], 'albums': [{ 'title': album.title, 'artist': album.artist, 'img': album.img, 'id': str(album.id) } for album in albums], 'artists': [{ 'name': artist.name, 'img': artist.img, 'id': str(artist.id) } for artist in artists] } return json.dumps(response)
def add_song(): """Handle add-song form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-songs """ # ADD THE NECESSARY CODE HERE FOR THIS ROUTE TO WORK form = SongForm() if form.validate_on_submit(): title = form.title.data artist = form.artist.data if Song.query.filter(Song.title == title, Song.artist == artist).first(): form.title.errors.append( 'A song with that name and artist already exists in the database.' ) return render_template('new_song.html', form=form) new_song = Song(title=title, artist=artist) db.session.add(new_song) db.session.commit() return redirect('/songs') return render_template('new_song.html', form=form)
def add_song(): """Handle add-song form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-songs """ # ADD THE NECESSARY CODE HERE FOR THIS ROUTE TO WORK form = SongForm() if request.method == "GET": return render_template('new_song.html', form=form) elif request.method == "POST": if form.validate_on_submit(): title = form.title.data artist = form.artist.data song = Song(title=title, artist=artist) db.session.add(song) db.session.commit() return redirect('/songs') else: return render_template('new_song.html', form=form) else: flash('something went wrong') return redirect('/songs')
def save_song(): """Save song to database.""" song_uri = request.args.get("songData") song_name = request.args.get("songTitle") song_img = request.args.get("songImg") playlist_no = int(request.args.get("playlist")) service = '' if 'spotify' in song_uri: service = 'spotify' elif '/' in song_uri: service = 'mixcloud' else: service = 'youtube' song = Song(service_id=song_uri, song_name=song_name, song_img=song_img, service=service) db.session.add(song) db.session.commit() playlist_song = PlaylistSong(playlist_id=playlist_no, song_id=song.song_id) db.session.add(playlist_song) db.session.commit() return jsonify('Success.')
def test_show_favorites(self): """Test favorite page.""" with app.test_client() as client: with client.session_transaction() as session: session["USER_ID"] = self.user_id # Without favorites res = client.get("/favorites") html = res.get_data(as_text=True) self.assertEqual(res.status_code, 200) self.assertIn("You have <b>no</b> favorite songs.", html) # With favorites favorite = Favorite(user_id=self.user_id, song_key=SONG_JSON["key"]) song = Song(playlist_id=None, external_song_key=SONG_JSON["key"], song_title=SONG_JSON["title"], song_artist=SONG_JSON["subtitle"]) db.session.add_all((favorite, song)) db.session.commit() res = client.get("/favorites") html = res.get_data(as_text=True) self.assertEqual(res.status_code, 200) self.assertIn(SONG_JSON["title"], html)
def songs_avg_difficulty(): id = 'all songs' pipelines = [] try: level = request.args['level'] pipelines.append({ '$match': { 'level': int( level ), # TODO: deserialise all inputs so there's no need to cast to int here } }) id = f'level {level} songs' except KeyError: # No level pass pipelines.append({ '$group': { '_id': id, 'average_difficulty': { '$avg': '$difficulty' }, }, }) try: result = next(Song.collection().aggregate(pipeline=pipelines)) except StopIteration: result = dict( _id='Database is empty', average_difficulty=None, ) return jsonify(result)
def update_fav(): """Handle add/remove favorite.""" if not g.user: flash("Access unauthorized.", "danger") return redirect("/") user = User.query.get_or_404(g.user.id) req = request.json track_id = req.get("trackId") favs_id = [fav.song_id for fav in g.user.favors] if track_id not in favs_id: song = Song(**req) if not Song.query.filter_by(trackId=song.trackId).first(): db.session.add(song) db.session.commit() fav = Favors(user_id=g.user.id, song_id=song.trackId) db.session.add(fav) db.session.commit() return jsonify({'message': 'successfully added'}) else: fav = Favors.query.filter_by(song_id=track_id, user_id=user.id).first() user.favors.remove(fav) db.session.commit() return jsonify({'message': 'successfully deleted'})
def songs(): query = Song.select() query_results = list(query) results = [song_join_to_json(result) for result in query_results] return jsonify({"objects": results})
def save_song(self, song_id): data = self.get_song_by_id(song_id) new_song = Song(id=data['id'], name=data['title'], lyrics=data['lyrics'].decode('utf-8')) session.add(new_song) session.commit()
def get(self): order = Song.query().order(-Song.views).fetch(5) popularList = { "list" : order } popular_template = jinja_env.get_template('/templates/popularsearch.html') self.response.write(popular_template.render(popularList))
def new_song(request): if request.method == "POST": form = SongForm(request.POST) if form.is_valid(): data = analyze(form.cleaned_data['lyrics']) try : artist = Artist.objects.all().filter(name=form.cleaned_data['artist-name']) except: artist = Artist(name=form.cleaned_data['artist_name']) artist.save() song = Song(name=form.cleaned_data['song_name'], lyrics = form.cleaned_data['lyrics'], artist=artist, number_of_words= data['total_words'], number_unique_words=data['unique_words'], unique_word_percent=data['percentage'], repeated_rhymes=data['repeated_rhymes'], bad_words=data['bad_words'], thug_rating=data['thug_rating'], avg_syllables=data['thug_rating']) song.save() return redirect("/") form = SongForm() return render(request, 'lyrics/new_song.html', { 'form': form })
def get(self): """ http -f POST http://127.0.0.1:8888/api/song/search keyword=J """ keyword = self.get_argument('keyword') song_infos = xiami_api.search_song_info_by_name(keyword) songs = [Song.from_xiami_song_info(x) for x in song_infos] self.add_header('X-count', len(songs)) self.write(json.dumps([x.to_api_dic() for x in songs]))
def process_song(name, content): """ Processes a song upload: saving it and reading the meta information returns the song object and mutagen audio object, or None if it couldn't parse the file. """ if not valid_song(name): raise BadContent(name) # Save the song into the database -- we'll fix the tags in a moment. song = Song(track=0, time=0) song.audio.save(name, content) audio = annotate_metadata(song) annotate_checksum(song) song.save() return (song, audio)
def next(self, request, **kwargs): if request.GET['album'] and request.GET['track_num']: song = Song.get_song(int(request.GET['album']), int(request.GET['track_num'])) if request.GET['album'] and not song: song = Album.get_similar_album(request.GET['album']).song_set[0] if not song: song = Album.get(0).song_set[0] bundle = self.build_bundle(obj=song, request=request) bundle = self.full_dehydrate(bundle) return self.create_response(request, { 'song': bundle })
def parse_soundcloud(data): """ Turns a JSON response from Soundcloud into a list of Songs :param data: JSON response of tracks from Soundcloud :return: List of Songs from search """ songs = [] for track in data: if track['streamable']: song = check_if_exists({'source': 'Soundcloud', 'tag': track['id']}) if song is not None: songs.append(song) else: song = Song(name=unicode(track['title']), artist=unicode(track['user']['username']), album='', source='Soundcloud', tag=track['id'], inherited_popularity=track['playback_count'] / float(200000)) song.save() songs.append(song) return songs
def _fetch_data(self, url): resp = requests.get(url) if not resp.ok: print "Failed to get %s [%s]" % (resp.url, resp.status_code) return False try: data = resp.json() except ValueError as e: print e return False if not data: return False count = 0 while count < 100: if str(count) not in data: break track = data[str(count)] song = self._check_id(track['mediaid']) if not song: song = Song(track['mediaid']) song.title = track['title'] song.artist = track['artist'] song.url = track['stream_url_raw'] db.session.add(song) else: song.downloaded += 1 song.url = track['stream_url_raw'] db.session.add(song) db.session.commit() self.songs.append(song) count += 1 return True
def testManyToManyOperation(self): team = Team.create(name="Houkago Tea Time") for name in self.names: team.members.append(first_name=name[0], last_name=name[1], part=name[2], age=name[3]) song1 = Song.create(name="Utauyo!! MIRACLE") song2 = Song.create(name="Tenshi ni Fureta yo!") for m in Member.all(): song1.members.append(m) for m in Member.select(age=17): song2.members.append(m) members = song1.members self.assertEqual(members.count(), 5) members = song2.members self.assertEqual(members.count(), 4) azusa = Member.get(first_name="Azusa") songs = azusa.songs self.assertEqual(songs.count(), 1) self.assertEqual(songs[0].name, "Utauyo!! MIRACLE")
def put(self): """ """ xiami_song_id = self.get_argument('song_id') song_info = xiami_api.request_song_info(xiami_song_id) if song_info is None: self.set_status(404) return song = Song.from_xiami_song_info(song_info) count = play.play_song(song) self.write(json.dumps({'count': count}))
def test_new_song_has_updated_at(self): with gillard.app.app_context(): song = Song() song = test_utils.save_and_refresh( gillard.db.session, song ) # updated_at starts empty assert song.updated_at is None song.artist = 'fake_ass_bullshit' song = test_utils.save_and_refresh( gillard.db.session, song ) # on update, updated_at gets set to now-ish assert (datetime.datetime.now() - song.updated_at).\ total_seconds() < 2
def songrequest(request): c = {} c['title'] = 'Request a song' if request.method == 'POST': songRequestForm = SongRequestForm(request.POST) response = '' if songRequestForm.is_valid(): try: song = Song.objects.get(text=songRequestForm.cleaned_data['song']) except Song.DoesNotExist: song = Song(text=songRequestForm.cleaned_data['song']) song.save() #Check if same song has been requested in the last 15 min lastSongRequests = SongRequest.objects.filter(date__gte=(now() - timedelta(minutes=15))) for x in lastSongRequests: if x.song == song: response = alerthtml('alert-error', 'Error!', 'That song has already been requested in the last 15 minutes') break else: songRequest = SongRequest(song=song) songRequest.save() response = alerthtml('alert-success', 'Success!', 'Your song has been requested') else: response = alerthtml('alert-error', 'Error!', 'Please fill in all fields!') if request.is_ajax(): return HttpResponse(simplejson.dumps({'html': response}), content_type="application/json") else: c['songrequest_result'] = response c['songRequestForm'] = SongRequestForm() #Previous songs for typeahead c['songs'] = Song.objects.order_by('-date')[:500] return render_helper('esc_songrequest.html', c, request)
def get_playlist_by_id(self, request): """ Returns a playlist based on the plalist id """ pl = Playlist.find_by_id(request.pid) response = PlaylistResponse(pid=pl.key.id(), name=pl.name, songs=[]) songs = Song.find_by_playlist(pl.key).fetch() for song in songs: response.songs.append(SongMessage(id=song.key.id(), spotify_id=song.spotify_id, name=song.name, vote_count=song.vote_count)) return response
def parse_spotify(data): """ Parse JSON of list of Spotify track search results and return a list of Steazy songs associated with them. Doesn't create new songs if they already exist in the database :param data: JSON list of Spotify track results. Described at https://developer.spotify.com/web-api/search-item/ :return: """ songs = [] for track in data: song = check_if_exists({'source': 'Spotify', 'tag': track['id']}) if song is not None: songs.append(song) else: artists = '' for art in track['artists']: artists += unicode(art['name']) + ', ' artists = artists[:len(artists) - 2] song = Song(name=unicode(track['name']), artist=artists, album=unicode(track['album']['name']), source='Spotify', tag=track['id'], inherited_popularity=track['popularity']) song.save() songs.append(song) return songs
def get(self): self.response.headers["Content-Type"] = "text/plain" # self.response.out.write(json.dumps(rssloader.rssdata)) week_date = "2012-06-16" # read songs = Song.gql("WHERE ANCESTOR IS :1 " "ORDER BY rank DESC LIMIT 10", week_key(week_date)) res = {} res[week_date] = [db.to_dict(song) for song in songs] # res[week_date] = [dictify.to_dict(song) for song in songs] self.response.out.write(json.dumps(res, default=dthandler))
def run(self): self.curl.perform() html_string = self.buffer.getvalue() if not html_string: print("Pusto") self.curl.perform() try: szkielet = lxml.html.fromstring(html_string) lista = szkielet.cssselect('ul.contents li div.content') for element in lista: title = element.cssselect('a.content_title')[0].text_content().encode('utf-8') title = re.sub('\s+', ' ', title) user = element.cssselect('a.user_name span')[0].text_content() upvotes = element.cssselect('a.like span.content_vote_count')[0].text_content() downvotes = element.cssselect('a.dislike span.content_vote_count')[0].text_content() songdate = element.cssselect('ul span.color_gray span')[0].get('title') songdate = DateHelper.makeDate(songdate) domain = element.cssselect('h2 span.color_gray a')[0].text_content() url = element.cssselect('ul.content_info_actions li a')[0].get('href') yturl = element.cssselect('a.content_title')[0].get('href') if domain == 'youtube.com': try: exist = Song.objects.get(url=url) exist.votes = int(upvotes)-int(downvotes) exist.upvotes = int(upvotes) exist.downvotes = int(downvotes) exist.save() except ObjectDoesNotExist: url_data = urlparse(yturl) query = parse_qs(url_data.query) ytid = query["v"][0] print domain song = Song(title=title, user=user, upvotes=int(upvotes), downvotes=int(downvotes),\ date=datetime.strptime(songdate, '%d %m %Y %H:%M:%S'), url=url,yturl=yturl,\ ytid=ytid, strim=self.strim, votes=int(upvotes)-int(downvotes)) song.save() except Exception as err: logging.exception('Error %s', err)
def query(request): key = request.GET.get('song', '') query = Song.all().search(key).fetch(limit=10) songs = [] for s in query: songs.append({ 'title' : s.title, 'location' : s.location, 'info' : s.info }) enc = simplejson.JSONEncoder() data = enc.encode(songs) return HttpResponse(data)
def add(request): if(request.method == "POST"): name = request.POST.get("name","") movie = request.POST.get("movie", "") artist = request.POST.get("artist", "") scale = request.POST.get("scale", "") notes = request.FILES['notes'] #notes = request.POST.get('notes') tempo = request.POST.get("tempo", "0") form_count = request.POST.get("count", 0) song = Song(name=name,movie=movie,artist=artist,scale=scale,tempo=tempo,notation="",notes=notes,user=request.user) song.save() if(form_count > 0): for i in range(1,int(form_count)+1): ref = Ref(name=request.POST.get("ref_name"+str(i)),link=(request.POST.get("ref_url"+str(i))).replace("watch?v=","embed/"),comment=request.POST.get("ref_comment"+str(i)),category=request.POST.get("ref_category"+str(i)),song=song) ref.save() t = get_template('add_done.html') html = t.render(RequestContext(request,{})) return HttpResponse(html) else: t = get_template('add.html') html = t.render(RequestContext(request,{})) return HttpResponse(html)
def scan_path(self, state, dir, files): """ Scan the given list of files in the given directory for new media and updated metadata. """ print dir # Go through each of the files... for file_name in files: # Figure out where on the filesystem it is file_path = os.path.join(dir, file_name) # Update our scanned file count before anything bad happens state["scanned"] += 1 # From this point on, any number of errors can occur try: song = Song(file_path=file_path) # Only save the Song if the update went OK if song.update_from_file(): song.save() except Exception, e: if self.raise_errors: raise else: print "Error %s while processing file %s" % (e, file_path)
def build_playlist_response(playlists): """ Builds a playlist response for the given playlists """ response = MultiplePlaylistResponse(playlists=[]) for pl in playlists: playlist = PlaylistResponse(pid=pl.key.id(), name=pl.name, songs=[]) songs = Song.find_by_playlist(pl.key).fetch() for song in songs: playlist.songs.append(SongMessage(id=song.key.id(), spotify_id=song.spotify_id, name=song.name, vote_count=song.vote_count)) response.playlists.append(playlist) return response
def parser_song(song_id, artist): tree = get_tree(SONG_URL.format(song_id)) song = Song.objects.filter(id=song_id) r = post(COMMENTS_URL.format(song_id)) if r.status_code != 200: print 'API Error: Song {}'.format(song_id) return data = r.json() if not song: for404 = tree.xpath('//div[@class="n-for404"]') if for404: return try: song_name = tree.xpath('//em[@class="f-ff2"]/text()')[0].strip() except IndexError: try: song_name = tree.xpath( '//meta[@name="keywords"]/@content')[0].strip() except IndexError: print 'Fetch limit!' time.sleep(10) return parser_song(song_id, artist) song = Song(id=song_id, name=song_name, artist=artist, comment_count=data['total']) song.save() else: song = song[0] comments = [] for comment_ in data['hotComments']: comment_id = comment_['commentId'] content = comment_['content'] like_count = comment_['likedCount'] user = comment_['user'] if not user: continue user = User.get_or_create(id=user['userId'], name=user['nickname'], picture=user['avatarUrl']) comment = Comment.get_or_create(id=comment_id, content=content, like_count=like_count, user=user, song=song) comment.save() comments.append(comment) song.comments = comments song.save() time.sleep(1) return song
def get(self): site_name = self.request.get('user') url, url_linktext = IsUserLoggedIn(self.request.uri) user = users.get_current_user() songList = UserPrefs.all().filter('user ='******'songs': songs, 'url': url, 'url_linktext': url_linktext, } path = os.path.join(os.path.dirname(__file__), 'usersongs.html') self.response.out.write(template.render(path, template_values))