Exemplo n.º 1
0
def addbar():
    # TODO: ADD data verification, ensure everything is there...
    request_data = request.args

    line = request_data.get('line')
    artist_name = request_data.get('correct_artist')
    title = request_data.get('song')

    # Create artist if not in the database
    correct_artist = models.Artist.query.filter_by(Name=artist_name).first()
    if(correct_artist == None):
        genius = apimanager.Genius()
        img_url = genius.search(artist_name)[
            'response']['hits'][0]['result']['primary_artist']['image_url']
        correct_artist = models.Artist(Name=artist_name, Image=img_url)
        db.session.add(correct_artist)
        db.session.commit()  # may not be necessary to commit new artist here

    # Create song if not in the database
    s = models.Song.query.filter_by(Name=title).first()
    if(s == None):
        genius = apimanager.Genius()
        img_url = genius.search(title + ", " + correct_artist.Name)[
            'response']['hits'][0]['result']['song_art_image_url']
        s = models.Song(Name=title, artist=correct_artist, Image=img_url)
        db.session.add(s)
        db.session.commit()  # may not be necessary to commit new song here

    db.session.add(models.Bar(Line=line, CorrectArtist=correct_artist.ArtistID, song=s))
    db.session.commit()
    return jsonify({'response': 'Success'})
Exemplo n.º 2
0
    def get_all(self):
        '''
		Spoof a lot of the data on the server
		'''
        if os.environ['SERVER_SOFTWARE'].startswith('Development') == False:
            self.say('This handler can not be accessed')
            return
        remote_url = 'http://pattest.radius-levr.appspot.com/artist/test'
        data = json.loads(urllib2.urlopen(remote_url).read())

        # extract all the genres
        tags = list(set([d['genre'] for d in data]))
        counts = range(1, 101) + [0 for i in range(1, 601)]  #@UnusedVariable

        #		logging.info(data)
        self.say(json.dumps(data))
        return
        artist_futures = []
        for d in data:
            # create random tag counts
            parsed_tags = {tag: random.choice(counts) for tag in tags}
            prepped_tags = self.prep_tags_for_datastore(parsed_tags)
            artist_futures.append(
                models.Artist(username=d['username'],
                              genre=d['genre'],
                              track_id=d['track_id'],
                              tags_=prepped_tags,
                              city=d['city']).put_async())
        for f in artist_futures:
            self.say(f.get_result())
        self.say('Done!')
Exemplo n.º 3
0
def artistss():
    if request.method != 'POST':
        abort(400)
    if not request.is_json:
        abort(400)

    content = request.json
    newName = content.get("name")
    if newName is None:
        abort(400)
    (ret, ), = db_session.query(exists().where(models.Artist.name == newName))
    if (ret == True):
        abort(400)

    newArtist = models.Artist(name=newName)
    db_session.add(newArtist)
    db_session.commit()

    added = db_session.query(models.Artist).order_by(
        models.Artist.artist_id.desc()).first()
    result_dict = []
    result_dict.append(added.__dict__)
    print(result_dict)
    for i in result_dict:
        del i['_sa_instance_state']
        dic = list(i.keys())
        for di in dic:
            i[di] = str(i[di])
    if result_dict[0] is None:
        abort(400)
    return jsonify(result_dict[0])
Exemplo n.º 4
0
def add_artist():
    if request.method == 'POST':
        data = request.get_json()
        try:
            new_name = data['name']
            if not isinstance(new_name, str):
                abort(400)
            if not len(data) == 1:
                abort(400)
        except KeyError:
            abort(400)
        new_artist = models.Artist(name=new_name)
        db_session.add(new_artist)
        db_session.commit()
        serialized = serialize_artist(new_artist)
        return Response(json.dumps(serialized), 200)
Exemplo n.º 5
0
def create_artist_submission():
    form = ArtistForm()

    try:
        name = form.name.data
        genres = form.genres.data
        city = form.city.data
        state = form.state.data
        phone = form.phone.data
        website_link = form.website_link.data
        facebook_link = form.facebook_link.data
        seeking_venue = True if form.seeking_venue.data == 'Yes' else False
        seeking_description = form.seeking_description.data
        image_link = form.image_link.data

        artist = models.Artist(
            name=name,
            genres=genres,
            city=city,
            state=state,
            phone=phone,
            website_link=website_link,
            facebook_link=facebook_link,
            seeking_venue=seeking_venue,
            seeking_description=seeking_description,
            image_link=image_link,
            upcoming_shows_count=0,  # default for new artist
            past_shows_count=0  # default for new artist
        )

        db.session.add(artist)
        db.session.commit()

        flash('Artist ' + name + ' was successfully listed!')
    except:
        flash('An error occurred. Artist ' + form.name.data +
              ' could not be listed.')
        db.session.rollback()
    finally:
        db.session.close()

    return render_template('pages/home.html')
Exemplo n.º 6
0
def create_artist_submission():

    error = False
    try:
        artist = models.Artist(name=request.form['name'],
                               city=request.form['city'],
                               state=request.form['state'],
                               phone=request.form['phone'],
                               genres=request.form['genres'],
                               facebook_link=request.form['facebook_link'])
        db.session.add(artist)
        db.session.commit()
    except:
        error = True
        db.session.rollback()
        print('this is an error')
        print("Oops!", sys.exc_info()[0], "occurred.")

    finally:
        db.session.close()
    if error:
        flash('An error occurred. models.Artist ' + request.form['name'] +
              ' could not be listed.')
        abort(400)
    else:
        flash('models.Artist ' + request.form['name'] +
              ' was successfully listed!')

    # called upon submitting the new artist listing form
    # TODO: insert form data as a new models.Venue record in the db, instead
    # TODO: modify data to be the data object returned from db insertion

    # on successful db insert, flash success
    #flash('models.Artist ' + request.form['name'] + ' was successfully listed!')
    # TODO: on unsuccessful db insert, flash an error instead.
    # e.g., flash('An error occurred. models.Artist ' + data.name + ' could not be listed.')
    return render_template('pages/home.html')
