Skip to content

Commit 0d30f19

Browse files
committed
Project Rebase
- Changelog: Improved Performance Fixed Stucked Messages Seperated Download Progress Status From Listener Disabled Upload Progress (Temporarily)
1 parent 4f9fa3f commit 0d30f19

18 files changed

+246
-228
lines changed

Dockerfile

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
FROM python:3.8-slim-buster
1+
FROM ubuntu:18.04
22

33
WORKDIR /usr/src/app
44
RUN chmod 777 /usr/src/app
55
COPY . .
6-
RUN pip install --no-cache-dir -r requirements.txt
76
RUN apt-get update
8-
RUN apt-get install -y aria2
7+
RUN apt-get install -y aria2 megatools ffmpeg python3 python3-pip
8+
RUN pip3 install --no-cache-dir -r requirements.txt
99

10-
CMD ["bash","start.sh"]
10+
CMD ["bash","start.sh"]

aria.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
export MAX_DOWNLOAD_SPEED=0
2-
export MAX_CONCURRENT_DOWNLOADS=2
2+
export MAX_CONCURRENT_DOWNLOADS=3
33
aria2c --enable-rpc --rpc-listen-all=false --rpc-listen-port 6800 \
44
--max-connection-per-server=10 --rpc-max-request-size=1024M \
55
--seed-time=0.01 --min-split-size=10M --follow-torrent=mem --split=10 \

bot/__init__.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import logging
22
import aria2p
33
import threading
4-
from telegram.ext import Updater
4+
import telegram.ext as tg
5+
from telegram import Bot
56
import os
6-
from dotenv import load_dotenv
7+
import configparser
78
import time
89

910
botStartTime = time.time()
@@ -15,11 +16,13 @@
1516
handlers=[logging.FileHandler('log.txt'), logging.StreamHandler()],
1617
level=logging.INFO)
1718

18-
load_dotenv('config.env')
19+
config = configparser.ConfigParser()
20+
config.read('bot/config.ini')
1921

22+
Interval = []
2023

2124
def getConfig(name: str):
22-
return os.environ[name]
25+
return config['DEFAULT'][name]
2326

2427

2528
LOGGER = logging.getLogger(__name__)
@@ -39,6 +42,7 @@ def getConfig(name: str):
3942
)
4043
)
4144

45+
4246
DOWNLOAD_DIR = None
4347
BOT_TOKEN = None
4448

@@ -71,6 +75,8 @@ def getConfig(name: str):
7175
LOGGER.error("One or more env variables missing! Exiting now")
7276
exit(1)
7377

74-
bot = Bot(BOT_TOKEN)
75-
updater = Updater(token=BOT_TOKEN, use_context=True)
78+
bot = Bot(BOT_TOKEN)
79+
updater = tg.Updater(token=BOT_TOKEN)
7680
dispatcher = updater.dispatcher
81+
82+

bot/__main__.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88
import shutil
99
from .helper.telegram_helper.filters import CustomFilters
1010
from bot.helper.telegram_helper.bot_commands import BotCommands
11-
from .modules import authorize, list, cancel_mirror, mirror_status, mirror
11+
from .modules import authorize, list, cancel_mirror, mirror_status, mirror,eval, shell,lydia
1212

1313
@run_async
14-
def stats(update, context):
14+
def stats(bot,update):
1515
currentTime = get_readable_time((time.time() - botStartTime))
1616
total, used, free = shutil.disk_usage('.')
1717
total = get_readable_file_size(total)
@@ -21,31 +21,31 @@ def stats(update, context):
2121
f'Total disk space: {total}\n' \
2222
f'Used: {used}\n' \
2323
f'Free: {free}'
24-
sendMessage(stats, context, update)
24+
sendMessage(stats, bot, update)
2525

2626

2727

