chiark / gitweb /
correct eclient for new hashes
[disorder] / lib / queue.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2005, 2006 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
21 #include <config.h>
22 #include "types.h"
23
24 #include <string.h>
25 #include <stdio.h>
26 #include <errno.h>
27 #include <stdlib.h>
28 #include <time.h>
29 #include <stddef.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <unistd.h>
33
34 #include "mem.h"
35 #include "queue.h"
36 #include "log.h"
37 #include "configuration.h"
38 #include "split.h"
39 #include "syscalls.h"
40 #include "charset.h"
41 #include "table.h"
42 #include "inputline.h"
43 #include "printf.h"
44 #include "plugin.h"
45 #include "basen.h"
46 #include "eventlog.h"
47 #include "disorder.h"
48
49 const char *playing_states[] = {
50   "failed",
51   "isscratch",
52   "no_player",
53   "ok",
54   "paused",
55   "quitting",
56   "random",
57   "scratched",
58   "started",
59   "unplayed"
60 };
61
62 /* the head of the queue is played next, so normally we add to the tail */
63 struct queue_entry qhead = { &qhead, &qhead, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
64
65 /* the head of the recent list is the oldest thing, the tail the most recently
66  * played */
67 struct queue_entry phead = { &phead, &phead, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
68
69 static long pcount;
70
71 /* add new entry @n@ to a doubly linked list just after @b@ */
72 static void l_add(struct queue_entry *b, struct queue_entry *n) {
73   n->prev = b;
74   n->next = b->next;
75   n->next->prev = n;
76   n->prev->next = n;
77 }
78
79 /* remove an entry from a doubly-linked list */
80 static void l_remove(struct queue_entry *node) {
81   node->next->prev = node->prev;
82   node->prev->next = node->next;
83 }
84
85 #define VALUE(q, offset, type) *(type *)((char *)q + offset)
86
87 static int unmarshall_long(char *data, struct queue_entry *q,
88                            size_t offset,
89                            void (*error_handler)(const char *, void *),
90                            void *u) {
91   if(xstrtol(&VALUE(q, offset, long), data, 0, 0)) {
92     error_handler(strerror(errno), u);
93     return -1;
94   }
95   return 0;
96 }
97
98 static const char *marshall_long(const struct queue_entry *q, size_t offset) {
99   char buffer[256];
100   int n;
101
102   n = byte_snprintf(buffer, sizeof buffer, "%ld", VALUE(q, offset, long));
103   if(n < 0)
104     fatal(errno, "error converting int");
105   else if((size_t)n >= sizeof buffer)
106     fatal(0, "long converted to decimal is too long");
107   return xstrdup(buffer);
108 }
109
110 static int unmarshall_string(char *data, struct queue_entry *q,
111                              size_t offset,
112                              void attribute((unused)) (*error_handler)(const char *, void *),
113                              void attribute((unused)) *u) {
114   VALUE(q, offset, char *) = data;
115   return 0;
116 }
117
118 static const char *marshall_string(const struct queue_entry *q, size_t offset) {
119   return VALUE(q, offset, char *);
120 }
121
122 static int unmarshall_time_t(char *data, struct queue_entry *q,
123                              size_t offset,
124                              void (*error_handler)(const char *, void *),
125                              void *u) {
126   long_long ul;
127
128   if(xstrtoll(&ul, data, 0, 0)) {
129     error_handler(strerror(errno), u);
130     return -1;
131   }
132   VALUE(q, offset, time_t) = ul;
133   return 0;
134 }
135
136 static const char *marshall_time_t(const struct queue_entry *q, size_t offset) {
137   char buffer[256];
138   int n;
139
140   n = byte_snprintf(buffer, sizeof buffer,
141                     "%"PRIdMAX, (intmax_t)VALUE(q, offset, time_t));
142   if(n < 0)
143     fatal(errno, "error converting time");
144   else if((size_t)n >= sizeof buffer)
145     fatal(0, "time converted to decimal is too long");
146   return xstrdup(buffer);
147 }
148
149 static int unmarshall_state(char *data, struct queue_entry *q,
150                             size_t offset,
151                             void (*error_handler)(const char *, void *),
152                             void *u) {
153   int n;
154
155   if((n = table_find(playing_states, 0, sizeof (char *),
156                      sizeof playing_states / sizeof *playing_states,
157                      data)) < 0) {
158     D(("state=[%s] n=%d", data, n));
159     error_handler("invalid state", u);
160     return -1;
161   }
162   VALUE(q, offset, enum playing_state) = n;
163   return 0;
164 }
165
166 static const char *marshall_state(const struct queue_entry *q, size_t offset) {
167   return playing_states[VALUE(q, offset, enum playing_state)];
168 }
169
170 #define F(n, h) { #n, offsetof(struct queue_entry, n), marshall_##h, unmarshall_##h }
171
172 static const struct field {
173   const char *name;
174   size_t offset;
175   const char *(*marshall)(const struct queue_entry *q, size_t offset);
176   int (*unmarshall)(char *data, struct queue_entry *q, size_t offset,
177                     void (*error_handler)(const char *, void *),
178                     void *u);
179 } fields[] = {
180   /* Keep this table sorted. */
181   F(expected, time_t),
182   F(id, string),
183   F(played, time_t),
184   F(scratched, string),
185   F(sofar, long),
186   F(state, state),
187   F(submitter, string),
188   F(track, string),
189   F(when, time_t),
190   F(wstat, long)
191 };
192
193 int queue_unmarshall(struct queue_entry *q, const char *s,
194                      void (*error_handler)(const char *, void *),
195                      void *u) {
196   char **vec;
197   int nvec;
198
199   if(!(vec = split(s, &nvec, SPLIT_QUOTES, error_handler, u)))
200     return -1;
201   return queue_unmarshall_vec(q, nvec, vec, error_handler, u);
202 }
203
204 int queue_unmarshall_vec(struct queue_entry *q, int nvec, char **vec,
205                          void (*error_handler)(const char *, void *),
206                          void *u) {
207   int n;
208
209   if(nvec % 2 != 0) {
210     error_handler("invalid marshalled queue format", u);
211     return -1;
212   }
213   while(*vec) {
214     D(("key %s value %s", vec[0], vec[1]));
215     if((n = TABLE_FIND(fields, struct field, name, *vec)) < 0) {
216       error_handler("unknown key in queue data", u);
217       return -1;
218     } else {
219       if(fields[n].unmarshall(vec[1], q, fields[n].offset, error_handler, u))
220         return -1;
221     }
222     vec += 2;
223   }
224   return 0;
225 }
226
227 void queue_fix_sofar(struct queue_entry *q) {
228   long sofar;
229   
230   /* Fake up SOFAR field for currently-playing tracks that don't have it filled
231    * in by the speaker process.  XXX this horrible bodge should go away when we
232    * have a more general implementation of pausing as that field will always
233    * have to be right for the playing track. */
234   if((q->state == playing_started
235       || q->state == playing_paused)
236      && q->type & DISORDER_PLAYER_PAUSES
237      && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW) {
238     if(q->lastpaused) {
239       if(q->uptopause == -1)            /* Don't know how far thru. */
240         sofar = -1;
241       else if(q->lastresumed)           /* Has been paused and resumed. */
242         sofar = q->uptopause + time(0) - q->lastresumed;
243       else                              /* Currently paused. */
244         sofar = q->uptopause;
245     } else                              /* Never been paused. */
246       sofar = time(0) - q->played;
247     q->sofar = sofar;
248   }
249 }
250
251 char *queue_marshall(const struct queue_entry *q) {
252   unsigned n;
253   const char *vec[sizeof fields / sizeof *fields], *v;
254   char *r, *s;
255   size_t len = 1;
256
257   for(n = 0; n < sizeof fields / sizeof *fields; ++n)
258     if((v = fields[n].marshall(q, fields[n].offset))) {
259       vec[n] = quoteutf8(v);
260       len += strlen(vec[n]) + strlen(fields[n].name) + 2;
261     } else
262       vec[n] = 0;
263   s = r = xmalloc_noptr(len);
264   for(n = 0; n < sizeof fields / sizeof *fields; ++n)
265     if(vec[n]) {
266       *s++ = ' ';
267       s += strlen(strcpy(s, fields[n].name));
268       *s++ = ' ';
269       s += strlen(strcpy(s, vec[n]));
270     }
271   return r;
272 }
273
274 static void queue_read_error(const char *msg,
275                              void *u) {
276   fatal(0, "error parsing queue %s: %s", (const char *)u, msg);
277 }
278
279 static void queue_do_read(struct queue_entry *head, const char *path) {
280   char *buffer;
281   FILE *fp;
282   struct queue_entry *q;
283
284   if(!(fp = fopen(path, "r"))) {
285     if(errno == ENOENT)
286       return;                   /* no queue */
287     fatal(errno, "error opening %s", path);
288   }
289   head->next = head->prev = head;
290   while(!inputline(path, fp, &buffer, '\n')) {
291     q = xmalloc(sizeof *q);
292     queue_unmarshall(q, buffer, queue_read_error, (void *)path);
293     if(head == &qhead
294        && (!q->track
295            || !q->when))
296       fatal(0, "incomplete queue entry in %s", path);
297     l_add(head->prev, q);
298   }
299   if(ferror(fp)) fatal(errno, "error reading %s", path);
300   fclose(fp);
301 }
302
303 void queue_read(void) {
304   queue_do_read(&qhead, config_get_file("queue"));
305 }
306
307 void recent_read(void) {
308   struct queue_entry *q;
309
310   queue_do_read(&phead, config_get_file("recent"));
311   /* reset pcount after loading */
312   pcount = 0;
313   q = phead.next;
314   while(q != &phead) {
315     ++pcount;
316     q = q->next;
317   }
318 }
319
320 static void queue_do_write(const struct queue_entry *head, const char *path) {
321   char *tmp;
322   FILE *fp;
323   struct queue_entry *q;
324
325   byte_xasprintf(&tmp, "%s.new", path);
326   if(!(fp = fopen(tmp, "w"))) fatal(errno, "error opening %s", tmp);
327   for(q = head->next; q != head; q = q->next)
328     if(fprintf(fp, "%s\n", queue_marshall(q)) < 0)
329       fatal(errno, "error writing %s", tmp);
330   if(fclose(fp) < 0) fatal(errno, "error closing %s", tmp);
331   if(rename(tmp, path) < 0) fatal(errno, "error replacing %s", path);
332 }
333
334 void queue_write(void) {
335   queue_do_write(&qhead, config_get_file("queue"));
336 }
337
338 void recent_write(void) {
339   queue_do_write(&phead, config_get_file("recent"));
340 }
341
342 void queue_id(struct queue_entry *q) {
343   static unsigned long serial;
344   unsigned long a[3];
345   char buffer[128];
346
347   a[0] = serial++ & 0xFFFFFFFFUL;
348   a[1] = time(0) & 0xFFFFFFFFUL;
349   a[2] = getpid() & 0xFFFFFFFFUL;
350   basen(a, 3, buffer, sizeof buffer, 62);
351   q->id = xstrdup(buffer);
352 }
353
354 struct queue_entry *queue_add(const char *track, const char *submitter,
355                               int where) {
356   struct queue_entry *q, *beforeme;
357
358   q = xmalloc(sizeof *q);
359   q->track = xstrdup(track);
360   q->submitter = submitter ? xstrdup(submitter) : 0;
361   q->state = playing_unplayed;
362   queue_id(q);
363   time(&q->when);
364   switch(where) {
365   case WHERE_START:
366     l_add(&qhead, q);
367     break;
368   case WHERE_END:
369     l_add(qhead.prev, q);
370     break;
371   case WHERE_BEFORE_RANDOM:
372     /* We want to find the point in the queue before the block of random tracks
373      * at the end. */
374     beforeme = &qhead;
375     while(beforeme->prev != &qhead
376           && beforeme->prev->state == playing_random)
377       beforeme = beforeme->prev;
378     l_add(beforeme->prev, q);
379     break;
380   }
381   /* submitter will be a null pointer for a scratch */
382   if(submitter)
383     notify_queue(track, submitter);
384   eventlog_raw("queue", queue_marshall(q), (const char *)0);
385   return q;
386 }
387
388 int queue_move(struct queue_entry *q, int delta, const char *who) {
389   int moved = 0;
390   char buffer[20];
391
392   /* not the most efficient approach but hopefuly relatively comprehensible:
393    * the idea is that for each step we determine which nodes are affected, and
394    * fill in all the links starting at the 'prev' end and moving towards the
395    * 'next' end. */
396   
397   while(delta > 0 && q->prev != &qhead) {
398     struct queue_entry *n, *p, *pp;
399
400     n = q->next;
401     p = q->prev;
402     pp = p->prev;
403     pp->next = q;
404     q->prev = pp;
405     q->next = p;
406     p->prev = q;
407     p->next = n;
408     n->prev = p;
409     --delta;
410     ++moved;
411   }
412
413   while(delta < 0 && q->next != &qhead) {
414     struct queue_entry *n, *p, *nn;
415
416     p = q->prev;
417     n = q->next;
418     nn = n->next;
419     p->next = n;
420     n->prev = p;
421     n->next = q;
422     q->prev = n;
423     q->next = nn;
424     nn->prev = q;
425     ++delta;
426     --moved;
427   }
428
429   if(moved) {
430     info("user %s moved %s", who, q->id);
431     notify_queue_move(q->track, who);
432     sprintf(buffer, "%d", moved);
433     eventlog("moved", who, (char *)0);
434   }
435   
436   return delta;
437 }
438
439 static int find_in_list(struct queue_entry *needle,
440                         int nqs, struct queue_entry **qs) {
441   int n;
442
443   for(n = 0; n < nqs; ++n)
444     if(qs[n] == needle)
445       return 1;
446   return 0;
447 }
448
449 void queue_moveafter(struct queue_entry *target,
450                      int nqs, struct queue_entry **qs,
451                      const char *who) {
452   struct queue_entry *q;
453   int n;
454
455   /* Normalize */
456   if(!target)
457     target = &qhead;
458   else
459     while(find_in_list(target, nqs, qs))
460       target = target->prev;
461   /* Do the move */
462   for(n = 0; n < nqs; ++n) {
463     q = qs[n];
464     l_remove(q);
465     l_add(target, q);
466     target = q;
467     /* Log the individual tracks */
468     info("user %s moved %s", who, q->id);
469     notify_queue_move(q->track, who);
470   }
471   /* Report that the queue changed to the event log */
472   eventlog("moved", who, (char *)0);
473 }
474
475 void queue_remove(struct queue_entry *which, const char *who) {
476   if(who) {
477     info("user %s removed %s", who, which->id);
478     notify_queue_move(which->track, who);
479   }
480   eventlog("removed", which->id, who, (const char *)0);
481   l_remove(which);
482 }
483
484 struct queue_entry *queue_find(const char *key) {
485   struct queue_entry *q;
486
487   for(q = qhead.next;
488       q != &qhead && strcmp(q->track, key) && strcmp(q->id, key);
489       q = q->next)
490     ;
491   return q != &qhead ? q : 0;
492 }
493
494 void queue_played(struct queue_entry *q) {
495   while(pcount && pcount >= config->history) {
496     eventlog("recent_removed", phead.next->id, (char *)0);
497     l_remove(phead.next);
498     pcount--;
499   }
500   if(config->history) {
501     eventlog_raw("recent_added", queue_marshall(q), (char *)0);
502     l_add(phead.prev, q);
503     ++pcount;
504   }
505 }
506
507 /*
508 Local Variables:
509 c-basic-offset:2
510 comment-column:40
511 fill-column:79
512 End:
513 */