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 error Error keyword
240 static void login_error(const char *error) {
241 dcgi_error_string = error;
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 dcgi_expand("login", 1);
296 static void act_logout(void) {
298 /* Ask the server to revoke the cookie */
299 if(!disorder_revoke(dcgi_client))
300 dcgi_status_string = "logoutok";
302 dcgi_error_string = "revokefailed";
304 /* We can't guarantee a logout if we can't connect to the server to revoke
305 * the cookie, so we report an error. We'll still ask the browser to
306 * forget the cookie though. */
307 dcgi_error_string = "connect";
309 /* Attempt to reconnect without the cookie */
312 /* Back to login page, hopefuly forcing the browser to forget the cookie. */
313 dcgi_expand("login", 1);
316 static void act_register(void) {
317 const char *username, *password, *password2, *email;
318 char *confirm, *content_type;
319 const char *text, *encoding, *charset;
321 /* If we're not connected then this is a hopeless exercise */
323 login_error("connect");
327 /* Collect arguments */
328 username = cgi_get("username");
329 password = cgi_get("password1");
330 password2 = cgi_get("password2");
331 email = cgi_get("email");
333 /* Verify arguments */
334 if(!username || !*username) {
335 login_error("nousername");
338 if(!password || !*password) {
339 login_error("nopassword");
342 if(!password2 || !*password2 || strcmp(password, password2)) {
343 login_error("passwordmismatch");
346 if(!email || !*email) {
347 login_error("noemail");
350 /* We could well do better address validation but for now we'll just do the
352 if(!strchr(email, '@')) {
353 login_error("bademail");
356 if(disorder_register(dcgi_client, username, password, email, &confirm)) {
357 login_error("cannotregister");
360 /* Send the user a mail */
361 /* TODO templatize this */
362 byte_xasprintf((char **)&text,
363 "Welcome to DisOrder. To active your login, please visit this URL:\n"
365 "%s?c=%s\n", config->url, urlencodestring(confirm));
366 if(!(text = mime_encode_text(text, &charset, &encoding)))
367 fatal(0, "cannot encode email");
368 byte_xasprintf(&content_type, "text/plain;charset=%s",
369 quote822(charset, 0));
370 sendmail("", config->mail_sender, email, "Welcome to DisOrder",
371 encoding, content_type, text); /* TODO error checking */
372 /* We'll go back to the login page with a suitable message */
373 dcgi_status_string = "registered";
374 dcgi_expand("login", 1);
377 static void act_confirm(void) {
378 const char *confirmation;
380 /* If we're not connected then this is a hopeless exercise */
382 login_error("connect");
386 if(!(confirmation = cgi_get("c"))) {
387 login_error("noconfirm");
390 /* Confirm our registration */
391 if(disorder_confirm(dcgi_client, confirmation)) {
392 login_error("badconfirm");
396 if(disorder_make_cookie(dcgi_client, &dcgi_cookie)) {
397 login_error("cookiefailed");
400 /* Junk cached data */
403 dcgi_status_string = "confirmed";
404 dcgi_expand("login", 1);
407 static void act_edituser(void) {
408 const char *email = cgi_get("email"), *password = cgi_get("changepassword1");
409 const char *password2 = cgi_get("changepassword2");
412 /* If we're not connected then this is a hopeless exercise */
414 login_error("connect");
420 /* If either password or password2 is set we insist they match. If they
421 * don't we report an error. */
422 if((password && *password) || (password2 && *password2)) {
423 if(!password || !password2 || strcmp(password, password2)) {
424 login_error("passwordmismatch");
428 password = password2 = 0;
429 if(email && !strchr(email, '@')) {
430 login_error("bademail");
436 if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
438 login_error("badedit");
443 if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
444 "password", password)) {
445 login_error("badedit");
452 /* If we changed the password, the cookie is now invalid, so we must log
454 if(login_as(disorder_user(dcgi_client), password))
458 dcgi_status_string = "edited";
459 dcgi_expand("login", 1);
462 static void act_reminder(void) {
463 const char *const username = cgi_get("username");
465 /* If we're not connected then this is a hopeless exercise */
467 login_error("connect");
471 if(!username || !*username) {
472 login_error("nousername");
475 if(disorder_reminder(dcgi_client, username)) {
476 login_error("reminderfailed");
480 dcgi_status_string = "reminded";
481 dcgi_expand("login", 1);
484 /** @brief Get the numbered version of an argument
485 * @param argname Base argument name
486 * @param numfile File number
487 * @return cgi_get(NUMFILE_ARGNAME)
489 static const char *numbered_arg(const char *argname, int numfile) {
492 byte_xasprintf(&fullname, "%d_%s", numfile, argname);
493 return cgi_get(fullname);
496 /** @brief Set preferences for file @p numfile
497 * @return 0 on success, -1 if there is no such track number
499 * The old @b nfiles parameter has been abolished, we just keep look for more
500 * files until we run out.
502 static int process_prefs(int numfile) {
503 const char *file, *name, *value, *part, *parts, *context;
506 if(!(file = numbered_arg("track", numfile)))
508 if(!(parts = cgi_get("parts")))
509 parts = "artist album title";
510 if(!(context = cgi_get("context")))
512 partslist = split(parts, 0, 0, 0, 0);
513 while((part = *partslist++)) {
514 if(!(value = numbered_arg(part, numfile)))
516 byte_xasprintf((char **)&name, "trackname_%s_%s", context, part);
517 disorder_set(dcgi_client, file, name, value);
519 if((value = numbered_arg("random", numfile)))
520 disorder_unset(dcgi_client, file, "pick_at_random");
522 disorder_set(dcgi_client, file, "pick_at_random", "0");
523 if((value = numbered_arg("tags", numfile))) {
525 disorder_unset(dcgi_client, file, "tags");
527 disorder_set(dcgi_client, file, "tags", value);
529 if((value = numbered_arg("weight", numfile))) {
531 disorder_unset(dcgi_client, file, "weight");
533 disorder_set(dcgi_client, file, "weight", value);
538 static void act_set(void) {
542 for(numfile = 0; !process_prefs(numfile); ++numfile)
548 /** @brief Table of actions */
549 static const struct action {
550 /** @brief Action name */
552 /** @brief Action handler */
553 void (*handler)(void);
554 /** @brief Union of suitable rights */
557 { "confirm", act_confirm, 0 },
558 { "disable", act_disable, RIGHT_GLOBAL_PREFS },
559 { "edituser", act_edituser, 0 },
560 { "enable", act_enable, RIGHT_GLOBAL_PREFS },
561 { "login", act_login, 0 },
562 { "logout", act_logout, 0 },
563 { "manage", act_playing, 0 },
564 { "move", act_move, RIGHT_MOVE__MASK },
565 { "pause", act_pause, RIGHT_PAUSE },
566 { "play", act_play, RIGHT_PLAY },
567 { "playing", act_playing, 0 },
568 { "randomdisable", act_random_disable, RIGHT_GLOBAL_PREFS },
569 { "randomenable", act_random_enable, RIGHT_GLOBAL_PREFS },
570 { "register", act_register, 0 },
571 { "reminder", act_reminder, 0 },
572 { "remove", act_remove, RIGHT_MOVE__MASK|RIGHT_SCRATCH__MASK },
573 { "resume", act_resume, RIGHT_PAUSE },
574 { "set", act_set, RIGHT_PREFS },
575 { "volume", act_volume, RIGHT_VOLUME },
578 /** @brief Check that an action name is valid
580 * @return 1 if valid, 0 if not
582 static int dcgi_valid_action(const char *name) {
585 /* First character must be letter or digit (this also requires there to _be_
586 * a first character) */
587 if(!isalnum((unsigned char)*name))
589 /* Only letters, digits, '.' and '-' allowed */
590 while((c = (unsigned char)*name++)) {
599 /** @brief Expand a template
600 * @param name Base name of template, or NULL to consult CGI args
601 * @param header True to write header
603 void dcgi_expand(const char *name, int header) {
604 const char *p, *found;
606 /* Parse macros first */
607 if((found = mx_find("macros.tmpl")))
608 mx_expand_file(found, sink_discard(), 0);
609 /* For unknown actions check that they aren't evil */
610 if(!dcgi_valid_action(name))
611 fatal(0, "invalid action name '%s'", name);
612 byte_xasprintf((char **)&p, "%s.tmpl", name);
613 if(!(found = mx_find(p)))
614 fatal(errno, "cannot find %s", p);
616 if(printf("Content-Type: text/html\n"
618 "\n", dcgi_cookie_header()) < 0)
619 fatal(errno, "error writing to stdout");
621 if(mx_expand_file(found, sink_stdio("stdout", stdout), 0) == -1
622 || fflush(stdout) < 0)
623 fatal(errno, "error writing to stdout");
626 /** @brief Execute a web action
627 * @param action Action to perform, or NULL to consult CGI args
629 * If no recognized action is specified then 'playing' is assumed.
631 void dcgi_action(const char *action) {
634 /* Consult CGI args if caller had no view */
636 action = cgi_get("action");
637 /* Pick a default if nobody cares at all */
639 /* We allow URLs which are just c=... in order to keep confirmation URLs,
640 * which are user-facing, as short as possible. Actually we could lose the
646 /* Make sure 'action' is always set */
647 cgi_set("action", action);
649 if((n = TABLE_FIND(actions, struct action, name, action)) >= 0) {
650 if(actions[n].rights) {
651 /* Some right or other is required */
652 dcgi_lookup(DCGI_RIGHTS);
653 if(!(actions[n].rights & dcgi_rights)) {
654 /* Failed operations jump you to the login screen with an error
656 login_error("noright");
660 /* It's a known action */
661 actions[n].handler();
663 /* Just expand the template */
664 dcgi_expand(action, 1/*header*/);
668 /** @brief Generate an error page */
669 void dcgi_error(const char *key) {
670 dcgi_error_string = xstrdup(key);
671 dcgi_expand("error", 1);