summaryrefslogtreecommitdiff
path: root/lib/LuaTask.cc
blob: ac3df8d5933f82e7ead0e28d643658cca59374b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <LuaTask.h>
#include <LuaHandle.h>
#ifndef LUATASK_OMIT_HTTPCLIENT
#include <HttpClient.h>
#endif

LuaTask * LuaTask::top = 0;

LuaTask::LuaTask(Lua * _L, const String & _cmd) : L(_L), cmd(_cmd), nargs(0), c(0), b(0) {
    if (top) {
        WaitFor(top);
    } else {
        SetBurst();
    }
    top = this;
    stacktop = L->gettop() + 1;
}

LuaTask::LuaTask(Lua * _L, int _nargs) : L(_L), cmd(""), nargs(_nargs), c(0), b(0) {
    if (top) {
        WaitFor(top);
    } else {
        SetBurst();
    }
    top = this;
    stacktop = L->gettop() - nargs;
}

LuaTask::~LuaTask() {
    if (top == this) {
        top = 0;
    }
}

String LuaTask::GetName() {
    return "LuaTask(" + cmd + ")";
}

int LuaTask::Do() throw (GeneralException) {
    switch (current) {
    case 0:
        current = 1;
        if (cmd != "") {
            L->resume(cmd);
        } else {
            L->resume(nargs);
        }
    case 1:
        if (c) {
            int nargs = 0;

#ifndef LUATASK_OMIT_HTTPCLIENT
            if (task == "HttpClient") {
                LuaBuffer o(b);
                o.pushdestruct(L);
                nargs = 1;
            }
#endif

            delete c;
            c = 0;

            L->resume(nargs);
        }
        if (L->gettop() >= 1) {
            task = L->tostring(1);
            if (task == "") {
                L->error("Must precise a task-type to execute.");
                return TASK_DONE;
#ifndef LUATASK_OMIT_HTTPCLIENT
            } else if (task == "HttpClient") {
                String url = L->tostring(2);
                t_headers headers;

                b = new Buffer(true);

                headers.push_back("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0");
                c = new HttpClient(url, b, "", headers);
                WaitFor(c);
                Suspend(TASK_ON_HOLD);
#endif
            } else {
                L->error("Unknow requested task: " + task);
                return TASK_DONE;
            }
        } else {
            return TASK_DONE;
        }
    }

    return TASK_ON_HOLD;
}