Пример #1
0
    def get(self, pk_or_uri):
        """ Returns a single track object by primary key, if the track does
        not exist a 404 will be returned.

        Arguments
        ---------
        pk : str
            The track primary key
        """

        try:
            uuid.UUID(pk_or_uri, version=4)
        except ValueError:
            field = Track.spotify_uri
        else:
            field = Track.id

        track = Track.query.filter(field == pk_or_uri).first()
        if track is None:
            return http.NotFound()

        data = TrackSerializer().serialize(track)
        data['audio_summary'] = track.audio_summary

        return http.OK(data)
Пример #2
0
    def get(self, *args, **kwargs):
        """ Returns a paginated list of tracks currently in the playlist.
        """

        offset = kwargs.pop('offset')
        limit = kwargs.pop('limit')

        queue = redis.lrange(config.PLAYLIST_REDIS_KEY, offset,
                             (offset + limit - 1))
        total = redis.llen(config.PLAYLIST_REDIS_KEY)

        response = []

        if total > 0:
            for item in queue:
                item = json.loads(item)
                track = Track.query.filter(
                    Track.spotify_uri == item['uri']).first()
                user = User.query.filter(User.id == item['user']).first()
                if track is not None and user is not None:
                    response.append({
                        'track': TrackSerializer().serialize(track),
                        'user': UserSerializer().serialize(user),
                        'uuid': item.get('uuid', None),
                    })

        return http.OK(response,
                       page=kwargs.get('page'),
                       total=total,
                       limit=limit)
Пример #3
0
    def get(self):
        """ Returns the currently playing track.

        Returns
        -------
        http.Response
            A http response instance, 204 or 200
        """

        track, user = self.get_current_track()
        if track is None or user is None:
            return http.NoContent()

        # Get Pause State
        try:
            paused = int(redis.get('fm:player:paused'))
        except (ValueError, TypeError):
            paused = 0

        elapsed = self.elapsed(paused=bool(paused))

        headers = {'Paused': paused}
        response = {
            'track': TrackSerializer().serialize(track),
            'user': UserSerializer().serialize(user),
            'player': {
                'elapsed_time': elapsed,  # ms
                'elapsed_percentage': (elapsed / track.duration) * 100,  # %
                'elapsed_seconds': elapsed / 1000  # seconds
            }
        }

        return http.OK(response, headers=headers)
Пример #4
0
    def get(self):
        """
        """

        return http.OK({
            'message': 'Welcome to the thisissoon.fm API',
        })
Пример #5
0
    def delete(self):
        """ Unapuses the player.
        """
        event = {'event': 'resume'}
        redis.publish(config.PLAYER_CHANNEL, json.dumps(event))

        return http.OK(event)
Пример #6
0
    def get(self):
        """ Retrieve the current volume level for the physical player.
        """

        try:
            volume = int(redis.get('fm:player:volume'))
        except (ValueError, TypeError):
            volume = 0

        return http.OK({'volume': volume})
Пример #7
0
    def delete(self):
        """ Set the player mute state to False.
        """

        redis.publish(config.PLAYER_CHANNEL,
                      json.dumps({
                          'event': 'set_mute',
                          'mute': False
                      }))

        return http.OK({'mute': self.is_mute()})
Пример #8
0
    def get(self, *args, **kwargs):
        queue = list(Queue.get_queue())
        tracks = list(Queue.get_tracks())

        return http.OK({
            'total':
            Queue.length(),
            'genres':
            Counter(g.name for g in self.get_list_of_genres(tracks)),
            'users':
            Counter(q['user'] for q in queue),
            'play_time':
            sum(track.duration for track in tracks)
        })
Пример #9
0
    def get(self, *args, **kwargs):
        """ Returns a paginated list of tracks stored in our DB.
        """

        total = Track.query.count()
        rows = Track.query \
            .limit(kwargs.get('limit')) \
            .offset(kwargs.get('offset')) \
            .all()

        return http.OK(TrackSerializer().serialize(rows, many=True),
                       limit=kwargs.get('limit'),
                       page=kwargs.get('page'),
                       total=total)
