def read_playlist(datafile): print("read_playlist_data") if not os.path.exists(full_path(datafile)): return Playlist() with open(full_path(datafile), 'r') as f: return Playlist(**json.loads(f.read()))
def hello_world(): access_code = request.args.get('code') ##### body = { 'grant_type': 'authorization_code', 'code': access_code, 'redirect_uri': 'http://localhost:5000/auth', 'client_id': client_id, 'client_secret': client_secret } token = requests.post(url='https://accounts.spotify.com/api/token', data=body).json() access_token = token['access_token'] refresh_token = token['refresh_token'] header = { 'Authorization': f"Bearer {access_token}", 'Content-Type': 'application/json' } user = requests.get(url='https://api.spotify.com/v1/me', headers=header).json() user_id = user['id'] # print(user) playlists = requests.get(url='https://api.spotify.com/v1/me/playlists', headers=header).json() discover_forever_id = None for p in playlists['items']: if p['name'] == 'Discover Weekly': discover_id = p['id'] elif p['name'] == 'Discover Forever': discover_forever_id = p['id'] if not discover_forever_id: playlist_body = { "name": "Discover Forever", "description": "A collection of all your Discover Weekly songs", "public": True } new_playlist = requests.post( url=f"https://api.spotify.com/v1/users/{user['id']}/playlists", headers=header, data=json.dumps(playlist_body)).json() discover_forever_id = new_playlist['id'] new_user = User(user_id, discover_forever_id, refresh_token) if not new_user.exists(new_user.id): new_user.save_user() forever_playlist = Playlist(discover_forever_id, discover_id) if not forever_playlist.exists(forever_playlist.id): forever_playlist.save_playlist() discover_forever_playlist = requests.get( url=f'https://api.spotify.com/v1/playlists/{discover_forever_id}', headers=header).json() new_playlist.save_tracks(header) return redirect( f"/success/{user['id']}/{discover_forever_playlist['name']}")
def create_playlist(): playlist_json = request.json playlist = Playlist(request.json['name']) playlist.user_id = session['user_id'] playlist.save() g.user.add_playlist(playlist) return ""
def add(request, animation): dajax = Dajax() dajax.remove_css_class('#movie-inspector label', 'error') animation = json.loads(animation) animation.update({ 'type': 'm', 'user': request.user is None and '' or request.user.id, }) if int(animation['max_duration']) > 60: animation['max_duration'] = 60 movie_duration = 0 for frame in animation['data']: frame['duration'] = int(frame['duration']) if frame['duration'] > 2000: frame['duration'] = 2000 movie_duration += frame['duration'] if movie_duration > 60000: dajax.script('MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")') return dajax.json() form = AnimationForm(animation) if form.is_valid(): a = form.save() p = Playlist( title = 'stub \'%s\' playlist' % form.cleaned_data['title'], user = User.objects.all()[0] ) p.save() ai = AnimationInstance( playlist = p, animation = a ) ai.save() # queue playlist sj = SpoolJob( playlist = p, priority = 2, added = datetime.now() ) sj.save() dajax.script('MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")' % p.id) else: for error in form.errors: dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error') dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")') return dajax.json()
def add(request, animation): dajax = Dajax() dajax.remove_css_class('#movie-inspector label', 'error') animation = json.loads(animation) animation.update({ 'type': 'm', 'user': request.user is None and '' or request.user.id, }) if int(animation['max_duration']) > 60: animation['max_duration'] = 60 movie_duration = 0 for frame in animation['data']: frame['duration'] = int(frame['duration']) if frame['duration'] > 2000: frame['duration'] = 2000 movie_duration += frame['duration'] if movie_duration > 60000: dajax.script( 'MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")' ) return dajax.json() form = AnimationForm(animation) if form.is_valid(): a = form.save() p = Playlist(title='stub \'%s\' playlist' % form.cleaned_data['title'], user=User.objects.all()[0]) p.save() ai = AnimationInstance(playlist=p, animation=a) ai.save() # queue playlist sj = SpoolJob(playlist=p, priority=2, added=datetime.now()) sj.save() dajax.script( 'MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")' % p.id) else: for error in form.errors: dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error') dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")') return dajax.json()
def add_playlist(): """Handle add-playlist form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-playlists """ form = PlaylistForm() if form.validate_on_submit(): Playlist.create_playlist(form) return redirect(f"/playlists") return render_template('new_playlist.html', form=form)
def test_add_song_to_playlist(self): with gillard.app.app_context(): song = Song() playlist = Playlist() playlist.songs = [song] playlist = test_utils.save_and_refresh(gillard.db.session, playlist) assert len(playlist.songs) == 1 # cascading add assert playlist.songs[0].id is not None
def generate_playlist(request): print(request.POST.keys()) artists = request.POST.get("artists").replace('/', '\n').split('\n') if artists: client = soundcloud.Client(access_token=request.COOKIES['access_token']) print(artists) all_tracks = [] for artist in artists: artist = artist.strip() print artist tracks = client.get('/tracks', q=artist, limit=20) short_tracks = [] count = 0 for track in tracks: max_tracks = int(request.POST.get("max_tracks")) if count > max_tracks: break max_length = int(request.POST.get("max_length")) if max_length == 0 or track.duration < (max_length * 60 * 1000): #Skip ones longer than max_length mins count += 1 short_tracks.append(track) all_tracks.extend(track.id for track in short_tracks) print len(all_tracks) if request.POST.get("randomize"): print("Randomize = true") random.shuffle(all_tracks) # create an array of track ids all_tracks_ids = map(lambda id: dict(id=id), all_tracks) # create the playlist # FIXME: timeout more than ~400 sounds in total print("Creating Playlist...") ret = client.post('/playlists', playlist={ 'title': request.POST.get("title"), 'sharing': "public", #TODO: cutomize this viw a tickbox 'tracks': all_tracks_ids }) try: user = client.get('/me') plst = Playlist(name=ret.title, author=user.username, author_id=user.uri, url=ret.permalink_url) plst.save() except Exception as exc: print("++ ERROR while trying to save the playlist: %s" % exc) print("Created %s available at: %s!" % (ret.title, ret.permalink_url)) return HttpResponse(simplejson.dumps({"link": ret.permalink_url, "title": ret.title}), content_type="application/json") else: print("no artists found!") return HttpResponseServerError()
def get_playlist(user, name): """ Checks to see if the user has a playlist named name If not, create the playlist :param user: User object :param name: String of name of playlist :return: Playlist owned by user, named name """ search = Playlist.objects.filter(name=name, owner=user) if search.exists(): return search[0] else: playlist = Playlist(owner=user, name=name) playlist.save() return playlist
def download_channel_video_list(channel_id): # 获取上传列表Id from youtube import get_uploads_list_id,get_playlist_items upload_list_id = get_uploads_list_id(channel_id) video_id_list = get_playlist_items(upload_list_id) # 将上传列表加入数据库 from models import Video, Playlist playlist = Playlist(playlist_id=upload_list_id) global ThreadSession session = ThreadSession() session.add(playlist) session.commit() # 将视频与上传列表建立关系,并加入数据库 def _add_video(video_id, session): # todo 复习闭包 video = Video(video_id=video_id) video.playlists.append(playlist) session.add(video) session.commit() [_add_video(video_id,session) for video_id in video_id_list] ThreadSession.remove() return None
def add_playlist(): """Handle add-playlist form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-playlists """ form = PlaylistForm() if form.validate_on_submit(): name = form.name.data desc = form.description.data # Check if input is empty if name.isspace(): flash("Platlist Name is required", "danger") return redirect("/playlists/add") playlist = Playlist(name=name, description=desc) db.session.add(playlist) db.session.commit() flash("Playlist Added!", "success") return redirect("/playlists") return render_template("new_playlist.html", form=form)
def add_playlist(): """Handle add-playlist form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-playlists """ # ADD THE NECESSARY CODE HERE FOR THIS ROUTE TO WORK form = PlaylistForm() # if the CSRF token is validated after the form is submitted if form.validate_on_submit(): name = form.name.data description = form.description.data # Create a new playlist instance new_playlist = Playlist(name=name, description=description or None) db.session.add(new_playlist) try: db.session.commit() flash("Playlist created!") return redirect('/playlists') except IntegrityError: form.name.errors.append( "That playlist name is taken. Please choose another name.") return render_template('new_playlist.html', form=form)
def get(self, request): songs = Song.all_by_id() playlists = Playlist.all() context = {'songs': songs, 'playlists': playlists, } return render(request, 'music/index.html/', context)
def playlists(username): """Show playlists and create playlists.""" user = User.query.filter_by(username=username).first() if not user: abort(404, f"{username} not found") form = PlaylistForm() if user and g.user and user.id is g.user.id: if form.validate_on_submit(): if user.id is g.user.id: playlist = Playlist(user_id=user.id, name=form.name.data, description=form.description.data) user.playlists.append(playlist) db.session.commit() return redirect(f'/u/{user.username}/playlists/{playlist.id}') else: flash('Sign up to make playlsits', 'light') return redirect('/sign-up') else: form = False return render_template('playlist/playlists.html', form=form, user=user)
def save_new_playlist(): """Save new playlist created by user into database.""" new_playlist = request.args.get("newPlaylistName") user_id = session['logged_user']['user_id'] playlist = db.session.query(Playlist).filter( User.user_id == user_id, Playlist.playlist_name == new_playlist).first() if playlist: return jsonify("User already has a playlist with that name.") else: playlist = Playlist(user_id=user_id, playlist_name=new_playlist) db.session.add(playlist) db.session.commit() playlistData = { 'playlist_no': playlist.playlist_id, 'playlist_name': playlist.playlist_name } return jsonify(playlistData)
def get_playlist_videos(playlist_title): query = Playlist.all() query.filter('title =', playlist_title) playlist = query.get() query = VideoPlaylist.all() query.filter('playlist =', playlist) query.filter('live_association = ', True) query.order('video_position') videos = [] for pv in query.fetch(500): v = pv.video video_dict = { 'youtube_id': v.youtube_id, 'youtube_url': v.url, 'title': v.title, 'description': v.description, 'keywords': v.keywords, 'readable_id': v.readable_id, 'ka_url': "http://www.khanacademy.org/video/%s?playlist=%s" % (v.readable_id, urllib.quote_plus(playlist_title)), 'video_position': pv.video_position, 'views': v.views, } videos.append(video_dict) return json.dumps(videos, indent=4)
def new_playlist(): """Show new playlist form, handle form submission. Redirect to my playlists""" # If no user logged in, flash error message and redirect them to login page if not g.user: flash('You must be logged in to create a playlist!', 'danger') return redirect('/login') else: form = PlaylistForm() u_playlists = [playlist.name for playlist in g.user.playlists] # If form is submitted: if form.validate_on_submit(): # import pdb # pdb.set_trace() # save playlist to DB, redirect to user's playlist page if form.name.data not in u_playlists: playlist = Playlist(name=form.name.data, description=form.description.data, user_id=g.user.id) db.session.add(playlist) db.session.commit() return redirect(f'/users/{g.user.id}/playlists') else: flash('You already have a playlist with that name', 'danger') return render_template('new_playlist.html', user=g.user, form=form) else: # show new playlist form: return render_template('new_playlist.html', user=g.user, form=form)
def add_playlist(): """Handle add-playlist form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-playlists """ # ADD THE NECESSARY CODE HERE FOR THIS ROUTE TO WORK form = PlaylistForm() if request.method == "GET": return render_template('new_playlist.html', form=form) elif request.method == "POST": if form.validate_on_submit(): name = form.name.data description = form.description.data playlist = Playlist(name=name, description=description) db.session.add(playlist) db.session.commit() return redirect('/playlists') else: return render_template('new_playlist.html', form=form) else: flash('something went wrong') return redirect('/playlists')
def get_playlists(self): if not self.library_goosed: print("The library is not goosed. Call goose_up_library().") return False if not self.playlists: playlists_directory = "{0}/src/playlists".format( self.base_location) playlist_files = os.scandir(playlists_directory) self.playlists = [] for playlist_file in playlist_files: with open(playlist_file.path) as pfp: playlist_json = json.load(pfp) playlist = Playlist(title=playlist_json["title"]) for track_path in playlist_json["tracks"]: track_full_path = "{0}{1}".format( self.media_path, track_path) track = Track.init_from_file(track_full_path) if track: playlist.playlist_tracks.append(track) self.playlists.append(playlist) return self.playlists
def playlist_title_dicts(): return map(lambda playlist: { "title": playlist.title, "key": str(playlist.key()), "ka_url": playlist.relative_url, # remove once js clients update "url": playlist.relative_url }, Playlist.all())
def add_playlist(request): postdata = request.POST.copy() track_slug = postdata.get('track_slug', '') p = get_object_or_404(Track, link = track_slug) playlist_list = get_playlist(request) track_in_playlist = False for list in playlist_list: if list.track.id == p.id : track_in_playlist = True if not track_in_playlist: ci = Playlist() ci.track = p ci.playlist_id = _playlist_id(request) ci.save()
def add_video(): playlist_id = request.form.get("playlist_id") if playlist_id.strip() == "": return jsonify({'error': "You must specify a playlist ID for this video."}) playlist = Playlist.query.get(playlist_id) if playlist == None: return jsonify({'error': "Playlist not found"}) slug = request.form.get("slug") if slug.strip() == "": return jsonify({'error': "You must specify a slug for this video."}) thumbnail_url = request.form.get("thumbnail_url") if thumbnail_url.strip() == "": return jsonify({'error': "You must specify a thumbnail for this video."}) title = request.form.get("title") if title.strip() == "": return jsonify({'error': "You must specify a title for this video."}) v = Video(playlist_id, slug, thumbnail_url, title) db_session.add(v) db_session.commit() # Publish to Redis so that all clients update playlist data = { "action": "update_playlist", "playlist": Playlist.get_videos(playlist_id) } redis.publish(playlist_id, json.dumps(data)) return jsonify({"success": True})
def add_playlist(): """Handle add-playlist form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-playlists """ form = PlaylistForm() if form.validate_on_submit(): name = form.name.data description = form.description.data new_playlist = Playlist(name=name, description=description) db.session.add(new_playlist) try: db.session.commit() except IntegrityError as e: if 'name' in e.orig.pgerror: form.name.errors.append( 'Playlist name already exists. Please choose another.') return render_template('new_playlist.html', form=form) return redirect('/playlists') return render_template('new_playlist.html', form=form)
def playlist_title_dicts(): return map( lambda playlist: { "title": playlist.title, "key": str(playlist.key()), "ka_url": "/#%s" % slugify(playlist.title.lower()) }, Playlist.all())
def add_playlist(): """Handle add-playlist form: - if form not filled out or invalid: show form - if valid: add playlist to SQLA and redirect to list-of-playlists """ form = PlaylistForm() if form.validate_on_submit(): name = form.name.data description = form.description.data new_playlist = Playlist(name=name, description=description) db.session.add(new_playlist) try: db.session.commit() except IntegrityError: form.name.errors.append( 'Playlist name taken. Please pick another.') return render_template('new_playlist.html', form=form) flash('Successfully created new playlist!', "success") return redirect('/playlists') return render_template('new_playlist.html', form=form)
def createPlaylist(request, track_id, playlist_name, owner_id): created_by = User.objects.get(id=owner_id) new_list = Playlist( name = playlist_name, owner = created_by, pub_date = timezone.now(), ) new_list.save() track = Track.objects.get(id=track_id) new_list.tracks.add(track) context = { 'track' : track, 'playlist' : new_list, 'msg' : "has been added into the new playlist! " } return HttpResponseRedirect('/playlist/')
def post(self): # Get arguments from request args = player_parser.parse_args() if 'id' not in args: highest = Player.query.order_by(Player.id).last() player_id = highest + 1 else: player_id = args['id'] player = Player(id=player_id, email=args['email'], password=args['password'], first_name=args['first_name'], last_name=args['last_name'], hockey_level=args['hockey_level'], skill_level=args['skill_level'], hand=args['hand']) db.session.add(player) playlist = Playlist(id=player_id) db.session.add(playlist) player.playlist = playlist db.session.commit() return player, 201
def get_all_tracks_in_playlist(self, playlist_id): try: playlist = Playlist.get(playlist_id) except ValueError as e: raise tracks = playlist.get_all_tracks() ret = [track.__dict__ for track in tracks] return ret
def test_mk_new_playlist(self): with gillard.app.app_context(): playlist = Playlist() playlist = test_utils.save_and_refresh(gillard.db.session, playlist) assert playlist.id is not None
def test_new_playlist_has_no_songs(self): with gillard.app.app_context(): playlist = Playlist() playlist = test_utils.save_and_refresh(gillard.db.session, playlist) assert len(playlist.songs) == 0
def playlist_title_dicts(): return map( lambda playlist: { "title": playlist.title, "key": str(playlist.key()), "ka_url": playlist.relative_url, # remove once js clients update "url": playlist.relative_url }, Playlist.all())
def test_playlist_updated_at(self): with gillard.app.app_context(): playlist = Playlist() playlist = test_utils.save_and_refresh(gillard.db.session, playlist) # updated_at starts empty assert playlist.updated_at is None playlist.display_id = 'NEWTESTDISPID' playlist = test_utils.save_and_refresh(gillard.db.session, playlist) # on update, updated_at gets set to now-ish assert (datetime.datetime.now() - playlist.updated_at).\ total_seconds() < 2
async def post(self): request_data = await self.request.content.read() request_data = json.loads(request_data) try: request_data["user_id"] = 1 playlist = Playlist(**request_data) except Exception as e: return web.json_response({"message": f"invalid request: {e}"}, status=400) playlist.id = self.extract_id(playlist.url) exists_playlist = await self.collection.find_one({"id": playlist.id}) if not exists_playlist: await self.collection.insert_one(playlist.dict()) await self.publish_message(playlist) return web.json_response(playlist.dict(), status=201)
def create_playlist(self, request): """ Creates a playlist for the user """ # TODO: Max amount of playlists at 20 for a user user = Account.find_by_id(request.userid) if user is None: print "User not found" return PlaylistResponse(errmsg="User ID not found") new_pl = Playlist.add_new_playlist(user.key, request.name) return PlaylistResponse(pid=new_pl.key.id())
def playlist(user_id): if request.method == 'GET': playlists = Playlist.objects().filter(user_id=user_id) return playlists.to_json() if request.method == 'POST': playlist = Playlist() playlist.user_id = user_id playlist.name = 'New Playlist' playlist.song_ids = [] playlist.save() return playlist.to_json()
def playlist_content_html(): """" Returns the HTML for the structure of the playlists as they will be populated ont he homepage. Does not actually contain the list of video names as those are filled in later asynchronously via the cache. """ # No cache found -- regenerate HTML smart_history = getSmartHistoryContent() dict_playlists_by_title = {} all_playlists = [] for playlist in Playlist.all(): if playlist.title in topics_list: dict_playlists_by_title[playlist.title] = playlist for topic in topics_list: if topic in dict_playlists_by_title: playlist = dict_playlists_by_title[topic] video_count = playlist.get_video_count() # 3 columns, 18px per row. This must be updated in conjunction # with code in homepage.js height = math.ceil(video_count / 3) * 18 playlist_data = { 'title': topic, 'topic': topic, 'playlist': playlist, 'list_height': height, 'next': None, } all_playlists.append(playlist_data) playlist_data_prev = None for playlist_data in all_playlists: if playlist_data_prev: playlist_data_prev['next'] = playlist_data playlist_data_prev = playlist_data timestamp = time.time() template_values = { 'App' : App, 'all_playlists': all_playlists, 'smart_history': smart_history, # convert timestamp to a nice integer for the JS 'timestamp': int(round(timestamp * 1000)), } html = shared_jinja.get().render_template("library_playlist_template.html", **template_values) Setting.cached_playlist_content_date( str(datetime.datetime.fromtimestamp(timestamp))) return html
def playlist_content_html(): """" Returns the HTML for the structure of the playlists as they will be populated ont he homepage. Does not actually contain the list of video names as those are filled in later asynchronously via the cache. """ # No cache found -- regenerate HTML smart_history = getSmartHistoryContent() dict_playlists_by_title = {} all_playlists = [] for playlist in Playlist.all(): if playlist.title in topics_list: dict_playlists_by_title[playlist.title] = playlist for topic in topics_list: if topic in dict_playlists_by_title: playlist = dict_playlists_by_title[topic] video_count = playlist.get_video_count() # 3 columns, 18px per row. This must be updated in conjunction # with code in homepage.js height = math.ceil(video_count / 3) * 18 playlist_data = { 'title': topic, 'topic': topic, 'playlist': playlist, 'list_height': height, 'next': None, } all_playlists.append(playlist_data) playlist_data_prev = None for playlist_data in all_playlists: if playlist_data_prev: playlist_data_prev['next'] = playlist_data playlist_data_prev = playlist_data timestamp = time.time() template_values = { 'App': App, 'all_playlists': all_playlists, 'smart_history': smart_history, # convert timestamp to a nice integer for the JS 'timestamp': int(round(timestamp * 1000)), } html = shared_jinja.get().render_template("library_playlist_template.html", **template_values) Setting.cached_playlist_content_date( str(datetime.datetime.fromtimestamp(timestamp))) return html
def test_new_playlist_has_created_at(self): with gillard.app.app_context(): playlist = Playlist() playlist = test_utils.save_and_refresh(gillard.db.session, playlist) assert \ (datetime.datetime.now() - playlist.created_at).\ total_seconds() < 2
def setUp(self): self.client = Client() # Adds some example songs and playlists to the test db self.song1 = Song.create(name="song1", path="path1") self.song2 = Song.create(name="song2", path="path2") self.song3 = Song.create(name="song3", path="path3") self.playlist1 = Playlist.create(name="playlist1") self.playlist2 = Playlist.create(name="playlist2") self.playlist3 = Playlist.create(name="playlist3") self.playlist1.songs.add(self.song1) self.playlist1.songs.add(self.song2) self.playlist1.songs.add(self.song3) self.playlist2.songs.add(self.song1) self.playlist2.songs.add(self.song2) self.playlist3.songs.add(self.song1)
def test_playlist_updated_at(self): with gillard.app.app_context(): playlist = Playlist() playlist = test_utils.save_and_refresh( gillard.db.session, playlist ) # updated_at starts empty assert playlist.updated_at is None playlist.display_id = 'NEWTESTDISPID' playlist = test_utils.save_and_refresh( gillard.db.session, playlist ) # on update, updated_at gets set to now-ish assert (datetime.datetime.now() - playlist.updated_at).\ total_seconds() < 2
def test_playlist_model(self): u = User(username="******", password="******") p = Playlist(name='Spring', user_id=1) db.session.add(p) db.session.add(u) db.session.commit() # User should have id 1, and 1 playlist self.assertEqual((p.user_id), 1) self.assertEqual(len(u.playlists), 1)
def get_playlist(): playlist_id = request.args.get("playlist_id") # Now get the updated playlist and send it to the client videos = Video.query.filter(Video.playlist_id==playlist_id).order_by("rank desc") data = { "playlist": Playlist.get_videos(playlist_id) } return jsonify(data)
def post(self, request): data = json.loads(request.body) name = data['name'] songs = data['songs'] playlist = Playlist.create(name=name) playlist.save() pool = ThreadPool(POOLSIZE) songs = (Song.get(pk=song_id) for song_id in songs) pool.map(playlist.songs.add, songs) pool.join() return HttpResponseRedirect('/music')
def fork(request, username, slug): """ creates new for of playlist, with parent set as current playlist Does not copy editors, followers or votes """ parent_owner = shortcuts.get_object_or_404(User, username=username) parent_playlist = shortcuts.get_object_or_404(Playlist, slug=slug, user=parent_owner) # create new fork new_playlist = Playlist(use=request.user, title = parent_playlist.title, slug = parent_playlist.slug, parent_fork=parent_playlist) new_playlist.save() Playlist.objects.save_bookmarks(new_playlist, parent_playlist.bookmarks.values_list('id')) messages.info(request, 'Playlist forked - You are now viewing your fork') return http.HttpResponseRedirect(reverse('bookmarks.playlist_views.view', args=[new_playlist.user.username,new_playlist.slug,]))
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 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 load_videos(version, title=None): root = Topic.get_by_id("root", version) if title is None: playlist = Playlist.all().order('title').get() else: playlist = Playlist.all().filter('title = ', title).get() title = playlist.title nextplaylist = Playlist.all().filter('title >', title).order('title').get() if nextplaylist: next_title = nextplaylist.title playlists = [playlist] # playlists = Playlist.all().order('title').fetch(100000) for i, p in enumerate(playlists): videos = p.get_videos() content_keys = [v.key() for v in videos] added = 0 for i, v in enumerate(videos): for e in v.related_exercises(): if e.key() not in content_keys: content_keys.insert(i + added, e.key()) added += 1 topic = Topic.insert(title=p.title, parent=root, description=p.description, tags=p.tags, child_keys=content_keys) logging.info("loading " + title) if nextplaylist: deferred.defer(load_videos, version, next_title) else: deferred.defer(hide_topics, version)
def create(request): if request.method == 'POST': url = request.POST.get('playlist_location', '') # #regexp here!!!!!!!!! # result = urlfetch.fetch(url + "code/xspf.php") if result.status_code == 200: # xml = minidom.parseString(unicode(result.content, "utf-8" )) try: xml = minidom.parseString(result.content.replace("&", "&")) except: return render_to_response('create.html', {'flash' : "Ops. Something went wrong!!!..."}) tracks = xml.getElementsByTagName('track') playlist = Playlist(title="lorem ipsum dolor", location=url) playlist.save() for song in tracks: loc = song.getElementsByTagName('location')[0] me = song.getElementsByTagName('meta')[0] ti = song.getElementsByTagName('title')[0] fo = song.getElementsByTagName('info')[0] s = SongForm({ 'location': getText(loc.childNodes), 'meta': getText(me.childNodes), 'title': getText(ti.childNodes), 'info': getText(fo.childNodes), }) if s.is_valid(): s.playlist = playlist s.save() return render_to_response('create.html', {'flash' : "Playlist added! <a href=\"/\">Go back to home page.</a>"}) return render_to_response('create.html')
def update_playlist(data): url = 'http://wrfl.fm/playlist/' r = urllib.urlopen(url).read() soup = BeautifulSoup(r, "html5lib") t = soup.find('tbody') data = ([[c.contents[0].contents for c in row.findAll('td')] for row in t.findAll('tr')]) for track in data[0:30]: try: playlist = Playlist.objects.get(playtime = cleanDateTime(track[0])) except: dj, created = DJ.objects.get_or_create(name=(track[4][0]).encode('utf-8')) dj_id = dj.id playlist = Playlist( dj = DJ(id=dj_id), artist = track[1][0], album = track[3][0], song = track[2][0], playtime = cleanDateTime(track[0]), url = getTinysongURL(track[1][0], track[2][0]), ) playlist.save() playlist_list = Playlist.objects.all() return render_to_response('update_playlist.html', {'playlist_list': playlist_list })
def get_playlists(): playlists = [] for playlist_title in all_topics_list: query = Playlist.all() query.filter('title =', playlist_title) playlist = query.get() playlist_dict = {'youtube_id': playlist.youtube_id, 'youtube_url': playlist.url, 'title': playlist.title, 'description': playlist.description, 'api_url': "http://www.khanacademy.org/api/playlistvideos?playlist=%s" % (urllib.quote_plus(playlist_title)), } playlists.append(playlist_dict) return json.dumps(playlists, indent=4)
def get_playlist_videos_json(playlist_title): query = Playlist.all() query.filter('title =', playlist_title) playlist = query.get() video_query = Video.all() video_query.filter('playlists = ', playlist_title) video_key_dict = Video.get_dict(video_query, lambda video: video.key()) video_playlist_query = VideoPlaylist.all() video_playlist_query.filter('playlist =', playlist) video_playlist_query.filter('live_association =', True) video_playlist_key_dict = VideoPlaylist.get_key_dict(video_playlist_query) return json.dumps(get_playlist_video_api_dicts(playlist, video_key_dict, video_playlist_key_dict), indent=4)
def create_playlist(playlist_name): user = get_user_from_db() # Create spotify playlist try: playlist_id = create_spotify_playlist(playlist_name) except SpotifyAPIError as e: print e # TODO: Handle error gracefully return e.message # Update db with playlist name and id playlist_data = { 'spotify_id': playlist_id, 'name': playlist_name, 'user_id': user.id } playlist = Playlist(**playlist_data) db.session.add(playlist) # add all songs to playlist songs = get_songs_from_db() add_songs_to_playlist(songs, user, playlist) playlist.last_updated = datetime.now() db.session.commit() flash('Your playlist, ' + playlist_name + ', was successfully created!', 'success') return render_template('index.html')
def get(self): playlist_title = "SAT Preparation" query = Playlist.all() query.filter('title =', playlist_title) playlist = query.get() query = VideoPlaylist.all() query.filter('playlist =', playlist) query.filter('live_association = ', True) #need to change this to true once I'm done with all of my hacks query.order('video_position') playlist_videos = query.fetch(500) template_values = { 'videos': playlist_videos, } self.render_jinja2_template('sat.html', template_values)
def get_video_library_json_compressed(): playlist_api_dicts = [] playlists = Playlist.get_for_all_topics() video_key_dict = Video.get_dict(Video.all(), lambda video: video.key()) video_playlist_query = VideoPlaylist.all() video_playlist_query.filter('live_association =', True) video_playlist_key_dict = VideoPlaylist.get_key_dict(video_playlist_query) for playlist in playlists: playlist_api_dict = ApiDict.playlist(playlist) playlist_api_dict["videos"] = get_playlist_video_api_dicts(playlist, video_key_dict, video_playlist_key_dict) playlist_api_dicts.append(playlist_api_dict) # We compress this huge json payload so it'll fit in memcache return zlib.compress(json.dumps(playlist_api_dicts, indent=4))
def getalltracks(): playlists = Playlist.all() response = {} for playlist in playlists: pl = {} tracks = {} i = 1 for track in playlist.tracks: trackobj = Track.get(track) tracks[i] = {'url':trackobj.url, 'type':'sc'} #FIXME 'sc' for now, change to track.type i += 1 pl['tracks'] = tracks response[playlist.name] = pl return jsonify(response)
def mark_played(): playlist_id = request.form.get("playlist_id") video_slug = request.form.get("video_slug") video = Video.query.filter(Video.playlist_id==playlist_id).filter(Video.slug==video_slug).first() db_session.delete(video) db_session.commit() # Publish to Redis so that all clients update playlist data = { "action": "update_playlist", "playlist": Playlist.get_videos(playlist_id) } redis.publish(playlist_id, json.dumps(data)) return jsonify({"success": True})
def API_removeTracks(self, track_ids, request): for track_id in track_ids.split(','): # don't crash on trailing comma if track_id != '': track_id = int(track_id) # For now if we are trying to remove the existing playing track. Do nothing. if (track_id == self.active_playlist_id): logging.warning("Not allowed to remove playing track") continue playlist = Playlist.get(self.tmpqueue_id) playlist.remove_playlist_tracks_id(track_id) self.needs_push_update = True self.playlist_version += 1 self.vote_version += 1 request.push({'vote_version': self.vote_version}) request.finish()
def copyTopicsToPlaylist(self): topic_list = Topic.get_content_topics() for topic in topic_list: playlist = Playlist.all().filter("title =", topic.standalone_title).get() if playlist: logging.info("Copying topic " + topic.standalone_title + " to playlist.") child_keys = topic.child_keys vps = VideoPlaylist.all().filter("playlist =", playlist).order("video_position").fetch(10000) playlist_keys = [] for vp in vps: try: playlist_keys.append(vp.video.key()) except db.ReferencePropertyResolveError: logging.info("Found reference to missing video in VideoPlaylist!") topic_keys = [key for key in topic.child_keys if key.kind() == "Video"] if playlist_keys == topic_keys: logging.info("Child keys identical. No changes will be made.") else: # logging.info("PLAYLIST: " + repr([str(key) for key in playlist_keys])) # logging.info("TOPIC: " + repr([str(key) for key in topic_keys])) logging.info("Deleting old VideoPlaylists...") db.delete(vps) vps = [] for i, child_key in enumerate(topic.child_keys): if child_key.kind() == "Video": vps.append(VideoPlaylist( video=child_key, playlist=playlist, video_position=i, live_association = True )) logging.info("Creating new VideoPlaylists...") db.put(vps) else: logging.info("Playlist matching topic " + topic.standalone_title + " not found.")
def test_Playlist_initialization(self): owner=Account(username='******', email='*****@*****.**').put() try: Playlist().put() self.assertEqual(1,2) except BadValueError: pass try: Playlist(owner=owner).put() self.assertEqual(1,2) except BadValueError: pass try: Playlist(name='atlejljd').put() self.assertEqual(1,2) except BadValueError: pass Playlist(owner=owner, name='MM\'s awesome playlist').put() self.assertEqual(1, len(Playlist.query().fetch(2)))