utility-scripts/process_ebooks.py

63 lines
1.8 KiB
Python
Executable File

#!/usr/bin/env python
#
# Process ebooks (unzip or unrar) and put them into calibre.
#
# Either drop files as arguments to this script on the command line
# or run it as is, where it'll pick up the most recent files (defined by
# age) in your ebook directory and add them to calibre.
#
import glob, fileinput, os, re, shutil, subprocess, sys, tempfile, time
import rarfile, zipfile
ebook_dir = "~/Downloads/xchat"
age = time.time() - 5*60*60 # 5 hours
books=[]
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
books.append(arg)
else:
ebook_dir = os.path.expanduser(ebook_dir)
for root, dirs, files in os.walk(ebook_dir):
for file in files:
if re.search('.(rar|zip|epub|mobi|lit|html)(.\d+)?', file):
try:
if os.path.getmtime(file) >= age:
books.append(os.path.join(root, file))
except OSError:
pass
for book in books:
print "Processing " + book + "..."
next
# create temp dir
tmp=tempfile.mkdtemp()
# unrar or unzip into temp dir
if re.search('.rar', book):
# unrar
archive = rarfile.RarFile(book)
archive.extractall(tmp)
elif re.search('.zip', book):
# unzip
archive = zipfile.ZipFile(book)
archive.extractall(tmp)
elif re.search('.(epub|mobi|lit|html)', book):
# copy book into tmp
shutil.copy(book, tmp)
# find epub, mobi or lit and import into calibre
for root, dirs, files in os.walk(tmp):
for file in files:
if re.search('.(epub|mobi|lit|html)$', file):
try:
subprocess.call(["calibredb", "add", os.path.join(root, file)])
except Exception, e:
print e
pass
# cleanup
shutil.rmtree(tmp)
# vim: set expandtab shiftwidth=4 softtabstop=4 :