chiark / gitweb /
Merge playlist branch against trunk to date.
[disorder] / clients / disorder.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-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 3 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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU 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, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file clients/disorder.c
19  * @brief Command-line client
20  */
21
22 #include "common.h"
23
24 #include <getopt.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <errno.h>
29 #include <locale.h>
30 #include <time.h>
31 #include <stddef.h>
32 #include <unistd.h>
33 #include <pcre.h>
34 #include <ctype.h>
35 #include <langinfo.h>
36
37 #include "configuration.h"
38 #include "syscalls.h"
39 #include "log.h"
40 #include "queue.h"
41 #include "client.h"
42 #include "wstat.h"
43 #include "table.h"
44 #include "charset.h"
45 #include "kvp.h"
46 #include "split.h"
47 #include "sink.h"
48 #include "mem.h"
49 #include "defs.h"
50 #include "authorize.h"
51 #include "vector.h"
52 #include "version.h"
53 #include "dateparse.h"
54 #include "inputline.h"
55
56 static disorder_client *client;
57
58 static const struct option options[] = {
59   { "help", no_argument, 0, 'h' },
60   { "version", no_argument, 0, 'V' },
61   { "config", required_argument, 0, 'c' },
62   { "debug", no_argument, 0, 'd' },
63   { "local", no_argument, 0, 'l' },
64   { "no-per-user-config", no_argument, 0, 'N' },
65   { "help-commands", no_argument, 0, 'H' },
66   { "user", required_argument, 0, 'u' },
67   { "password", required_argument, 0, 'p' },
68   { 0, 0, 0, 0 }
69 };
70
71 /* display usage message and terminate */
72 static void help(void) {
73   xprintf("Usage:\n"
74           "  disorder [OPTIONS] COMMAND ...\n"
75           "Options:\n"
76           "  --help, -h              Display usage message\n"
77           "  --help-commands, -H     List commands\n"
78           "  --version, -V           Display version number\n"
79           "  --config PATH, -c PATH  Set configuration file\n"
80           "  --local, -l             Force connection to local server\n"
81           "  --debug, -d             Turn on debugging\n");
82   xfclose(stdout);
83   exit(0);
84 }
85
86 static disorder_client *getclient(void) {
87   if(!client) {
88     if(!(client = disorder_new(1))) exit(EXIT_FAILURE);
89     if(disorder_connect(client)) exit(EXIT_FAILURE);
90   }
91   return client;
92 }
93
94 static void cf_version(char attribute((unused)) **argv) {
95   char *v;
96
97   if(disorder_version(getclient(), &v)) exit(EXIT_FAILURE);
98   xprintf("%s\n", nullcheck(utf82mb(v)));
99 }
100
101 static void print_queue_entry(const struct queue_entry *q) {
102   if(q->track) xprintf("track %s\n", nullcheck(utf82mb(q->track)));
103   if(q->id) xprintf("  id %s\n", nullcheck(utf82mb(q->id)));
104   switch(q->origin) {
105   case origin_adopted:
106   case origin_picked:
107   case origin_scheduled:
108     xprintf("  %s by %s at %s",
109             track_origins[q->origin],
110             nullcheck(utf82mb(q->submitter)), ctime(&q->when));
111     break;
112   default:
113     break;
114   }
115   if(q->played) xprintf("  played at %s", ctime(&q->played));
116   if(q->state == playing_started
117      || q->state == playing_paused) xprintf("  %lds so far",  q->sofar);
118   else if(q->expected) xprintf("  might start at %s", ctime(&q->expected));
119   if(q->scratched) xprintf("  scratched by %s\n",
120                            nullcheck(utf82mb(q->scratched)));
121   else xprintf("  %s\n", playing_states[q->state]);
122   if(q->wstat) xprintf("  %s\n", wstat(q->wstat));
123 }
124
125 static void cf_playing(char attribute((unused)) **argv) {
126   struct queue_entry *q;
127
128   if(disorder_playing(getclient(), &q)) exit(EXIT_FAILURE);
129   if(q)
130     print_queue_entry(q);
131   else
132     xprintf("nothing\n");
133 }
134
135 static void cf_play(char **argv) {
136   while(*argv)
137     if(disorder_play(getclient(), *argv++)) exit(EXIT_FAILURE);
138 }
139
140 static void cf_remove(char **argv) {
141   if(disorder_remove(getclient(), argv[0])) exit(EXIT_FAILURE);
142 }
143
144 static void cf_disable(char attribute((unused)) **argv) {
145   if(disorder_disable(getclient())) exit(EXIT_FAILURE);
146 }
147
148 static void cf_enable(char attribute((unused)) **argv) {
149   if(disorder_enable(getclient())) exit(EXIT_FAILURE);
150 }
151
152 static void cf_scratch(char **argv) {
153   if(disorder_scratch(getclient(), argv[0])) exit(EXIT_FAILURE);
154 }
155
156 static void cf_shutdown(char attribute((unused)) **argv) {
157   if(disorder_shutdown(getclient())) exit(EXIT_FAILURE);
158 }
159
160 static void cf_reconfigure(char attribute((unused)) **argv) {
161   /* Re-check configuration for server */
162   if(config_read(1)) fatal(0, "cannot read configuration");
163   if(disorder_reconfigure(getclient())) exit(EXIT_FAILURE);
164 }
165
166 static void cf_rescan(char attribute((unused)) **argv) {
167   if(disorder_rescan(getclient())) exit(EXIT_FAILURE);
168 }
169
170 static void cf_somequeue(int (*fn)(disorder_client *c,
171                                    struct queue_entry **qp)) {
172   struct queue_entry *q;
173
174   if(fn(getclient(), &q)) exit(EXIT_FAILURE);
175   while(q) {
176     print_queue_entry(q);
177     q = q->next;
178   }
179 }
180
181 static void cf_recent(char attribute((unused)) **argv) {
182   cf_somequeue(disorder_recent);
183 }
184
185 static void cf_queue(char attribute((unused)) **argv) {
186   cf_somequeue(disorder_queue);
187 }
188
189 static void cf_quack(char attribute((unused)) **argv) {
190   if(!strcasecmp(nl_langinfo(CODESET), "utf-8")) {
191 #define TL "\xE2\x95\xAD"
192 #define TR "\xE2\x95\xAE"
193 #define BR "\xE2\x95\xAF"
194 #define BL "\xE2\x95\xB0"
195 #define H "\xE2\x94\x80"
196 #define V "\xE2\x94\x82"
197 #define T "\xE2\x94\xAC"
198     xprintf("\n"
199             " "TL H H H H H H H H H H H H H H H H H H TR"\n"
200             " "V" Naath is a babe! "V"\n"
201             " "BL H H H H H H H H H T H H H H H H H H BR"\n"
202             "            \\\n"
203             "              >0\n"
204             "               (<)'\n"
205             "~~~~~~~~~~~~~~~~~~~~~~\n"
206             "\n");
207   } else {
208     xprintf("\n"
209             " .------------------.\n"
210             " | Naath is a babe! |\n"
211             " `---------+--------'\n"
212             "            \\\n"
213             "              >0\n"
214             "               (<)'\n"
215             "~~~~~~~~~~~~~~~~~~~~~~\n"
216             "\n");
217   }
218 }
219
220 static void cf_somelist(char **argv,
221                         int (*fn)(disorder_client *c,
222                                   const char *arg, const char *re,
223                                   char ***vecp, int *nvecp)) {
224   char **vec;
225   const char *re;
226
227   if(argv[1])
228     re = xstrdup(argv[1] + 1);
229   else
230     re = 0;
231   if(fn(getclient(), argv[0], re, &vec, 0)) exit(EXIT_FAILURE);
232   while(*vec)
233     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
234 }
235
236 static int isarg_regexp(const char *s) {
237   return s[0] == '~';
238 }
239
240 static void cf_dirs(char **argv) {
241   cf_somelist(argv, disorder_directories);
242 }
243
244 static void cf_files(char **argv) {
245   cf_somelist(argv, disorder_files);
246 }
247
248 static void cf_allfiles(char **argv) {
249   cf_somelist(argv, disorder_allfiles);
250 }
251
252 static void cf_get(char **argv) {
253   char *value;
254
255   if(disorder_get(getclient(), argv[0], argv[1], &value)) exit(EXIT_FAILURE);
256   xprintf("%s\n", nullcheck(utf82mb(value)));
257 }
258
259 static void cf_length(char **argv) {
260   long length;
261
262   if(disorder_length(getclient(), argv[0], &length)) exit(EXIT_FAILURE);
263   xprintf("%ld\n", length);
264 }
265
266 static void cf_set(char **argv) {
267   if(disorder_set(getclient(), argv[0], argv[1], argv[2])) exit(EXIT_FAILURE);
268 }
269
270 static void cf_unset(char **argv) {
271   if(disorder_unset(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
272 }
273
274 static void cf_prefs(char **argv) {
275   struct kvp *k;
276
277   if(disorder_prefs(getclient(), argv[0], &k)) exit(EXIT_FAILURE);
278   for(; k; k = k->next)
279     xprintf("%s = %s\n",
280             nullcheck(utf82mb(k->name)), nullcheck(utf82mb(k->value)));
281 }
282
283 static void cf_search(char **argv) {
284   char **results;
285   int nresults, n;
286
287   if(disorder_search(getclient(), *argv, &results, &nresults)) exit(EXIT_FAILURE);
288   for(n = 0; n < nresults; ++n)
289     xprintf("%s\n", nullcheck(utf82mb(results[n])));
290 }
291
292 static void cf_random_disable(char attribute((unused)) **argv) {
293   if(disorder_random_disable(getclient())) exit(EXIT_FAILURE);
294 }
295
296 static void cf_random_enable(char attribute((unused)) **argv) {
297   if(disorder_random_enable(getclient())) exit(EXIT_FAILURE);
298 }
299
300 static void cf_stats(char attribute((unused)) **argv) {
301   char **vec;
302
303   if(disorder_stats(getclient(), &vec, 0)) exit(EXIT_FAILURE);
304   while(*vec)
305       xprintf("%s\n", nullcheck(utf82mb(*vec++)));
306 }
307
308 static void cf_get_volume(char attribute((unused)) **argv) {
309   int l, r;
310
311   if(disorder_get_volume(getclient(), &l, &r)) exit(EXIT_FAILURE);
312   xprintf("%d %d\n", l, r);
313 }
314
315 static void cf_set_volume(char **argv) {
316   if(disorder_set_volume(getclient(), atoi(argv[0]), atoi(argv[1]))) exit(EXIT_FAILURE);
317 }
318
319 static void cf_log(char attribute((unused)) **argv) {
320   if(disorder_log(getclient(), sink_stdio("stdout", stdout))) exit(EXIT_FAILURE);
321 }
322
323 static void cf_move(char **argv) {
324   long n;
325   int e;
326   
327   if((e = xstrtol(&n, argv[1], 0, 10)))
328     fatal(e, "cannot convert '%s'", argv[1]);
329   if(n > INT_MAX || n < INT_MIN)
330     fatal(e, "%ld out of range", n);
331   if(disorder_move(getclient(), argv[0], (int)n)) exit(EXIT_FAILURE);
332 }
333
334 static void cf_part(char **argv) {
335   char *s;
336
337   if(disorder_part(getclient(), &s, argv[0], argv[1], argv[2])) exit(EXIT_FAILURE);
338   xprintf("%s\n", nullcheck(utf82mb(s)));
339 }
340
341 static int isarg_filename(const char *s) {
342   return s[0] == '/';
343 }
344
345 static void cf_authorize(char **argv) {
346   authorize(getclient(), argv[0], argv[1]);
347 }
348
349 static void cf_resolve(char **argv) {
350   char *track;
351
352   if(disorder_resolve(getclient(), &track, argv[0])) exit(EXIT_FAILURE);
353   xprintf("%s\n", nullcheck(utf82mb(track)));
354 }
355
356 static void cf_pause(char attribute((unused)) **argv) {
357   if(disorder_pause(getclient())) exit(EXIT_FAILURE);
358 }
359
360 static void cf_resume(char attribute((unused)) **argv) {
361   if(disorder_resume(getclient())) exit(EXIT_FAILURE);
362 }
363
364 static void cf_tags(char attribute((unused)) **argv) {
365   char **vec;
366
367   if(disorder_tags(getclient(), &vec, 0)) exit(EXIT_FAILURE);
368   while(*vec)
369       xprintf("%s\n", nullcheck(utf82mb(*vec++)));
370 }
371
372 static void cf_users(char attribute((unused)) **argv) {
373   char **vec;
374
375   if(disorder_users(getclient(), &vec, 0)) exit(EXIT_FAILURE);
376   while(*vec)
377     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
378 }
379
380 static void cf_get_global(char **argv) {
381   char *value;
382
383   if(disorder_get_global(getclient(), argv[0], &value)) exit(EXIT_FAILURE);
384   xprintf("%s\n", nullcheck(utf82mb(value)));
385 }
386
387 static void cf_set_global(char **argv) {
388   if(disorder_set_global(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
389 }
390
391 static void cf_unset_global(char **argv) {
392   if(disorder_unset_global(getclient(), argv[0])) exit(EXIT_FAILURE);
393 }
394
395 static int isarg_integer(const char *s) {
396   if(!*s) return 0;
397   while(*s) {
398     if(!isdigit((unsigned char)*s))
399       return 0;
400     ++s;
401   }
402   return 1;
403 }
404
405 static void cf_new(char **argv) {
406   char **vec;
407
408   if(disorder_new_tracks(getclient(), &vec, 0, argv[0] ? atoi(argv[0]) : 0))
409     exit(EXIT_FAILURE);
410   while(*vec)
411     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
412 }
413
414 static void cf_rtp_address(char attribute((unused)) **argv) {
415   char *address, *port;
416
417   if(disorder_rtp_address(getclient(), &address, &port)) exit(EXIT_FAILURE);
418   xprintf("address: %s\nport: %s\n", address, port);
419 }
420
421 static int isarg_rights(const char *arg) {
422   return strchr(arg, ',') || !parse_rights(arg, 0, 0);
423 }
424
425 static void cf_adduser(char **argv) {
426   if(disorder_adduser(getclient(), argv[0], argv[1], argv[2]))
427     exit(EXIT_FAILURE);
428 }
429
430 static void cf_deluser(char **argv) {
431   if(disorder_deluser(getclient(), argv[0]))
432     exit(EXIT_FAILURE);
433 }
434
435 static void cf_edituser(char **argv) {
436   if(disorder_edituser(getclient(), argv[0], argv[1], argv[2]))
437     exit(EXIT_FAILURE);
438 }
439
440 static void cf_userinfo(char **argv) {
441   char *s;
442
443   if(disorder_userinfo(getclient(), argv[0], argv[1], &s))
444     exit(EXIT_FAILURE);
445   xprintf("%s\n", nullcheck(utf82mb(s)));
446 }
447
448 static int isarg_option(const char *arg) {
449   return arg[0] == '-';
450 }
451
452 static int argvlen(char **argv) {
453   char **start = argv;
454   
455   while(*argv)
456     ++argv;
457   return argv - start;
458 }
459
460 static const struct option setup_guest_options[] = {
461   { "help", no_argument, 0, 'h' },
462   { "online-registration", no_argument, 0, 'r' },
463   { "no-online-registration", no_argument, 0, 'R' },
464   { 0, 0, 0, 0 }
465 };
466
467 static void help_setup_guest(void) {
468   xprintf("Usage:\n"
469           "  disorder setup-guest [OPTIONS]\n"
470           "Options:\n"
471           "  --help, -h                Display usage message\n"
472           "  --online-registration     Enable online registration (default)\n"
473           "  --no-online-registration  Disable online registration\n");
474   xfclose(stdout);
475   exit(0);
476 }
477
478 static void cf_setup_guest(char **argv) {
479   int n, online_registration = 1;
480   
481   while((n = getopt_long(argvlen(argv) + 1, argv - 1,
482                          "hrR", setup_guest_options, 0)) >= 0) {
483     switch(n) {
484     case 'h': help_setup_guest();
485     case 'r': online_registration = 1; break;
486     case 'R': online_registration = 0; break;
487     default: fatal(0, "invalid option");
488     }
489   }
490   if(online_registration && !config->mail_sender)
491     fatal(0, "you MUST set mail_sender if you want online registration");
492   if(disorder_adduser(getclient(), "guest", "",
493                       online_registration ? "read,register" : "read"))
494     exit(EXIT_FAILURE);
495 }
496
497 struct scheduled_event {
498   time_t when;
499   struct kvp *actiondata;
500   char *id;
501 };
502
503 static int compare_event(const void *av, const void *bv) {
504   struct scheduled_event *a = (void *)av, *b = (void *)bv;
505
506   /* Primary sort key is the trigger time */
507   if(a->when < b->when)
508     return -1;
509   else if(a->when > b->when)
510     return 1;
511   /* For events that go off at the same time just sort by ID */
512   return strcmp(a->id, b->id);
513 }
514
515 static void cf_schedule_list(char attribute((unused)) **argv) {
516   char **ids;
517   int nids, n;
518   struct scheduled_event *events;
519   char tb[128];
520   const char *action, *key, *value, *priority;
521   int prichar;
522
523   /* Get all known events */
524   if(disorder_schedule_list(getclient(), &ids, &nids))
525     exit(EXIT_FAILURE);
526   events = xcalloc(nids, sizeof *events);
527   for(n = 0; n < nids; ++n) {
528     events[n].id = ids[n];
529     if(disorder_schedule_get(getclient(), ids[n], &events[n].actiondata))
530       exit(EXIT_FAILURE);
531     events[n].when = atoll(kvp_get(events[n].actiondata, "when"));
532   }
533   /* Sort by trigger time */
534   qsort(events, nids, sizeof *events, compare_event);
535   /* Display them */
536   for(n = 0; n < nids; ++n) {
537     strftime(tb, sizeof tb, "%Y-%m-%d %H:%M:%S %Z", localtime(&events[n].when));
538     action = kvp_get(events[n].actiondata, "action");
539     priority = kvp_get(events[n].actiondata, "priority");
540     if(!strcmp(priority, "junk"))
541       prichar = 'J';
542     else if(!strcmp(priority, "normal"))
543       prichar = 'N';
544     else
545       prichar = '?';
546     xprintf("%11s %-25s %c %-8s %s",
547             events[n].id, tb, prichar, kvp_get(events[n].actiondata, "who"),
548             action);
549     if(!strcmp(action, "play"))
550       xprintf(" %s",
551               nullcheck(utf82mb(kvp_get(events[n].actiondata, "track"))));
552     else if(!strcmp(action, "set-global")) {
553       key = kvp_get(events[n].actiondata, "key");
554       value = kvp_get(events[n].actiondata, "value");
555       if(value)
556         xprintf(" %s=%s",
557                 nullcheck(utf82mb(key)),
558                 nullcheck(utf82mb(value)));
559       else
560         xprintf(" %s unset",
561                 nullcheck(utf82mb(key)));
562     }
563     xprintf("\n");
564   }
565 }
566
567 static void cf_schedule_del(char **argv) {
568   if(disorder_schedule_del(getclient(), argv[0]))
569     exit(EXIT_FAILURE);
570 }
571
572 static void cf_schedule_play(char **argv) {
573   if(disorder_schedule_add(getclient(),
574                            dateparse(argv[0]),
575                            argv[1],
576                            "play",
577                            argv[2]))
578     exit(EXIT_FAILURE);
579 }
580
581 static void cf_schedule_set_global(char **argv) {
582   if(disorder_schedule_add(getclient(),
583                            dateparse(argv[0]),
584                            argv[1],
585                            "set-global",
586                            argv[2],
587                            argv[3]))
588     exit(EXIT_FAILURE);
589 }
590
591 static void cf_schedule_unset_global(char **argv) {
592   if(disorder_schedule_add(getclient(),
593                            dateparse(argv[0]),
594                            argv[1],
595                            "set-global",
596                            argv[2],
597                            (char *)0))
598     exit(EXIT_FAILURE);
599 }
600
601 static void cf_adopt(char **argv) {
602   if(disorder_adopt(getclient(), argv[0]))
603     exit(EXIT_FAILURE);
604 }
605
606 static void cf_playlists(char attribute((unused)) **argv) {
607   char **vec;
608
609   if(disorder_playlists(getclient(), &vec, 0))
610     exit(EXIT_FAILURE);
611   while(*vec)
612     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
613 }
614
615 static void cf_playlist_del(char **argv) {
616   if(disorder_playlist_delete(getclient(), argv[0]))
617     exit(EXIT_FAILURE);
618 }
619
620 static void cf_playlist_get(char **argv) {
621   char **vec;
622
623   if(disorder_playlist_get(getclient(), argv[0], &vec, 0))
624     exit(EXIT_FAILURE);
625   while(*vec)
626     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
627 }
628
629 static void cf_playlist_set(char **argv) {
630   struct vector v[1];
631   FILE *input;
632   const char *tag;
633   char *l;
634
635   if(argv[1]) {
636     // Read track list from file
637     if(!(input = fopen(argv[1], "r")))
638       fatal(errno, "opening %s", argv[1]);
639     tag = argv[1];
640   } else {
641     // Read track list from standard input
642     input = stdin;
643     tag = "stdin";
644   }
645   vector_init(v);
646   while(!inputline(tag, input, &l, '\n')) {
647     if(!strcmp(l, "."))
648       break;
649     vector_append(v, l);
650   }
651   if(ferror(input))
652     fatal(errno, "reading %s", tag);
653   if(input != stdin)
654     fclose(input);
655   if(disorder_playlist_lock(getclient(), argv[0])
656      || disorder_playlist_set(getclient(), argv[0], v->vec, v->nvec)
657      || disorder_playlist_unlock(getclient()))
658     exit(EXIT_FAILURE);
659 }
660
661 static const struct command {
662   const char *name;
663   int min, max;
664   void (*fn)(char **);
665   int (*isarg)(const char *);
666   const char *argstr, *desc;
667 } commands[] = {
668   { "adduser",        2, 3, cf_adduser, isarg_rights, "USERNAME PASSWORD [RIGHTS]",
669                       "Create a new user" },
670   { "adopt",          1, 1, cf_adopt, 0, "ID",
671                       "Adopt a randomly picked track" },
672   { "allfiles",       1, 2, cf_allfiles, isarg_regexp, "DIR [~REGEXP]",
673                       "List all files and directories in DIR" },
674   { "authorize",      1, 2, cf_authorize, isarg_rights, "USERNAME [RIGHTS]",
675                       "Authorize user USERNAME to connect" },
676   { "deluser",        1, 1, cf_deluser, 0, "USERNAME",
677                       "Delete user USERNAME" },
678   { "dirs",           1, 2, cf_dirs, isarg_regexp, "DIR [~REGEXP]",
679                       "List directories in DIR" },
680   { "disable",        0, 0, cf_disable, 0, "",
681                       "Disable play" },
682   { "disable-random", 0, 0, cf_random_disable, 0, "",
683                       "Disable random play" },
684   { "edituser",       3, 3, cf_edituser, 0, "USERNAME PROPERTY VALUE",
685                       "Set a property of user USERNAME" },
686   { "enable",         0, 0, cf_enable, 0, "",
687                       "Enable play" },
688   { "enable-random",  0, 0, cf_random_enable, 0, "",
689                       "Enable random play" },
690   { "files",          1, 2, cf_files, isarg_regexp, "DIR [~REGEXP]",
691                       "List files in DIR" },
692   { "get",            2, 2, cf_get, 0, "TRACK NAME",
693                       "Get a preference value" },
694   { "get-global",     1, 1, cf_get_global, 0, "NAME",
695                       "Get a global preference value" },
696   { "get-volume",     0, 0, cf_get_volume, 0, "",
697                       "Get the current volume" },
698   { "length",         1, 1, cf_length, 0, "TRACK",
699                       "Get the length of TRACK in seconds" },
700   { "log",            0, 0, cf_log, 0, "",
701                       "Copy event log to stdout" },
702   { "move",           2, 2, cf_move, 0, "TRACK DELTA",
703                       "Move a track in the queue" },
704   { "new",            0, 1, cf_new, isarg_integer, "[MAX]",
705                       "Get the most recently added MAX tracks" },
706   { "part",           3, 3, cf_part, 0, "TRACK CONTEXT PART",
707                       "Find a track name part" },
708   { "pause",          0, 0, cf_pause, 0, "",
709                       "Pause the currently playing track" },
710   { "play",           1, INT_MAX, cf_play, isarg_filename, "TRACKS...",
711                       "Add TRACKS to the end of the queue" },
712   { "playing",        0, 0, cf_playing, 0, "",
713                       "Report the playing track" },
714   { "playlist-del",   1, 1, cf_playlist_del, 0, "PLAYLIST",
715                       "Delete a playlist" },
716   { "playlist-get",   1, 1, cf_playlist_get, 0, "PLAYLIST",
717                       "Get the contents of a playlist" },
718   { "playlist-set",   1, 2, cf_playlist_set, isarg_filename, "PLAYLIST [PATH]",
719                       "Set the contents of a playlist" },
720   { "playlists",      0, 0, cf_playlists, 0, "",
721                       "List playlists" },
722   { "prefs",          1, 1, cf_prefs, 0, "TRACK",
723                       "Display all the preferences for TRACK" },
724   { "quack",          0, 0, cf_quack, 0, 0, 0 },
725   { "queue",          0, 0, cf_queue, 0, "",
726                       "Display the current queue" },
727   { "random-disable", 0, 0, cf_random_disable, 0, "",
728                       "Disable random play" },
729   { "random-enable",  0, 0, cf_random_enable, 0, "",
730                       "Enable random play" },
731   { "recent",         0, 0, cf_recent, 0, "",
732                       "Display recently played track" },
733   { "reconfigure",    0, 0, cf_reconfigure, 0, "",
734                       "Reconfigure the daemon" },
735   { "remove",         1, 1, cf_remove, 0, "TRACK",
736                       "Remove a track from the queue" },
737   { "rescan",         0, 0, cf_rescan, 0, "",
738                       "Rescan for new tracks" },
739   { "resolve",        1, 1, cf_resolve, 0, "TRACK",
740                       "Resolve alias for TRACK" },
741   { "resume",         0, 0, cf_resume, 0, "",
742                       "Resume after a pause" },
743   { "rtp-address",    0, 0, cf_rtp_address, 0, "",
744                       "Report server's broadcast address" },
745   { "schedule-del",   1, 1, cf_schedule_del, 0, "EVENT",
746                       "Delete a scheduled event" },
747   { "schedule-list",  0, 0, cf_schedule_list, 0, "",
748                       "List scheduled events" },
749   { "schedule-play",  3, 3, cf_schedule_play, 0, "WHEN PRI TRACK",
750                       "Play TRACK later" },
751   { "schedule-set-global", 4, 4, cf_schedule_set_global, 0, "WHEN PRI NAME VAL",
752                       "Set a global preference later" },
753   { "schedule-unset-global", 3, 3, cf_schedule_unset_global, 0, "WHEN PRI NAME",
754                       "Unset a global preference later" },
755   { "scratch",        0, 0, cf_scratch, 0, "",
756                       "Scratch the currently playing track" },
757   { "scratch-id",     1, 1, cf_scratch, 0, "ID",
758                       "Scratch the currently playing track" },
759   { "search",         1, 1, cf_search, 0, "WORDS",
760                       "Display tracks matching all the words" },
761   { "set",            3, 3, cf_set, 0, "TRACK NAME VALUE",
762                       "Set a preference value" },
763   { "set-global",     2, 2, cf_set_global, 0, "NAME VALUE",
764                       "Set a global preference value" },
765   { "set-volume",     2, 2, cf_set_volume, 0, "LEFT RIGHT",
766                       "Set the volume" },
767   { "setup-guest",    0, INT_MAX, cf_setup_guest, isarg_option, "[OPTIONS]",
768                       "Create the guest login" },
769   { "shutdown",       0, 0, cf_shutdown, 0, "",
770                       "Shut down the daemon" },
771   { "stats",          0, 0, cf_stats, 0, "",
772                       "Display server statistics" },
773   { "tags",           0, 0, cf_tags, 0, "",
774                       "List known tags" },
775   { "unset",          2, 2, cf_unset, 0, "TRACK NAME",
776                       "Unset a preference" },
777   { "unset-global",   1, 1, cf_unset_global, 0, "NAME",
778                       "Unset a global preference" },
779   { "userinfo",       2, 2, cf_userinfo, 0, "USERNAME PROPERTY",
780                       "Get a property of a user" },
781   { "users",          0, 0, cf_users, 0, "",
782                       "List all users" },
783   { "version",        0, 0, cf_version, 0, "",
784                       "Display the server version" },
785 };
786
787 static void help_commands(void) {
788   unsigned n, max = 0, l;
789
790   xprintf("Command summary:\n");
791   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
792     if(!commands[n].desc) continue;
793     l = strlen(commands[n].name);
794     if(*commands[n].argstr)
795       l += strlen(commands[n].argstr) + 1;
796     if(l > max)
797       max = l;
798   }
799   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
800     if(!commands[n].desc) continue;
801     l = strlen(commands[n].name);
802     if(*commands[n].argstr)
803       l += strlen(commands[n].argstr) + 1;
804     xprintf("  %s%s%s%*s  %s\n", commands[n].name,
805             *commands[n].argstr ? " " : "",
806             commands[n].argstr,
807             max - l, "",
808             commands[n].desc);
809   }
810   xfclose(stdout);
811   exit(0);
812 }
813
814 int main(int argc, char **argv) {
815   int n, i, j, local = 0;
816   int status = 0;
817   struct vector args;
818   const char *user = 0, *password = 0;
819
820   mem_init();
821   /* garbage-collect PCRE's memory */
822   pcre_malloc = xmalloc;
823   pcre_free = xfree;
824   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
825   if(!setlocale(LC_TIME, "")) fatal(errno, "error calling setlocale");
826   while((n = getopt_long(argc, argv, "+hVc:dHlNu:p:", options, 0)) >= 0) {
827     switch(n) {
828     case 'h': help();
829     case 'H': help_commands();
830     case 'V': version("disorder");
831     case 'c': configfile = optarg; break;
832     case 'd': debugging = 1; break;
833     case 'l': local = 1; break;
834     case 'N': config_per_user = 0; break;
835     case 'u': user = optarg; break;
836     case 'p': password = optarg; break;
837     default: fatal(0, "invalid option");
838     }
839   }
840   if(config_read(0)) fatal(0, "cannot read configuration");
841   if(user) {
842     config->username = user;
843     config->password = 0;
844   }
845   if(password)
846     config->password = password;
847   if(local)
848     config->connect.n = 0;
849   n = optind;
850   optind = 1;                           /* for subsequent getopt calls */
851   /* accumulate command args */
852   while(n < argc) {
853     if((i = TABLE_FIND(commands, name, argv[n])) < 0)
854       fatal(0, "unknown command '%s'", argv[n]);
855     if(n + commands[i].min >= argc)
856       fatal(0, "missing arguments to '%s'", argv[n]);
857     vector_init(&args);
858     /* Include the command name in the args, but at element -1, for
859      * the benefit of subcommand getopt calls */
860     vector_append(&args, argv[n]);
861     n++;
862     for(j = 0; j < commands[i].min; ++j)
863       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
864     for(; j < commands[i].max
865           && n + j < argc
866           && commands[i].isarg(argv[n + j]); ++j)
867       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
868     vector_terminate(&args);
869     commands[i].fn(args.vec + 1);
870     n += j;
871   }
872   if(client && disorder_close(client)) exit(EXIT_FAILURE);
873   if(fclose(stdout) < 0) fatal(errno, "error closing stdout");
874   return status;
875 }
876
877 /*
878 Local Variables:
879 c-basic-offset:2
880 comment-column:40
881 End:
882 */