Loading opds_catalog/dl.py +52 −0 Original line number Diff line number Diff line Loading @@ -19,6 +19,58 @@ from book_tools.format.mimetype import Mimetype from constance import config from PIL import Image def getFileName(book): if config.SOPDS_TITLE_AS_FILENAME: transname = utils.translit(book.title + '.' + book.format) else: transname = utils.translit(book.filename) return utils.to_ascii(transname) def getFileData(book): full_path = os.path.join(config.SOPDS_ROOT_LIB, book.path) if book.cat_type==opdsdb.CAT_INP: # Убираем из пути INPX файл inpx_path, zip_name = os.path.split(full_path) path, inpx_file = os.path.split(inpx_path) full_path = os.path.join(path,zip_name) z = None fz = None s = None if book.cat_type==opdsdb.CAT_NORMAL: file_path=os.path.join(full_path, book.filename) try: fo=codecs.open(file_path, "rb") s = fo.read() except FileNotFoundError: s = None elif book.cat_type in [opdsdb.CAT_ZIP, opdsdb.CAT_INP]: try: fz=codecs.open(full_path, "rb") z = zipfile.ZipFile(fz, 'r', allowZip64=True) fo= z.open(book.filename) s=fo.read() except FileNotFoundError: s = None fo.close() if z: z.close() if fz: fz.close() return s def getFileDataZip(s,transname): dio = io.BytesIO() zo = zipfile.ZipFile(dio, 'w', zipfile.ZIP_DEFLATED) zo.writestr(transname, s) zo.close() buf = dio.getvalue() return buf def Download(request, book_id, zip_flag): """ Загрузка файла книги """ book = Book.objects.get(id=book_id) Loading opds_catalog/management/commands/sopds_telebot.py +60 −12 Original line number Diff line number Diff line Loading @@ -9,7 +9,7 @@ from django.conf import settings as main_settings from django.urls import reverse from opds_catalog.models import Book, Author from opds_catalog import settings from opds_catalog import settings, dl from constance import config from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler from telegram import InlineKeyboardButton, InlineKeyboardMarkup Loading Loading @@ -111,21 +111,65 @@ class Command(BaseCommand): authors = ', '.join([a['full_name'] for a in book.authors.values()]) response = '<b>%(title)s</b>\n%(author)s\n<b>Аннотация:</b>%(annotation)s\n' % {'title': book.title, 'author': authors, 'annotation':book.annotation} buttons = [InlineKeyboardButton(book.format.upper(), url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download", kwargs={"book_id": book.id, "zip_flag": 0}))] buttons = [InlineKeyboardButton(book.format.upper(), callback_data='/getfile%s'%book_id)] # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download", kwargs={"book_id": book.id, "zip_flag": 0}))] if not book.format in settings.NOZIP_FORMATS: buttons += [InlineKeyboardButton(book.format.upper()+'.ZIP', url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download",kwargs={"book_id": book.id, "zip_flag": 1}))] if (config.SOPDS_FB2TOEPUB != "") and (book.format == 'fb2'): buttons += [InlineKeyboardButton('EPUB', url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "epub"}))] if (config.SOPDS_FB2TOMOBI != "") and (book.format == 'fb2'): buttons += [InlineKeyboardButton('MOBI', url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "mobi"}))] buttons += [InlineKeyboardButton(book.format.upper()+'.ZIP', callback_data='/getfilezip%s'%book_id)] # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download",kwargs={"book_id": book.id, "zip_flag": 1}))] # if (config.SOPDS_FB2TOEPUB != "") and (book.format == 'fb2'): # buttons += [InlineKeyboardButton('EPUB', # # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "epub"}))] # if (config.SOPDS_FB2TOMOBI != "") and (book.format == 'fb2'): # buttons += [InlineKeyboardButton('MOBI', # # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "mobi"}))] markup = InlineKeyboardMarkup([buttons]) bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML', reply_markup=markup) self.logger.info("Send download buttons: %s" % buttons) self.logger.info("Send download buttons.") def getBookFile(self, bot, update): book_id_set=re.findall(r'\d+$',update.message.text) if len(book_id_set)==1: try: book_id=int(book_id_set[0]) book=Book.objects.get(id=book_id) except: book=None else: book_id=None book=None if book==None: response = 'Книга по указанной Вами ссылке не найдена, попробуйте повторить поиск книги сначала.' bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML') self.logger.info("Not find download links: %s" % response) return filename=dl.getFileName(book) bot.send_document(chat_id=update.message.chat_id, document=dl.getFileData(book),filename=filename) self.logger.info("Send file: %s" % filename) def getBookFileZip(self, bot, update): book_id_set=re.findall(r'\d+$',update.message.text) if len(book_id_set)==1: try: book_id=int(book_id_set[0]) book=Book.objects.get(id=book_id) except: book=None else: book_id=None book=None if book==None: response = 'Книга по указанной Вами ссылке не найдена, попробуйте повторить поиск книги сначала.' bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML') self.logger.info("Not find download links: %s" % response) return filename=dl.getFileName(book) bot.send_document(chat_id=update.message.chat_id, document=dl.getFileDataZip(dl.getFileData(book),filename),filename=filename+'.zip') self.logger.info("Send file: %s" % (filename+'.zip')) def start(self): writepid(self.pidfile) Loading @@ -137,10 +181,14 @@ class Command(BaseCommand): start_command_handler = CommandHandler('start', self.startCommand) getBook_handler = MessageHandler(Filters.text, self.getBooks) download_handler = RegexHandler('^/download\d+$',self.downloadBooks) sendfile_handler = RegexHandler('^/getfile\d+$', self.getBookFile) sendfilezip_handler = RegexHandler('^/getfilezip\d+$', self.getBookFileZip) updater.dispatcher.add_handler(start_command_handler) updater.dispatcher.add_handler(getBook_handler) updater.dispatcher.add_handler(download_handler) updater.dispatcher.add_handler(sendfile_handler) updater.dispatcher.add_handler(sendfilezip_handler) updater.start_polling(clean=True) updater.idle() except (KeyboardInterrupt, SystemExit): Loading Loading
opds_catalog/dl.py +52 −0 Original line number Diff line number Diff line Loading @@ -19,6 +19,58 @@ from book_tools.format.mimetype import Mimetype from constance import config from PIL import Image def getFileName(book): if config.SOPDS_TITLE_AS_FILENAME: transname = utils.translit(book.title + '.' + book.format) else: transname = utils.translit(book.filename) return utils.to_ascii(transname) def getFileData(book): full_path = os.path.join(config.SOPDS_ROOT_LIB, book.path) if book.cat_type==opdsdb.CAT_INP: # Убираем из пути INPX файл inpx_path, zip_name = os.path.split(full_path) path, inpx_file = os.path.split(inpx_path) full_path = os.path.join(path,zip_name) z = None fz = None s = None if book.cat_type==opdsdb.CAT_NORMAL: file_path=os.path.join(full_path, book.filename) try: fo=codecs.open(file_path, "rb") s = fo.read() except FileNotFoundError: s = None elif book.cat_type in [opdsdb.CAT_ZIP, opdsdb.CAT_INP]: try: fz=codecs.open(full_path, "rb") z = zipfile.ZipFile(fz, 'r', allowZip64=True) fo= z.open(book.filename) s=fo.read() except FileNotFoundError: s = None fo.close() if z: z.close() if fz: fz.close() return s def getFileDataZip(s,transname): dio = io.BytesIO() zo = zipfile.ZipFile(dio, 'w', zipfile.ZIP_DEFLATED) zo.writestr(transname, s) zo.close() buf = dio.getvalue() return buf def Download(request, book_id, zip_flag): """ Загрузка файла книги """ book = Book.objects.get(id=book_id) Loading
opds_catalog/management/commands/sopds_telebot.py +60 −12 Original line number Diff line number Diff line Loading @@ -9,7 +9,7 @@ from django.conf import settings as main_settings from django.urls import reverse from opds_catalog.models import Book, Author from opds_catalog import settings from opds_catalog import settings, dl from constance import config from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler from telegram import InlineKeyboardButton, InlineKeyboardMarkup Loading Loading @@ -111,21 +111,65 @@ class Command(BaseCommand): authors = ', '.join([a['full_name'] for a in book.authors.values()]) response = '<b>%(title)s</b>\n%(author)s\n<b>Аннотация:</b>%(annotation)s\n' % {'title': book.title, 'author': authors, 'annotation':book.annotation} buttons = [InlineKeyboardButton(book.format.upper(), url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download", kwargs={"book_id": book.id, "zip_flag": 0}))] buttons = [InlineKeyboardButton(book.format.upper(), callback_data='/getfile%s'%book_id)] # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download", kwargs={"book_id": book.id, "zip_flag": 0}))] if not book.format in settings.NOZIP_FORMATS: buttons += [InlineKeyboardButton(book.format.upper()+'.ZIP', url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download",kwargs={"book_id": book.id, "zip_flag": 1}))] if (config.SOPDS_FB2TOEPUB != "") and (book.format == 'fb2'): buttons += [InlineKeyboardButton('EPUB', url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "epub"}))] if (config.SOPDS_FB2TOMOBI != "") and (book.format == 'fb2'): buttons += [InlineKeyboardButton('MOBI', url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "mobi"}))] buttons += [InlineKeyboardButton(book.format.upper()+'.ZIP', callback_data='/getfilezip%s'%book_id)] # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download",kwargs={"book_id": book.id, "zip_flag": 1}))] # if (config.SOPDS_FB2TOEPUB != "") and (book.format == 'fb2'): # buttons += [InlineKeyboardButton('EPUB', # # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "epub"}))] # if (config.SOPDS_FB2TOMOBI != "") and (book.format == 'fb2'): # buttons += [InlineKeyboardButton('MOBI', # # url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "mobi"}))] markup = InlineKeyboardMarkup([buttons]) bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML', reply_markup=markup) self.logger.info("Send download buttons: %s" % buttons) self.logger.info("Send download buttons.") def getBookFile(self, bot, update): book_id_set=re.findall(r'\d+$',update.message.text) if len(book_id_set)==1: try: book_id=int(book_id_set[0]) book=Book.objects.get(id=book_id) except: book=None else: book_id=None book=None if book==None: response = 'Книга по указанной Вами ссылке не найдена, попробуйте повторить поиск книги сначала.' bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML') self.logger.info("Not find download links: %s" % response) return filename=dl.getFileName(book) bot.send_document(chat_id=update.message.chat_id, document=dl.getFileData(book),filename=filename) self.logger.info("Send file: %s" % filename) def getBookFileZip(self, bot, update): book_id_set=re.findall(r'\d+$',update.message.text) if len(book_id_set)==1: try: book_id=int(book_id_set[0]) book=Book.objects.get(id=book_id) except: book=None else: book_id=None book=None if book==None: response = 'Книга по указанной Вами ссылке не найдена, попробуйте повторить поиск книги сначала.' bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML') self.logger.info("Not find download links: %s" % response) return filename=dl.getFileName(book) bot.send_document(chat_id=update.message.chat_id, document=dl.getFileDataZip(dl.getFileData(book),filename),filename=filename+'.zip') self.logger.info("Send file: %s" % (filename+'.zip')) def start(self): writepid(self.pidfile) Loading @@ -137,10 +181,14 @@ class Command(BaseCommand): start_command_handler = CommandHandler('start', self.startCommand) getBook_handler = MessageHandler(Filters.text, self.getBooks) download_handler = RegexHandler('^/download\d+$',self.downloadBooks) sendfile_handler = RegexHandler('^/getfile\d+$', self.getBookFile) sendfilezip_handler = RegexHandler('^/getfilezip\d+$', self.getBookFileZip) updater.dispatcher.add_handler(start_command_handler) updater.dispatcher.add_handler(getBook_handler) updater.dispatcher.add_handler(download_handler) updater.dispatcher.add_handler(sendfile_handler) updater.dispatcher.add_handler(sendfilezip_handler) updater.start_polling(clean=True) updater.idle() except (KeyboardInterrupt, SystemExit): Loading