Пример #1
0
    def test_insert_user_stats_mult_ranges_listening_activity(self):
        """ Test if multiple time range data is inserted correctly """
        with open(self.path_to_data_file(
                'user_listening_activity_db.json')) as f:
            listening_activity_data = json.load(f)
        listening_activity_data_year = deepcopy(listening_activity_data)
        listening_activity_data_year['stats_range'] = 'year'

        db_stats.insert_user_jsonb_data(
            user_id=self.user['id'],
            stats_type='listening_activity',
            stats=StatRange[UserListeningActivityRecord](
                **listening_activity_data))
        db_stats.insert_user_jsonb_data(
            user_id=self.user['id'],
            stats_type='listening_activity',
            stats=StatRange[UserListeningActivityRecord](
                **listening_activity_data_year))

        result = db_stats.get_user_listening_activity(1, 'all_time')
        self.assertDictEqual(
            result.dict(exclude={'user_id', 'last_updated', 'count'}),
            listening_activity_data)

        result = db_stats.get_user_listening_activity(1, 'year')
        self.assertDictEqual(
            result.dict(exclude={'user_id', 'last_updated', 'count'}),
            listening_activity_data_year)
Пример #2
0
    def test_insert_user_stats_mult_ranges_listening_activity(self):
        """ Test if multiple time range data is inserted correctly """
        with open(self.path_to_data_file('user_listening_activity_db.json')) as f:
            listening_activity_data = json.load(f)

        db_stats.insert_user_listening_activity(
            user_id=self.user['id'], listening_activity=UserListeningActivityStatJson(**{'year': listening_activity_data}))
        db_stats.insert_user_listening_activity(
            self.user['id'], UserListeningActivityStatJson(**{'all_time': listening_activity_data}))

        result = db_stats.get_user_listening_activity(1, 'all_time')
        self.assertDictEqual(result.all_time.dict(), listening_activity_data)

        result = db_stats.get_user_listening_activity(1, 'year')
        self.assertDictEqual(result.year.dict(), listening_activity_data)
Пример #3
0
 def test_get_user_listening_activity(self):
     data_inserted = self.insert_test_data()
     result = db_stats.get_user_listening_activity(self.user['id'],
                                                   'all_time')
     self.assertDictEqual(
         result.dict(exclude={'user_id', 'last_updated', 'count'}),
         data_inserted['user_listening_activity'])
Пример #4
0
def get_listening_activity(user_name: str):
    """
    Get the listening activity for user ``user_name``. The listening activity shows the number of listens
    the user has submitted over a period of time.

    A sample response from the endpoint may look like::

        {
            "payload": {
                "from_ts": 1587945600,
                "last_updated": 1592807084,
                "listening_activity": [
                    {
                        "from_ts": 1587945600,
                        "listen_count": 26,
                        "time_range": "Monday 27 April 2020",
                        "to_ts": 1588031999
                    },
                    {
                        "from_ts": 1588032000,
                        "listen_count": 57,
                        "time_range": "Tuesday 28 April 2020",
                        "to_ts": 1588118399
                    },
                    {
                        "from_ts": 1588118400,
                        "listen_count": 33,
                        "time_range": "Wednesday 29 April 2020",
                        "to_ts": 1588204799
                    },
                "to_ts": 1589155200,
                "user_id": "ishaanshah"
            }
        }
    .. note::
        - This endpoint is currently in beta
        - The example above shows the data for three days only, however we calculate the statistics for
          the current time range and the previous time range. For example for weekly statistics the data
          is calculated for the current as well as the past week.
        - For ``all_time`` listening activity statistics we only return the years which have more than
          zero listens.

    :param range: Optional, time interval for which statistics should be returned, possible values are ``week``,
        ``month``, ``year``, ``all_time``, defaults to ``all_time``
    :type range: ``str``
    :statuscode 200: Successful query, you have data!
    :statuscode 204: Statistics for the user haven't been calculated, empty response will be returned
    :statuscode 400: Bad request, check ``response['error']`` for more details
    :statuscode 404: User not found
    :resheader Content-Type: *application/json*

    """
    user = db_user.get_by_mb_id(user_name)
    if user is None:
        raise APINotFound("Cannot find user: {}".format(user_name))

    stats_range = request.args.get('range', default='all_time')
    if not _is_valid_range(stats_range):
        raise APIBadRequest("Invalid range: {}".format(stats_range))

    stats = db_stats.get_user_listening_activity(user['id'], stats_range)
    if stats is None or getattr(stats, stats_range) is None:
        raise APINoContent('')

    listening_activity = [
        x.dict() for x in getattr(stats, stats_range).listening_activity
    ]
    return jsonify({
        "payload": {
            "user_id": user_name,
            "listening_activity": listening_activity,
            "from_ts": int(getattr(stats, stats_range).from_ts),
            "to_ts": int(getattr(stats, stats_range).to_ts),
            "range": stats_range,
            "last_updated": int(stats.last_updated.timestamp())
        }
    })
