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");
52 * Expands \fIplaying.tmpl\fR as if there was no special 'playing' action, but
53 * adds a Refresh: field to the HTTP header. The maximum refresh interval is
54 * defined by \fBrefresh\fR (see \fBdisorder_config\fR(5)) but may be less if
55 * the end of the track is near.
59 * Expands \fIplaying.tmpl\fR (NB not \fImanage.tmpl\fR) as if there was no
60 * special 'playing' action, and adds a Refresh: field to the HTTP header. The
61 * maximum refresh interval is defined by \Bfrefresh\fR (see
62 * \fBdisorder_config\fR(5)) but may be less if the end of the track is near.
64 static void act_playing(void) {
65 long refresh
= config
->refresh
;
71 dcgi_lookup(DCGI_PLAYING
|DCGI_QUEUE
|DCGI_ENABLED
|DCGI_RANDOM_ENABLED
);
73 && dcgi_playing
->state
== playing_started
/* i.e. not paused */
74 && !disorder_length(dcgi_client
, dcgi_playing
->track
, &length
)
76 && dcgi_playing
->sofar
>= 0) {
77 /* Try to put the next refresh at the start of the next track. */
79 fin
= now
+ length
- dcgi_playing
->sofar
+ config
->gap
;
80 if(now
+ refresh
> fin
)
83 if(dcgi_queue
&& dcgi_queue
->state
== playing_isscratch
) {
84 /* next track is a scratch, don't leave more than the inter-track gap */
85 if(refresh
> config
->gap
)
86 refresh
= config
->gap
;
90 && dcgi_queue
->state
!= playing_random
)
91 || dcgi_random_enabled
)
93 /* no track playing but playing is enabled and there is something coming
94 * up, must be in a gap */
95 if(refresh
> config
->gap
)
96 refresh
= config
->gap
;
98 if((action
= cgi_get("action")))
99 url
= cgi_makeurl(config
->url
, "action", action
, (char *)0);
102 if(printf("Refresh: %ld;url=%s\n",
104 fatal(errno
, "error writing to stdout");
105 dcgi_expand("playing", 1);
112 static void act_disable(void) {
114 disorder_disable(dcgi_client
);
122 static void act_enable(void) {
124 disorder_enable(dcgi_client
);
130 * Disables random play.
132 static void act_random_disable(void) {
134 disorder_random_disable(dcgi_client
);
140 * Enables random play.
142 static void act_random_enable(void) {
144 disorder_random_enable(dcgi_client
);
150 * Pauses the current track (if there is one and it's not paused already).
152 static void act_pause(void) {
154 disorder_pause(dcgi_client
);
160 * Resumes the current track (if there is one and it's paused).
162 static void act_resume(void) {
164 disorder_resume(dcgi_client
);
170 * Removes the track given by the \fBid\fR argument. If this is the currently
171 * playing track then it is scratched.
173 static void act_remove(void) {
175 struct queue_entry
*q
;
178 if(!(id
= cgi_get("id")))
179 error(0, "missing 'id' argument");
180 else if(!(q
= dcgi_findtrack(id
)))
181 error(0, "unknown queue id %s", id
);
182 else switch(q
->state
) {
183 case playing_isscratch
:
185 case playing_no_player
:
187 case playing_quitting
:
188 case playing_scratched
:
189 error(0, "does not make sense to scratch %s", id
);
191 case playing_paused
: /* started but paused */
192 case playing_started
: /* started to play */
193 disorder_scratch(dcgi_client
, id
);
195 case playing_random
: /* unplayed randomly chosen track */
196 case playing_unplayed
: /* haven't played this track yet */
197 disorder_remove(dcgi_client
, id
);
206 * Moves the track given by the \fBid\fR argument the distance given by the
207 * \fBdelta\fR argument. If this is positive the track is moved earlier in the
208 * queue and if negative, later.
210 static void act_move(void) {
211 const char *id
, *delta
;
212 struct queue_entry
*q
;
215 if(!(id
= cgi_get("id")))
216 error(0, "missing 'id' argument");
217 else if(!(delta
= cgi_get("delta")))
218 error(0, "missing 'delta' argument");
219 else if(!(q
= dcgi_findtrack(id
)))
220 error(0, "unknown queue id %s", id
);
221 else switch(q
->state
) {
222 case playing_random
: /* unplayed randomly chosen track */
223 case playing_unplayed
: /* haven't played this track yet */
224 disorder_move(dcgi_client
, id
, atol(delta
));
227 error(0, "does not make sense to scratch %s", id
);
236 * Play the track given by the \fBtrack\fR argument, or if that is not set all
237 * the tracks in the directory given by the \fBdir\fR argument.
239 static void act_play(void) {
240 const char *track
, *dir
;
243 struct dcgi_entry
*e
;
246 if((track
= cgi_get("track"))) {
247 disorder_play(dcgi_client
, track
);
248 } else if((dir
= cgi_get("dir"))) {
249 if(disorder_files(dcgi_client
, dir
, 0, &tracks
, &ntracks
))
251 e
= xmalloc(ntracks
* sizeof (struct dcgi_entry
));
252 for(n
= 0; n
< ntracks
; ++n
) {
253 e
[n
].track
= tracks
[n
];
254 e
[n
].sort
= trackname_transform("track", tracks
[n
], "sort");
255 e
[n
].display
= trackname_transform("track", tracks
[n
], "display");
257 qsort(e
, ntracks
, sizeof (struct dcgi_entry
), dcgi_compare_entry
);
258 for(n
= 0; n
< ntracks
; ++n
)
259 disorder_play(dcgi_client
, e
[n
].track
);
265 static int clamp(int n
, int min
, int max
) {
275 * If the \fBdelta\fR argument is set: adjust both channels by that amount (up
276 * if positive, down if negative).
278 * Otherwise if \fBleft\fR and \fBright\fR are set, set the channels
279 * independently to those values.
281 static void act_volume(void) {
282 const char *l
, *r
, *d
;
286 if((d
= cgi_get("delta"))) {
287 dcgi_lookup(DCGI_VOLUME
);
288 nd
= clamp(atoi(d
), -255, 255);
289 disorder_set_volume(dcgi_client
,
290 clamp(dcgi_volume_left
+ nd
, 0, 255),
291 clamp(dcgi_volume_right
+ nd
, 0, 255));
292 } else if((l
= cgi_get("left")) && (r
= cgi_get("right")))
293 disorder_set_volume(dcgi_client
, atoi(l
), atoi(r
));
298 /** @brief Expand the login template with @b @@error set to @p error
299 * @param e Error keyword
301 static void login_error(const char *e
) {
302 dcgi_error_string
= e
;
303 dcgi_expand("login", 1);
307 * @param username Login name
308 * @param password Password
309 * @return 0 on success, non-0 on error
311 * On error, calls login_error() to expand the login template.
313 static int login_as(const char *username
, const char *password
) {
316 if(dcgi_cookie
&& dcgi_client
)
317 disorder_revoke(dcgi_client
);
318 /* We'll need a new connection as we are going to stop being guest */
320 if(disorder_connect_user(c
, username
, password
)) {
321 login_error("loginfailed");
324 /* Generate a cookie so we can log in again later */
325 if(disorder_make_cookie(c
, &dcgi_cookie
)) {
326 login_error("cookiefailed");
329 /* Use the new connection henceforth */
337 * If \fBusername\fR and \fBpassword\fR are set (and the username isn't
338 * "guest") then attempt to log in using those credentials. On success,
339 * redirects to the \fBback\fR argument if that is set, or just expands
340 * \fIlogin.tmpl\fI otherwise, with \fB@status\fR set to \fBloginok\fR.
342 * If they aren't set then just expands \fIlogin.tmpl\fI.
344 static void act_login(void) {
345 const char *username
, *password
;
347 /* We try all this even if not connected since the subsequent connection may
350 username
= cgi_get("username");
351 password
= cgi_get("password");
354 || !strcmp(username
, "guest")/*bodge to avoid guest cookies*/) {
355 /* We're just visiting the login page, not performing an action at all. */
356 dcgi_expand("login", 1);
359 if(!login_as(username
, password
)) {
360 /* Report the succesful login */
361 dcgi_status_string
= "loginok";
362 /* Redirect back to where we came from, if necessary */
366 dcgi_expand("login", 1);
372 * Logs out the current user and expands \fIlogin.tmpl\fR with \fBstatus\fR or
373 * \fB@error\fR set according to the result.
375 static void act_logout(void) {
377 /* Ask the server to revoke the cookie */
378 if(!disorder_revoke(dcgi_client
))
379 dcgi_status_string
= "logoutok";
381 dcgi_error_string
= "revokefailed";
383 /* We can't guarantee a logout if we can't connect to the server to revoke
384 * the cookie, so we report an error. We'll still ask the browser to
385 * forget the cookie though. */
386 dcgi_error_string
= "connect";
388 /* Attempt to reconnect without the cookie */
391 /* Back to login page, hopefuly forcing the browser to forget the cookie. */
392 dcgi_expand("login", 1);
397 * Register a new user using \fBusername\fR, \fBpassword1\fR, \fBpassword2\fR
398 * and \fBemail\fR and expands \fIlogin.tmpl\fR with \fBstatus\fR or
399 * \fB@error\fR set according to the result.
401 static void act_register(void) {
402 const char *username
, *password
, *password2
, *email
;
403 char *confirm
, *content_type
;
404 const char *text
, *encoding
, *charset
;
406 /* If we're not connected then this is a hopeless exercise */
408 login_error("connect");
412 /* Collect arguments */
413 username
= cgi_get("username");
414 password
= cgi_get("password1");
415 password2
= cgi_get("password2");
416 email
= cgi_get("email");
418 /* Verify arguments */
419 if(!username
|| !*username
) {
420 login_error("nousername");
423 if(!password
|| !*password
) {
424 login_error("nopassword");
427 if(!password2
|| !*password2
|| strcmp(password
, password2
)) {
428 login_error("passwordmismatch");
431 if(!email
|| !*email
) {
432 login_error("noemail");
435 /* We could well do better address validation but for now we'll just do the
437 if(!strchr(email
, '@')) {
438 login_error("bademail");
441 if(disorder_register(dcgi_client
, username
, password
, email
, &confirm
)) {
442 login_error("cannotregister");
445 /* Send the user a mail */
446 /* TODO templatize this */
447 byte_xasprintf((char **)&text
,
448 "Welcome to DisOrder. To active your login, please visit this URL:\n"
450 "%s?c=%s\n", config
->url
, urlencodestring(confirm
));
451 if(!(text
= mime_encode_text(text
, &charset
, &encoding
)))
452 fatal(0, "cannot encode email");
453 byte_xasprintf(&content_type
, "text/plain;charset=%s",
454 quote822(charset
, 0));
455 sendmail("", config
->mail_sender
, email
, "Welcome to DisOrder",
456 encoding
, content_type
, text
); /* TODO error checking */
457 /* We'll go back to the login page with a suitable message */
458 dcgi_status_string
= "registered";
459 dcgi_expand("login", 1);
464 * Confirm a user registration using the nonce supplied in \fBc\fR and expands
465 * \fIlogin.tmpl\fR with \fBstatus\fR or \fB@error\fR set according to the
468 static void act_confirm(void) {
469 const char *confirmation
;
471 /* If we're not connected then this is a hopeless exercise */
473 login_error("connect");
477 if(!(confirmation
= cgi_get("c"))) {
478 login_error("noconfirm");
481 /* Confirm our registration */
482 if(disorder_confirm(dcgi_client
, confirmation
)) {
483 login_error("badconfirm");
487 if(disorder_make_cookie(dcgi_client
, &dcgi_cookie
)) {
488 login_error("cookiefailed");
491 /* Junk cached data */
494 dcgi_status_string
= "confirmed";
495 dcgi_expand("login", 1);
500 * Edit user details using \fBusername\fR, \fBchangepassword1\fR,
501 * \fBchangepassword2\fR and \fBemail\fR and expands \fIlogin.tmpl\fR with
502 * \fBstatus\fR or \fB@error\fR set according to the result.
504 static void act_edituser(void) {
505 const char *email
= cgi_get("email"), *password
= cgi_get("changepassword1");
506 const char *password2
= cgi_get("changepassword2");
509 /* If we're not connected then this is a hopeless exercise */
511 login_error("connect");
517 /* If either password or password2 is set we insist they match. If they
518 * don't we report an error. */
519 if((password
&& *password
) || (password2
&& *password2
)) {
520 if(!password
|| !password2
|| strcmp(password
, password2
)) {
521 login_error("passwordmismatch");
525 password
= password2
= 0;
526 if(email
&& !strchr(email
, '@')) {
527 login_error("bademail");
533 if(disorder_edituser(dcgi_client
, disorder_user(dcgi_client
),
535 login_error("badedit");
540 if(disorder_edituser(dcgi_client
, disorder_user(dcgi_client
),
541 "password", password
)) {
542 login_error("badedit");
549 /* If we changed the password, the cookie is now invalid, so we must log
551 if(login_as(disorder_user(dcgi_client
), password
))
555 dcgi_status_string
= "edited";
556 dcgi_expand("login", 1);
561 * Issue an email password reminder to \fBusername\fR and expands
562 * \fIlogin.tmpl\fR with \fBstatus\fR or \fB@error\fR set according to the
565 static void act_reminder(void) {
566 const char *const username
= cgi_get("username");
568 /* If we're not connected then this is a hopeless exercise */
570 login_error("connect");
574 if(!username
|| !*username
) {
575 login_error("nousername");
578 if(disorder_reminder(dcgi_client
, username
)) {
579 login_error("reminderfailed");
583 dcgi_status_string
= "reminded";
584 dcgi_expand("login", 1);
587 /** @brief Get the numbered version of an argument
588 * @param argname Base argument name
589 * @param numfile File number
590 * @return cgi_get(NUMFILE_ARGNAME)
592 static const char *numbered_arg(const char *argname
, int numfile
) {
595 byte_xasprintf(&fullname
, "%d_%s", numfile
, argname
);
596 return cgi_get(fullname
);
599 /** @brief Set preferences for file @p numfile
600 * @return 0 on success, -1 if there is no such track number
602 * The old @b nfiles parameter has been abolished, we just keep look for more
603 * files until we run out.
605 static int process_prefs(int numfile
) {
606 const char *file
, *name
, *value
, *part
, *parts
, *context
;
609 if(!(file
= numbered_arg("track", numfile
)))
611 if(!(parts
= cgi_get("parts")))
612 parts
= "artist album title";
613 if(!(context
= cgi_get("context")))
615 partslist
= split(parts
, 0, 0, 0, 0);
616 while((part
= *partslist
++)) {
617 if(!(value
= numbered_arg(part
, numfile
)))
619 byte_xasprintf((char **)&name
, "trackname_%s_%s", context
, part
);
620 disorder_set(dcgi_client
, file
, name
, value
);
622 if((value
= numbered_arg("random", numfile
)))
623 disorder_unset(dcgi_client
, file
, "pick_at_random");
625 disorder_set(dcgi_client
, file
, "pick_at_random", "0");
626 if((value
= numbered_arg("tags", numfile
))) {
628 disorder_unset(dcgi_client
, file
, "tags");
630 disorder_set(dcgi_client
, file
, "tags", value
);
632 if((value
= numbered_arg("weight", numfile
))) {
634 disorder_unset(dcgi_client
, file
, "weight");
636 disorder_set(dcgi_client
, file
, "weight", value
);
643 * Set preferences on a number of tracks.
645 * The tracks to modify are specified in arguments \fB0_track\fR, \fB1_track\fR
646 * etc. The number sequence must be contiguous and start from 0.
648 * For each track \fIINDEX\fB_track\fR:
649 * - \fIINDEX\fB_\fIPART\fR is used to set the trackname preference for
650 * that part. (See \fBparts\fR below.)
651 * - \fIINDEX\fB_\fIrandom\fR if present enables random play for this track
652 * or disables it if absent.
653 * - \fIINDEX\fB_\fItags\fR sets the list of tags for this track.
654 * - \fIINDEX\fB_\fIweight\fR sets the weight for this track.
656 * \fBparts\fR can be set to the track name parts to modify. The default is
657 * "artist album title".
659 * \fBcontext\fR can be set to the context to modify. The default is
662 * If the server detects a preference being set to its default, it removes the
663 * preference, thus keeping the database tidy.
665 static void act_set(void) {
669 for(numfile
= 0; !process_prefs(numfile
); ++numfile
)
675 /** @brief Table of actions */
676 static const struct action
{
677 /** @brief Action name */
679 /** @brief Action handler */
680 void (*handler
)(void);
681 /** @brief Union of suitable rights */
684 { "confirm", act_confirm
, 0 },
685 { "disable", act_disable
, RIGHT_GLOBAL_PREFS
},
686 { "edituser", act_edituser
, 0 },
687 { "enable", act_enable
, RIGHT_GLOBAL_PREFS
},
688 { "login", act_login
, 0 },
689 { "logout", act_logout
, 0 },
690 { "manage", act_playing
, 0 },
691 { "move", act_move
, RIGHT_MOVE__MASK
},
692 { "pause", act_pause
, RIGHT_PAUSE
},
693 { "play", act_play
, RIGHT_PLAY
},
694 { "playing", act_playing
, 0 },
695 { "randomdisable", act_random_disable
, RIGHT_GLOBAL_PREFS
},
696 { "randomenable", act_random_enable
, RIGHT_GLOBAL_PREFS
},
697 { "register", act_register
, 0 },
698 { "reminder", act_reminder
, 0 },
699 { "remove", act_remove
, RIGHT_MOVE__MASK
|RIGHT_SCRATCH__MASK
},
700 { "resume", act_resume
, RIGHT_PAUSE
},
701 { "set", act_set
, RIGHT_PREFS
},
702 { "volume", act_volume
, RIGHT_VOLUME
},
705 /** @brief Check that an action name is valid
707 * @return 1 if valid, 0 if not
709 static int dcgi_valid_action(const char *name
) {
712 /* First character must be letter or digit (this also requires there to _be_
713 * a first character) */
714 if(!isalnum((unsigned char)*name
))
716 /* Only letters, digits, '.' and '-' allowed */
717 while((c
= (unsigned char)*name
++)) {
726 /** @brief Expand a template
727 * @param name Base name of template, or NULL to consult CGI args
728 * @param header True to write header
730 void dcgi_expand(const char *name
, int header
) {
731 const char *p
, *found
;
733 /* Parse macros first */
734 if((found
= mx_find("macros.tmpl", 1/*report*/)))
735 mx_expand_file(found
, sink_discard(), 0);
736 if((found
= mx_find("user.tmpl", 0/*report*/)))
737 mx_expand_file(found
, sink_discard(), 0);
738 /* For unknown actions check that they aren't evil */
739 if(!dcgi_valid_action(name
))
740 fatal(0, "invalid action name '%s'", name
);
741 byte_xasprintf((char **)&p
, "%s.tmpl", name
);
742 if(!(found
= mx_find(p
, 0/*report*/)))
743 fatal(errno
, "cannot find %s", p
);
745 if(printf("Content-Type: text/html\n"
747 "\n", dcgi_cookie_header()) < 0)
748 fatal(errno
, "error writing to stdout");
750 if(mx_expand_file(found
, sink_stdio("stdout", stdout
), 0) == -1
751 || fflush(stdout
) < 0)
752 fatal(errno
, "error writing to stdout");
755 /** @brief Execute a web action
756 * @param action Action to perform, or NULL to consult CGI args
758 * If no recognized action is specified then 'playing' is assumed.
760 void dcgi_action(const char *action
) {
763 /* Consult CGI args if caller had no view */
765 action
= cgi_get("action");
766 /* Pick a default if nobody cares at all */
768 /* We allow URLs which are just c=... in order to keep confirmation URLs,
769 * which are user-facing, as short as possible. Actually we could lose the
775 /* Make sure 'action' is always set */
776 cgi_set("action", action
);
778 if((n
= TABLE_FIND(actions
, name
, action
)) >= 0) {
779 if(actions
[n
].rights
) {
780 /* Some right or other is required */
781 dcgi_lookup(DCGI_RIGHTS
);
782 if(!(actions
[n
].rights
& dcgi_rights
)) {
783 const char *back
= cgi_thisurl(config
->url
);
784 /* Failed operations jump you to the login screen with an error
785 * message. On success, the user comes back to the page they were
788 cgi_set("back", back
);
789 login_error("noright");
793 /* It's a known action */
794 actions
[n
].handler();
796 /* Just expand the template */
797 dcgi_expand(action
, 1/*header*/);
801 /** @brief Generate an error page */
802 void dcgi_error(const char *key
) {
803 dcgi_error_string
= xstrdup(key
);
804 dcgi_expand("error", 1);