Пример #10
0
    def get(self, *args, **kwargs):
        """ Returns a paginated play list history.
        """

        total = PlaylistHistory.query.count()

        rows = db.session.query(PlaylistHistory) \
            .order_by(desc(PlaylistHistory.created)) \
            .limit(kwargs.get('limit')) \
            .offset(kwargs.get('offset')) \
            .all()

        return http.OK(HistorySerializer().serialize(rows, many=True),
                       limit=kwargs.get('limit'),
                       page=kwargs.get('page'),
                       total=total)
Пример #11
0
    def get(self, user_pk):
        """ Get user's playlists.
        If user is not authorized its Spotify account view returns HTTP code
        for NO CONTENT
        Arguments
        ---------
        user_pk: str
            The user primary key UUID
        """
        user = User.query.get(user_pk)
        if user.spotify_id is None:
            return http.NoContent('User hasn\'t authorized Spotify account')
        update_spotify_credentials(user)

        spotify_api = SpotifyApi(user)
        return http.OK(PlaylistSerializer().serialize(
            [pl for pl in spotify_api.playlist_iterator()], many=True))
Пример #12
0
    def post(self):
        """ Change the volume level for the player.
        """

        serializer = VolumeSerializer()

        try:
            data = serializer.marshal(request.json)
        except MappingErrors as e:
            return http.UnprocessableEntity(errors=e.message)

        redis.publish(
            config.PLAYER_CHANNEL,
            json.dumps({
                'event': 'set_volume',
                'volume': data['volume']
            }))
        return http.OK(data)
Пример #13
0
    def get(self, pk):
        """ Get a serialized user object.

        Arguments
        ---------
        pk : str
            The user primary key UUID
        """

        try:
            uuid.UUID(pk, version=4)
        except ValueError:
            user = None
        else:
            user = User.query.get(pk)

        if user is None:
            return http.NotFound()

        return http.OK(UserSerializer().serialize(user))
Пример #14
0
    def get(self, id=None):
        """Returns the artist data from spotify
        """

        if id is None:
            return http.NotFound()

        # TODO: exception handling
        token = get_client_credentials()

        r = requests.get(
            'https://api.spotify.com/v1/artists/{0}'.format(id),
            headers={
                "Authorization": "Bearer {0}".format(token),
            })

        if r.status_code != httplib.OK:
            return http.NotFound()

        return http.OK(r.json())
Пример #15
0
    def get(self, user_pk, playlist_pk):
        """ Get user's track in particular playlist.
        If user is not authorized its Spotify account view returns HTTP code
        for NO CONTENT
        Arguments
        ---------
        user_pk: str
            The user primary key UUID
        playlist_pk: str
            The playlist spotify id
        """
        user = User.query.get(user_pk)
        if user.spotify_id is None:
            return http.NoContent('User hasn\'t authorized Spotify account')
        update_spotify_credentials(user)

        spotify_api = SpotifyApi(user)
        return http.OK(TrackSerializer().serialize(
            [pl for pl in spotify_api.get_playlists_tracks(playlist_pk)],
            many=True))
Пример #16
0
    def get(self, id=None):
        """Returns an albums tracks
        """

        if id is None:
            return http.NotFound()

        # TODO: exception handling
        token = get_client_credentials()

        r = requests.get(
            'https://api.spotify.com/v1/albums/{0}/tracks'.format(id),
            headers={
                "Authorization": "Bearer {0}".format(token),
            },
            params=request.args)

        if r.status_code != httplib.OK:
            return http.NotFound()

        return http.OK(r.json())