2828
@run_async
29-
def start(update, context):
29+
def start(bot,update):
3030
sendMessage("This is a bot which can mirror all your links to Google drive!\n"
31-
"Type /help to get a list of available commands", context, update)
31+
"Type /help to get a list of available commands", bot, update)
3232

3333

3434
@run_async
35-
def ping(update, context):
35+
def ping(bot,update):
3636
start_time = int(round(time.time() * 1000))
37-
reply = sendMessage("Starting Ping", context, update)
37+
reply = sendMessage("Starting Ping", bot, update)
3838
end_time = int(round(time.time()*1000))
39-
editMessage(f'{end_time - start_time} ms', context, reply)
39+
editMessage(f'{end_time - start_time} ms',reply)
4040

4141

4242
@run_async
43-
def log(update, context):
44-
sendLogFile(context, update)
43+
def log(bot,update):
44+
sendLogFile(bot, update)
4545

4646

4747
@run_async
48-
def bot_help(update, context):
48+
def bot_help(bot,update):
4949
help_string = f'''
5050
/{BotCommands.HelpCommand}: To get this message
5151
@@ -66,7 +66,7 @@ def bot_help(update, context):
6666
/{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports
6767
6868
'''
69-
sendMessage(help_string, context, update)
69+
sendMessage(help_string, bot, update)
7070

7171

7272
def main():

bot/helper/ext_utils/bot_utils.py

+33-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from bot import download_dict, download_dict_lock
22
import logging
33
import re
4+
import threading
5+
import time
6+
import math
47

58
LOGGER = logging.getLogger(__name__)
69

@@ -22,14 +25,30 @@ class MirrorStatus:
2225

2326
SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
2427

28+
class setInterval :
29+
def __init__(self,interval,action) :
30+
self.interval=interval
31+
self.action=action
32+
self.stopEvent=threading.Event()
33+
thread=threading.Thread(target=self.__setInterval)
34+
thread.start()
35+
36+
def __setInterval(self) :
37+
nextTime=time.time()+self.interval
38+
while not self.stopEvent.wait(nextTime-time.time()) :
39+
nextTime+=self.interval
40+
self.action()
41+
42+
def cancel(self) :
43+
self.stopEvent.set()
2544

2645
def get_readable_file_size(size_in_bytes) -> str:
2746
index = 0
2847
while size_in_bytes >= 1024:
2948
size_in_bytes /= 1024
3049
index += 1
3150
try:
32-
return f'{round(size_in_bytes, 2)} {SIZE_UNITS[index]}'
51+
return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}'
3352
except IndexError:
3453
return 'File too large'
3554

@@ -80,20 +99,21 @@ def get_download_str():
8099
result += (status.progress() + status.speed() + status.status())
81100
return result
82101

83-
84102
def get_readable_message():
85103
with download_dict_lock:
86-
progress_list = list(download_dict.values())
87-
msg = ''
88-
for download in progress_list:
89-
msg += f'<b>Name:</b> {download.name()}\n' \
90-
f'<b>Status:</b> {download.status()}\n' \
91-
f'<code>{get_progress_bar_string(download)}</code> {download.progress()} of {download.size()}\n' \
92-
f'<b>Speed:</b> {download.speed()}\n' \
93-
f'<b>ETA:</b> {download.eta()}\n\n'
94-
# LOGGER.info(msg)
95-
return msg
96-
104+
msg = ""
105+
for download in list(download_dict.values()):
106+
msg += f"<i>{download.name()}</i> - "
107+
if download.status() == MirrorStatus.STATUS_UPLOADING:
108+
msg += "Uploading\n\n"
109+
elif download.status() == MirrorStatus.STATUS_ARCHIVING:
110+
msg += "Archiving\n\n"
111+
elif download.status() == MirrorStatus.STATUS_WAITING:
112+
msg += "Queued\n\n"
113+
else:
114+
msg += f"<code>{get_progress_bar_string(download)} {download.progress()}</code> of {get_readable_file_size(download.download().total_length)}" \
115+
f" at {get_readable_file_size(download.download().download_speed)}ps, ETA: {download.eta()}\n\n"
116+
return msg
97117

