diff --git a/server/djrandom/frontend/api_views.py b/server/djrandom/frontend/api_views.py index 8cae5d75bf0a8bae791bc125d7dfb041695e057b..fb02dc30b896ecea910c0edab8f7435d690a1d64 100644 --- a/server/djrandom/frontend/api_views.py +++ b/server/djrandom/frontend/api_views.py @@ -156,6 +156,14 @@ def most_played_json(): return jsonify(results=most_played) +@app.route('/json/never_played', methods=['GET']) +@require_auth +def never_played_json(): + n = int(request.args.get('n', 20)) + never_played = MP3.never_played(n) + return jsonify(results=never_played) + + @app.route('/json/last_uploaded', methods=['GET']) @require_auth def last_uploaded_json(): diff --git a/server/djrandom/model/mp3.py b/server/djrandom/model/mp3.py index 10bdfc819b2a80119fe6a9dd332a02216c9d757d..0504ec44ddec57cb1a0f3d81438e5f68040736e9 100644 --- a/server/djrandom/model/mp3.py +++ b/server/djrandom/model/mp3.py @@ -54,13 +54,16 @@ class MP3(Base): desc(cls.uploaded_at)).limit(n) @classmethod - def get_random_songs(cls, n=10): + def get_random_songs(cls, n=10, where_clause=None): """Return N completely random songs.""" results = [] - num_songs = cls.query.filter_by(state=cls.READY).count() + if where_clause is None: + where_clause = (cls.state == cls.READY) + num_songs = cls.query.filter(where_clause).count() fraction = float(n) / num_songs + where_clause = where_clause & (func.rand() < fraction) while len(results) < n: - tmprows = Session.query(cls.sha1).filter(func.rand() < fraction).limit(n) + tmprows = Session.query(cls.sha1).filter(where_clause).limit(n) for row in tmprows: results.append(row[0]) return results @@ -70,6 +73,11 @@ class MP3(Base): return cls.query.filter_by( state=cls.READY, artist=artist, album=album) + @classmethod + def never_played(cls, n=10): + """Return N random songs that were never played.""" + return cls.get_random_songs(n, where_clause=(cls.play_count == 0)) + class PlayLog(Base):