forked from acidpop/xpebot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsdownload.py
executable file
·340 lines (279 loc) · 12.2 KB
/
dsdownload.py
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
#-*- coding: utf-8 -*-
import main
import psycopg2
import CommonUtil
import telepot
import traceback
from LogManager import log
# psycopg2 document page : http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
class dsdownload(object):
"""description of class"""
#global conn
#global curs
TOKEN = main.botConfig.GetBotToken()
dsm_id = main.botConfig.GetDsmId()
chat_id = main.botConfig.GetChatId()
conn = None
curs = None
bot = telepot.Bot(TOKEN)
def db_connect(self, host='localhost', dbname='download', user='postgres', password=''):
#global curs
#global conn
conn_string = "host='%s' dbname='%s' user='%s' password='%s'" % (host, dbname, user, password)
try:
self.conn = psycopg2.connect(conn_string)
self.conn.autocommit = True
except Exception as e:
log.error("dsdownload db_connect error")
log.error(e)
return False
self.curs = self.conn.cursor()
return True
def db_query(self, query):
ret = True
if self.curs == None:
ret = self.db_connect()
if ret == True:
try:
self.curs.execute(query.decode('utf-8'))
result = self.curs.fetchall()
except psycopg2.IntegrityError as err:
if err.pgcode != '23505':
log.error('db_query|DB IntegrityError : %s', err)
else:
log.error('db_query|DB Not Intergrity Error : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
except Exception as err:
log.error('db_query|DB Exception : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
return False, ''
except:
log.error("db_query|psycopg except : " + e)
self.curs.close()
self.conn.close()
self.curs = None
return False, ''
return True, result
def db_exec(self, query):
ret = True
if self.curs == None:
ret = self.db_connect()
if ret == True:
try:
self.curs.execute(query)
log.info('db_exec complete')
return True
except psycopg2.IntegrityError as err:
if err.pgcode != '23505':
log.error('db_exec|DB IntegrityError : %s', err)
else:
log.error('db_exec|DB Not Intergrity Error : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
except Exception as err:
log.error('db_exec|DB Exception : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
except:
log.error("db_exec|psycopg except : " + e)
self.curs.close()
self.conn.close()
self.curs = None
return False
def CreateMonitorTable(self):
query = """CREATE TABLE btdownload_event(
task_id integer NOT NULL,
username character varying(128),
filename text,
status integer,
total_size bigint,
isread integer,
create_time date
);"""
if self.db_exec(query) :
log.info('CreateMonitorTable Success')
else:
log.info('CreateMonitorTable Fail')
return
def CreateMonitorProcedure(self):
query = """CREATE OR REPLACE FUNCTION process_btdownload_event() RETURNS TRIGGER AS $btdownload_event$
DECLARE
rec_count integer;
BEGIN
IF (TG_OP = 'INSERT') THEN
RETURN NEW;
ELSIF (TG_OP = 'UPDATE') THEN
IF (NEW.status = 2 AND NEW.total_size > 0 AND NEW.current_size > 0) THEN
SELECT COUNT(*) into rec_count FROM btdownload_event WHERE task_id = NEW.task_id AND status = 2;
IF ( rec_count = 0 ) THEN
INSERT INTO btdownload_event VALUES(NEW.task_id, NEW.username, NEW.filename, NEW.status, NEW.total_size, 0, now());
END IF;
ELSIF (NEW.status = 5 ) THEN
SELECT COUNT(*) into rec_count FROM btdownload_event WHERE task_id = NEW.task_id AND status = 5;
IF ( rec_count = 0 ) THEN
INSERT INTO btdownload_event VALUES(NEW.task_id, NEW.username, NEW.filename, NEW.status, NEW.total_size, 0, now());
END IF;
ELSIF (NEW.status = 118) THEN
UPDATE download_queue SET status = 5, extra_info = '' WHERE task_id = NEW.task_id;
DELETE FROM task_plugin WHERE task_id = NEW.task_id;
DELETE FROM thumbnail WHERE task_id = NEW.task_id;
END IF;
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
DELETE FROM btdownload_event WHERE task_id = OLD.task_id;
RETURN OLD;
END IF;
RETURN NULL;
END;
$btdownload_event$ LANGUAGE plpgsql;"""
if self.db_exec(query) :
log.info('CreateMonitorProcedure Success')
else:
log.info('CreateMonitorProcedure Fail')
return
def CreateMonitorTrigger(self):
query = """CREATE TRIGGER btdownload_event
AFTER INSERT OR UPDATE OR DELETE ON download_queue
FOR EACH ROW EXECUTE PROCEDURE process_btdownload_event();"""
if self.db_exec(query) :
log.info('CreateMonitorTrigger Success')
else:
log.info('CreateMonitorTrigger Fail')
return
def dsdown_status_to_str(self, status):
if status == 1:
return "대기 중"
elif status == 2:
return "다운로드 중"
elif status == 3:
return "일시 정지"
elif status == 4:
return "종료 중"
elif status == 5:
return "다운로드 완료"
elif status == 6:
return "해시 체크 중"
elif status == 7:
return "시딩 중"
elif status == 8:
return "파일 호스팅 대기"
elif status == 9:
return "압축 해제 중"
else:
return "알 수 없는 코드 [" + str(status) + "]"
def CheckDownloadMonitorTable(self):
log.info('CheckDownloadMonitorTable start...')
ret = True
if self.curs == None:
ret = self.db_connect()
if ret == True:
table_query = "select count(*) from information_schema.tables where table_name = 'btdownload_event';"
proc_query = "select count(*) from pg_proc where proname = 'process_btdownload_event';"
trigger_query = "select count(*) from pg_trigger where tgname = 'btdownload_event';"
try:
# Check Table Exist
self.curs.execute(table_query)
rowitem = self.curs.fetchone()
if rowitem[0] == 0:
log.info('monitor table is not exist.. try create table')
self.CreateMonitorTable()
self.bot.sendMessage(self.chat_id, 'DS Download Monitor Table 등록')
# Check Procedure Exist
self.curs.execute(proc_query)
rowitem = self.curs.fetchone()
if rowitem[0] == 0:
log.info('monitor procedure is not exist.. try create procedure')
self.CreateMonitorProcedure()
self.bot.sendMessage(self.chat_id, 'DS Download Monitor Procedure 등록')
# Check Trigger Exist
self.curs.execute(trigger_query)
rowitem = self.curs.fetchone()
if rowitem[0] == 0:
log.info('monitor trigger is not exist... try create trigger')
self.CreateMonitorTrigger()
self.bot.sendMessage(self.chat_id, 'DS Download Monitor Trigger 등록')
except psycopg2.IntegrityError as err:
if err.pgcode != '23505':
log.error('CheckDownloadMonitorTable|DB IntegrityError : %s', err)
else:
log.error('CheckDownloadMonitorTable|DB Not Intergrity Error : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
except Exception as err:
log.error('CheckDownloadMonitorTable|DB Exception : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
except:
log.error("CheckDownloadMonitorTable|psycopg except : " + e)
self.curs.close()
self.conn.close()
self.curs = None
log.info('CheckDownloadMonitorTable exit...')
return
def PrintException(self):
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
#print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
log.info('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
def download_db_timer(self):
ret = True
if self.curs == None:
ret = self.db_connect()
if ret == True:
query = 'SELECT * FROM btdownload_event WHERE isread=0;'
try:
self.curs.execute(query)
rowitems = self.curs.fetchall()
if len(rowitems) > 0:
for row in rowitems:
# task_id|username|filename|status|total_size|isread|create_time
task_id = row[0]
username = row[1]
tor_name = row[2]
status = self.dsdown_status_to_str(row[3])
total_size = CommonUtil.hbytes(row[4])
# bot.sendMessage(24501560, "<b>Bold Text</b>\n<pre color='blue'>Test Message</pre>\nHTML Mode", parse_mode='HTML')
# Markdown 문법에서 _ 는 * 로 대체 되므로 \_ 로 변경
tor_name = tor_name.replace('_', '\_')
# Markdown 문법에서 *는 MarkDown 문법을 시작하는 문자이므로 \* 로 변경
tor_name = tor_name.replace('*', '\*')
msg = '*상태* : %s\n*이름* : %s\n*크기* : %s\n*사용자* : %s' % (status, tor_name, total_size, username)
self.bot.sendMessage(self.chat_id, msg, parse_mode='Markdown')
query = "UPDATE btdownload_event SET isread = 1 WHERE task_id = %d" % (task_id)
self.curs.execute(query)
except psycopg2.IntegrityError as err:
if err.pgcode != '23505':
log.error('download_db_timer|DB IntegrityError : %s', err)
else:
log.error('download_db_timer|DB Not Intergrity Error : %s', err)
self.curs.close()
self.conn.close()
self.curs = None
except Exception as err:
log.error('download_db_timer|DB Exception : %s', err)
log.error("download_db_timer Exception : %s", traceback.format_exc())
strErr = str(err.message)
log.error('error ---- %s, %d', strErr, strErr.find('relation "btdownload_event" does not exist'))
if strErr.find('relation "btdownload_event" does not exist') != -1:
self.CheckDownloadMonitorTable()
self.curs.close()
self.conn.close()
self.curs = None
except:
log.error("download_db_timer|psycopg except : " + e)
self.curs.close()
self.conn.close()
self.curs = None
#finally: