Exemplo n.º 1
0
Arquivo: data.py Projeto: tjkemper/jre
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()))
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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')
Exemplo n.º 4
0
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
Exemplo n.º 5
0
    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
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
    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
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
    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
Exemplo n.º 15
0
def playlist(request):
    if request.method == 'GET':
        queryset = Playlist.objects.filter(user=request.user).order_by('-created_at')
        playlist_serializer = PlaylistSerializer(queryset, context={'request': request}, many=True)
        return Response(playlist_serializer.data, status=status.HTTP_200_OK)
    data = request.data
    user = request.user
    playlist_to_save = Playlist()
    playlist_to_save.title = data.get('title')
    playlist_to_save.message = data.get('message')
    playlist_to_save.locked = True if data.get('locked') == 'true' else False
    playlist_to_save.public = True if data.get('public') == 'true' else False
    playlist_to_save.latitude = data.get('latitude')
    playlist_to_save.longitude = data.get('longitude')
    playlist_to_save.user = user
    playlist_to_save.playlist_image = request.FILES.get('image')
    playlist_to_save.playlist_video = request.FILES.get('video')
    playlist_to_save.save()

    songs = data.get('songs', [])
    if type(songs) == type(""):
        songs = json.loads(songs)

    # Save songs
    for song_json in songs:
        images = song_json['album']['images']
        song, _ = Song.objects.get_or_create(
            title=song_json['name'],
            spotify_id=song_json['id'],
            spotify_uri=song_json['uri'],
            track_preview_url=song_json['preview_url'],
            album_artwork=images[0].get('url') if images else '',
            album_title=song_json['album']['name']
        )
        song.save()
        playlist_to_save.songs.add(song)

        for artist_json in song_json['artists']:
            artist, _ = Artist.objects.get_or_create(
                name=artist_json['name'],
                spotify_id=artist_json['id']
            )
            song.artists.add(artist)
    
    profiles = data.get('profiles', [])
    if type(profiles) == type(""):
        profiles = json.loads(profiles)
    
    for profile in profiles:
        share_with_user = get_object_or_404(user_model, username=profile['user']['username'])
        # user_id = profile_json['user']['id']
        playlist_to_save.shared_with_users.add(share_with_user)
    
    # notify_feed_of_playlist(user.userprofile, playlist_to_save)

    return Response(PlaylistSerializer(playlist_to_save,
                                       context={'request': request}).data,
                    status=status.HTTP_201_CREATED)
Exemplo n.º 16
0
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']}")
Exemplo n.º 17
0
    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 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)
Exemplo n.º 19
0
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()
Exemplo n.º 20
0
    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)
Exemplo n.º 21
0
    def test_add_playlist_to_show(self):
        with gillard.app.app_context():
            playlist = Playlist()
            show = Show('TESTID','TESTPW')

            show.playlists = [playlist]

            show = test_utils.save_and_refresh(gillard.db.session, show)

            assert len(show.playlists) == 1

            # cascading add
            assert show.playlists[0].id is not None
Exemplo n.º 22
0
    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
Exemplo n.º 23
0
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 = Playlist(name=form.name.data, description=form.description.data)
        db.session.add(playlist)
        db.session.commit()
        return redirect("/playlists")
    return render_template("new_playlist.html", form=form)
Exemplo n.º 24
0
def add_playlist():
    """Handle add-playlist form."""

    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)
        db.session.commit()
        return redirect("/playlists")

    return render_template("new_playlist.html", form=form)
