def populate_db(): a1 = Artist(name="Billy Joel", hometown="Long Island, NY") a2 = Artist(name="Tash Sultana", hometown="Melbourne, Australia") a3 = Artist(name="Mac Miller", hometown="Pittsburgh, PA") a4 = Artist(name="Red Hot Chili Peppers", hometown="Los Angeles, CA") db.session.add_all([a1, a2, a3, a4]) db.session.commit() s1 = Song(name="Zanzibar", artist=a1) s2 = Song(name="Mystik", artist=a2) s3 = Song(name="Woods", artist=a3) s4 = Song(name="The Longest Wave", artist=a4) db.session.add_all([s1, s2, s3, s4]) db.session.commit() print(s1) p1 = Playlist(name="Rock") p2 = Playlist(name="Slow Jams") stp1 = SongToPlaylist(song=s1, playlist=p1) stp2 = SongToPlaylist(song=s2, playlist=p1) stp3 = SongToPlaylist(song=s3, playlist=p2) stp4 = SongToPlaylist(song=s4, playlist=p2) db.session.add_all([p1, p2, stp1, stp2, stp3, stp4]) db.session.commit() print("Artist - Woods", s3.artist.name) return "Database has been populated."
def newLibrary(request): if request.method == 'POST': user = request.user if checkPermission(["LIBR"], user): response = json.loads(request.body) if 'URL' in response and 'NAME' in response: dirPath = response['URL'] if os.path.isdir(dirPath): # Removing / at the end of the dir path if present if dirPath.endswith("/"): dirPath = dirPath[:-1] library = Library() library.path = dirPath playlist = Playlist() playlist.user = user playlist.isLibrary = True playlist.name = strip_tags(response['NAME']) playlist.save() library.playlist = playlist library.save() data = { 'LIBRARY_ID': library.id, 'LIBRARY_NAME': library.playlist.name, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "dirNotFound") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "permissionError") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def load_playlist(fname): try: with open(fname + ".playlist") as f: playlist = Playlist() data = json.load(f) playlist.name = data['name'] playlist.thumbnail = data['thumbnail'] db.session.add(playlist) db.session.commit() for s in data['songs']: song_obj = Song.query.filter_by( itunes_resource_id=s['itunes_resource_id']).first() if song_obj is None: song_obj = Song() song_obj.name = s['name'] song_obj.artist = s['artist'] song_obj.album = s['album'] song_obj.thumbnail_url = s['thumbnail_url'] song_obj.preview_url = s['preview_url'] song_obj.external_url = s['external_url'] song_obj.itunes_resource_id = s['itunes_resource_id'] db.session.add(song_obj) db.session.commit() playlist.songs.append(song_obj) db.session.commit() return True except IOError as e: return False return False
def rescanLibrary(request): if request.method == 'POST': response = json.loads(request.body) if 'LIBRARY_ID' in response: library = strip_tags(response['LIBRARY_ID']) if Library.objects.filter(id=library).count() == 1: library = Library.objects.get(id=library) # Check if the library is not used somewhere else if library.playlist.isScanned: # Delete all the old tracks library.playlist.delete() # Recreating playlist playlist = Playlist() playlist.name = library.name playlist.user = request.user playlist.isLibrary = True playlist.save() library.playlist = playlist library.save() # Scan library data = scanLibrary(library, playlist, library.convertID3) else: data = errorCheckMessage(False, "rescanError") else: data = errorCheckMessage(False, "dbError") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def setUp(self): self.username = '******' self.email = '*****@*****.**' self.password = '******' self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) self.client = Client() self.client.login(username=self.username, password=self.password) self.anonymous_client = Client() self.playlist = Playlist(user=self.user) self.playlist.save() self.channel = Channel.objects.create(user=self.user, title='Testing Playlist', duration='150', group='The best group', path='no path') self.channel.playlists.add(self.playlist) self.sample_m3u8 = '\n'.join([ '#EXTM3U', '#EXTINF:0,BBC NEWS', '#EXTGRP:News', 'http://example.com/bbc-news-tv.m3u8', '#EXTINF:0,Fox NEWS', '#EXTGRP:News', 'http://example.com/fox-news-tv.m3u8', '#EXTINF:Invalid channel', 'http://example.com/invalid-channel.m3u8' ])
def playlist_new(): form = NewPlaylistForm() if form.validate_on_submit(): playlist = Playlist(title=form.title.data) db.session.add(playlist) db.session.commit() return redirect(url_for('playlist_all')) return render_template('playlist_new.html', form=form)
def playlist(playlist_id, spotify): user_id = spotify.current_user()['id'] api_response = spotify.user_playlist(user_id, playlist_id) playlist = Playlist(api_response) form = SongSearchForm() return render_template('playlist.html', playlist=playlist, items=playlist.items(), form=form)
def _make_db_playlist(sp_playlist): db_playlist = Playlist( id=sp_playlist['id'], name=sp_playlist['name'], description=sp_playlist['description'], ) db.session.add(db_playlist) _add_item_tracks(db_playlist, sp_playlist['tracks']) return db_playlist
def add_playlist_to_db(sentence, pl_tracks): pls = [str(track.id) for track in pl_tracks] ids_str = "-".join(pls) pl = Playlist(name=sentence.lower(), url_id=str(uuid4()).replace('-', ''), tracks_str=ids_str) db.session.add(pl) db.session.commit() return pl
def Make_playlist(): data = request.json print(data) p = Playlist(title=data['title'], desc=data['desc'], account_id=current_user.id) db.session.add(p) db.session.commit() flash('Playlist Created') return str(p.id)
def create_playlist(): data = request.json try: playlist = Playlist(name=data['playlistName'], user_id=data['id']) db.session.add(playlist) db.session.commit() return {'playlist': playlist.to_dict()} except AssertionError as message: return jsonify({"error": str(message)}), 400
def __init__(self, festival, year, bands): self.festival = festival self.year = year self.bands = bands self.playlist_storage = Playlist(name=self.festival, year=int(year), bands=", ".join(self.bands)) db.session.add(self.playlist_storage) for band in self.bands: self.process_band(band, year) db.session.commit()
def create_playlist(): form = PlaylistForm() # if form was submitted and contained no errors if form.validate_on_submit(): new_playlist = Playlist(name=form.name.data, songs_in_playlist=form.songs_in_playlist.data) db.session.add(new_playlist) db.session.commit() flash('New playlist was created successfully.') return redirect(url_for('main.homepage', playlist_id=new_playlist.id)) return render_template('create_playlist.html', form=form)
def test_get_playlists(self): ''' Test case to check if all playlists are returned by the get_playlists function ''' self.new_playlist.save_playlist() test_playlist = Playlist(name="The Production List") test_playlist.save_playlist() gotten_playlists = Playlist.get_playlists() self.assertTrue(len(gotten_playlists) == len(Playlist.query.all()))
def get(self): global threads global threadid parser = reqparse.RequestParser() parser.add_argument('spotifyid', type=str, required=True, help='spotify playlist URI') parser.add_argument('name', type=str, required=True, help='name for playlist') parser.add_argument('auth', type=str, required=True, help='auth token defined in ..env') args = parser.parse_args() args['spotifyid'] = args['spotifyid'].split(':')[-1] if args['auth'] != Config.PLAYLIST_API_SECRET: return {"message": "unauthorized"}, 401 # create and populate the metadata of the new playlist playlist_object = Playlist() playlist_object.name = args['name'] playlist_object.thumbnail = "/resource/placeholder.png" playlist_object.spotifyid = args['spotifyid'] db.session.add(playlist_object) db.session.commit() # create the thread to populate it threadid += 1 thread = GetSpotifyPlaylistWithITunesThread(playlist_object.id, args['spotifyid'], threadid, name="Playlist-thread-%i" % threadid) # add new thread to queue and start it if no threads running threads.append(thread) if not thread_running: threads.pop().start() return { 'threadid': threadid, 'queue_length': len(threads), 'started': True } return { 'threadid': threadid, 'queue_length': len(threads), 'started': False }
def test_delete_playlist(self): ''' Test case to check if test_playlist is deleted from the database ''' self.new_playlist.save_playlist() test_playlist = Playlist(name="The Bose List") test_playlist.save_playlist() test_playlist.delete_playlist(test_playlist.id) gotten_playlists = Playlist.get_playlists() self.assertTrue(len(gotten_playlists) == len(Playlist.query.all()))
def player(): video_id = request.args.get('id', None) vid_title = request.args.get('title', None) if not video_id: return "Peak", 500 url = request.args.get('url', None) results = search_results(vid_title, video_id, url) form = MakePlaylistForm() if form.validate_on_submit(): s = Song(title=vid_title, youtube_id=video_id) p = Playlist(name=form.playlist_name.data) p.songs.append(s) current_user.playlists.append(p) db.session.add(s) db.session.add(p) db.session.commit() return redirect(url_for('main.index')) return render_template("song_player.html", results=results, form=form)
def newPlaylist(request): if request.method == 'POST': response = json.loads(request.body) if 'NAME' in response: playlist = Playlist() playlist.name = strip_tags(response['NAME']) playlist.user = request.user playlist.save() data = { 'PLAYLIST_ID': playlist.id, 'NAME': playlist.name, } data = {**data, **errorCheckMessage(True, None)} else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def addToPlaylist(): data = request.json playlist = Playlist( name=data['name'], song_id=data['songId'], user_id=data['userId'], ) db.session.add(playlist) db.session.commit() playlists = Playlist.query.filter_by(user_id=data['userId']).all() playlistList = [] for playlist in playlists: playlist_id = playlist.id playlist_dict = playlist.to_dict() # playlist_dict['playlist_id'] = playlist_id playlistList.append(playlist_dict) return jsonify(playlistList)
def newLibrary(request): if request.method == 'POST': user = request.user if checkPermission(["LIBR"], user): response = json.loads(request.body) if 'URL' in response and 'NAME' in response: dirPath = response['URL'] if os.path.isdir(dirPath): # Removing / at the end of the dir path if present if dirPath.endswith("/"): dirPath = dirPath[:-1] library = Library() library.path = dirPath playlist = Playlist() playlist.user = user playlist.isLibrary = True playlist.name = strip_tags(response['NAME']) playlist.save() library.playlist = playlist library.save() data = { 'INFO': { 'ID': library.id, 'NAME': library.playlist.name, 'DESCRIPTION': library.playlist.description, 'IS_PUBLIC': library.playlist.isPublic, 'IS_LIBRARY': library.playlist.isLibrary, 'TOTAL_TRACK': "TO BE IMPLEMENTED", 'TOTAL_DURATION': "TO BE IMPLEMENTED", 'AVERAGE_BITRATE': "TO BE IMPLEMENTED", 'OWNER': library.playlist.user.username } } data = {**data, **errorCheckMessage(True, None, newLibrary)} else: data = errorCheckMessage(False, ErrorEnum.DIR_NOT_FOUND, newLibrary) else: data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, newLibrary, user) else: data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, newLibrary, user) else: data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, newLibrary) return JsonResponse(data)
def addPlaylist(): data = request.json # form = PlaylistForm() # form['csrf_token'].data = request.cookies['csrf_token'] playlist = Playlist( name=data['name'], user_id=data['userId'], song_id=None, ) db.session.add(playlist) db.session.commit() playlists = Playlist.query.filter_by(user_id=data['userId']).all() playlistList = [] for playlist in playlists: playlist_id = playlist.id playlist_dict = playlist.to_dict() # playlist_dict['playlist_id'] = playlist_id playlistList.append(playlist_dict) return jsonify(playlistList)
def new_playlist(): form = MakePlaylistForm() video_id = request.args.get('id', None) vid_title = request.args.get('title', None) url = request.args.get('url', None) print('res', video_id, vid_title, url) if form.validate_on_submit(): s = Song(title=vid_title, youtube_id=video_id) p = Playlist(name=form.playlist_name.data) p.songs.append(s) current_user.playlists.append(p) db.session.add(s) db.session.add(p) db.session.commit() return redirect(url_for('main.index')) return render_template("new_playlist.html", form=form, video_id=video_id, vid_title=vid_title, url=url)
def initialScan(request): print("Asked for initial scan") if request.method == 'POST': response = json.loads(request.body) if 'LIBRARY_ID' in response: library = Library.objects.get(id=response['LIBRARY_ID']) if os.path.isdir(library.path): playlist = Playlist() playlist.name = library.name playlist.user = request.user playlist.isLibrary = True playlist.save() data = scanLibrary(library, playlist, library.convertID3) else: data = errorCheckMessage(False, "dirNotFound") else: data = errorCheckMessage(False, "badFormat") else: data = errorCheckMessage(False, "badRequest") return JsonResponse(data)
def get_all_playlists(): auth_header = _auth_header(_get_access_token()) payload = {'limit': '50', 'offset': 0} response = requests.get("https://api.spotify.com/v1/me/playlists", headers=auth_header, params=payload) playlists_info = response.json() has_next = True playlists_in_db = Playlist.query.filter_by(user_id=g.current_user.id).all() for playlist in playlists_in_db: playlist.deleted = True while has_next: for item in playlists_info['items']: playlist_id = item['id'] playlist_name = item['name'] current_playlist = Playlist.query.filter_by( user_id=g.current_user.id, playlist_id=playlist_id).first() if current_playlist is None: new_playlist = Playlist(playlist_id=playlist_id, name=playlist_name, user_id=g.current_user.id, deleted=False) db.session.add(new_playlist) else: current_playlist.name = playlist_name current_playlist.deleted = False if playlists_info['next'] is not None: response = requests.get(playlists_info['next'], headers=auth_header) playlists_info = response.json() else: has_next = False db.session.commit() for playlist in playlists_in_db: if playlist.deleted is True: db.session.delete(playlist) db.session.commit()
def newPlaylist(request): if request.method == 'POST': response = json.loads(request.body) user = request.user if checkPermission(["PLST"], user): if 'PLAYLIST_NAME' in response: playlist = Playlist() playlist.name = strip_tags(response['PLAYLIST_NAME']) playlist.user = request.user playlist.save() data = { 'PLAYLIST_ID': playlist.id, 'PLAYLIST_NAME': playlist.name, } data = {**data, **errorCheckMessage(True, None, newPlaylist)} else: data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, newPlaylist, user) else: data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, newPlaylist, user) else: data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, newPlaylist) return JsonResponse(data)
def setUp(self): ''' Set up method that will run before every Test ''' self.new_playlist = Playlist(name='The Banana List')
def get_playlist(): with app.app_context(): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', } url = 'https://www.kuwo.cn/api/pc/classify/playlist/getRcmPlayList' order = random.choice(['hot', 'new']) params = { 'pn': 1, 'rn': 10, 'order': order, # new/hot 最新/最热 'httpsStatus': 1, } res = requests.get(url=url, headers=headers, params=params) if res.status_code == 200: page_text = res.json() playlist_ids = jsonpath(page_text, '$..id') for i in playlist_ids: pid = i detail_url = 'https://www.kuwo.cn/playlist_detail/' + i res = requests.get(url=detail_url, headers=headers) if res.status_code == 200: detail_page = res.text tree = etree.HTML(detail_page) title = tree.xpath( '//*[@id="__layout"]/div/div[2]/div/div[1]/div[2]/div[1]/p[1]/text()' )[0] info = tree.xpath( '//*[@id="__layout"]/div/div[2]/div/div[1]/div[1]/p[2]/text()' )[0] # print(title, info) slist = tree.xpath( '//*[@id="__layout"]/div/div[2]/div/div[1]/div[2]/div[1]/div[2]/div[1]/ul/li' ) # cover = tree.xpath('//*[@id="__layout"]/div/div[2]/div/div[1]/div[1]/div[1]/img/@src')[0] #无效图片 script = re.findall('data:(\[.*?\]),fetch:', detail_page)[0] rids = re.findall(r'rid:(\d+)', script) cover = re.search('img700.*?"(.*?)",', detail_page).group( 1).encode('utf-8').decode("unicode_escape") song_num = len(rids) try: playlist = Playlist( name=title, info=info, pid=pid, cover=cover, ) # playlist = Playlist.query.filter_by(pid=pid).first() # playlist.cover = cover db.session.add(playlist) db.session.commit() print(title, '歌单添加成功') except Exception as e: # print(e) print(title, '添加失败') db.session.rollback() else: for i in range(song_num): rid = rids[i] name = slist[i].xpath('./div[2]/a/text()')[0] artist = slist[i].xpath('./div[3]//text()')[0] timelength = slist[i].xpath('./div[5]//text()')[0] # print(name, artist, timelength, rid) try: music = Music( name=name, artist=artist, time_length=timelength, rid=rid, playlist=Playlist.query.filter_by( pid=pid).first()) db.session.add(music) db.session.commit() print(name, '添加成功') except Exception as e: # print(e) print(name, '添加歌曲失败') db.session.rollback() else: print('获取歌单详情页失败') time.sleep(3) else: print('获取歌单列表失败')