ebook-downloader/bookrequest.py
2023-03-28 22:10:40 -04:00

68 lines
2.2 KiB
Python

from libgen_api import *
import requests, sys, getopt, configparser, shutil, os
config = configparser.ConfigParser()
try:
config.read('config.ini')
except Exception as e:
print(e)
print('Config file not found. Please ensure conf.ini is in the same \
location as bookrequest.py')
def searchBook(book, unattended=False):
s = LibgenSearch()
filter = {"Extension": "epub"}
results = s.search_title_filtered(book, filter)
j = 0
if len(results) == 0:
print('No results found. Quiting...')
sys.exit()
for i in results:
i = i['Title']
if unattended == False:
print(f'[{j}]: {i}')
j+=1
if unattended is False:
choice = input('Please select the book to download or press enter to exit: ')
if choice == '':
print('Quiting...')
sys.exit()
elif unattended is True:
choice = 0
download = results[int(choice)]
download = s.resolve_download_links(download)
link = download['GET']
result = {"title": results[int(choice)]['Title'],
"author": results[int(choice)]['Author'],
"link": link
}
return result
def downloadBook(bookDict):
print('Downloading book. Please wait...')
r = requests.get(bookDict['link'], allow_redirects=True)
open(bookDict['title']+'.epub', 'wb').write(r.content)
print('Book Downloaded!')
os.makedirs(config['data']['folder_location'] + '\\' + bookDict['author'])
shutil.move(bookDict['title']+'.epub', config['data']['folder_location'] + '\\' + bookDict['author'] + '\\' + bookDict['title']+'.epub')
def main(argv):
if len(argv) == 0:
book = input('Please enter the title of the book you are looking for: ')
results = searchBook(book)
downloadBook(results)
else:
opts, args = getopt.getopt(argv, "hb:",["help=","book="])
for opt, arg in opts:
if opt in ('-h', "--help"):
print('bookrequest.py -b <booktitle>')
elif opt in ('-b', '--book'):
book = arg
results = searchBook(book, unattended=True)
downloadBook(results)
if __name__ == "__main__":
main(sys.argv[1:])