(request: WSGIRequest)
return JsonResponse(response)
Perform an analysis of the database in the given timeframe.
Perform an analysis of the database in the given timeframe.
Perform an analysis of the database in the given timeframe .
def analyse(request: WSGIRequest) -> HttpResponse:
    """Perform an analysis of the database in the given timeframe."""

    try:
        start, end = _parse_datetimes(request)
    except ValueError as e:
        return HttpResponseBadRequest(e.args[0])

    played = PlayLog.objects.all().filter(created__gte=start).filter(created__lt=end)
    if not played.exists():
        return HttpResponseBadRequest("No songs played in the given time span")

    requested = (
        RequestLog.objects.all().filter(created__gte=start).filter(created__lt=end)
    )
    played_count = (
        played.values("song__url", "song__artist", "song__title")
        .values(
            "song__url", "song__artist", "song__title", count=models.Count("song__url")
        )
        .order_by("-count")
    )
    played_votes = (
        PlayLog.objects.all()
        .filter(created__gte=start)
        .filter(created__lt=end)
        .order_by("-votes")
    )
    devices = (
        requested.values("session_key")
        .values("session_key", count=models.Count("session_key"))
        .order_by("-count")
    )

    response = {
        "songsPlayed": len(played),
        "mostPlayedSong": (
            song_utils.displayname(
                played_count[0]["song__artist"], played_count[0]["song__title"]
            )
            + f" ({played_count[0]['count']})"
        ),
        "highestVotedSong": (
            played_votes[0].song_displayname() + f" ({played_votes[0].votes})"
        ),
        "mostActiveDevice": (devices[0]["session_key"] + f" ({devices[0]['count']})"),
    }
    requested_by_session = requested.filter(session_key=devices[0]["session_key"])
    for i in range(6):
        if i >= len(requested_by_session):
            break
        response["mostActiveDevice"] += "\n"
        if i == 5:
            response["mostActiveDevice"] += "..."
        else:
            response["mostActiveDevice"] += requested_by_session[i].item_displayname()

    binsize = 3600
    number_of_bins = math.ceil((end - start).total_seconds() / binsize)
    request_bins = [0 for _ in range(number_of_bins)]

    for request_log in requested:
        seconds = (request_log.created - start).total_seconds()
        index = int(seconds / binsize)
        request_bins[index] += 1

    current_time = start
    current_index = 0
    response["requestActivity"] = ""
    while current_time < end:
        response["requestActivity"] += current_time.strftime("%H:%M")
        response["requestActivity"] += ":\t" + str(request_bins[current_index])
        response["requestActivity"] += "\n"
        current_time += timedelta(seconds=binsize)
        current_index += 1

    localtz = tz.gettz(conf.TIME_ZONE)
    playlist = ""
    for play_log in played:
        localtime = play_log.created.astimezone(localtz)
        playlist += "[{:02d}:{:02d}] {}\n".format(
            localtime.hour, localtime.minute, play_log.song_displayname()
        )
    response["playlist"] = playlist

    return JsonResponse(response)
def analyse ( request : WSGIRequest ) -> HttpResponse : try : start , end = _parse_datetimes ( request ) except ValueError as e : return HttpResponseBadRequest ( e . args [ 0 ] ) played = PlayLog . objects . all ( ) . filter ( created__gte = start ) . filter ( created__lt = end ) if not played . exists ( ) : return HttpResponseBadRequest ( "No songs played in the given time span" ) requested = ( RequestLog . objects . all ( ) . filter ( created__gte = start ) . filter ( created__lt = end ) ) played_count = ( played . values ( "song__url" , "song__artist" , "song__title" ) . values ( "song__url" , "song__artist" , "song__title" , count = models . Count ( "song__url" ) ) . order_by ( "-count" ) ) played_votes = ( PlayLog . objects . all ( ) . filter ( created__gte = start ) . filter ( created__lt = end ) . order_by ( "-votes" ) ) devices = ( requested . values ( "session_key" ) . values ( "session_key" , count = models . Count ( "session_key" ) ) . order_by ( "-count" ) ) response = { "songsPlayed" : len ( played ) , "mostPlayedSong" : ( song_utils . displayname ( played_count [ 0 ] [ "song__artist" ] , played_count [ 0 ] [ "song__title" ] ) + f" ({played_count[0]['count']})" ) , "highestVotedSong" : ( played_votes [ 0 ] . song_displayname ( ) + f" ({played_votes[0].votes})" ) , "mostActiveDevice" : ( devices [ 0 ] [ "session_key" ] + f" ({devices[0]['count']})" ) , } requested_by_session = requested . filter ( session_key = devices [ 0 ] [ "session_key" ] ) for i in range ( 6 ) : if i >= len ( requested_by_session ) : break response [ "mostActiveDevice" ] += "\n" if i == 5 : response [ "mostActiveDevice" ] += "..." else : response [ "mostActiveDevice" ] += requested_by_session [ i ] . item_displayname ( ) binsize = 3600 number_of_bins = math . ceil ( ( end - start ) . total_seconds ( ) / binsize ) request_bins = [ 0 for _ in range ( number_of_bins ) ] for request_log in requested : seconds = ( request_log . created - start ) . total_seconds ( ) index = int ( seconds / binsize ) request_bins [ index ] += 1 current_time = start current_index = 0 response [ "requestActivity" ] = "" while current_time < end : response [ "requestActivity" ] += current_time . strftime ( "%H:%M" ) response [ "requestActivity" ] += ":\t" + str ( request_bins [ current_index ] ) response [ "requestActivity" ] += "\n" current_time += timedelta ( seconds = binsize ) current_index += 1 localtz = tz . gettz ( conf . TIME_ZONE ) playlist = "" for play_log in played : localtime = play_log . created . astimezone ( localtz ) playlist += "[{:02d}:{:02d}] {}\n" . format ( localtime . hour , localtime . minute , play_log . song_displayname ( ) ) response [ "playlist" ] = playlist return JsonResponse ( response )