Add python module (note: must be compiled seperately)
[doldaconnect.git] / lib / python / dolmod.c
1 /*
2  *  Dolda Connect - Modular multiuser Direct Connect-style client
3  *  Copyright (C) 2004 Fredrik Tolf (fredrik@dolda2000.com)
4  *  
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.
9  *  
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *  
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  USA
18 */
19 #include <Python.h>
20 #include <sys/poll.h>
21 #include <doldaconnect/uilib.h>
22 #include <doldaconnect/uimisc.h>
23 #include <doldaconnect/utils.h>
24 #include <wchar.h>
25
26 struct respobj {
27     PyObject_HEAD
28     struct dc_response *resp;
29 };
30
31 static int fd = -1;
32
33 static void resptype_del(struct respobj *self)
34 {
35     dc_freeresp(self->resp);
36     self->ob_type->tp_free((PyObject *)self);
37 }
38
39 static PyObject *resp_getcode(struct respobj *self)
40 {
41     return(Py_BuildValue("i", self->resp->code));
42 }
43
44 static PyObject *resp_gettag(struct respobj *self)
45 {
46     return(Py_BuildValue("i", self->resp->tag));
47 }
48
49 static PyObject *resp_getcmd(struct respobj *self)
50 {
51     return(PyUnicode_FromWideChar(self->resp->cmdname, wcslen(self->resp->cmdname)));
52 }
53
54 static PyObject *resp_extract(struct respobj *self)
55 {
56     int i, o;
57     PyObject *ret, *sl;
58     wchar_t *c;
59     
60     ret = PyList_New(self->resp->numlines);
61     for(i = 0; i < self->resp->numlines; i++) {
62         sl = PyList_New(self->resp->rlines[i].argc);
63         for(o = 0; o < self->resp->rlines[i].argc; o++) {
64             c = self->resp->rlines[i].argv[o];
65             PyList_SetItem(sl, o, PyUnicode_FromWideChar(c, wcslen(c)));
66         }
67         PyList_SetItem(ret, i, sl);
68     }
69     return(ret);
70 }
71
72 static PyObject *resp_intresp(struct respobj *self)
73 {
74     int i;
75     PyObject *ret, *sl;
76     struct dc_intresp *ires;
77     
78     ret = PyList_New(0);
79     self->resp->curline = 0;
80     while((ires = dc_interpret(self->resp)) != NULL) {
81         sl = PyList_New(ires->argc);
82         for(i = 0; i < ires->argc; i++) {
83             switch(ires->argv[i].type) {
84             case 1:
85                 PyList_SetItem(sl, i, PyUnicode_FromWideChar(ires->argv[i].val.str, wcslen(ires->argv[i].val.str)));
86                 break;
87             case 2:
88                 PyList_SetItem(sl, i, PyInt_FromLong(ires->argv[i].val.num));
89                 break;
90             case 3:
91                 PyList_SetItem(sl, i, PyFloat_FromDouble(ires->argv[i].val.flnum));
92                 break;
93             }
94         }
95         dc_freeires(ires);
96         PyList_Append(ret, sl);
97     }
98     return(ret);
99 }
100
101 static PyMethodDef respmethods[] = {
102     {"getcode", (PyCFunction)resp_getcode, METH_NOARGS,
103      "Get the numerical code from the response"},
104     {"gettag", (PyCFunction)resp_gettag, METH_NOARGS,
105      "Get the tag from the response"},
106     {"getcmd", (PyCFunction)resp_getcmd, METH_NOARGS,
107      "Get the command name from the response"},
108     {"extract", (PyCFunction)resp_extract, METH_NOARGS,
109      "Extract the lines and columns from the response"},
110     {"intresp", (PyCFunction)resp_intresp, METH_NOARGS,
111      "Interpret all the lines from the response with native datatypes"},
112     {NULL, NULL, 0, NULL}
113 };
114
115 static PyTypeObject resptype = {
116     PyObject_HEAD_INIT(NULL)
117     .tp_name = "dolcon.Response",
118     .tp_basicsize = sizeof(struct respobj),
119     .tp_flags = Py_TPFLAGS_DEFAULT,
120     .tp_doc = "Dolda Connect response objects",
121     .tp_dealloc = (destructor)resptype_del,
122     .tp_methods = respmethods,
123 };
124
125 static struct respobj *makeresp(struct dc_response *resp)
126 {
127     struct respobj *new;
128     
129     new = (struct respobj *)resptype.tp_alloc(&resptype, 0);
130     new->resp = resp;
131     return(new);
132 }
133
134 static PyObject *mod_connect(PyObject *self, PyObject *args)
135 {
136     char *host;
137     int port;
138     
139     port = -1;
140     if(!PyArg_ParseTuple(args, "s|i", &host, &port))
141         return(NULL);
142     if(fd >= 0)
143         dc_disconnect();
144     if((fd = dc_connect(host, port)) < 0) {
145         PyErr_SetFromErrno(PyExc_OSError);
146         return(NULL);
147     }
148     return(Py_BuildValue("i", fd));
149 }
150
151 static PyObject *mod_disconnect(PyObject *self, PyObject *args)
152 {
153     if(fd != -1) {
154         dc_disconnect();
155         fd = -1;
156     }
157     Py_RETURN_NONE;
158 }
159
160 static PyObject *mod_connected(PyObject *self, PyObject *args)
161 {
162     if(fd == -1)
163         Py_RETURN_FALSE;
164     else
165         Py_RETURN_TRUE;
166 }
167
168 static PyObject *mod_select(PyObject *self, PyObject *args)
169 {
170     struct pollfd pfd;
171     int timeout, ret;
172     
173     timeout = -1;
174     if(!PyArg_ParseTuple(args, "|i", &timeout))
175         return(NULL);
176     if(fd < 0) {
177         PyErr_SetString(PyExc_RuntimeError, "Not connected");
178         return(NULL);
179     }
180     pfd.fd = fd;
181     pfd.events = POLLIN;
182     if(dc_wantwrite())
183         pfd.events |= POLLOUT;
184     if((ret = poll(&pfd, 1, timeout)) < 0) {
185         if(errno == EINTR)
186             Py_RETURN_FALSE;
187         dc_disconnect();
188         fd = -1;
189         PyErr_SetFromErrno(PyExc_OSError);
190         return(NULL);
191     }
192     if(((pfd.revents & POLLIN) && dc_handleread()) || ((pfd.revents & POLLOUT) && dc_handlewrite())) {
193         if(errno == 0) {
194             fd = -1;
195             Py_RETURN_FALSE;
196         }
197         PyErr_SetFromErrno(PyExc_OSError);
198     }
199     if(ret > 0)
200         Py_RETURN_TRUE;
201     Py_RETURN_FALSE;
202 }
203
204 static PyObject *mod_getresp(PyObject *self, PyObject *args)
205 {
206     int tag;
207     struct dc_response *resp;
208     
209     tag = -1;
210     if(!PyArg_ParseTuple(args, "|i", &tag))
211         return(NULL);
212     if(tag == -1)
213         resp = dc_getresp();
214     else
215         resp = dc_gettaggedresp(tag);
216     if(resp == NULL)
217         Py_RETURN_NONE;
218     return((PyObject *)makeresp(resp));
219 }
220
221 static int qcmd_cb(struct dc_response *resp)
222 {
223     PyObject *pycb, *args, *ret;
224     
225     pycb = resp->data;
226     args = Py_BuildValue("(N)", makeresp(resp));
227     ret = PyObject_Call(pycb, args, NULL);
228     Py_DECREF(args);
229     Py_DECREF(ret);
230     Py_DECREF(pycb);
231     return(2);
232 }
233
234 static PyObject *mod_qcmd(PyObject *self, PyObject *args, PyObject *kwargs)
235 {
236     int i, tag;
237     wchar_t **toks, *tok, *cmd;
238     size_t tokssize, toksdata, toksize;
239     PyObject *c, *n, *cb, *ret;
240     
241     toks = NULL;
242     tokssize = toksdata = 0;
243     cmd = NULL;
244     for(i = 0; i < PySequence_Size(args); i++) {
245         c = PySequence_GetItem(args, i);
246         if(!PyUnicode_Check(c)) {
247             n = PyUnicode_FromObject(c);
248             Py_DECREF(c);
249             c = n;
250         }
251         tok = smalloc((toksize = (PyUnicode_GetSize(c) + 1)) * sizeof(*tok));
252         tok[PyUnicode_AsWideChar((PyUnicodeObject *)c, tok, toksize)] = L'\0';
253         Py_DECREF(c);
254         if(cmd == NULL)
255             cmd = tok;
256         else
257             addtobuf(toks, tok);
258     }
259     if(cmd == NULL) {
260         PyErr_SetString(PyExc_TypeError, "qcmd needs at least 1 argument");
261         return(NULL);
262     }
263     addtobuf(toks, NULL);
264     ret = NULL;
265     if(PyMapping_HasKeyString(kwargs, "cb")) {
266         cb = PyMapping_GetItemString(kwargs, "cb");
267         if(PyCallable_Check(cb)) {
268             ret = PyInt_FromLong(dc_queuecmd(qcmd_cb, cb, cmd, L"%%a", toks, NULL));
269         } else {
270             PyErr_SetString(PyExc_TypeError, "Callback must be callable");
271             Py_DECREF(cb);
272         }
273     } else {
274         ret = PyInt_FromLong(dc_queuecmd(NULL, NULL, cmd, L"%%a", toks, NULL));
275     }
276     dc_freewcsarr(toks);
277     free(cmd);
278     return(ret);
279 }
280
281 static void login_cb(int err, wchar_t *reason, PyObject *cb)
282 {
283     char *errstr;
284     PyObject *args, *pyerr, *pyreason, *ret;
285     
286     switch(err) {
287     case DC_LOGIN_ERR_SUCCESS:
288         errstr = "success";
289         break;
290     case DC_LOGIN_ERR_NOLOGIN:
291         errstr = "nologin";
292         break;
293     case DC_LOGIN_ERR_SERVER:
294         errstr = "server";
295         break;
296     case DC_LOGIN_ERR_USER:
297         errstr = "user";
298         break;
299     case DC_LOGIN_ERR_CONV:
300         errstr = "conv";
301         break;
302     case DC_LOGIN_ERR_AUTHFAIL:
303         errstr = "authfail";
304         break;
305     }
306     pyerr = PyString_FromString(errstr);
307     if(reason == NULL)
308         Py_INCREF(pyreason = Py_None);
309     else
310         pyreason = PyUnicode_FromWideChar(reason, wcslen(reason));
311     args = PyTuple_Pack(2, pyerr, pyreason);
312     Py_DECREF(pyerr); Py_DECREF(pyreason);
313     ret = PyObject_Call(cb, args, NULL);
314     Py_DECREF(cb);
315     Py_DECREF(args);
316     Py_DECREF(ret);
317 }
318
319 static PyObject *mod_loginasync(PyObject *self, PyObject *args, PyObject *kwargs)
320 {
321     int useauthless;
322     char *username;
323     PyObject *o, *cb, *conv;
324     
325     username = NULL;
326     conv = NULL;
327     useauthless = 1;
328     if(!PyArg_ParseTuple(args, "O|i", &cb, &useauthless))
329         return(NULL);
330     if(!PyCallable_Check(cb)) {
331         PyErr_SetString(PyExc_TypeError, "Callback must be callable");
332         return(NULL);
333     }
334     if(PyMapping_HasKeyString(kwargs, "username")) {
335         o = PyMapping_GetItemString(kwargs, "username");
336         username = PyString_AsString(o);
337         Py_DECREF(o);
338         if(username == NULL)
339             return(NULL);
340     }
341     if(PyMapping_HasKeyString(kwargs, "conv")) {
342         conv = PyMapping_GetItemString(kwargs, "conv");
343         if(!PyCallable_Check(conv)) {
344             PyErr_SetString(PyExc_TypeError, "Conv callback must be callable");
345             return(NULL);
346         }
347         PyErr_SetString(PyExc_NotImplementedError, "Custom conv functions are not yet supported by the Python interface");
348         return(NULL);
349     }
350     Py_INCREF(cb);
351     dc_loginasync(username, useauthless, NULL, (void (*)(int, wchar_t *, void *))login_cb, cb);
352     Py_RETURN_NONE;
353 }
354
355 static PyObject *mod_lexsexpr(PyObject *self, PyObject *args)
356 {
357     PyObject *arg, *se, *ret;
358     wchar_t **arr, **ap, *buf;
359     size_t bufsize;
360     
361     if(!PyArg_ParseTuple(args, "O", &arg))
362         return(NULL);
363     if((se = PyUnicode_FromObject(arg)) == NULL)
364         return(NULL);
365     buf = smalloc((bufsize = (PyUnicode_GetSize(se) + 1)) * sizeof(*buf));
366     buf[PyUnicode_AsWideChar((PyUnicodeObject *)se, buf, bufsize)] = L'\0';
367     arr = dc_lexsexpr(buf);
368     free(buf);
369     Py_DECREF(se);
370     ret = PyList_New(0);
371     if(arr != NULL) {
372         for(ap = arr; *ap; ap++)
373             PyList_Append(ret, PyUnicode_FromWideChar(*ap, wcslen(*ap)));
374         dc_freewcsarr(arr);
375     }
376     return(ret);
377 }
378
379 static PyMethodDef methods[] = {
380     {"connect", mod_connect, METH_VARARGS,
381      "Connect to a Dolda Connect server"},
382     {"disconnect", mod_disconnect, METH_VARARGS,
383      "Disconnect from the server"},
384     {"connected", mod_connected, METH_VARARGS,
385      "Return a boolean indicated whether there currently is a connection to a server"},
386     {"select", mod_select, METH_VARARGS,
387      "Handle data from the server connection, optionally blocking until something happens"},
388     {"getresp", mod_getresp, METH_VARARGS,
389      "Get a queued response object"},
390     {"qcmd", (PyCFunction)mod_qcmd, METH_VARARGS | METH_KEYWORDS,
391      "Queue a command to be sent to the server"},
392     {"loginasync", (PyCFunction)mod_loginasync, METH_VARARGS | METH_KEYWORDS,
393      "Perform an asynchronous login procedure"},
394     {"lexsexpr", mod_lexsexpr, METH_VARARGS,
395      "Use a standard algorithm to lex a search expression"},
396     {NULL, NULL, 0, NULL}
397 };
398
399 PyMODINIT_FUNC initdolmod(void)
400 {
401     PyObject *m;
402     
403     if(PyType_Ready(&resptype) < 0)
404         return;
405     m = Py_InitModule("dolmod", methods);
406     Py_INCREF(&resptype);
407     PyModule_AddObject(m, "Response", (PyObject *)&resptype);
408     dc_init();
409 }