]> git.tdb.fi Git - xinema.git/blob - source/client.cpp
dbe6091df0f6232c9bfb642663921d7505471297
[xinema.git] / source / client.cpp
1 #include <msp/fs/dir.h>
2 #include <msp/fs/stat.h>
3 #include "client.h"
4 #include "xinema.h"
5
6 using namespace std;
7 using namespace Msp;
8
9 Client::Client(Xinema &x, Net::StreamSocket *s):
10         xinema(x),
11         socket(s),
12         stale(false)
13 {
14         socket->signal_data_available.connect(sigc::mem_fun(this, &Client::data_available));
15         socket->signal_end_of_file.connect(sigc::mem_fun(this, &Client::end_of_stream));
16 }
17
18 void Client::data_available()
19 {
20         char rbuf[1024];
21         unsigned len = socket->read(rbuf, sizeof(rbuf));
22         buffer.append(rbuf, len);
23
24         string::size_type start = 0;
25         while(1)
26         {
27                 string::size_type newline = buffer.find('\n', start);
28                 if(newline==string::npos)
29                         break;
30
31                 try
32                 {
33                         process_command(buffer.substr(start, newline-start));
34                 }
35                 catch(const exception &e)
36                 {
37                         send_reply(string("error ")+e.what());
38                         return;
39                 }
40
41                 start = newline+1;
42         }
43
44         buffer.erase(0, start);
45 }
46
47 void Client::end_of_stream()
48 {
49         stale = true;
50 }
51
52 void Client::process_command(const string &cmd)
53 {
54         string::size_type space = cmd.find(' ');
55         string keyword = cmd.substr(0, space);
56         string args;
57         if(space!=string::npos)
58                 args = cmd.substr(space+1);
59         if(keyword=="list_directory")
60                 list_directory(args);
61         else if(keyword=="play_file")
62                 xinema.play_file(args);
63         else
64                 send_reply("error Invalid command");
65 }
66
67 void Client::send_reply(const string &reply)
68 {
69         socket->write(reply);
70         socket->put('\n');
71 }
72
73 void Client::list_directory(const FS::Path &dn)
74 {
75         list<string> files = FS::list_files(dn);
76
77         send_reply("directory "+dn.str());
78         for(list<string>::const_iterator i=files.begin(); i!=files.end(); ++i)
79         {
80                 if(FS::is_dir(dn / *i))
81                         send_reply("subdir "+*i);
82                 else
83                         send_reply("file "+*i);
84         }
85 }