-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpythonplugins.pas
382 lines (325 loc) · 11.4 KB
/
pythonplugins.pas
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
unit PythonPlugins;
interface
procedure pythonLoadPlugins();
implementation
uses
sysutils, fpjson, process,
PythonEngine,
LongpollChat, Utils, Database, VKAPI;
type
TPythonCommand = class (TCommand)
handlerObj: PPyObject;
procedure handler(msg: TJSONObject); override;
end;
TPythonHandler = class (THandler)
handlerObj: PPyObject;
procedure handler(msg: TJSONObject); override;
end;
var
py: TPythonEngine;
module: TPythonModule;
function JSONtoPyObj(json: TJSONData): PPyObject;
var
enum: TJSONEnum;
obj: PPyObject;
begin
case json.JSONType of
TJSONtype.jtNull:
exit(py.Py_None);
TJSONtype.jtBoolean:
if json.asBoolean then
exit(PPyObject(py.Py_True))
else
exit(PPyObject(py.Py_False));
TJSONtype.jtNumber:
if TJSONNumber(json).NumberType = TJSONNumberType.ntFloat then
exit(py.PyFloat_FromDouble(json.asFloat))
else
exit(py.PyLong_FromLongLong(json.asInt64));
TJSONtype.jtString:
exit(py.PyUnicode_FromWideString(json.AsUnicodeString));
TJSONtype.jtObject:
begin
obj := py.PyDict_New();
for enum in json do
begin
py.PyDict_SetItemString(obj, PChar(enum.key), JSONtoPyObj(enum.value))
end;
exit(obj);
end;
TJSONtype.jtArray:
begin
obj := py.PyList_New(0);
for enum in json do
begin
py.PyList_Append(obj, JSONtoPyObj(enum.value));
end;
exit(obj);
end;
end;
end;
function PyObjToJSON(obj: PPyObject): TJSONData;
var
idx: PNativeInt;
idx2: Integer;
key, value: PPyObject;
begin
if obj = py.Py_None then
exit(TJSONNull.Create)
else if py.PyBool_Check(obj) then
if Boolean(py.PyObject_IsTrue(obj)) then
exit(TJSONBoolean.Create(true))
else
exit(TJSONBoolean.Create(false))
else if py.PyLong_Check(obj) then
exit(TJSONInt64Number.Create(py.PyLong_AsLongLong(obj)))
else if py.PyFloat_Check(obj) then
exit(TJSONFloatNumber.Create(py.PyFloat_AsDouble(obj)))
else if py.PyString_Check(obj) then
exit(TJSONString.Create(py.PyString_AsDelphiString(obj)))
else if py.PyDict_Check(obj) then
begin
result := TJSONObject.Create;
while Boolean(py.PyDict_Next(obj, idx, @key, @value)) do
TJSONObject(result).Add(py.PyObjectAsString(key), PyObjToJSON(value));
end
else if py.PyList_Check(obj) then
begin
result := TJSONArray.Create;
for idx2 := 0 to py.PyList_Size(obj) - 1 do
TJSONArray(result).Add(PyObjToJSON(py.PyList_GetItem(obj, idx2)));
end;
end;
procedure TPythonCommand.handler(msg: TJSONObject);
var
arglist: PPyObject;
gil: PyGILState_STATE;
begin
gil := py.PyGILState_Ensure();
arglist := py.Py_BuildValue('(O)', JSONtoPyObj(msg));
if py.PyObject_CallObject(self.handlerObj, arglist) = nil then
py.PyErr_Print();
py.Py_DECREF(arglist);
py.PyGILState_Release(gil);
end;
procedure TPythonHandler.handler(msg: TJSONObject);
var
arglist: PPyObject;
gil: PyGILState_STATE;
begin
gil := py.PyGILState_Ensure();
arglist := py.Py_BuildValue('(O)', JSONtoPyObj(msg));
if py.PyObject_CallObject(self.handlerObj, arglist) = nil then
py.PyErr_Print();
py.Py_DECREF(arglist);
py.PyGILState_Release(gil);
end;
function registerHandlerPython(self, args: PPyObject) : PPyObject; cdecl;
var
nameP: PChar;
nameLen: Integer;
handlerObj: PPyObject;
hndlr: TPythonHandler;
begin
hndlr := TPythonHandler.Create();
py.PyArg_ParseTuple(args, 's#O', @nameP, @nameLen, @handlerObj);
setLength(hndlr.name, nameLen);
hndlr.name := nameP;
hndlr.handlerObj := handlerObj;
py.Py_INCREF(hndlr.handlerObj);
//add critical sections!!!!!!!!
setLength(handlers, length(handlers)+1);
handlers[high(handlers)] := hndlr;
Result := py.Py_None;
py.Py_IncRef(Result);
end;
function registerCommandPython(self, args: PPyObject) : PPyObject; cdecl;
var
cmdObj, levelObj, kwObj: PPyObject;
cmd: TPythonCommand;
keywordObj: PPyObject;
i: Integer;
begin
cmd := TPythonCommand.Create();
py.PyArg_ParseTuple(args, 'O', @cmdObj);
py.PyObjectAsString(cmdObj);
levelObj := py.PyObject_GetAttrString(cmdObj, 'level');
cmd.level := py.PyLong_AsLongLong(levelObj);
kwObj := py.PyObject_GetAttrString(cmdObj, 'keywords');
for i := 0 to py.PyList_Size(kwObj)-1 do
begin
setLength(cmd.keywords, length(cmd.keywords)+1);
keywordObj := py.PyList_GetItem(kwObj, i);
cmd.keywords[high(cmd.keywords)] := UTF8Encode(py.PyUnicode_AsWideString(py.PyObject_Str(keywordObj)));
end;
cmd.handlerObj := py.PyObject_GetAttrString(cmdObj, 'handler');
py.Py_INCREF(cmd.handlerObj);
// ADD CRITICAL SECTIONS!!!!!!!
setLength(commandsArray, length(commandsArray)+1);
commandsArray[high(commandsArray)] := cmd;
Result := py.Py_None;
py.Py_IncRef(Result);
end;
function changeHandlerPython(self, args: PPyObject) : PPyObject; cdecl;
var
handlerName: String;
handlerNameP: PChar;
handlerNameLen: Integer;
userId: Integer;
handler: THandler;
begin
py.PyArg_ParseTuple(args, 'is#', @userId, @handlerNameP, @handlerNameLen);
setLength(handlerName, handlerNameLen);
handlerName := handlerNameP;
if handlerName = 'main' then
dbExecIn('UPDATE users SET handler="main" WHERE id="'+intToStr(userId)+'";')
else
for handler in handlers do
if handler.name = handlerName then
begin
dbExecIn('UPDATE users SET handler="'+handlerName+'" WHERE id="'+intToStr(userId)+'";');
break;
end;
Result := py.Py_None;
py.Py_IncRef(Result);
end;
function dbExecInPython(self, args: PPyObject) : PPyObject; cdecl;
var
query: String;
queryP: PChar;
queryLen: Integer;
begin
py.PyArg_ParseTuple(args, 's#', @queryP, @queryLen);
setLength(query, queryLen);
query := queryP;
dbExecIn(query);
Result := py.Py_None;
py.Py_IncRef(Result);
end;
function dbExecOutPython(self, args: PPyObject) : PPyObject; cdecl;
var
query: String;
queryP: PChar;
queryLen: Integer;
dbResponse: TJSONArray;
begin
py.PyArg_ParseTuple(args, 's#', @queryP, @queryLen);
setLength(query, queryLen);
query := queryP;
dbResponse := dbExecOut(query);
result := JSONtoPyObj(dbResponse);
py.Py_IncRef(result);
FreeAndNil(dbResponse);
end;
function vkApiPython(self, args: PPyObject) : PPyObject; cdecl;
var
method: String;
methodP: PChar;
methodLen: Integer;
parametersObj: PPyObject;
parameters: Array of String;
key, value: PPyObject;
idx: PNativeInt;
idx2: Int64 = 0;
response: TJSONData;
begin
parametersObj := nil;
setLength(parameters, 0);
py.PyArg_ParseTuple(args, 's#|O', @methodP, @methodLen, @parametersObj);
setLength(method, methodLen);
method := methodP;
if (parametersObj <> nil) and
py.PyDict_Check(parametersObj) and
(py.PyDict_Size(parametersObj) <> 0) then
begin
idx := @idx2;
while Boolean(py.PyDict_Next(parametersObj, idx, @key, @value)) do
begin
setLength(parameters, length(parameters)+2);
parameters[high(parameters)-1] := UTF8Encode(py.PyUnicode_AsWideString(py.PyObject_Str(key)));
parameters[high(parameters)] := UTF8Encode(py.PyUnicode_AsWideString(py.PyObject_Str(value)));
end;
end;
response := callVkApi(method, parameters);
result := JSONtoPyObj(response);
py.Py_IncRef(result);
FreeAndNil(response);
SetLength(parameters, 0);
end;
function logWritePython(self, args: PPyObject) : PPyObject; cdecl;
var
strP, logTypeStrP: PChar;
strL, logTypeStrL: Integer;
str, logTypeStr: String;
logType: TLogType;
begin
logTypeStrP := nil;
py.PyArg_ParseTuple(args, 's#|s#', @strP, @strL, @logTypeStrP, @logTypeStrL);
setLength(str, strL);
str := strP;
if logTypeStrP <> nil then
begin
setLength(logTypeStr, logTypeStrL);
logTypeStr := logTypeStrP;
end;
case logTypeStr of
'normal': logType := TLogType.logNormal;
'good': logType := TLogType.logGood;
'error': logType := TLogType.logError;
'warning': logType := TLogType.logWarning;
else logType := TLogType.logNormal;
end;
logWrite(str, logType);
result := py.Py_None;
py.Py_IncRef(result);
end;
procedure pythonLoadPlugins();
var
fSearchRes: TSearchRec;
pName, pModule: PPyObject;
pluginName: String;
ldConfOutput: String;
thread: PPyThreadState;
begin
logWrite('Create python instance...');
py := TPythonEngine.Create(Nil);
py.DllName := 'libpython3.7m.so';
runCommand('find /usr/lib -name '+py.DllName, ldConfOutput);
py.DllPath := ldConfOutput.split(LineEnding)[0].replace(py.DllName, '');
logWrite('Loading python library: "'+py.DllPath+py.DllName+'"');
// создание модуля kb и создание его функций
module:= TPythonModule.Create(nil);
module.Engine := py;
module.ModuleName := 'kb';
module.AddMethod('reg_handler', @registerHandlerPython, 'Register new handler function');
module.AddMethod('reg_command', @registerCommandPython, 'Register new command');
module.AddMethod('change_handler', @changeHandlerPython, 'Change handler for VKID');
module.AddMethod('dbexec_in', @dbExecInPython, 'Main database SQL query IN');
module.AddMethod('dbexec_out', @dbExecOutPython, 'Main database SQL query OUT');
module.AddMethod('vkapi', @vkApiPython, 'Request to VK API');
module.AddMethod('log_write', @logWritePython, 'Write text to log');
// init python
py.LoadDll();
//создание переменных модуля kb
module.SetVar('CONFIG', JSONtoPyObj(config));
module.SetVar('config', JSONtoPyObj(config));
py.PyRun_SimpleString('import sys');
py.PyRun_SimpleString('sys.path.append("./plugins")');
py.PyRun_SimpleString('sys.dont_write_bytecode = True');
logWrite('Python instance created');
if findFirst('./plugins/*.py', faAnyFile, fSearchRes) = 0 then
repeat
pluginName := copy(fSearchRes.name, 0, length(fSearchRes.name)-3);
logWrite('Loading and initilizing python plugin: '+pluginName);
pName := py.PyUnicode_FromWideString(pluginName);
pModule := py.PyImport_Import(pName);
if pModule = nil then
begin
py.PyErr_Print();
halt();
end;
until findNext(fSearchRes) <> 0;
findClose(fSearchRes);
thread := py.PyEval_SaveThread();
end;
end.