]> git.sesse.net Git - vlc/blob - share/lua/intf/cli.lua
567f07c6411cdbccdff2b865cc3abe74ce30bf44
[vlc] / share / lua / intf / cli.lua
1 --[==========================================================================[
2  cli.lua: CLI module for VLC
3 --[==========================================================================[
4  Copyright (C) 2007-2011 the VideoLAN team
5  $Id$
6
7  Authors: Antoine Cellerier <dionoea at videolan dot org>
8           Pierre Ynard
9
10  This program is free software; you can redistribute it and/or modify
11  it under the terms of the GNU General Public License as published by
12  the Free Software Foundation; either version 2 of the License, or
13  (at your option) any later version.
14
15  This program is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  GNU General Public License for more details.
19
20  You should have received a copy of the GNU General Public License
21  along with this program; if not, write to the Free Software
22  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 --]==========================================================================]
24
25 description=
26 [============================================================================[
27  Command Line Interface for VLC
28
29  This is a modules/control/rc.c look alike (with a bunch of new features).
30  It also provides a VLM interface copied from the telnet interface.
31
32  Use on local term:
33     vlc -I cli
34  Use on tcp connection:
35     vlc -I cli --lua-config "cli={host='localhost:4212'}"
36  Use on telnet connection:
37     vlc -I cli --lua-config "cli={host='telnet://localhost:4212'}"
38  Use on multiple hosts (term + plain tcp port + telnet):
39     vlc -I cli --lua-config "cli={hosts={'*console','localhost:4212','telnet://localhost:5678'}}"
40
41  Note:
42     -I cli and -I luacli are aliases for -I lua --lua-intf cli
43
44  Configuration options setable throught the --lua-config option are:
45     * hosts: A list of hosts to listen on.
46     * host: A host to listen on. (won't be used if `hosts' is set)
47     * password: The password used for telnet clients.
48  The following can be set using the --lua-config option or in the interface
49  itself using the `set' command:
50     * prompt: The prompt.
51     * welcome: The welcome message.
52     * width: The default terminal width (used to format text).
53     * autocompletion: When issuing an unknown command, print a list of
54                       possible commands to autocomplete with. (0 to disable,
55                       1 to enable).
56     * autoalias: If autocompletion returns only one possibility, use it
57                  (0 to disable, 1 to enable).
58     * flatplaylist: 0 to disable, 1 to enable.
59 ]============================================================================]
60
61 require("common")
62 skip = common.skip
63 skip2 = function(foo) return skip(skip(foo)) end
64 setarg = common.setarg
65 strip = common.strip
66
67 _ = vlc.gettext._
68 N_ = vlc.gettext.N_
69
70 --[[ Setup default environement ]]
71 env = { prompt = "> ";
72         width = 70;
73         autocompletion = 1;
74         autoalias = 1;
75         welcome = _("Command Line Interface initialized. Type `help' for help.");
76         flatplaylist = 0;
77       }
78
79 --[[ Import custom environement variables from the command line config (if possible) ]]
80 for k,v in pairs(env) do
81     if config[k] then
82         if type(env[k]) == type(config[k]) then
83             env[k] = config[k]
84             vlc.msg.dbg("set environement variable `"..k.."' to "..tostring(env[k]))
85         else
86             vlc.msg.err("environement variable `"..k.."' should be of type "..type(env[k])..". config value will be discarded.")
87         end
88     end
89 end
90
91 --[[ Command functions ]]
92 function set_env(name,client,value)
93     if value then
94         local var,val = split_input(value)
95         if val then
96             local s = string.gsub(val,"\"(.*)\"","%1")
97             if type(client.env[var])==type(1) then
98                 client.env[var] = tonumber(s)
99             else
100                 client.env[var] = s
101             end
102         else
103             client:append( tostring(client.env[var]) )
104         end
105     else
106         for e,v in common.pairs_sorted(client.env) do
107             client:append(e.."="..v)
108         end
109     end
110 end
111
112 function save_env(name,client,value)
113     env = common.table_copy(client.env)
114 end
115
116 function alias(client,value)
117     if value then
118         local var,val = split_input(value)
119         if commands[var] and type(commands[var]) ~= type("") then
120             client:append("Error: cannot use a primary command as an alias name")
121         else
122             if commands[val] then
123                 commands[var]=val
124             else
125                 client:append("Error: unknown primary command `"..val.."'.")
126             end
127         end
128     else
129         for c,v in common.pairs_sorted(commands) do
130             if type(v)==type("") then
131                 client:append(c.."="..v)
132             end
133         end
134     end
135 end
136
137 function lock(name,client)
138     if client.type == host.client_type.telnet then
139         client:switch_status( host.status.password )
140         client.buffer = ""
141     else
142         client:append("Error: the prompt can only be locked when logged in through telnet")
143     end
144 end
145
146 function logout(name,client)
147     if client.type == host.client_type.net
148     or client.type == host.client_type.telnet then
149         client:send("Bye-bye!\r\n")
150         client:del()
151     else
152         client:append("Error: Can't logout of stdin/stdout. Use quit or shutdown to close VLC.")
153     end
154 end
155
156 function shutdown(name,client)
157     client:append("Bye-bye!")
158     h:broadcast("Shutting down.\r\n")
159     vlc.msg.info("Requested shutdown.")
160     vlc.misc.quit()
161 end
162
163 function quit(name,client)
164     if client.type == host.client_type.net
165     or client.type == host.client_type.telnet then
166         logout(name,client)
167     else
168         shutdown(name,client)
169     end
170 end
171
172 function add(name,client,arg)
173     -- TODO: parse single and double quotes properly
174     local f
175     if name == "enqueue" then
176         f = vlc.playlist.enqueue
177     else
178         f = vlc.playlist.add
179     end
180     local options = {}
181     for o in string.gmatch(arg," +:([^ ]*)") do
182         table.insert(options,o)
183     end
184     arg = string.gsub(arg," +:.*$","")
185     f({{path=arg,options=options}})
186 end
187
188 function playlist_is_tree( client )
189     if client.env.flatplaylist == 0 then
190         return true
191     else
192         return false
193     end
194 end
195
196 function playlist(name,client,arg)
197     function playlist0(item,prefix)
198         local prefix = prefix or ""
199         if not item.flags.disabled then
200             local str = "| "..prefix..tostring(item.id).." - "..item.name
201             if item.duration > 0 then
202                 str = str.." ("..common.durationtostring(item.duration)..")"
203             end
204             if item.nb_played > 0 then
205                 str = str.." [played "..tostring(item.nb_played).." time"
206                 if item.nb_played > 1 then
207                     str = str .. "s"
208                 end
209                 str = str .. "]"
210             end
211             client:append(str)
212         end
213         if item.children then
214             for _, c in ipairs(item.children) do
215                 playlist0(c,prefix.."  ")
216             end
217         end
218     end
219     local playlist
220     local tree = playlist_is_tree(client)
221     if name == "search" then
222         playlist = vlc.playlist.search(arg or "", tree)
223     else
224         if tonumber(arg) then
225             playlist = vlc.playlist.get(tonumber(arg), tree)
226         elseif arg then
227             playlist = vlc.playlist.get(arg, tree)
228         else
229             playlist = vlc.playlist.get(nil, tree)
230         end
231     end
232     if name == "search" then
233         client:append("+----[ Search - "..(arg or "`reset'").." ]")
234     else
235         client:append("+----[ Playlist - "..playlist.name.." ]")
236     end
237     if playlist.children then
238         for _, item in ipairs(playlist.children) do
239             playlist0(item)
240         end
241     else
242         playlist0(playlist)
243     end
244     if name == "search" then
245         client:append("+----[ End of search - Use `search' to reset ]")
246     else
247         client:append("+----[ End of playlist ]")
248     end
249 end
250
251 function playlist_sort(name,client,arg)
252     if not arg then
253         client:append("Valid sort keys are: id, title, artist, genre, random, duration, album.")
254     else
255         local tree = playlist_is_tree(client)
256         vlc.playlist.sort(arg,false,tree)
257     end
258 end
259
260 function services_discovery(name,client,arg)
261     if arg then
262         if vlc.sd.is_loaded(arg) then
263             vlc.sd.remove(arg)
264             client:append(arg.." disabled.")
265         else
266             vlc.sd.add(arg)
267             client:append(arg.." enabled.")
268         end
269     else
270         local sd = vlc.sd.get_services_names()
271         client:append("+----[ Services discovery ]")
272         for n,ln in pairs(sd) do
273             local status
274             if vlc.sd.is_loaded(n) then
275                 status = "enabled"
276             else
277                 status = "disabled"
278             end
279             client:append("| "..n..": " .. ln .. " (" .. status .. ")")
280         end
281         client:append("+----[ End of services discovery ]")
282     end
283 end
284
285 function print_text(label,text)
286     return function(name,client)
287         client:append("+----[ "..label.." ]")
288         client:append "|"
289         for line in string.gmatch(text,".-\r?\n") do
290             client:append("| "..string.gsub(line,"\r?\n",""))
291         end
292         client:append "|"
293         client:append("+----[ End of "..string.lower(label).." ]")
294     end
295 end
296
297 function help(name,client,arg)
298     if arg == nil then
299         client:append("+----[ VLM commands ]")
300         local message, vlc_err = vlm:execute_command("help")
301         vlm_message_to_string( client, message, "|" )
302     end
303
304     local width = client.env.width
305     local long = (name == "longhelp")
306     local extra = ""
307     if arg then extra = "matching `" .. arg .. "' " end
308     client:append("+----[ CLI commands "..extra.."]")
309     for i, cmd in ipairs(commands_ordered) do
310         if (cmd == "" or not commands[cmd].adv or long)
311         and (not arg or string.match(cmd,arg)) then
312             local str = "| " .. cmd
313             if cmd ~= "" then
314                 local val = commands[cmd]
315                 if val.aliases then
316                     for _,a in ipairs(val.aliases) do
317                         str = str .. ", " .. a
318                     end
319                 end
320                 if val.args then str = str .. " " .. val.args end
321                 if #str%2 == 1 then str = str .. " " end
322                 str = str .. string.rep(" .",(width-(#str+#val.help)-1)/2)
323                 str = str .. string.rep(" ",width-#str-#val.help) .. val.help
324             end
325             client:append(str)
326         end
327     end
328     client:append("+----[ end of help ]")
329 end
330
331 function input_info(name,client)
332     local item = vlc.input.item()
333     if(item == nil) then return end
334     local categories = item:info()
335     for cat, infos in pairs(categories) do
336         client:append("+----[ "..cat.." ]")
337         client:append("|")
338         for name, value in pairs(infos) do
339             client:append("| "..name..": "..value)
340         end
341         client:append("|")
342     end
343     client:append("+----[ end of stream info ]")
344 end
345
346 function stats(name,client)
347     local item = vlc.input.item()
348     if(item == nil) then return end
349     local stats_tab = item:stats()
350
351     client:append("+----[ begin of statistical info")
352     client:append("+-[Incoming]")
353     client:append("| input bytes read : "..string.format("%8.0f KiB",stats_tab["read_bytes"]/1024))
354     client:append("| input bitrate    :   "..string.format("%6.0f kb/s",stats_tab["input_bitrate"]*8000))
355     client:append("| demux bytes read : "..string.format("%8.0f KiB",stats_tab["demux_read_bytes"]/1024))
356     client:append("| demux bitrate    :   "..string.format("%6.0f kb/s",stats_tab["demux_bitrate"]*8000))
357     client:append("| demux corrupted  :    "..string.format("%5i",stats_tab["demux_corrupted"]))
358     client:append("| discontinuities  :    "..string.format("%5i",stats_tab["demux_discontinuity"]))
359     client:append("|")
360     client:append("+-[Video Decoding]")
361     client:append("| video decoded    :    "..string.format("%5i",stats_tab["decoded_video"]))
362     client:append("| frames displayed :    "..string.format("%5i",stats_tab["displayed_pictures"]))
363     client:append("| frames lost      :    "..string.format("%5i",stats_tab["lost_pictures"]))
364     client:append("|")
365     client:append("+-[Audio Decoding]")
366     client:append("| audio decoded    :    "..string.format("%5i",stats_tab["decoded_audio"]))
367     client:append("| buffers played   :    "..string.format("%5i",stats_tab["played_abuffers"]))
368     client:append("| buffers lost     :    "..string.format("%5i",stats_tab["lost_abuffers"]))
369     client:append("|")
370     client:append("+-[Streaming]")
371     client:append("| packets sent     :    "..string.format("%5i",stats_tab["sent_packets"]))
372     client:append("| bytes sent       : "..string.format("%8.0f KiB",stats_tab["sent_bytes"]/1024))
373     client:append("| sending bitrate  :   "..string.format("%6.0f kb/s",stats_tab["send_bitrate"]*8000))
374     client:append("+----[ end of statistical info ]")
375 end
376
377 function playlist_status(name,client)
378     local item = vlc.input.item()
379     if(item ~= nil) then
380         client:append( "( new input: " .. vlc.strings.decode_uri(item:uri()) .. " )" )
381     end
382     client:append( "( audio volume: " .. tostring(vlc.volume.get()) .. " )")
383     client:append( "( state " .. vlc.playlist.status() .. " )")
384 end
385
386 function is_playing(name,client)
387     if vlc.input.is_playing() then client:append "1" else client:append "0" end
388 end
389
390 function get_title(name,client)
391     local item = vlc.input.item()
392     if item then
393         client:append(item:name())
394     else
395         client:append("")
396     end
397 end
398
399 function ret_print(foo,start,stop)
400     local start = start or ""
401     local stop = stop or ""
402     return function(discard,client,...) client:append(start..tostring(foo(...))..stop) end
403 end
404
405 function get_time(var)
406     return function(name,client)
407         local input = vlc.object.input()
408         client:append(math.floor(vlc.var.get( input, var )))
409     end
410 end
411
412 function titlechap(name,client,value)
413     local input = vlc.object.input()
414     local var = string.gsub( name, "_.*$", "" )
415     if value then
416         vlc.var.set( input, var, value )
417     else
418         local item = vlc.var.get( input, var )
419         -- Todo: add item name conversion
420         client:append(item)
421     end
422 end
423
424 function titlechap_offset(var,offset)
425     local input = vlc.object.input()
426     vlc.var.set( input, var, vlc.var.get( input, var ) + offset )
427 end
428
429 function title_next(name,client,value)
430     titlechap_offset('title', 1)
431 end
432
433 function title_previous(name,client,value)
434     titlechap_offset('title', -1)
435 end
436
437 function chapter_next(name,client,value)
438     titlechap_offset('chapter', 1)
439 end
440
441 function chapter_previous(name,client,value)
442     titlechap_offset('chapter', -1)
443 end
444
445 function seek(name,client,value)
446     common.seek(value)
447 end
448
449 function volume(name,client,value)
450     if value then
451         common.volume(value)
452     else
453         client:append(tostring(vlc.volume.get()))
454     end
455 end
456
457 function rate(name,client,value)
458     local input = vlc.object.input()
459     if name == "rate" then
460         vlc.var.set(input, "rate", tonumber(value))
461     elseif name == "normal" then
462         vlc.var.set(input,"rate",1)
463     else
464         vlc.var.set(input,"rate-"..name,nil)
465     end
466 end
467
468 function frame(name,client)
469     vlc.var.trigger_callback(vlc.object.input(),"frame-next");
470 end
471
472 function listvalue(obj,var)
473     return function(client,value)
474         local o = vlc.object.find(nil,obj,"anywhere")
475         if not o then return end
476         if value then
477             vlc.var.set( o, var, value )
478         else
479             local c = vlc.var.get( o, var )
480             local v, l = vlc.var.get_list( o, var )
481             client:append("+----[ "..var.." ]")
482             for i,val in ipairs(v) do
483                 local mark = (val==c)and " *" or ""
484                 client:append("| "..tostring(val).." - "..tostring(l[i])..mark)
485             end
486             client:append("+----[ end of "..var.." ]")
487         end
488     end
489 end
490
491 function menu(name,client,value)
492     local map = { on='show', off='hide', up='up', down='down', left='prev', right='next', ['select']='activate' }
493     if map[value] and vlc.osd.menu[map[value]] then
494         vlc.osd.menu[map[value]]()
495     else
496         client:append("Unknown menu command '"..tostring(value).."'")
497     end
498 end
499
500 function hotkey(name, client, value)
501     if not value then
502         client:append("Please specify a hotkey (ie key-quit or quit)")
503     elseif not common.hotkey(value) and not common.hotkey("key-"..value) then
504         client:append("Unknown hotkey '"..value.."'")
505     end
506 end
507
508 --[[ Declare commands, register their callback functions and provide
509      help strings here.
510      Syntax is:
511      "<command name>"; { func = <function>; [ args = "<str>"; ] help = "<str>"; [ adv = <bool>; ] [ aliases = { ["<str>";]* }; ] }
512      ]]
513 commands_ordered = {
514     { "add"; { func = add; args = "XYZ"; help = "add XYZ to playlist" } };
515     { "enqueue"; { func = add; args = "XYZ"; help = "queue XYZ to playlist" } };
516     { "playlist"; { func = playlist; help = "show items currently in playlist" } };
517     { "search"; { func = playlist; args = "[string]"; help = "search for items in playlist (or reset search)" } };
518     { "sort"; { func = playlist_sort; args = "key"; help = "sort the playlist" } };
519     { "sd"; { func = services_discovery; args = "[sd]"; help = "show services discovery or toggle" } };
520     { "play"; { func = skip2(vlc.playlist.play); help = "play stream" } };
521     { "stop"; { func = skip2(vlc.playlist.stop); help = "stop stream" } };
522     { "next"; { func = skip2(vlc.playlist.next); help = "next playlist item" } };
523     { "prev"; { func = skip2(vlc.playlist.prev); help = "previous playlist item" } };
524     { "goto"; { func = skip2(vlc.playlist.goto); help = "goto item at index" } };
525     { "repeat"; { func = skip2(vlc.playlist.repeat_); args = "[on|off]"; help = "toggle playlist repeat" } };
526     { "loop"; { func = skip2(vlc.playlist.loop); args = "[on|off]"; help = "toggle playlist loop" } };
527     { "random"; { func = skip2(vlc.playlist.random); args = "[on|off]"; help = "toggle playlist random" } };
528     { "clear"; { func = skip2(vlc.playlist.clear); help = "clear the playlist" } };
529     { "status"; { func = playlist_status; help = "current playlist status" } };
530     { "title"; { func = titlechap; args = "[X]"; help = "set/get title in current item" } };
531     { "title_n"; { func = title_next; help = "next title in current item" } };
532     { "title_p"; { func = title_previous; help = "previous title in current item" } };
533     { "chapter"; { func = titlechap; args = "[X]"; help = "set/get chapter in current item" } };
534     { "chapter_n"; { func = chapter_next; help = "next chapter in current item" } };
535     { "chapter_p"; { func = chapter_previous; help = "previous chapter in current item" } };
536     { "" };
537     { "seek"; { func = seek; args = "X"; help = "seek in seconds, for instance `seek 12'" } };
538     { "pause"; { func = skip2(vlc.playlist.pause); help = "toggle pause" } };
539     { "fastforward"; { func = setarg(common.hotkey,"key-jump+extrashort"); help = "set to maximum rate" } };
540     { "rewind"; { func = setarg(common.hotkey,"key-jump-extrashort"); help = "set to minimum rate" } };
541     { "faster"; { func = rate; help = "faster playing of stream" } };
542     { "slower"; { func = rate; help = "slower playing of stream" } };
543     { "normal"; { func = rate; help = "normal playing of stream" } };
544     { "rate"; { func = rate; args = "[playback rate]"; help = "set playback rate to value" } };
545     { "frame"; { func = frame; help = "play frame by frame" } };
546     { "fullscreen"; { func = skip2(vlc.video.fullscreen); args = "[on|off]"; help = "toggle fullscreen"; aliases = { "f", "F" } } };
547     { "info"; { func = input_info; help = "information about the current stream" } };
548     { "stats"; { func = stats; help = "show statistical information" } };
549     { "get_time"; { func = get_time("time"); help = "seconds elapsed since stream's beginning" } };
550     { "is_playing"; { func = is_playing; help = "1 if a stream plays, 0 otherwise" } };
551     { "get_title"; { func = get_title; help = "the title of the current stream" } };
552     { "get_length"; { func = get_time("length"); help = "the length of the current stream" } };
553     { "" };
554     { "volume"; { func = volume; args = "[X]"; help = "set/get audio volume" } };
555     { "volup"; { func = ret_print(vlc.volume.up,"( audio volume: "," )"); args = "[X]"; help = "raise audio volume X steps" } };
556     { "voldown"; { func = ret_print(vlc.volume.down,"( audio volume: "," )"); args = "[X]"; help = "lower audio volume X steps" } };
557     { "adev"; { func = skip(listvalue("aout","audio-device")); args = "[X]"; help = "set/get audio device" } };
558     { "achan"; { func = skip(listvalue("aout","audio-channels")); args = "[X]"; help = "set/get audio channels" } };
559     { "atrack"; { func = skip(listvalue("input","audio-es")); args = "[X]"; help = "set/get audio track" } };
560     { "vtrack"; { func = skip(listvalue("input","video-es")); args = "[X]"; help = "set/get video track" } };
561     { "vratio"; { func = skip(listvalue("vout","aspect-ratio")); args = "[X]"; help = "set/get video aspect ratio" } };
562     { "vcrop"; { func = skip(listvalue("vout","crop")); args = "[X]"; help = "set/get video crop"; aliases = { "crop" } } };
563     { "vzoom"; { func = skip(listvalue("vout","zoom")); args = "[X]"; help = "set/get video zoom"; aliases = { "zoom" } } };
564     { "snapshot"; { func = common.snapshot; help = "take video snapshot" } };
565     { "strack"; { func = skip(listvalue("input","spu-es")); args = "[X]"; help = "set/get subtitles track" } };
566     { "hotkey"; { func = hotkey; args = "[hotkey name]"; help = "simulate hotkey press"; adv = true; aliases = { "key" } } };
567     { "menu"; { func = menu; args = "[on|off|up|down|left|right|select]"; help = "use menu"; adv = true } };
568     { "" };
569     { "set"; { func = set_env; args = "[var [value]]"; help = "set/get env var"; adv = true } };
570     { "save_env"; { func = save_env; help = "save env vars (for future clients)"; adv = true } };
571     { "alias"; { func = skip(alias); args = "[cmd]"; help = "set/get command aliases"; adv = true } };
572     { "description"; { func = print_text("Description",description); help = "describe this module" } };
573     { "license"; { func = print_text("License message",vlc.misc.license()); help = "print VLC's license message"; adv = true } };
574     { "help"; { func = help; args = "[pattern]"; help = "a help message"; aliases = { "?" } } };
575     { "longhelp"; { func = help; args = "[pattern]"; help = "a longer help message" } };
576     { "lock"; { func = lock; help = "lock the telnet prompt" } };
577     { "logout"; { func = logout; help = "exit (if in a socket connection)" } };
578     { "quit"; { func = quit; help = "quit VLC (or logout if in a socket connection)" } };
579     { "shutdown"; { func = shutdown; help = "shutdown VLC" } };
580     }
581
582 commands = {}
583 for i, cmd in ipairs( commands_ordered ) do
584     if #cmd == 2 then
585         commands[cmd[1]]=cmd[2]
586         if cmd[2].aliases then
587             for _,a in ipairs(cmd[2].aliases) do
588                 commands[a]=cmd[1]
589             end
590         end
591     end
592     commands_ordered[i]=cmd[1]
593 end
594 --[[ From now on commands_ordered is a list of the different command names
595      and commands is a associative array indexed by the command name. ]]
596
597 -- Compute the column width used when printing a the autocompletion list
598 env.colwidth = 0
599 for c,_ in pairs(commands) do
600     if #c > env.colwidth then env.colwidth = #c end
601 end
602 env.coldwidth = env.colwidth + 1
603
604 --[[ Utils ]]
605 function split_input(input)
606     local input = strip(input)
607     local s = string.find(input," ")
608     if s then
609         return string.sub(input,0,s-1), strip(string.sub(input,s))
610     else
611         return input
612     end
613 end
614
615 function vlm_message_to_string(client,message,prefix)
616     local prefix = prefix or ""
617     if message.value then
618         client:append(prefix .. message.name .. " : " .. message.value)
619     else
620         client:append(prefix .. message.name)
621     end
622     if message.children then
623         for i,c in ipairs(message.children) do
624             vlm_message_to_string(client,c,prefix.."    ")
625         end
626     end
627 end
628
629 --[[ Command dispatch ]]
630 function call_command(cmd,client,arg)
631     if type(commands[cmd]) == type("") then
632         cmd = commands[cmd]
633     end
634     local ok, msg
635     if arg ~= nil then
636         ok, msg = pcall( commands[cmd].func, cmd, client, arg )
637     else
638         ok, msg = pcall( commands[cmd].func, cmd, client )
639     end
640     if not ok then
641         local a = arg and " "..arg or ""
642         client:append("Error in `"..cmd..a.."' ".. msg)
643     end
644 end
645
646 function call_vlm_command(cmd,client,arg)
647     if arg ~= nil then
648         cmd = cmd.." "..arg
649     end
650     local message, vlc_err = vlm:execute_command( cmd )
651     vlm_message_to_string( client, message )
652     return vlc_err
653 end
654
655 function call_libvlc_command(cmd,client,arg)
656     local ok, vlcerr = pcall( vlc.var.libvlc_command, cmd, arg )
657     if not ok then
658         local a = arg and " "..arg or ""
659         client:append("Error in `"..cmd..a.."' ".. vlcerr) -- when pcall fails, the 2nd arg is the error message.
660     end
661     return vlcerr
662 end
663
664 function call_object_command(cmd,client,arg)
665     local var, val
666     if arg ~= nil then
667         var, val = split_input(arg)
668     end
669     local ok, vlcmsg, vlcerr = pcall( vlc.var.command, cmd, var, val )
670     if not ok then
671         local v = var and " "..var or ""
672         local v2 = val and " "..val or ""
673         client:append("Error in `"..cmd..v..v2.."' ".. vlcmsg) -- when pcall fails the 2nd arg is the error message
674     end
675     if vlcmsg ~= "" then
676         client:append(vlcmsg)
677     end
678     return vlcerr
679 end
680
681 function client_command( client )
682     local cmd,arg = split_input(client.buffer)
683     client.buffer = ""
684
685     if commands[cmd] then
686         call_command(cmd,client,arg)
687     elseif string.sub(cmd,0,1)=='@'
688     and call_object_command(string.sub(cmd,2,#cmd),client,arg) == 0 then
689         --
690     elseif call_vlm_command(cmd,client,arg) == 0 then
691         --
692     elseif client.type == host.client_type.stdio
693     and call_libvlc_command(cmd,client,arg) == 0 then
694         --
695     else
696         local choices = {}
697         if client.env.autocompletion ~= 0 then
698             for v,_ in common.pairs_sorted(commands) do
699                 if string.sub(v,0,#cmd)==cmd then
700                     table.insert(choices, v)
701                 end
702             end
703         end
704         if #choices == 1 and client.env.autoalias ~= 0 then
705             -- client:append("Aliasing to \""..choices[1].."\".")
706             cmd = choices[1]
707             call_command(cmd,client,arg)
708         else
709             client:append("Unknown command `"..cmd.."'. Type `help' for help.")
710             if #choices ~= 0 then
711                 client:append("Possible choices are:")
712                 local cols = math.floor(client.env.width/(client.env.colwidth+1))
713                 local fmt = "%-"..client.env.colwidth.."s"
714                 for i = 1, #choices do
715                     choices[i] = string.format(fmt,choices[i])
716                 end
717                 for i = 1, #choices, cols do
718                     local j = i + cols - 1
719                     if j > #choices then j = #choices end
720                     client:append("  "..table.concat(choices," ",i,j))
721                 end
722             end
723         end
724     end
725 end
726
727 --[[ Some telnet command special characters ]]
728 WILL = "\251" -- Indicates the desire to begin performing, or confirmation that you are now performing, the indicated option.
729 WONT = "\252" -- Indicates the refusal to perform, or continue performing, the indicated option.
730 DO   = "\253" -- Indicates the request that the other party perform, or confirmation that you are expecting the other party to perform, the indicated option.
731 DONT = "\254" -- Indicates the demand that the other party stop performing, or confirmation that you are no longer expecting the other party to perform, the indicated option.
732 IAC  = "\255" -- Interpret as command
733
734 ECHO = "\001"
735
736 function telnet_commands( client )
737     -- remove telnet command replies from the client's data
738     client.buffer = string.gsub( client.buffer, IAC.."["..DO..DONT..WILL..WONT.."].", "" )
739 end
740
741 --[[ Client status change callbacks ]]
742 function on_password( client )
743     client.env = common.table_copy( env )
744     if client.type == host.client_type.telnet then
745         client:send( "Password: " ..IAC..WILL..ECHO )
746     else
747         if client.env.welcome ~= "" then
748             client:send( client.env.welcome .. "\r\n")
749         end
750         client:switch_status( host.status.read )
751     end
752 end
753 -- Print prompt when switching a client's status to `read'
754 function on_read( client )
755     client:send( client.env.prompt )
756 end
757 function on_write( client )
758 end
759
760 --[[ Setup host ]]
761 require("host")
762 h = host.host()
763
764 h.status_callbacks[host.status.password] = on_password
765 h.status_callbacks[host.status.read] = on_read
766 h.status_callbacks[host.status.write] = on_write
767
768 h:listen( config.hosts or config.host or "*console" )
769 password = config.password or "admin"
770
771 --[[ Launch vlm ]]
772 vlm = vlc.vlm()
773
774 --[[ The main loop ]]
775 while not vlc.misc.should_die() do
776     local write, read = h:accept_and_select()
777
778     for _, client in pairs(write) do
779         local len = client:send()
780         client.buffer = string.sub(client.buffer,len+1)
781         if client.buffer == "" then client:switch_status(host.status.read) end
782     end
783
784     for _, client in pairs(read) do
785         local input = client:recv(1000)
786
787         if input == "" -- the telnet client program has left
788             or ((client.type == host.client_type.net
789                  or client.type == host.client_type.telnet)
790                 and input == "\004") then
791             -- Caught a ^D
792             client.cmds = "quit\n"
793         else
794             client.cmds = client.cmds .. input
795         end
796
797         client.buffer = ""
798         -- split the command at the first '\n'
799         while string.find(client.cmds, "\n") do
800             -- save the buffer to send to the client
801             local saved_buffer = client.buffer
802
803             -- get the next command
804             local index = string.find(client.cmds, "\n")
805             client.buffer = string.gsub(string.sub(client.cmds, 0, index - 1), "^%s*(.-)%s*$", "%1")
806             client.cmds = string.sub(client.cmds, index + 1)
807
808             -- Remove telnet commands from the command line
809             if client.type == host.client_type.telnet then
810                 telnet_commands( client )
811             end
812
813             -- Run the command
814             if client.status == host.status.password then
815                 if client.buffer == password then
816                     client:send( IAC..WONT..ECHO.."\r\nWelcome, Master\r\n" )
817                     client.buffer = ""
818                     client:switch_status( host.status.write )
819                 elseif client.buffer == "quit" then
820                     client_command( client )
821                 else
822                     client:send( "\r\nWrong password\r\nPassword: " )
823                     client.buffer = ""
824                 end
825             else
826                 client:switch_status( host.status.write )
827                 client_command( client )
828             end
829             client.buffer = saved_buffer .. client.buffer
830         end
831     end
832 end
833
834 --[[ Clean up ]]
835 vlm = nil