Пример #17
0
    def get(self, pk):

        try:
            uuid.UUID(pk, version=4)
        except ValueError:
            user = None
        else:
            user = User.query.get(pk)

        if user is None:
            return http.NotFound()

        since = request.args.get('from', None)
        if since:
            since = pytz.utc.localize(datetime.strptime(since, '%Y-%m-%d'))
        until = request.args.get('to', None)
        if until:
            until = pytz.utc.localize(datetime.strptime(until, '%Y-%m-%d'))

        payload = {
            'most_played_tracks': [{
                'track': FMTrackSerializer().serialize(u),
                'total': t
            } for u, t in self.most_played_tracks(pk, since, until)],
            'most_played_artists': [{
                'artist': ArtistSerializer().serialize(u),
                'total': t
            } for u, t in self.most_played_artists(pk, since, until)],
            'most_played_genres': [{
                'name': u.name,
                'total': t
            } for u, t in self.most_played_genres(pk, since, until)],
            'total_plays':
            self.total_plays(pk, since, until),
            'total_play_time':
            self.total_play_time(pk, since, until),
        }

        return http.OK(payload)
Пример #18
0
    def get(self):
        """Implements the search endpoint via the Spotify Web API
        which requires authentication
        """

        # TODO: exception handling
        token = get_client_credentials()

        r = requests.get(
            'https://api.spotify.com/v1/search',
            headers={
                "Authorization": "Bearer {0}".format(token),
            },
            params={
                'q': request.args.get('q'),
                'type': request.args.get('type'),
                'market': request.args.get('market'),
                'limit': request.args.get('limit'),
                'offset': request.args.get('offset'),
            })

        return http.OK(r.json())
Пример #19
0
    def get(self, *args, **kwargs):
        since = request.args.get('from', None)
        if since:
            since = pytz.utc.localize(datetime.strptime(since, '%Y-%m-%d'))
        until = request.args.get('to', None)
        if until:
            until = pytz.utc.localize(datetime.strptime(until, '%Y-%m-%d'))

        payload = {
            'most_active_djs': [{
                'user': UserSerializer().serialize(u),
                'total': t
            } for u, t in stats.most_active_djs(since, until).limit(10)],
            'most_played_tracks': [{
                'track': TrackSerializer().serialize(u),
                'total': t
            } for u, t in stats.most_played_tracks(since, until).limit(10)],
            'most_played_artists': [{
                'artist': ArtistSerializer().serialize(u),
                'total': t
            } for u, t in stats.most_played_artists(since, until).limit(10)],
            'most_played_genres': [{
                'name': u.name,
                'total': t
            } for u, t in stats.most_played_genres(since, until).limit(10)],
            'total_play_time_per_user':
            [{
                'user': UserSerializer().serialize(u),
                'total': t
            }
             for u, t in stats.total_play_time_per_user(since, until).limit(10)
             ],
            'total_play_time':
            stats.total_play_time(since, until).first()[0],
            'total_plays':
            stats.total_plays(since, until).count(),
        }
        return http.OK(payload)
Пример #20
0
    def delete(self):
        """ Skips the currently playing track.

        Returns
        -------
        http.Response
            A http response intance, in this case it should always be a 204
        """

        track, user = self.get_current_track()
        if track is None or user is None:
            return http.NoContent()

        redis.publish(
            config.PLAYER_CHANNEL,
            json.dumps({
                'event': 'stop',
                'user': str(user.id),
                'track': str(track.id),
                'uri': str(track.spotify_uri),
                'by': str(current_user.id),
            }))

        return http.OK()
Пример #21
0
 def get(self):
     """ Returns the current mute state of the player
     """
     return http.OK({'mute': self.is_mute()})
Пример #22
0
    def get(self):
        """ Returns the currently authenticated user
        """

        return http.OK(UserSerializer().serialize(current_user))
Пример #23
0
 def delete(self, uuid):
     try:
         Queue.delete(uuid=uuid)
     except ValueError:
         return http.NoContent()
     return http.OK()