2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2008 Richard Kettlewell
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.
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.
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
20 /** @file server/actions.c
21 * @brief DisOrder web actions
23 * Actions are anything that the web interface does beyond passive template
24 * expansion and inspection of state recieved from the server. This means
25 * playing tracks, editing prefs etc but also setting extra headers e.g. to
26 * auto-refresh the playing list.
29 #include "disorder-cgi.h"
31 /** @brief Redirect to some other action or URL */
32 static void redirect(const char *url) {
33 /* By default use the 'back' argument */
35 url = cgi_get("back");
37 if(strncmp(url, "http", 4))
38 /* If the target is not a full URL assume it's the action */
39 url = cgi_makeurl(config->url, "action", url, (char *)0);
41 /* If back= is not set just go back to the front page */
44 if(printf("Location: %s\n"
46 "\n", url, dcgi_cookie_header()) < 0)
47 fatal(errno, "error writing to stdout");
50 /* 'playing' and 'manage' just add a Refresh: header */
51 static void act_playing(void) {
52 long refresh = config->refresh;
58 dcgi_lookup(DCGI_PLAYING|DCGI_QUEUE|DCGI_ENABLED|DCGI_RANDOM_ENABLED);
60 && dcgi_playing->state == playing_started /* i.e. not paused */
61 && !disorder_length(dcgi_client, dcgi_playing->track, &length)
63 && dcgi_playing->sofar >= 0) {
64 /* Try to put the next refresh at the start of the next track. */
66 fin = now + length - dcgi_playing->sofar + config->gap;
67 if(now + refresh > fin)
70 if(dcgi_queue && dcgi_queue->state == playing_isscratch) {
71 /* next track is a scratch, don't leave more than the inter-track gap */
72 if(refresh > config->gap)
73 refresh = config->gap;
77 && dcgi_queue->state != playing_random)
78 || dcgi_random_enabled)
80 /* no track playing but playing is enabled and there is something coming
81 * up, must be in a gap */
82 if(refresh > config->gap)
83 refresh = config->gap;
85 if((action = cgi_get("action")))
86 url = cgi_makeurl(config->url, "action", action, (char *)0);
89 if(printf("Refresh: %ld;url=%s\n",
91 fatal(errno, "error writing to stdout");
92 dcgi_expand("playing", 1);
95 static void act_disable(void) {
97 disorder_disable(dcgi_client);
101 static void act_enable(void) {
103 disorder_enable(dcgi_client);
107 static void act_random_disable(void) {
109 disorder_random_disable(dcgi_client);
113 static void act_random_enable(void) {
115 disorder_random_enable(dcgi_client);
119 static void act_pause(void) {
121 disorder_pause(dcgi_client);
125 static void act_resume(void) {
127 disorder_resume(dcgi_client);
131 static void act_remove(void) {
133 struct queue_entry *q;
136 if(!(id = cgi_get("id")))
137 error(0, "missing 'id' argument");
138 else if(!(q = dcgi_findtrack(id)))
139 error(0, "unknown queue id %s", id);
140 else switch(q->state) {
141 case playing_isscratch:
143 case playing_no_player:
145 case playing_quitting:
146 case playing_scratched:
147 error(0, "does not make sense to scratch %s", id);
149 case playing_paused: /* started but paused */
150 case playing_started: /* started to play */
151 disorder_scratch(dcgi_client, id);
153 case playing_random: /* unplayed randomly chosen track */
154 case playing_unplayed: /* haven't played this track yet */
155 disorder_remove(dcgi_client, id);
162 static void act_move(void) {
163 const char *id, *delta;
164 struct queue_entry *q;
167 if(!(id = cgi_get("id")))
168 error(0, "missing 'id' argument");
169 else if(!(delta = cgi_get("delta")))
170 error(0, "missing 'delta' argument");
171 else if(!(q = dcgi_findtrack(id)))
172 error(0, "unknown queue id %s", id);
173 else switch(q->state) {
174 case playing_random: /* unplayed randomly chosen track */
175 case playing_unplayed: /* haven't played this track yet */
176 disorder_move(dcgi_client, id, atol(delta));
179 error(0, "does not make sense to scratch %s", id);
186 static void act_play(void) {
187 const char *track, *dir;
190 struct dcgi_entry *e;
193 if((track = cgi_get("track"))) {
194 disorder_play(dcgi_client, track);
195 } else if((dir = cgi_get("dir"))) {
196 if(disorder_files(dcgi_client, dir, 0, &tracks, &ntracks))
198 e = xmalloc(ntracks * sizeof (struct dcgi_entry));
199 for(n = 0; n < ntracks; ++n) {
200 e[n].track = tracks[n];
201 e[n].sort = trackname_transform("track", tracks[n], "sort");
202 e[n].display = trackname_transform("track", tracks[n], "display");
204 qsort(e, ntracks, sizeof (struct dcgi_entry), dcgi_compare_entry);
205 for(n = 0; n < ntracks; ++n)
206 disorder_play(dcgi_client, e[n].track);
212 static int clamp(int n, int min, int max) {
220 static void act_volume(void) {
221 const char *l, *r, *d;
225 if((d = cgi_get("delta"))) {
226 dcgi_lookup(DCGI_VOLUME);
227 nd = clamp(atoi(d), -255, 255);
228 disorder_set_volume(dcgi_client,
229 clamp(dcgi_volume_left + nd, 0, 255),
230 clamp(dcgi_volume_right + nd, 0, 255));
231 } else if((l = cgi_get("left")) && (r = cgi_get("right")))
232 disorder_set_volume(dcgi_client, atoi(l), atoi(r));
237 /** @brief Expand the login template with @b @@error set to @p error
238 * @param e Error keyword
240 static void login_error(const char *e) {
241 dcgi_error_string = e;
242 dcgi_expand("login", 1);
246 * @param username Login name
247 * @param password Password
248 * @return 0 on success, non-0 on error
250 * On error, calls login_error() to expand the login template.
252 static int login_as(const char *username, const char *password) {
255 if(dcgi_cookie && dcgi_client)
256 disorder_revoke(dcgi_client);
257 /* We'll need a new connection as we are going to stop being guest */
259 if(disorder_connect_user(c, username, password)) {
260 login_error("loginfailed");
263 /* Generate a cookie so we can log in again later */
264 if(disorder_make_cookie(c, &dcgi_cookie)) {
265 login_error("cookiefailed");
268 /* Use the new connection henceforth */
274 static void act_login(void) {
275 const char *username, *password;
277 /* We try all this even if not connected since the subsequent connection may
280 username = cgi_get("username");
281 password = cgi_get("password");
284 || !strcmp(username, "guest")/*bodge to avoid guest cookies*/) {
285 /* We're just visiting the login page, not performing an action at all. */
286 dcgi_expand("login", 1);
289 if(!login_as(username, password)) {
290 /* Report the succesful login */
291 dcgi_status_string = "loginok";
292 /* Redirect back to where we came from, if necessary */
296 dcgi_expand("login", 1);
300 static void act_logout(void) {
302 /* Ask the server to revoke the cookie */
303 if(!disorder_revoke(dcgi_client))
304 dcgi_status_string = "logoutok";
306 dcgi_error_string = "revokefailed";
308 /* We can't guarantee a logout if we can't connect to the server to revoke
309 * the cookie, so we report an error. We'll still ask the browser to
310 * forget the cookie though. */
311 dcgi_error_string = "connect";
313 /* Attempt to reconnect without the cookie */
316 /* Back to login page, hopefuly forcing the browser to forget the cookie. */
317 dcgi_expand("login", 1);
320 static void act_register(void) {
321 const char *username, *password, *password2, *email;
322 char *confirm, *content_type;
323 const char *text, *encoding, *charset;
325 /* If we're not connected then this is a hopeless exercise */
327 login_error("connect");
331 /* Collect arguments */
332 username = cgi_get("username");
333 password = cgi_get("password1");
334 password2 = cgi_get("password2");
335 email = cgi_get("email");
337 /* Verify arguments */
338 if(!username || !*username) {
339 login_error("nousername");
342 if(!password || !*password) {
343 login_error("nopassword");
346 if(!password2 || !*password2 || strcmp(password, password2)) {
347 login_error("passwordmismatch");
350 if(!email || !*email) {
351 login_error("noemail");
354 /* We could well do better address validation but for now we'll just do the
356 if(!strchr(email, '@')) {
357 login_error("bademail");
360 if(disorder_register(dcgi_client, username, password, email, &confirm)) {
361 login_error("cannotregister");
364 /* Send the user a mail */
365 /* TODO templatize this */
366 byte_xasprintf((char **)&text,
367 "Welcome to DisOrder. To active your login, please visit this URL:\n"
369 "%s?c=%s\n", config->url, urlencodestring(confirm));
370 if(!(text = mime_encode_text(text, &charset, &encoding)))
371 fatal(0, "cannot encode email");
372 byte_xasprintf(&content_type, "text/plain;charset=%s",
373 quote822(charset, 0));
374 sendmail("", config->mail_sender, email, "Welcome to DisOrder",
375 encoding, content_type, text); /* TODO error checking */
376 /* We'll go back to the login page with a suitable message */
377 dcgi_status_string = "registered";
378 dcgi_expand("login", 1);
381 static void act_confirm(void) {
382 const char *confirmation;
384 /* If we're not connected then this is a hopeless exercise */
386 login_error("connect");
390 if(!(confirmation = cgi_get("c"))) {
391 login_error("noconfirm");
394 /* Confirm our registration */
395 if(disorder_confirm(dcgi_client, confirmation)) {
396 login_error("badconfirm");
400 if(disorder_make_cookie(dcgi_client, &dcgi_cookie)) {
401 login_error("cookiefailed");
404 /* Junk cached data */
407 dcgi_status_string = "confirmed";
408 dcgi_expand("login", 1);
411 static void act_edituser(void) {
412 const char *email = cgi_get("email"), *password = cgi_get("changepassword1");
413 const char *password2 = cgi_get("changepassword2");
416 /* If we're not connected then this is a hopeless exercise */
418 login_error("connect");
424 /* If either password or password2 is set we insist they match. If they
425 * don't we report an error. */
426 if((password && *password) || (password2 && *password2)) {
427 if(!password || !password2 || strcmp(password, password2)) {
428 login_error("passwordmismatch");
432 password = password2 = 0;
433 if(email && !strchr(email, '@')) {
434 login_error("bademail");
440 if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
442 login_error("badedit");
447 if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
448 "password", password)) {
449 login_error("badedit");
456 /* If we changed the password, the cookie is now invalid, so we must log
458 if(login_as(disorder_user(dcgi_client), password))
462 dcgi_status_string = "edited";
463 dcgi_expand("login", 1);
466 static void act_reminder(void) {
467 const char *const username = cgi_get("username");
469 /* If we're not connected then this is a hopeless exercise */
471 login_error("connect");
475 if(!username || !*username) {
476 login_error("nousername");
479 if(disorder_reminder(dcgi_client, username)) {
480 login_error("reminderfailed");
484 dcgi_status_string = "reminded";
485 dcgi_expand("login", 1);
488 /** @brief Get the numbered version of an argument
489 * @param argname Base argument name
490 * @param numfile File number
491 * @return cgi_get(NUMFILE_ARGNAME)
493 static const char *numbered_arg(const char *argname, int numfile) {
496 byte_xasprintf(&fullname, "%d_%s", numfile, argname);
497 return cgi_get(fullname);
500 /** @brief Set preferences for file @p numfile
501 * @return 0 on success, -1 if there is no such track number
503 * The old @b nfiles parameter has been abolished, we just keep look for more
504 * files until we run out.
506 static int process_prefs(int numfile) {
507 const char *file, *name, *value, *part, *parts, *context;
510 if(!(file = numbered_arg("track", numfile)))
512 if(!(parts = cgi_get("parts")))
513 parts = "artist album title";
514 if(!(context = cgi_get("context")))
516 partslist = split(parts, 0, 0, 0, 0);
517 while((part = *partslist++)) {
518 if(!(value = numbered_arg(part, numfile)))
520 byte_xasprintf((char **)&name, "trackname_%s_%s", context, part);
521 disorder_set(dcgi_client, file, name, value);
523 if((value = numbered_arg("random", numfile)))
524 disorder_unset(dcgi_client, file, "pick_at_random");
526 disorder_set(dcgi_client, file, "pick_at_random", "0");
527 if((value = numbered_arg("tags", numfile))) {
529 disorder_unset(dcgi_client, file, "tags");
531 disorder_set(dcgi_client, file, "tags", value);
533 if((value = numbered_arg("weight", numfile))) {
535 disorder_unset(dcgi_client, file, "weight");
537 disorder_set(dcgi_client, file, "weight", value);
542 static void act_set(void) {
546 for(numfile = 0; !process_prefs(numfile); ++numfile)
552 /** @brief Table of actions */
553 static const struct action {
554 /** @brief Action name */
556 /** @brief Action handler */
557 void (*handler)(void);
558 /** @brief Union of suitable rights */
561 { "confirm", act_confirm, 0 },
562 { "disable", act_disable, RIGHT_GLOBAL_PREFS },
563 { "edituser", act_edituser, 0 },
564 { "enable", act_enable, RIGHT_GLOBAL_PREFS },
565 { "login", act_login, 0 },
566 { "logout", act_logout, 0 },
567 { "manage", act_playing, 0 },
568 { "move", act_move, RIGHT_MOVE__MASK },
569 { "pause", act_pause, RIGHT_PAUSE },
570 { "play", act_play, RIGHT_PLAY },
571 { "playing", act_playing, 0 },
572 { "randomdisable", act_random_disable, RIGHT_GLOBAL_PREFS },
573 { "randomenable", act_random_enable, RIGHT_GLOBAL_PREFS },
574 { "register", act_register, 0 },
575 { "reminder", act_reminder, 0 },
576 { "remove", act_remove, RIGHT_MOVE__MASK|RIGHT_SCRATCH__MASK },
577 { "resume", act_resume, RIGHT_PAUSE },
578 { "set", act_set, RIGHT_PREFS },
579 { "volume", act_volume, RIGHT_VOLUME },
582 /** @brief Check that an action name is valid
584 * @return 1 if valid, 0 if not
586 static int dcgi_valid_action(const char *name) {
589 /* First character must be letter or digit (this also requires there to _be_
590 * a first character) */
591 if(!isalnum((unsigned char)*name))
593 /* Only letters, digits, '.' and '-' allowed */
594 while((c = (unsigned char)*name++)) {
603 /** @brief Expand a template
604 * @param name Base name of template, or NULL to consult CGI args
605 * @param header True to write header
607 void dcgi_expand(const char *name, int header) {
608 const char *p, *found;
610 /* Parse macros first */
611 if((found = mx_find("macros.tmpl")))
612 mx_expand_file(found, sink_discard(), 0);
613 /* For unknown actions check that they aren't evil */
614 if(!dcgi_valid_action(name))
615 fatal(0, "invalid action name '%s'", name);
616 byte_xasprintf((char **)&p, "%s.tmpl", name);
617 if(!(found = mx_find(p)))
618 fatal(errno, "cannot find %s", p);
620 if(printf("Content-Type: text/html\n"
622 "\n", dcgi_cookie_header()) < 0)
623 fatal(errno, "error writing to stdout");
625 if(mx_expand_file(found, sink_stdio("stdout", stdout), 0) == -1
626 || fflush(stdout) < 0)
627 fatal(errno, "error writing to stdout");
630 /** @brief Execute a web action
631 * @param action Action to perform, or NULL to consult CGI args
633 * If no recognized action is specified then 'playing' is assumed.
635 void dcgi_action(const char *action) {
638 /* Consult CGI args if caller had no view */
640 action = cgi_get("action");
641 /* Pick a default if nobody cares at all */
643 /* We allow URLs which are just c=... in order to keep confirmation URLs,
644 * which are user-facing, as short as possible. Actually we could lose the
650 /* Make sure 'action' is always set */
651 cgi_set("action", action);
653 if((n = TABLE_FIND(actions, struct action, name, action)) >= 0) {
654 if(actions[n].rights) {
655 /* Some right or other is required */
656 dcgi_lookup(DCGI_RIGHTS);
657 if(!(actions[n].rights & dcgi_rights)) {
658 const char *back = cgi_thisurl(config->url);
659 /* Failed operations jump you to the login screen with an error
660 * message. On success, the user comes back to the page they were
663 cgi_set("back", back);
664 login_error("noright");
668 /* It's a known action */
669 actions[n].handler();
671 /* Just expand the template */
672 dcgi_expand(action, 1/*header*/);
676 /** @brief Generate an error page */
677 void dcgi_error(const char *key) {
678 dcgi_error_string = xstrdup(key);
679 dcgi_expand("error", 1);