Exemplo n.º 7
0
def post_artists():
    data = request.json
    new_name = data.get("name")
    if new_name is None:
        abort(400)

    try:
        art = models.Artist(name=new_name)
        db_session.add(art)
        db_session.commit()

        artist = db_session.query(models.Artist).filter(
            models.Artist.name == new_name).with_for_update().one()
        result_dict = artist.__dict__
        print(result_dict)

        del result_dict['_sa_instance_state']
        dic = list(result_dict.keys())
        for di in dic:
            result_dict[di] = str(result_dict[di])

        return jsonify(result_dict)
    except:
        abort(400)
Exemplo n.º 8
0
def export_account():
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_path=session_cache_path())
    if not auth_manager.get_cached_token():
        return redirect('/')

    sp = spotipy.Spotify(auth_manager=auth_manager)
    user_id = sp.me()['id']

    ret = {
        'playlists': [],
        'tracks': [],
        'artists': [],
        'user_id': user_id
    }

    # enumerate folled artists
    spotify_artists = sp.current_user_followed_artists()
    for spotify_artist in spotify_artists['artists']['items']:
        ret['artists'].append(models.Artist(spotify_artist).to_map())
    while spotify_artists['artists']['next'] is not None:
        spotify_artists = sp.next(spotify_artists['artists'])
        for spotify_artist in spotify_artists['artists']['items']:
            ret['artists'].append(models.Artist(spotify_artist).to_map())

    # enumerate tracks
    spotify_tracks = sp.current_user_saved_tracks()
    for spotify_track in spotify_tracks['items']:
        ret['tracks'].append(models.Track(spotify_track['track']).to_map())
    while spotify_tracks['next']:
        spotify_tracks = sp.next(spotify_tracks)
        for spotify_track in spotify_tracks['items']:
            ret['tracks'].append(models.Track(spotify_track['track']).to_map())

    # enumerate playlists
    spotify_playlists = sp.current_user_playlists()
    while spotify_playlists is not None:
        for spotify_playlist in spotify_playlists['items']:
            # create the playlist model
            playlist = models.Playlist(user_id, spotify_playlist)

            # we'll just re-follow when it's public and not owned
            if not playlist.owned and playlist.public:
                ret['playlists'].append(playlist.to_map())
                continue

            r = sp.playlist(spotify_playlist['id'], fields="tracks,next")

            spotify_tracks = r['tracks']
            for spotify_track in spotify_tracks['items']:
                playlist.add_track(spotify_track['track'])

            while spotify_tracks['next']:
                spotify_tracks = sp.next(spotify_tracks)
                for spotify_track in spotify_tracks['items']:
                    playlist.add_track(spotify_track['track'])

            ret['playlists'].append(playlist.to_map())

        if spotify_playlists['next']:
            spotify_playlists = sp.next(spotify_playlists)
        else:
            spotify_playlists = None
    return Response(
        json.dumps(ret),
        mimetype="application/json",
        headers={"Content-Disposition": "attachment;filename=account_export.json"}
    )
Exemplo n.º 9
0
 def setUpClass(self):
     self.utils = models.Utils()
     self.artist = models.Artist(
         self.utils.getWebsite(
             "http://www.tekstowo.pl/wykonawca,rick_astley.html"))
Exemplo n.º 10
0
class ConnectAccountHandler(handlers.ArtistHandler):
    def get(self):
        '''Complete oauth handshake with soundcloud
		'''

        logging.debug(self.request.url)
        # 		get the oauth code
        code = self.request.get('code', None)
        if code is None:
            return self.redirect(ARTIST_LOGIN)
        # init the cloudsound client
        client = soundcloud.Client(**sc_creds)
        # exchange the code for an access token
        response = client.exchange_token(code)
        # pull the access token from the response
        access_token = response.access_token

        # get the access token
        # 		access_token = self.request.get("access_token",None)

        logging.debug(access_token)

        # 		if access_token is None:
        # 			return self.redirect(ARTIST_LOGIN)

        # create a new client with the access token
        del client
        client = soundcloud.Client(access_token=access_token)
        current_user = client.get('/me')
        logging.info('city: ' + str(current_user.city))
        # pull the artist_id from the response
        artist_id = str(current_user.id)
        logging.debug(artist_id)
        logging.debug(current_user)

        # check for an existing user
        try:
            # will raise SessionError if artist doesnt exist in db
            artist = self.get_artist_by_id(artist_id)
        except self.SessionError, e:
            # artist does not exist yet. Create one
            # log some mixpanel shiiiiit!
            try:
                properties = {
                    '$username': current_user.username,
                    'city': current_user.city,
                    'country': current_user.country,
                    'signed_up': self.request.get('signed_up', 0),
                    'tracks_added': 0,
                    '$created': str(dt.now())
                }
                # set the first name for display purposes
                properties['$first_name'] = \
                 current_user.full_name or current_user.username
                rpc = mixpanel.track_person(str(current_user.id), properties)

            except Exception, e:
                logging.error(e)
            logging.info('artist does not exist')
            artist = models.Artist(
                id=artist_id,
                access_token=access_token,
                username=current_user.username,
                city=current_user.city,
                #							genre = current_user.genre
            )
            try:
                artist.genre = current_user.genre
            except AttributeError:
                pass
            except Exception, e:
                logging.error(e)
Exemplo n.º 11
0
 def getArtist(self, url):
     page = self._utils.getWebsite(url)
     return models.Artist(page)