-
Notifications
You must be signed in to change notification settings - Fork 5
/
telegram_torrent.py
executable file
·420 lines (368 loc) · 13.9 KB
/
telegram_torrent.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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!/usr/bin/python3
import sys
import os
import feedparser
import telepot
import json
import random
import string
from os.path import expanduser
from urllib import parse
from apscheduler.schedulers.background import BackgroundScheduler
from telepot.delegate import per_chat_id, create_open, pave_event_space
CONFIG_FILE = 'setting.json'
class DelugeAgent:
def __init__(self, sender):
self.STATUS_SEED = 'Seeding'
self.STATUS_DOWN = 'Downloading'
self.STATUS_ERR = 'Error' # Need Verification
self.weightList = {}
self.sender = sender
def download(self, item):
os.system("deluge-console add " + item)
def getCurrentList(self):
return os.popen('deluge-console info').read()
def printElement(self, e):
outString = 'NAME: ' + e['title'] + \
'\n' + 'STATUS: ' + e['status'] + '\n'
outString += 'PROGRESS: ' + e['progress'] + '\n'
outString += '\n'
return outString
def parseList(self, result):
if not result:
return
outList = []
for entry in result.split('\n \n'):
title = entry[entry.index('Name:') + 6:entry.index('ID:') - 1]
status = entry[entry.index('State:'):].split(' ')[1]
ID = entry[entry.index('ID:') + 4:entry.index('State:') - 1]
if status == self.STATUS_DOWN:
progress = entry[entry.index(
'Progress:') + 10:entry.index('% [') + 1]
else:
progress = '0.00%'
element = {'title': title, 'status': status,
'ID': ID, 'progress': progress}
outList.append(element)
return outList
def isOld(self, ID, progress):
"""weightList = {ID:[%,w],..}"""
if ID in self.weightList:
if self.weightList[ID][0] == progress:
self.weightList[ID][1] += 1
else:
self.weightList[ID][0] = progress
self.weightList[ID][1] = 1
if self.weightList[ID][1] > 3:
return True
else:
self.weightList[ID] = [progress, 1]
return False
return False
def check_torrents(self):
currentList = self.getCurrentList()
outList = self.parseList(currentList)
if not bool(outList):
self.sender.sendMessage('The torrent List is empty')
scheduler.remove_all_jobs()
self.weightList.clear()
return
for e in outList:
if e['status'] == self.STATUS_SEED:
self.sender.sendMessage(
'Download completed: {0}'.format(e['title']))
self.removeFromList(e['ID'])
elif e['status'] == self.STATUS_ERR:
self.sender.sendMessage(
'Download canceled (Error): {0}\n'.format(e['title']))
self.removeFromList(e['ID'])
else:
if self.isOld(e['ID'], e['progress']):
self.sender.sendMessage(
'Download canceled (pending): {0}\n'.format(e['title']))
self.removeFromList(e['ID'])
return
def removeFromList(self, ID):
if ID in self.weightList:
del self.weightList[ID]
os.system("deluge-console del " + ID)
class TransmissionAgent:
def __init__(self, sender):
self.STATUS_SEED = 'Seeding'
self.STATUS_ERR = 'Error' # Need Verification
self.weightList = {}
self.sender = sender
cmd = 'transmission-remote '
if TRANSMISSION_ID_PW:
cmd = cmd + '-n ' + TRANSMISSION_ID_PW + ' '
else:
cmd = cmd + '-n ' + 'transmission:transmission' + ' '
self.transmissionCmd = cmd
def download(self, magnet):
if TRANSMISSION_PORT:
pcmd = '-p ' + TRANSMISSION_PORT + ' '
else:
pcmd = ''
if DOWNLOAD_PATH:
wcmd = '-w ' + DOWNLOAD_PATH + ' '
else:
wcmd = ''
os.system(self.transmissionCmd + pcmd + wcmd + '-a ' + magnet)
def getCurrentList(self):
l = os.popen(self.transmissionCmd + '-l').read()
rowList = l.split('\n')
if len(rowList) < 4:
return
else:
return l
def printElement(self, e):
outString = 'NAME: ' + e['title'] + \
'\n' + 'STATUS: ' + e['status'] + '\n'
outString += 'PROGRESS: ' + e['progress'] + '\n'
outString += '\n'
return outString
def parseList(self, result):
if not result:
return
outList = []
resultlist = result.split('\n')
titlelist = resultlist[0]
resultlist = resultlist[1:-2]
for entry in resultlist:
title = entry[titlelist.index('Name'):].strip()
status = entry[titlelist.index(
'Status'):titlelist.index('Name') - 1].strip()
progress = entry[titlelist.index(
'Done'):titlelist.index('Done') + 4].strip()
id_ = entry[titlelist.index(
'ID'):titlelist.index('Done') - 1].strip()
if id_[-1:] == '*':
id_ = id_[:-1]
element = {'title': title, 'status': status,
'ID': id_, 'progress': progress}
outList.append(element)
return outList
def removeFromList(self, ID):
if ID in self.weightList:
del self.weightList[ID]
os.system(self.transmissionCmd + '-t ' + ID + ' -r')
def isOld(self, ID, progress):
"""weightList = {ID:[%,w],..}"""
if ID in self.weightList:
if self.weightList[ID][0] == progress:
self.weightList[ID][1] += 1
else:
self.weightList[ID][0] = progress
self.weightList[ID][1] = 1
if self.weightList[ID][1] > 3:
return True
else:
self.weightList[ID] = [progress, 1]
return False
return False
def check_torrents(self):
currentList = self.getCurrentList()
outList = self.parseList(currentList)
if not bool(outList):
self.sender.sendMessage('The torrent List is empty')
scheduler.remove_all_jobs()
self.weightList.clear()
return
for e in outList:
if e['status'] == self.STATUS_SEED:
self.sender.sendMessage(
'Download completed: {0}'.format(e['title']))
self.removeFromList(e['ID'])
elif e['status'] == self.STATUS_ERR:
self.sender.sendMessage(
'Download canceled (Error): {0}\n'.format(e['title']))
self.removeFromList(e['ID'])
else:
if self.isOld(e['ID'], e['progress']):
self.sender.sendMessage(
'Download canceled (pending): {0}\n'.format(e['title']))
self.removeFromList(e['ID'])
return
class Torrenter(telepot.helper.ChatHandler):
YES = '<OK>'
NO = '<NO>'
MENU0 = 'HOME'
MENU1 = 'SEARCH TORRENT'
MENU1_1 = 'INPUT A WORD'
MENU1_2 = 'CHOOSE AN ITEM'
MENU2 = 'TORRENT LIST'
rssUrl = """https://torrentkim1.net/bbs/rss.php?k="""
GREETING = "SELECT MENU"
global scheduler
global DOWNLOAD_PATH
mode = ''
navi = feedparser.FeedParserDict()
def __init__(self, *args, **kwargs):
super(Torrenter, self).__init__(*args, **kwargs)
self.agent = self.createAgent(AGENT_TYPE)
def createAgent(self, agentType):
if agentType == 'deluge':
return DelugeAgent(self.sender)
if agentType == 'transmission':
return TransmissionAgent(self.sender)
raise ('invalid torrent client')
def open(self, initial_msg, seed):
self.menu()
def menu(self):
mode = ''
show_keyboard = {'keyboard': [
[self.MENU1], [self.MENU2], [self.MENU0]]}
self.sender.sendMessage(self.GREETING, reply_markup=show_keyboard)
def yes_or_no(self, comment):
show_keyboard = {'keyboard': [[self.YES, self.NO], [self.MENU0]]}
self.sender.sendMessage(comment, reply_markup=show_keyboard)
def tor_get_keyword(self):
self.mode = self.MENU1_1
self.sender.sendMessage('Enter a Keyword')
def put_menu_button(self, l):
menulist = [self.MENU0]
l.append(menulist)
return l
def isDiskEnough(self):
stat = os.statvfs(DOWNLOAD_PATH)
freesize = (stat.f_bavail*stat.f_bsize)/(10**9)
if (freesize < 6):
self.sender.sendMessage('Error: The Disk size is under 6GB: {}GB'.format(freesize))
return False
return True
def tor_search(self, keyword):
self.mode = ''
self.sender.sendMessage('Searching torrent..')
self.navi = feedparser.parse(self.rssUrl + parse.quote(keyword))
outList = []
if not self.navi.entries:
self.sender.sendMessage('Sorry, No results')
self.mode = self.MENU1_1
return
for (i, entry) in enumerate(self.navi.entries):
if i == 10:
break
title = str(i + 1) + ". " + entry.title
templist = []
templist.append(title)
outList.append(templist)
show_keyboard = {'keyboard': self.put_menu_button(outList)}
self.sender.sendMessage('Choose one from below',
reply_markup=show_keyboard)
self.mode = self.MENU1_2
def tor_download(self, selected):
self.mode = ''
if not self.isDiskEnough():
self.menu()
return
index = int(selected.split('.')[0]) - 1
magnet = self.navi.entries[index].link
self.agent.download(magnet)
self.sender.sendMessage('Start Downloading')
self.navi.clear()
if not scheduler.get_jobs():
scheduler.add_job(self.agent.check_torrents, 'interval', minutes=1)
self.menu()
def tor_show_list(self):
self.mode = ''
self.sender.sendMessage('Let me check the torrent list..')
result = self.agent.getCurrentList()
if not result:
self.sender.sendMessage('The torrent list is empty')
self.menu()
return
outList = self.agent.parseList(result)
for e in outList:
self.sender.sendMessage(self.agent.printElement(e))
def handle_command(self, command):
if command == self.MENU0:
self.menu()
elif command == self.MENU1:
self.tor_get_keyword()
elif command == self.MENU2:
self.tor_show_list()
elif self.mode == self.MENU1_1: # Get Keyword
self.tor_search(command)
elif self.mode == self.MENU1_2: # Download Torrent
self.tor_download(command)
def handle_smifile(self, file_id, file_name):
try:
self.sender.sendMessage('Saving subtitle file..')
bot.download_file(file_id, DOWNLOAD_PATH + file_name)
except Exception as inst:
self.sender.sendMessage('ERORR: {0}'.format(inst))
return
self.sender.sendMessage('Done')
def handle_seedfile(self, file_id, file_name):
try:
self.sender.sendMessage('Saving torrent file..')
generated_file_path = DOWNLOAD_PATH + "/" + \
"".join(random.sample(string.ascii_letters, 8)) + ".torrent"
bot.download_file(file_id, generated_file_path)
self.agent.download(generated_file_path)
os.system("rm " + generated_file_path)
if not scheduler.get_jobs():
scheduler.add_job(self.agent.check_torrents,
'interval', minutes=1)
except Exception as inst:
self.sender.sendMessage('ERORR: {0}'.format(inst))
return
self.sender.sendMessage('Start Downloading')
def on_chat_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
# Check ID
if not chat_id in VALID_USERS:
print("Permission Denied")
return
if content_type is 'text':
self.handle_command(msg['text'])
return
if content_type is 'document':
file_name = msg['document']['file_name']
if file_name[-3:] == 'smi':
file_id = msg['document']['file_id']
self.handle_smifile(file_id, file_name)
return
if file_name[-7:] == 'torrent':
file_id = msg['document']['file_id']
self.handle_seedfile(file_id, file_name)
return
self.sender.sendMessage('Invalid File')
return
self.sender.sendMessage('Invalid File')
def on_close(self, exception):
pass
def parseConfig(filename):
path = os.path.dirname(os.path.realpath(__file__)) + '/' + filename
f = open(path, 'r')
js = json.loads(f.read())
f.close()
return js
def getConfig(config):
global TOKEN
global AGENT_TYPE
global VALID_USERS
global DOWNLOAD_PATH
TOKEN = config['common']['token']
AGENT_TYPE = config['common']['agent_type']
VALID_USERS = config['common']['valid_users']
DOWNLOAD_PATH = config['common']['download_path']
if DOWNLOAD_PATH[0] == '~':
DOWNLOAD_PATH = expanduser('~') + DOWNLOAD_PATH[1:]
if AGENT_TYPE == 'transmission':
global TRANSMISSION_ID_PW
global TRANSMISSION_PORT
TRANSMISSION_ID_PW = config['transmission']['id_pw']
TRANSMISSION_PORT = config['transmission']['port']
config = parseConfig(CONFIG_FILE)
if not bool(config):
print("Err: Setting file is not found")
exit()
getConfig(config)
scheduler = BackgroundScheduler()
scheduler.start()
bot = telepot.DelegatorBot(TOKEN, [
pave_event_space()(
per_chat_id(), create_open, Torrenter, timeout=120),
])
bot.message_loop(run_forever='Listening ...')