98118
def get_readable_time(seconds: int) -> str:
99119
result = ''
+24-43
Original file line numberDiff line numberDiff line change
@@ -1,90 +1,71 @@
1-
from bot import DOWNLOAD_STATUS_UPDATE_INTERVAL, aria2
1+
from bot import DOWNLOAD_STATUS_UPDATE_INTERVAL, aria2, Interval
22
from bot.helper.ext_utils.bot_utils import *
33
from .download_helper import DownloadHelper
44
from .download_status import DownloadStatus
5+
from bot.helper.telegram_helper.message_utils import *
6+
from bot.helper.mirror_utils.gdriveTools import GoogleDriveHelper
57
import threading
68
from aria2p import API, ClientException
79
import schedule
810
import time
911

10-
1112
class AriaDownloadHelper(DownloadHelper):
1213

13-
def __init__(self, listener):
14-
super(AriaDownloadHelper, self).__init__(listener)
15-
self.__is_torrent = False
14+
def __init__(self,listener):
1615
self.gid = None
17-
self.__scheduler = schedule.every(DOWNLOAD_STATUS_UPDATE_INTERVAL).seconds.do(self.__onDownloadProgress())
18-
19-
def __updater(self):
20-
while True:
21-
with self._resource_lock:
22-
if self.__scheduler is None:
23-
break
24-
schedule.run_pending()
25-
time.sleep(1)
16+
self._listener = listener
17+
self._resource_lock = threading.Lock()
2618

2719
def __onDownloadStarted(self, api, gid):
2820
with self._resource_lock:
2921
if self.gid == gid:
3022
download = api.get_download(gid)
3123
self.name = download.name
32-
self.size = download.length
33-
self._listener.onDownloadStarted()
34-
self.should_update = True
35-
36-
def __onDownloadProgress(self):
37-
with self._resource_lock:
38-
download = aria2.get_download(self.gid)
39-
self.progress = download.progress
40-
self.progress_string = download.progress_string
41-
self.eta_string = download.eta_string
42-
self.eta = download.eta
24+
update_all_messages()
4325

4426
def __onDownloadComplete(self, api: API, gid):
4527
with self._resource_lock:
4628
if self.gid == gid:
47-
if self.__is_torrent:
48-
self.__is_torrent = False
29+
if api.get_download(gid).followed_by_ids:
4930
self.gid = api.get_download(gid).followed_by_ids[0]
31+
download_dict[self._listener.uid] = DownloadStatus(self.gid,self._listener)
32+
update_all_messages()
5033
LOGGER.info(f'Changed gid from {gid} to {self.gid}')
5134
else:
52-
self._listener.onDownloadComplete()
53-
self.__scheduler = None
35+
self._listener.onDownloadComplete()
5436

5537
def __onDownloadPause(self, api, gid):
5638
if self.gid == gid:
39+
LOGGER.info("Called onDownloadPause")
5740
self._listener.onDownloadError('Download stopped by user!')
5841

5942
def __onDownloadStopped(self, api, gid):
6043
if self.gid == gid:
61-
self._listener.onDownloadError()
44+
LOGGER.info("Called on_download_stop")
6245

6346
def __onDownloadError(self, api, gid):
6447
with self._resource_lock:
6548
if self.gid == gid:
6649
download = api.get_download(gid)
6750
error = download.error_message
51+
LOGGER.info(f"Download Error: {error}")
6852
self._listener.onDownloadError(error)
6953