Пример #5
0
def get_listening_activity(user_name: str):
    """
    Get the listening activity for user ``user_name``. The listening activity shows the number of listens
    the user has submitted over a period of time.

    A sample response from the endpoint may look like:

    .. code-block:: json

        {
            "payload": {
                "from_ts": 1587945600,
                "last_updated": 1592807084,
                "listening_activity": [
                    {
                        "from_ts": 1587945600,
                        "listen_count": 26,
                        "time_range": "Monday 27 April 2020",
                        "to_ts": 1588031999
                    },
                    {
                        "from_ts": 1588032000,
                        "listen_count": 57,
                        "time_range": "Tuesday 28 April 2020",
                        "to_ts": 1588118399
                    },
                    {
                        "from_ts": 1588118400,
                        "listen_count": 33,
                        "time_range": "Wednesday 29 April 2020",
                        "to_ts": 1588204799
                    },
                "to_ts": 1589155200,
                "user_id": "ishaanshah"
            }
        }

    .. note::
        - This endpoint is currently in beta
        - The example above shows the data for three days only, however we calculate the statistics for
          the current time range and the previous time range. For example for weekly statistics the data
          is calculated for the current as well as the past week.
        - For ``all_time`` listening activity statistics we only return the years which have more than
          zero listens.

    :param range: Optional, time interval for which statistics should be returned, possible values are
        :data:`~data.model.common_stat.ALLOWED_STATISTICS_RANGE`, defaults to ``all_time``
    :type range: ``str``
    :statuscode 200: Successful query, you have data!
    :statuscode 204: Statistics for the user haven't been calculated, empty response will be returned
    :statuscode 400: Bad request, check ``response['error']`` for more details
    :statuscode 404: User not found
    :resheader Content-Type: *application/json*

    """
    user, stats_range = _validate_stats_user_params(user_name)

    stats = db_stats.get_user_listening_activity(user['id'], stats_range)
    if stats is None:
        raise APINoContent('')

    listening_activity = [x.dict() for x in stats.data.__root__]
    return jsonify({
        "payload": {
            "user_id": user_name,
            "listening_activity": listening_activity,
            "from_ts": stats.from_ts,
            "to_ts": stats.to_ts,
            "range": stats_range,
            "last_updated": int(stats.last_updated.timestamp())
        }
    })
Пример #6
0
 def test_get_user_listening_activity(self):
     data_inserted = self.insert_test_data()
     result = db_stats.get_user_listening_activity(self.user['id'], 'all_time')
     self.assertDictEqual(result.all_time.dict(), data_inserted['user_listening_activity'])
Пример #7
0
    def test_handle_user_listening_activity(self):
        data = {
            'type':
            'listening_activity',
            'stats_range':
            'all_time',
            'from_ts':
            1,
            'to_ts':
            10,
            'data': [{
                'user_id':
                1,
                'data': [
                    {
                        'from_ts': 1,
                        'to_ts': 5,
                        'time_range': '2020',
                        'listen_count': 200,
                    },
                    {
                        'from_ts': 6,
                        'to_ts': 10,
                        'time_range': '2021',
                        'listen_count': 150,
                    },
                ]
            }, {
                'user_id':
                2,
                'data': [{
                    'from_ts': 2,
                    'to_ts': 7,
                    'time_range': '2020',
                    'listen_count': 20,
                }]
            }]
        }

        handle_user_listening_activity(data)

        received = db_stats.get_user_listening_activity(1, 'all_time')
        self.assertEqual(
            received, StatApi[ListeningActivityRecord](
                user_id=1,
                to_ts=10,
                from_ts=1,
                stats_range='all_time',
                data=StatRecordList[ListeningActivityRecord](__root__=[
                    ListeningActivityRecord(
                        from_ts=1,
                        to_ts=5,
                        time_range='2020',
                        listen_count=200,
                    ),
                    ListeningActivityRecord(
                        from_ts=6,
                        to_ts=10,
                        time_range='2021',
                        listen_count=150,
                    ),
                ]),
                last_updated=received.last_updated))

        received = db_stats.get_user_listening_activity(2, 'all_time')
        self.assertEqual(
            received, StatApi[ListeningActivityRecord](
                user_id=2,
                to_ts=10,
                from_ts=1,
                stats_range='all_time',
                data=StatRecordList[ListeningActivityRecord](__root__=[
                    ListeningActivityRecord(
                        from_ts=2,
                        to_ts=7,
                        time_range='2020',
                        listen_count=20,
                    )
                ]),
                last_updated=received.last_updated))