chiark / gitweb /
6bf9126076a72533486797c03b54df0ff0f4fa8e
[disorder] / scripts / protocol
1 #! /usr/bin/perl -w
2 #
3 # This file is part of DisOrder.
4 # Copyright (C) 2010-11 Richard Kettlewell
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 use strict;
20
21 # This file contains the definition of the disorder protocol, plus
22 # code to generates stubs for it in the various supported languages.
23 #
24 # At the time of writing it is a work in progress!
25
26 #
27 # Types:
28 #
29 #    string         A (Unicode) string.
30 #    integer        An integer.  Decimal on the wire.
31 #    boolean        True or false.  "yes" or "no" on the wire.
32 #    list           In commands: a list of strings in the command.
33 #                   In returns: a list of lines in the response.
34 #    pair-list      In returns: a list of key-value pairs in a response body.
35 #    body           In commands: a list of strings as a command body.
36 #                   In returns: a list of strings as a response body.
37 #    queue          In returns: a list of queue entries in a response body.
38 #    queue-one      In returns: a queue entry in the response.
39 #
40
41 # Variables and utilities -----------------------------------------------------
42
43 our @h = ();
44 our @c = ();
45
46 # Write(PATH, LINES)
47 #
48 # Write array ref LINES to file PATH.
49 sub Write {
50     my $path = shift;
51     my $lines = shift;
52
53     (open(F, ">$path")
54      and print F @$lines
55      and close F)
56         or die "$0: $path: $!\n";
57 }
58
59 # Command classes -------------------------------------------------------------
60
61 # c_in_decl([TYPE, NAME])
62 #
63 # Return the C declaration for an input parameter of type TYPE with
64 # name NAME.
65 sub c_in_decl {
66     my $arg = shift;
67
68     my $type = $arg->[0];
69     my $name = $arg->[1];
70     if($type eq 'string') {
71         return "const char *$name";
72     } elsif($type eq 'integer') {
73         return "long $name";
74     } elsif($type eq 'list' or $type eq 'body') {
75         return ("char **$name",
76                 "int n$name");
77     } else {
78         die "$0: c_in_decl: unknown type '$type'\n";
79     }
80 }
81
82 # c_out_decl([TYPE, NAME])
83 #
84 # Return the C declaration for an output (reference) parameter of type
85 # TYPE with name NAME.
86 sub c_out_decl {
87     my $arg = shift;
88
89     return () unless defined $arg;
90     my $type = $arg->[0];
91     my $name = $arg->[1];
92     if($type eq 'string') {
93         return ("char **${name}p");
94     } elsif($type eq 'integer') {
95         return ("long *${name}p");
96     } elsif($type eq 'boolean') {
97         return ("int *${name}p");
98     } elsif($type eq 'list' or $type eq 'body') {
99         return ("char ***${name}p",
100                 "int *n${name}p");
101     } elsif($type eq 'pair-list') {
102         return ("struct kvp **${name}p");
103     } elsif($type eq 'queue' or $type eq 'queue-one') {
104         return ("struct queue_entry **${name}p");
105     } elsif($type eq 'user') {
106         return ();
107     } else {
108         die "$0: c_out_decl: unknown type '$type'\n";
109     }
110 }
111
112 # c_param_docs([TYPE, NAME})
113 #
114 # Return the doc string for a C input parameter.
115 sub c_param_docs {
116     my $args = shift;
117     my @d = ();
118     for my $arg (@$args) {
119         if($arg->[0] eq 'body' or $arg->[0] eq 'list') {
120             push(@d,
121                  " * \@param $arg->[1] $arg->[2]\n",
122                  " * \@param n$arg->[1] Length of $arg->[1]\n");
123         } else {
124             push(@d, " * \@param $arg->[1] $arg->[2]\n");
125         }
126     }
127     return @d;
128 }
129
130 # c_param_docs([TYPE, NAME})
131 #
132 # Return the doc string for a C output parameter.
133 sub c_return_docs {
134     my $return = shift;
135     return () unless defined $return;
136     my $type = $return->[0];
137     my $name = $return->[1];
138     my $descr = $return->[2];
139     if($type eq 'string'
140        or $type eq 'integer'
141        or $type eq 'boolean') {
142         return (" * \@param ${name}p $descr\n");
143     } elsif($type eq 'list' or $type eq 'body') {
144         return (" * \@param ${name}p $descr\n",
145                 " * \@param n${name}p Number of elements in ${name}p\n");
146     } elsif($type eq 'pair-list') {
147         return (" * \@param ${name}p $descr\n");
148     } elsif($type eq 'queue' or $type eq 'queue-one') {
149         return (" * \@param ${name}p $descr\n");
150     } elsif($type eq 'user') {
151         return ();
152     } else {
153         die "$0: c_return_docs: unknown type '$type'\n";
154     }
155 }
156
157 # simple(CMD, SUMMARY, DETAIL,
158 #        [[TYPE,NAME,DESCR], [TYPE,NAME,DESCR], ...],
159 #        [RETURN-TYPE, RETURN-NAME, RETURN_DESCR])
160 #
161 # CMD is normally just the name of the command, but can
162 # be [COMMAND,FUNCTION] if the function name should differ
163 # from the protocol command.
164 sub simple {
165     my $cmd = shift;
166     my $summary = shift;
167     my $detail = shift;
168     my $args = shift;
169     my $return = shift;
170
171     my $cmdc;
172     if(ref $cmd eq 'ARRAY') {
173         $cmdc = $$cmd[1];
174         $cmd = $$cmd[0];
175     } else {
176         $cmdc = $cmd;
177         $cmdc =~ s/-/_/g;
178     }
179     print STDERR "Processing $cmd... ";
180     # Synchronous C API
181     print STDERR "H ";
182     push(@h, "/** \@brief $summary\n",
183          " *\n",
184          " * $detail\n",
185          " *\n",
186          " * \@param c Client\n",
187          c_param_docs($args),
188          c_return_docs($return),
189          " * \@return 0 on success, non-0 on error\n",
190          " */\n",
191          "int disorder_$cmdc(",
192          join(", ", "disorder_client *c",
193                     map(c_in_decl($_), @$args),
194                     c_out_decl($return)),
195          ");\n\n");
196     print STDERR "C ";
197     push(@c, "int disorder_$cmdc(",
198          join(", ", "disorder_client *c",
199                     map(c_in_decl($_), @$args),
200                     c_out_decl($return)),
201          ") {\n");
202     my @cargs = ();
203     for my $arg (@$args) {
204         if($arg->[0] eq 'body' or $arg->[0] eq 'list') {
205             push(@cargs, "disorder_$arg->[0]", $arg->[1], "n$arg->[1]");
206         } elsif($arg->[0] eq 'string') {
207             push(@cargs, $arg->[1]);
208         } elsif($arg->[0] eq 'integer') {
209             push(@cargs, "buf_$arg->[1]");
210             push(@c, "  char buf_$arg->[1]\[16];\n",
211                  "  byte_snprintf(buf_$arg->[1], sizeof buf_$arg->[1], \"%ld\", $arg->[1]);\n");
212         } else {
213             die "$0: unsupported arg type '$arg->[0]' for '$cmd'\n";
214         }
215     }
216     if(!defined $return) {
217         push(@c, "  return disorder_simple(",
218              join(", ", "c", 0, "\"$cmd\"", @cargs, "(char *)0"),
219              ");\n");
220     } elsif($return->[0] eq 'string') {
221         push(@c, "  return dequote(disorder_simple(c, $return->[1]p, \"$cmd\"",
222              map(", $_", @cargs),
223              ", (char *)0), $return->[1]p);\n");
224     } elsif($return->[0] eq 'boolean') {
225         push(@c, "  char *v;\n",
226              "  int rc;\n",
227              "  if((rc = disorder_simple(c, &v, \"$cmd\"",
228              map(", $_", @cargs),
229              ", (char *)0)))\n",
230              "    return rc;\n",
231              "  return boolean(\"$cmd\", v, $return->[1]p);\n");
232     } elsif($return->[0] eq 'integer') {
233         push(@c, "  char *v;\n",
234              "  int rc;\n",
235              "\n",
236              "  if((rc = disorder_simple(c, &v, \"$cmd\"",
237              map(", $_", @cargs),
238              ", (char *)0)))\n",
239              "    return rc;\n",
240              "  *$return->[1]p = atol(v);\n",
241              "  xfree(v);\n",
242              "  return 0;\n");
243     } elsif($return->[0] eq 'user') {
244         push(@c, "  char *u;\n",
245              "  int rc;\n",
246              "  if((rc = disorder_simple(c, &u, \"$cmd\"",
247              map(", $_", @cargs),
248              "  )))\n",
249              "    return rc;\n",
250              "  c->user = u;\n",
251              "  return 0;\n");
252     } elsif($return->[0] eq 'body') {
253         push(@c, "  return disorder_simple_list(c, $return->[1]p, n$return->[1]p, \"$cmd\"",
254              map(", $_", @cargs),
255              ", (char *)0);\n");
256     } elsif($return->[0] eq 'queue') {
257         push(@c, "  return somequeue(c, \"$cmd\", $return->[1]p);\n");
258     } elsif($return->[0] eq 'queue-one') {
259         push(@c, "  return onequeue(c, \"$cmd\", $return->[1]p);\n");
260     } elsif($return->[0] eq 'pair-list') {
261         push(@c, "  return pairlist(c, $return->[1]p, \"$cmd\"",
262              map(", $_", @cargs), ", (char *)0);\n");
263     } else {
264         die "$0: C API: unknown type '$return->[0]' for '$cmd'\n";
265     }
266     push(@c, "}\n\n");
267
268     # Asynchronous C API
269     # TODO
270
271     # Python API
272     # TODO
273
274     # Java API
275     # TODO
276     print STDERR "\n";
277 }
278
279 # TODO other command classes
280
281 # Front matter ----------------------------------------------------------------
282
283 our @generated = ("/*\n",
284                   " * Automatically generated file, see scripts/protocol\n",
285                   " *\n",
286                   " * DO NOT EDIT.\n",
287                   " */\n");
288
289 our @gpl = ("/*\n",
290             " * This file is part of DisOrder.\n",
291             " * Copyright (C) 2010-11 Richard Kettlewell\n",
292             " *\n",
293             " * This program is free software: you can redistribute it and/or modify\n",
294             " * it under the terms of the GNU General Public License as published by\n",
295             " * the Free Software Foundation, either version 3 of the License, or\n",
296             " * (at your option) any later version.\n",
297             " *\n",
298             " * This program is distributed in the hope that it will be useful,\n",
299             " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n",
300             " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n",
301             " * GNU General Public License for more details.\n",
302             " *\n",
303             " * You should have received a copy of the GNU General Public License\n",
304             " * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n",
305             " */\n");
306
307
308 push(@h, @generated, @gpl,
309      "#ifndef CLIENT_STUBS_H\n",
310      "#define CLIENT_STUBS_H\n",
311      "\n");
312
313 push(@c, @generated, @gpl,
314      "\n");
315
316 # The protocol ----------------------------------------------------------------
317
318 simple("adopt",
319        "Adopt a track",
320        "Makes the calling user owner of a randomly picked track.",
321        [["string", "id", "Track ID"]]);
322
323 simple("adduser",
324        "Create a user",
325        "Create a new user.  Requires the 'admin' right.  Email addresses etc must be filled in in separate commands.",
326        [["string", "user", "New username"],
327         ["string", "password", "Initial password"],
328         ["string", "rights", "Initial rights (optional)"]]);
329
330 simple("allfiles",
331        "List files and directories in a directory",
332        "See 'files' and 'dirs' for more specific lists.",
333        [["string", "dir", "Directory to list (optional)"],
334         ["string", "re", "Regexp that results must match (optional)"]],
335        ["body", "files", "List of matching files and directories"]);
336
337 simple("confirm",
338        "Confirm registration",
339        "The confirmation string must have been created with 'register'.  The username is returned so the caller knows who they are.",
340        [["string", "confirmation", "Confirmation string"]],
341        ["user"]);
342
343 simple("cookie",
344        "Log in with a cookie",
345        "The cookie must have been created with 'make-cookie'.  The username is returned so the caller knows who they are.",
346        [["string", "cookie", "Cookie string"]],
347        ["user"]);
348
349 simple("deluser",
350        "Delete user",
351        "Requires the 'admin' right.",
352        [["string", "user", "User to delete"]]);
353
354 simple("dirs",
355        "List directories in a directory",
356        "",
357        [["string", "dir", "Directory to list (optional)"],
358         ["string", "re", "Regexp that results must match (optional)"]],
359        ["body", "files", "List of matching directories"]);
360
361 simple("disable",
362        "Disable play",
363        "Play will stop at the end of the current track, if one is playing.  Requires the 'global prefs' right.",
364        []);
365
366 simple("edituser",
367        "Set a user property",
368        "With the 'admin' right you can do anything.  Otherwise you need the 'userinfo' right and can only set 'email' and 'password'.",
369        [["string", "username", "User to modify"],
370         ["string", "property", "Property name"],
371         ["string", "value", "New property value"]]);
372
373 simple("enable",
374        "Enable play",
375        "Requires the 'global prefs' right.",
376        []);
377
378 simple("enabled",
379        "Detect whether play is enabled",
380        "",
381        [],
382        ["boolean", "enabled", "1 if play is enabled and 0 otherwise"]);
383
384 simple("exists",
385        "Test whether a track exists",
386        "",
387        [["string", "track", "Track name"]],
388        ["boolean", "exists", "1 if the track exists and 0 otherwise"]);
389
390 simple("files",
391        "List files in a directory",
392        "",
393        [["string", "dir", "Directory to list (optional)"],
394         ["string", "re", "Regexp that results must match (optional)"]],
395        ["body", "files", "List of matching files"]);
396
397 simple("get",
398        "Get a track preference",
399        "If the track does not exist that is an error.  If the track exists but the preference does not then a null value is returned.",
400        [["string", "track", "Track name"],
401         ["string", "pref", "Preference name"]],
402        ["string", "value", "Preference value"]);
403
404 simple("get-global",
405        "Get a global preference",
406        "If the preference does exist not then a null value is returned.",
407        [["string", "pref", "Global preference name"]],
408        ["string", "value", "Preference value"]);
409
410 simple("length",
411        "Get a track's length",
412        "If the track does not exist an error is returned.",
413        [["string", "track", "Track name"]],
414        ["integer", "length", "Track length in seconds"]);
415
416 # TODO log
417
418 simple("make-cookie",
419        "Create a login cookie for this user",
420        "The cookie may be redeemed via the 'cookie' command",
421        [],
422        ["string", "cookie", "Newly created cookie"]);
423
424 simple("move",
425        "Move a track",
426        "Requires one of the 'move mine', 'move random' or 'move any' rights depending on how the track came to be added to the queue.",
427        [["string", "track", "Track ID or name"],
428         ["integer", "delta", "How far to move the track towards the head of the queue"]]);
429
430 simple("moveafter",
431        "Move multiple tracks",
432        "Requires one of the 'move mine', 'move random' or 'move any' rights depending on how the track came to be added to the queue.",
433        [["string", "target", "Move after this track, or to head if \"\""],
434         ["list", "ids", "List of tracks to move by ID"]]);
435
436 simple(["new", "new_tracks"],
437        "List recently added tracks",
438        "",
439        [["integer", "max", "Maximum tracks to fetch, or 0 for all available"]],
440        ["body", "tracks", "Recently added tracks"]);
441
442 simple("nop",
443        "Do nothing",
444        "Used as a keepalive.  No authentication required.",
445        []);
446
447 simple("part",
448        "Get a track name part",
449        "If the name part cannot be constructed an empty string is returned.",
450        [["string", "track", "Track name"],
451         ["string", "context", "Context (\"sort\" or \"display\")"],
452         ["string", "part", "Name part (\"artist\", \"album\" or \"title\")"]],
453        ["string", "part", "Value of name part"]);
454
455 simple("pause",
456        "Pause the currently playing track",
457        "Requires the 'pause' right.",
458        []);
459
460 simple("play",
461        "Play a track",
462        "Requires the 'play' right.",
463        [["string", "track", "Track to play"]],
464        ["string", "id", "Queue ID of new track"]);
465
466 simple("playafter",
467        "Play multiple tracks",
468        "Requires the 'play' right.",
469        [["string", "target", "Insert into queue after this track, or at head if \"\""],
470         ["list", "tracks", "List of track names to play"]]);
471
472 simple("playing",
473        "Retrieve the playing track",
474        "",
475        [],
476        ["queue-one", "playing", "Details of the playing track"]);
477
478 simple("playlist-delete",
479        "Delete a playlist",
480        "Requires the 'play' right and permission to modify the playlist.",
481        [["string", "playlist", "Playlist to delete"]]);
482
483 simple("playlist-get",
484        "List the contents of a playlist",
485        "Requires the 'read' right and oermission to read the playlist.",
486        [["string", "playlist", "Playlist name"]],
487        ["body", "tracks", "List of tracks in playlist"]);
488
489 simple("playlist-get-share",
490        "Get a playlist's sharing status",
491        "Requires the 'read' right and permission to read the playlist.",
492        [["string", "playlist", "Playlist to read"]],
493        ["string", "share", "Sharing status (\"public\", \"private\" or \"shared\")"]);
494
495 simple("playlist-lock",
496        "Lock a playlist",
497        "Requires the 'play' right and permission to modify the playlist.  A given connection may lock at most one playlist.",
498        [["string", "playlist", "Playlist to delete"]]);
499
500 simple("playlist-set",
501        "Set the contents of a playlist",
502        "Requires the 'play' right and permission to modify the playlist, which must be locked.",
503        [["string", "playlist", "Playlist to modify"],
504         ["body", "tracks", "New list of tracks for playlist"]]);
505
506 simple("playlist-set-share",
507        "Set a playlist's sharing status",
508        "Requires the 'play' right and permission to modify the playlist.",
509        [["string", "playlist", "Playlist to modify"],
510         ["string", "share", "New sharing status (\"public\", \"private\" or \"shared\")"]]);
511
512 simple("playlist-unlock",
513        "Unlock the locked playlist playlist",
514        "The playlist to unlock is implicit in the connection.",
515        []);
516
517 simple("playlists",
518        "List playlists",
519        "Requires the 'read' right.  Only playlists that you have permission to read are returned.",
520        [],
521        ["body", "playlists", "Playlist names"]);
522
523 simple("prefs",
524        "Get all the preferences for a track",
525        "",
526        [["string", "track", "Track name"]],
527        ["pair-list", "prefs", "Track preferences"]);
528
529 simple("queue",
530        "List the queue",
531        "",
532        [],
533        ["queue", "queue", "Current queue contents"]);
534
535 simple("random-disable",
536        "Disable random play",
537        "Requires the 'global prefs' right.",
538        []);
539
540 simple("random-enable",
541        "Enable random play",
542        "Requires the 'global prefs' right.",
543        []);
544
545 simple("random-enabled",
546        "Detect whether random play is enabled",
547        "Random play counts as enabled even if play is disabled.",
548        [],
549        ["boolean", "enabled", "1 if random play is enabled and 0 otherwise"]);
550
551 simple("recent",
552        "List recently played tracks",
553        "",
554        [],
555        ["queue", "recent", "Recently played tracks"]);
556
557 simple("reconfigure",
558        "Re-read configuraiton file.",
559        "Requires the 'admin' right.",
560        []);
561
562 simple("register",
563        "Register a new user",
564        "Requires the 'register' right which is usually only available to the 'guest' user.  Redeem the confirmation string via 'confirm' to complete registration.",
565        [["string", "username", "Requested new username"],
566         ["string", "password", "Requested initial password"],
567         ["string", "email", "New user's email address"]],
568        ["string", "confirmation", "Confirmation string"]);
569
570 simple("reminder",
571        "Send a password reminder.",
572        "If the user has no valid email address, or no password, or a reminder has been sent too recently, then no reminder will be sent.",
573        [["string", "username", "User to remind"]]);
574
575 simple("remove",
576        "Remove a track form the queue.",
577        "Requires one of the 'remove mine', 'remove random' or 'remove any' rights depending on how the track came to be added to the queue.",
578        [["string", "id", "Track ID"]]);
579
580 simple("rescan",
581        "Rescan all collections for new or obsolete tracks.",
582        "Requires the 'rescan' right.",
583        []);     # TODO wait/fresh flags
584
585 simple("resolve",
586        "Resolve a track name",
587        "Converts aliases to non-alias track names",
588        [["string", "track", "Track name (might be an alias)"]],
589        ["string", "resolved", "Resolve track name (definitely not an alias)"]);
590
591 simple("resume",
592        "Resume the currently playing track",
593        "Requires the 'pause' right.",
594        []);
595
596 simple("revoke",
597        "Revoke a cookie.",
598        "It will not subsequently be possible to log in with the cookie.",
599        []);
600
601 # TODO rtp-address
602
603 simple("scratch",
604        "Terminate the playing track.",
605        "Requires one of the 'scratch mine', 'scratch random' or 'scratch any' rights depending on how the track came to be added to the queue.",
606        [["string", "id", "Track ID (optional)"]]);
607
608 # TODO schedule-add
609
610 simple("schedule-del",
611        "Delete a scheduled event.",
612        "Users can always delete their own scheduled events; with the admin right you can delete any event.",
613        [["string", "event", "ID of event to delete"]]);
614
615 simple("schedule-get",
616        "Get the details of scheduled event",
617        "",
618        [["string", "id", "Event ID"]],
619        ["pair-list", "actiondata", "Details of event"]);
620
621 simple("schedule-list",
622        "List scheduled events",
623        "This just lists IDs.  Use 'schedule-get' to retrieve more detail",
624        [],
625        ["body", "ids", "List of event IDs"]);
626
627 simple("search",
628        "Search for tracks",
629        "Terms are either keywords or tags formatted as 'tag:TAG-NAME'.",
630        [["string", "terms", "List of search terms"]],
631        ["body", "tracks", "List of matching tracks"]);
632
633 simple("set",
634        "Set a track preference",
635        "Requires the 'prefs' right.",
636        [["string", "track", "Track name"],
637         ["string", "pref", "Preference name"],
638         ["string", "value", "New value"]]);
639
640 simple("set-global",
641        "Set a global preference",
642        "Requires the 'global prefs' right.",
643        [["string", "pref", "Preference name"],
644         ["string", "value", "New value"]]);
645
646 simple("shutdown",
647        "Request server shutdown",
648        "Requires the 'admin' right.",
649        []);
650
651 simple("stats",
652        "Get server statistics",
653        "The details of what the server reports are not really defined.  The returned strings are intended to be printed out one to a line..",
654        [],
655        ["body", "stats", "List of server information strings."]);
656
657 simple("tags",
658        "Get a list of known tags",
659        "Only tags which apply to at least one track are returned.",
660        [],
661        ["body", "tags", "List of tags"]);
662
663 simple("unset",
664        "Unset a track preference",
665        "Requires the 'prefs' right.",
666        [["string", "track", "Track name"],
667         ["string", "pref", "Preference name"]]);
668
669 simple("unset-global",
670        "Set a global preference",
671        "Requires the 'global prefs' right.",
672        [["string", "pref", "Preference name"]]);
673
674 # 'user' only used for authentication
675
676 simple("userinfo",
677        "Get a user property.",
678        "If the user does not exist an error is returned, if the user exists but the property does not then a null value is returned.",
679        [["string", "username", "User to read"],
680         ["string", "property", "Property to read"]],
681        ["string", "value", "Value of property"]);
682
683 simple("users",
684        "Get a list of users",
685        "",
686        [],
687        ["body", "users", "List of users"]);
688
689 simple("version",
690        "Get the server version",
691        "",
692        [],
693        ["string", "version", "Server version string"]);
694
695 # TODO volume
696
697 # End matter ------------------------------------------------------------------
698
699 push(@h, "#endif\n");
700
701 # Write it all out ------------------------------------------------------------
702
703 Write("lib/client-stubs.h", \@h);
704 Write("lib/client-stubs.c", \@c);