Skip to content

Commit

Permalink
Add persistency to playlog.
Browse files Browse the repository at this point in the history
Refs #333.
  • Loading branch information
smimram committed May 25, 2021
1 parent 83ef619 commit a2d764c
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion libs/utils.liq
Expand Up @@ -48,22 +48,37 @@ end
# was last played and avoid repetitions.
# @param ~duration Duration (in seconds) after which songs are forgotten. By default, songs are not forgotten which means that the playlog will contain all the songs ever played.
# @param ~hash Function to extract an identifier from the metadata. By default, the filename is used but we could return the artist to know when a song from a given artist was last played for instance.
# @param ~persistency Set a file name where the values are stored and loaded in case the script is restarted.
# @category Source / Track Processing
# @method add Record that file with given metadata has been played.
# @method last How long ago a file was played (in seconds), `infinity` is returned if the song has never been played.
def playlog(~duration=infinity, ~hash=fun(m)->m["filename"])
def playlog(~duration=infinity, ~persistency=null(), ~hash=fun(m)->m["filename"])
l = ref([])
# Load from persistency file
if null.defined(persistency) then
l := of_json(default=[("", 0.)], file.contents(null.get(persistency)))
end
# Save into persistency file
def save()
if null.defined(persistency) then
file.write(data=json_of(!l), null.get(persistency))
end
end
# Remove too old elements
def prune()
if duration != infinity then
t = time()
l := list.assoc.filter(fun(f, tf) -> t - tf <= duration, !l)
end
end
# Add a new entry
def add(m)
prune()
f = hash(m)
l := list.add((f, time()), !l)
save()
end
# Last time this entry was played
def last(m)
f = hash(m)
time() - list.assoc(default = 0.-infinity, f, !l)
Expand Down

0 comments on commit a2d764c

Please sign in to comment.