Exemplo n.º 25
0
def get_all_playlsts(authToken):
    spotify = spotipy.Spotify(auth=authToken)
    letters = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ]
    # countries = ['ec', 'fr','ar','fi','no','it','lt','ph','tw','nz','ee','tr','us','sv','cr','de','cl','jp','br','hn','gt','ch','hu','ca','pe','be','my','dk','bo','pl','at','pt','se','mx','pa','uy','is','es','cz','ie','nl','sk','co','sg','id','do','lu','gb','global','py','au','lv','gr','hk']
    countries = ['hn']
    mind_aspects = ['E', 'I']
    energy_aspects = ['S', 'N']
    nature_aspects = ['T', 'F']
    tactics_aspects = ['J', 'P']
    identity_aspects = ['A', 'T']
    for i in numpy.arange(len(countries)):
        try:
            print("Started with: " + countries[i])
            for letter in numpy.arange(len(letters)):
                pl = spotify.search(letters[letter],
                                    type="playlist",
                                    market=countries[i],
                                    limit=50)
                offset_amount = math.ceil(pl['playlists']['total'] /
                                          pl['playlists']['limit'])
                for offset in numpy.arange(offset_amount):
                    playlists = spotify.search(q=letters[letter],
                                               type="playlist",
                                               market=countries[i],
                                               offset=offset + 1178,
                                               limit=50)['playlists']['items']
                    print(str((offset * 50) + 1069) + "/" + str(offset_amount))
                    for playlist in playlists:
                        if playlist['owner']['id'] != 'spotify':
                            db.session.add(
                                Playlist(playlist_id=playlist['id'],
                                         name=playlist['name'],
                                         owner=playlist['owner']['id']))
                            db.session.add(
                                User(playlist['owner']['id'],
                                     "",
                                     "",
                                     "",
                                     "",
                                     "",
                                     country=countries[i]))
                            db.session.commit()

        except Exception as e:
            print(e)
        print("finished with country: " + countries[i - 1])
Exemplo n.º 26
0
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 = request.form['name']
        description = request.form['description']
        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)
Exemplo n.º 27
0
    def post(self):
        args = playlist_parser.parse_args()

        player = Player.query.filter_by(id=args['player_id']).first()
        if player is None:
            abort(404, "Player %s: not found." % args['player_id'])

        playlist = Playlist(id=player.id)

        db.session.add(playlist)

        player.playlist = playlist

        db.sesson.commit()

        return playlist, 201
Exemplo n.º 28
0
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()
Exemplo n.º 29
0
def initdb_command():
    """Creates the database tables."""
    db.drop_all()
    db.create_all()

    drill1 = Drill(id=1, name="Figure 8", description="Move ball in figure 8 around cones")
    drill2 = Drill(id=2, name="Three Cones", description="Stickhandle ball around triangle of cones")
    drill3 = Drill(id=3, name="Toe Drag", description="Pull ball back with toe of stick")
    drill4 = Drill(id=4, name="Side-to-Side Dribble", description="Stickhandle ball in front of feet")
    drill5 = Drill(id=5, name="Forehand-to-Backhand", description="Stickhandle ball next to body")
    drill6 = Drill(id=6, name="Around the World", description="Stickhandle ball from one side of body to other side")
    drill7 = Drill(id=7, name="Line Drill", description="Stickhandle ball through four cones arranged in a straight line")
    drill8 = Drill(id=8, name="Lucky Clover", description="Stickhandle ball in clover shape around four cones")
    drill9 = Drill(id=9, name="Wide Dribble", description="Stickhandle ball in front of feet using wide motions")

    db.session.add(drill1)
    db.session.add(drill2)
    db.session.add(drill3)
    db.session.add(drill4)
    db.session.add(drill5)
    db.session.add(drill6)
    db.session.add(drill7)
    db.session.add(drill8)
    db.session.add(drill9)

    player = Player(id=1, email="*****@*****.**", password="******", first_name="Katie", last_name="Pucci", hockey_level=5, skill_level=3, hand=True)

    db.session.add(player)

    playlist = Playlist(id=player.id)
    player.playlist = playlist

    db.session.add(playlist)

    player.playlist.drills.append(drill1)
    player.playlist.drills.append(drill2)
    player.playlist.drills.append(drill3)
    player.playlist.drills.append(drill4)
    player.playlist.drills.append(drill5)
    player.playlist.drills.append(drill6)
    player.playlist.drills.append(drill7)
    player.playlist.drills.append(drill8)
    player.playlist.drills.append(drill9)

    db.session.commit()

    print('Initialized the database.')
Exemplo n.º 30
0
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 form.validate_on_submit():
        playlist = Playlist()
        form.populate_obj(playlist)
        db.session.add(playlist)
        db.session.commit()
        return redirect(url_for('show_all_playlists'))

    return render_template("new_playlist.html", form=form)