7054
def add_download(self, link: str, path):
7155
if is_magnet(link):
7256
download = aria2.add_magnet(link, {'dir': path})
73-
self.__is_torrent = True
7457
else:
7558
download = aria2.add_uris([link], {'dir': path})
76-
if download.name.endswith('.torrent'):
77-
self.__is_torrent = True
7859
self.gid = download.gid
60+
with download_dict_lock:
61+
download_dict[self._listener.uid] = DownloadStatus(self.gid,self._listener)
62+
if download.error_message:
63+
self._listener.onDownloadError(download.error_message)
64+
return
65+
LOGGER.info(f"Started: {self.gid} DIR:{download.dir} ")
7966
aria2.listen_to_notifications(threaded=True, on_download_start=self.__onDownloadStarted,
80-
on_download_error=self.__onDownloadError,
81-
on_download_complete=self.__onDownloadComplete)
82-
threading.Thread(target=self.__updater).start()
67+
on_download_error=self.__onDownloadError,
68+
on_download_pause=self.__onDownloadPause,
69+
on_download_stop=self.__onDownloadStopped,
70+
on_download_complete=self.__onDownloadComplete)
8371

84-
def cancel_download(self):
85-
# Returns None if successfully cancelled, else error string
86-
download = aria2.get_download(self.gid)
87-
try:
88-
download.pause(force=True)
89-
except ClientException:
90-
return 'Unable to cancel download! Internal error.'

bot/helper/mirror_utils/download_helper.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,20 @@
33

44

55
class MethodNotImplementedError(NotImplementedError):
6-
def __int__(self):
6+
def __init__(self):
77
super(self, 'Not implemented method')
88

99

1010
class DownloadHelper:
11-
def __int__(self, listener):
11+
def __init__(self):
1212
self.name = '' # Name of the download; empty string if no download has been started
1313
self.size = 0.0 # Size of the download
1414
self.downloaded_bytes = 0.0 # Bytes downloaded
1515
self.speed = 0.0 # Download speed in bytes per second
1616
self.progress = 0.0
1717
self.progress_string = '0.00%'
1818
self.eta = 0 # Estimated time of download complete
19-
self.eta_string = '0s'
20-
self._listener = listener # A listener class which have event callbacks
19+
self.eta_string = '0s' # A listener class which have event callbacks
2120
self._resource_lock = threading.Lock()
2221

2322
def add_download(self, link: str, path):

bot/helper/mirror_utils/download_status.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,16 @@ def get_download(gid):
88

99
class DownloadStatus:
1010

11-
def __init__(self, gid, message_id):
11+
def __init__(self, gid, listener):
1212
self.upload_name = None
1313
self.is_archiving = False
1414
self.__gid = gid
1515
self.__download = get_download(gid)
16-
self.__uid = message_id
16+
self.__uid = listener.uid
17+
self._listener = listener
1718
self.upload_helper = None
19+
self.last = None
20+
self.is_waiting = False
1821

1922
def __update(self):
2023
self.__download = get_download(self.__gid)
@@ -54,6 +57,7 @@ def speed(self):
5457
def name(self):
5558
if self.upload_name is not None:
5659
return self.upload_name
60+
self.__update()
5761
return self.__download.name
5862

5963
def path(self):

bot/helper/mirror_utils/gdriveTools.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,9 @@ def upload(self, file_name: str):
140140
self.__listener.onUploadStarted(_list, index)
141141
file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}"
142142
file_path = f"{file_dir}/{file_name}"
143-
LOGGER.info("Uploading File: " + file_name)
143+
LOGGER.info("Uploading File: " + file_path)
144144
self.start_time = time.time()
145-
threading.Thread(target=self._on_upload_progress).start()
145+
#threading.Thread(target=self._on_upload_progress).start()
146146
if os.path.isfile(file_path):
147147
try:
148148
mime_type = get_mime_type(file_path)

bot/helper/mirror_utils/listeners.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
class MirrorListeners:
22
def __init__(self, context, update):
3-
self.context = context
3+
self.bot = context
44
self.update = update
55
self.message = update.message
66
self.uid = self.message.message_id

0 commit comments

Comments
 (0)