chiark / gitweb /
f22bf6fa1878a6583702d2f798c4f24c96f83b36
[disorder] / server / choose.c
1 /*
2  * This file is part of DisOrder 
3  * Copyright (C) 2008 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file choose.c
21  * @brief Random track chooser
22  *
23  * Picks a track at random and writes it to standard output.  If for
24  * any reason no track can be picked - even a trivial reason like a
25  * deadlock - it just exits and expects the server to try again.
26  */
27
28 #include <config.h>
29 #include "types.h"
30
31 #include <getopt.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <db.h>
35 #include <locale.h>
36 #include <errno.h>
37 #include <sys/types.h>
38 #include <unistd.h>
39 #include <pcre.h>
40 #include <string.h>
41 #include <fcntl.h>
42 #include <syslog.h>
43 #include <time.h>
44
45 #include "configuration.h"
46 #include "log.h"
47 #include "defs.h"
48 #include "mem.h"
49 #include "kvp.h"
50 #include "syscalls.h"
51 #include "printf.h"
52 #include "trackdb.h"
53 #include "trackdb-int.h"
54 #include "version.h"
55 #include "trackname.h"
56
57 static DB_TXN *global_tid;
58
59 static const struct option options[] = {
60   { "help", no_argument, 0, 'h' },
61   { "version", no_argument, 0, 'V' },
62   { "config", required_argument, 0, 'c' },
63   { "debug", no_argument, 0, 'd' },
64   { "no-debug", no_argument, 0, 'D' },
65   { "syslog", no_argument, 0, 's' },
66   { "no-syslog", no_argument, 0, 'S' },
67   { 0, 0, 0, 0 }
68 };
69
70 /* display usage message and terminate */
71 static void help(void) {
72   xprintf("Usage:\n"
73           "  disorder-choose [OPTIONS]\n"
74           "Options:\n"
75           "  --help, -h              Display usage message\n"
76           "  --version, -V           Display version number\n"
77           "  --config PATH, -c PATH  Set configuration file\n"
78           "  --debug, -d             Turn on debugging\n"
79           "  --[no-]syslog           Enable/disable logging to syslog\n"
80           "\n"
81           "Track choose for DisOrder.  Not intended to be run\n"
82           "directly.\n");
83   xfclose(stdout);
84   exit(0);
85 }
86
87 /** @brief Weighted track record */
88 struct weighted_track {
89   /** @brief Next track in the list */
90   struct weighted_track *next;
91   /** @brief Track name */
92   const char *track;
93   /** @brief Weight for this track (always positive) */
94   unsigned long weight;
95 };
96
97 /** @brief List of tracks with nonzero weight */
98 static struct weighted_track *tracks;
99
100 /** @brief Sum of all weights */
101 static unsigned long long total_weight;
102
103 /** @brief Count of tracks */
104 static long ntracks;
105
106 static char **required_tags;
107 static char **prohibited_tags;
108
109 /** @brief Compute the weight of a track
110  * @param track Track name (UTF-8)
111  * @param data Track data
112  * @param prefs Track preferences
113  * @return Track weight (non-negative)
114  *
115  * Tracks to be excluded entirely are given a weight of 0.
116  */
117 static unsigned long compute_weight(const char *track,
118                                     struct kvp *data,
119                                     struct kvp *prefs) {
120   const char *s;
121   char **track_tags;
122   time_t last, now;
123
124   /* Reject tracks not in any collection (race between edit config and
125    * rescan) */
126   if(!find_track_root(track)) {
127     info("found track not in any collection: %s", track);
128     return 0;
129   }
130
131   /* Reject aliases to avoid giving aliased tracks extra weight */
132   if(kvp_get(data, "_alias_for"))
133     return 0;
134   
135   /* Reject tracks with random play disabled */
136   if((s = kvp_get(prefs, "pick_at_random"))
137      && !strcmp(s, "0"))
138     return 0;
139
140   /* Reject tracks played within the last 8 hours */
141   if((s = kvp_get(prefs, "played_time"))) {
142     last = atoll(s);
143     now = time(0);
144     if(now < last + 8 * 3600)       /* TODO configurable */
145       return 0;
146   }
147
148   /* We'll need tags for a number of things */
149   track_tags = parsetags(kvp_get(prefs, "tags"));
150
151   /* Reject tracks with prohibited tags */
152   if(prohibited_tags && tag_intersection(track_tags, prohibited_tags))
153     return 0;
154
155   /* Reject tracks that lack required tags */
156   if(*required_tags && !tag_intersection(track_tags, required_tags))
157     return 0;
158
159   return 90000;
160 }
161
162 /** @brief Called for each track */
163 static int collect_tracks_callback(const char *track,
164                                    struct kvp *data,
165                                    struct kvp *prefs,
166                                    void attribute((unused)) *u,
167                                    DB_TXN attribute((unused)) *tid) {
168   const unsigned long weight = compute_weight(track, data, prefs);
169
170   if(weight) {
171     struct weighted_track *const t = xmalloc(sizeof *t);
172
173     t->next = tracks;
174     t->track = track;
175     t->weight = weight;
176     tracks = t;
177     total_weight += weight;
178     ++ntracks;
179   }
180   return 0;
181 }
182
183 /** @brief Pick a random integer uniformly from [0, limit) */
184 static unsigned long long pick_weight(unsigned long long limit) {
185   unsigned long long n;
186   static int fd = -1;
187   int r;
188
189   if(fd < 0) {
190     if((fd = open("/dev/urandom", O_RDONLY)) < 0)
191       fatal(errno, "opening /dev/urandom");
192   }
193   if((r = read(fd, &n, sizeof n)) < 0)
194     fatal(errno, "reading /dev/urandom");
195   if((size_t)r < sizeof n)
196     fatal(0, "short read from /dev/urandom");
197   return n % limit;
198 }
199
200 /** @brief Pick a track at random and write it to stdout */
201 static void pick_track(void) {
202   long long w;
203   struct weighted_track *t;
204
205   w = pick_weight(total_weight);
206   t = tracks;
207   while(t && w >= t->weight) {
208     w -= t->weight;
209     t = t->next;
210   }
211   if(!t)
212     fatal(0, "ran out of tracks but %lld weighting left", w);
213   xprintf("%s", t->track);
214 }
215
216 int main(int argc, char **argv) {
217   int n, logsyslog = !isatty(2), err;
218   const char *tags;
219   
220   set_progname(argv);
221   mem_init();
222   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
223   while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
224     switch(n) {
225     case 'h': help();
226     case 'V': version("disorder-choose");
227     case 'c': configfile = optarg; break;
228     case 'd': debugging = 1; break;
229     case 'D': debugging = 0; break;
230     case 'S': logsyslog = 0; break;
231     case 's': logsyslog = 1; break;
232     default: fatal(0, "invalid option");
233     }
234   }
235   if(logsyslog) {
236     openlog(progname, LOG_PID, LOG_DAEMON);
237     log_default = &log_syslog;
238   }
239   if(config_read(0)) fatal(0, "cannot read configuration");
240   /* Generate the candidate track list */
241   trackdb_init(TRACKDB_NO_RECOVER);
242   trackdb_open(TRACKDB_NO_UPGRADE|TRACKDB_READ_ONLY);
243   global_tid = trackdb_begin_transaction();
244   if((err = trackdb_get_global_tid("required-tags", global_tid, &tags)))
245     fatal(0, "error getting required-tags: %s", db_strerror(err));
246   required_tags = parsetags(tags);
247   if((err = trackdb_get_global_tid("prohibited-tags", global_tid, &tags)))
248     fatal(0, "error getting prohibited-tags: %s", db_strerror(err));
249   prohibited_tags = parsetags(tags);
250   if(trackdb_scan(0, collect_tracks_callback, 0, global_tid))
251     exit(1);
252   trackdb_commit_transaction(global_tid);
253   trackdb_close();
254   trackdb_deinit();
255   //info("ntracks=%ld total_weight=%lld", ntracks, total_weight);
256   if(!total_weight)
257     fatal(0, "no tracks match random choice criteria");
258   /* Pick a track */
259   pick_track();
260   xfclose(stdout);
261   return 0;
262 }
263
264 /*
265 Local Variables:
266 c-basic-offset:2
267 comment-column:40
268 fill-column:79
269 indent-tabs-mode:nil
270 End:
271 */