1
0
mirror of https://github.com/janeczku/calibre-web synced 2024-11-24 10:37:23 +00:00

Adding unfinished upload function

This commit is contained in:
Cervinko Cera 2016-04-03 23:52:32 +02:00
parent cb2ac4d142
commit 3ddecc007c
5 changed files with 213 additions and 131 deletions

203
cps/db.py
View File

@ -25,99 +25,99 @@ conn.connection.create_function('title_sort', 1, title_sort)
Base = declarative_base()
books_authors_link = Table('books_authors_link', Base.metadata,
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('author', Integer, ForeignKey('authors.id'), primary_key=True)
)
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('author', Integer, ForeignKey('authors.id'), primary_key=True)
)
books_tags_link = Table('books_tags_link', Base.metadata,
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('tag', Integer, ForeignKey('tags.id'), primary_key=True)
)
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('tag', Integer, ForeignKey('tags.id'), primary_key=True)
)
books_series_link = Table('books_series_link', Base.metadata,
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('series', Integer, ForeignKey('series.id'), primary_key=True)
)
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('series', Integer, ForeignKey('series.id'), primary_key=True)
)
books_ratings_link = Table('books_ratings_link', Base.metadata,
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('rating', Integer, ForeignKey('ratings.id'), primary_key=True)
)
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('rating', Integer, ForeignKey('ratings.id'), primary_key=True)
)
books_languages_link = Table('books_languages_link', Base.metadata,
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('lang_code', Integer, ForeignKey('languages.id'), primary_key=True)
)
Column('book', Integer, ForeignKey('books.id'), primary_key=True),
Column('lang_code', Integer, ForeignKey('languages.id'), primary_key=True)
)
class Comments(Base):
__tablename__ = 'comments'
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
text = Column(String)
book = Column(Integer, ForeignKey('books.id'))
id = Column(Integer, primary_key=True)
text = Column(String)
book = Column(Integer, ForeignKey('books.id'))
def __init__(self, text, book):
self.text = text
self.book = book
def __init__(self, text, book):
self.text = text
self.book = book
def __repr__(self):
return u"<Comments({0})>".format(self.text)
def __repr__(self):
return u"<Comments({0})>".format(self.text)
class Tags(Base):
__tablename__ = 'tags'
__tablename__ = 'tags'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String)
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String)
def __init__(self, name):
self.name = name
def __init__(self, name):
self.name = name
def __repr__(self):
return u"<Tags('{0})>".format(self.name)
def __repr__(self):
return u"<Tags('{0})>".format(self.name)
class Authors(Base):
__tablename__ = 'authors'
__tablename__ = 'authors'
id = Column(Integer, primary_key=True)
name = Column(String)
sort = Column(String)
link = Column(String)
id = Column(Integer, primary_key=True)
name = Column(String)
sort = Column(String)
link = Column(String)
def __init__(self, name, sort, link):
self.name = name
self.sort = sort
self.link = link
def __init__(self, name, sort, link):
self.name = name
self.sort = sort
self.link = link
def __repr__(self):
return u"<Authors('{0},{1}{2}')>".format(self.name, self.sort, self.link)
def __repr__(self):
return u"<Authors('{0},{1}{2}')>".format(self.name, self.sort, self.link)
class Series(Base):
__tablename__ = 'series'
__tablename__ = 'series'
id = Column(Integer, primary_key=True)
name = Column(String)
sort = Column(String)
id = Column(Integer, primary_key=True)
name = Column(String)
sort = Column(String)
def __init__(self, name, sort):
self.name = name
self.sort = sort
def __init__(self, name, sort):
self.name = name
self.sort = sort
def __repr__(self):
return u"<Series('{0},{1}')>".format(self.name, self.sort)
def __repr__(self):
return u"<Series('{0},{1}')>".format(self.name, self.sort)
class Ratings(Base):
__tablename__ = 'ratings'
__tablename__ = 'ratings'
id = Column(Integer, primary_key=True)
rating = Column(Integer)
id = Column(Integer, primary_key=True)
rating = Column(Integer)
def __init__(self,rating):
self.rating = rating
def __init__(self,rating):
self.rating = rating
def __repr__(self):
return u"<Ratings('{0}')>".format(self.rating)
def __repr__(self):
return u"<Ratings('{0}')>".format(self.rating)
class Languages(Base):
__tablename__ = 'languages'
@ -132,59 +132,58 @@ class Languages(Base):
return u"<Languages('{0}')>".format(self.lang_code)
class Data(Base):
__tablename__ = 'data'
__tablename__ = 'data'
id = Column(Integer, primary_key=True)
book = Column(Integer, ForeignKey('books.id'))
format = Column(String)
uncompressed_size = Column(Integer)
name = Column(String)
id = Column(Integer, primary_key=True)
book = Column(Integer, ForeignKey('books.id'))
format = Column(String)
uncompressed_size = Column(Integer)
name = Column(String)
def __init__(self, book, format, uncompressed_size, name):
self.book = book
self.format = format
self.uncompressed_size = uncompressed_size
self.name = name
def __init__(self, book, format, uncompressed_size, name):
self.book = book
self.format = format
self.uncompressed_size = uncompressed_size
self.name = name
def __repr__(self):
return u"<Data('{0},{1}{2}{3}')>".format(self.book, self.format, self.uncompressed_size, self.name)
def __repr__(self):
return u"<Data('{0},{1}{2}{3}')>".format(self.book, self.format, self.uncompressed_size, self.name)
class Books(Base):
__tablename__ = 'books'
__tablename__ = 'books'
id = Column(Integer,primary_key=True)
title = Column(String)
sort = Column(String)
author_sort = Column(String)
timestamp = Column(String)
pubdate = Column(String)
series_index = Column(String)
last_modified = Column(String)
path = Column(String)
has_cover = Column(Integer)
id = Column(Integer,primary_key=True)
title = Column(String)
sort = Column(String)
author_sort = Column(String)
timestamp = Column(String)
pubdate = Column(String)
series_index = Column(String)
last_modified = Column(String)
path = Column(String)
has_cover = Column(Integer)
authors = relationship('Authors', secondary=books_authors_link, backref='books')
tags = relationship('Tags', secondary=books_tags_link, backref='books')
comments = relationship('Comments', backref='books')
data = relationship('Data', backref='books')
series = relationship('Series', secondary=books_series_link, backref='books')
ratings = relationship('Ratings', secondary=books_ratings_link, backref='books')
languages = relationship('Languages', secondary=books_languages_link, backref='books')
authors = relationship('Authors', secondary=books_authors_link, backref='books')
tags = relationship('Tags', secondary=books_tags_link, backref='books')
comments = relationship('Comments', backref='books')
data = relationship('Data', backref='books')
series = relationship('Series', secondary=books_series_link, backref='books')
ratings = relationship('Ratings', secondary=books_ratings_link, backref='books')
languages = relationship('Languages', secondary=books_languages_link, backref='books')
def __init__(self, title, sort, author_sort, timestamp, pubdate, series_index, last_modified, path, has_cover, authors, tags):
self.title = title
self.sort = sort
self.author_sort = author_sort
self.timestamp = timestamp
self.pubdate = pubdate
self.series_index = series_index
self.last_modified = last_modified
self.path = path
self.has_cover = has_cover
self.tags = tags
def __init__(self, title, sort, author_sort, timestamp, pubdate, series_index, last_modified, path, has_cover, authors, tags):
self.title = title
self.sort = sort
self.author_sort = author_sort
self.timestamp = timestamp
self.pubdate = pubdate
self.series_index = series_index
self.last_modified = last_modified
self.path = path
self.has_cover = has_cover
def __repr__(self):
return u"<Books('{0},{1}{2}{3}{4}{5}{6}{7}{8}')>".format(self.title, self.sort, self.author_sort, self.timestamp, self.pubdate, self.series_index, self.last_modified ,self.path, self.has_cover)
def __repr__(self):
return u"<Books('{0},{1}{2}{3}{4}{5}{6}{7}{8}')>".format(self.title, self.sort, self.author_sort, self.timestamp, self.pubdate, self.series_index, self.last_modified ,self.path, self.has_cover)
Base.metadata.create_all(engine)
Session = sessionmaker()

View File

@ -154,7 +154,7 @@ def get_attachment(file_path):
'permissions?')
return None
def get_valid_filename(value):
def get_valid_filename(value, replace_whitespace=True):
"""
Returns the given string converted to a string that can be used for a clean
filename. Limits num characters to 128 max.
@ -164,7 +164,9 @@ def get_valid_filename(value):
value = unicodedata.normalize('NFKD', value)
re_slugify = re.compile('[^\w\s-]', re.UNICODE)
value = unicode(re_slugify.sub('', value).strip())
value = re.sub('[\s]+', '_', value, flags=re.U)
if replace_whitespace:
value = re.sub('[\s]+', '_', value, flags=re.U)
value = value.replace(u"\u00DF", "ss")
return value
def get_normalized_author(value):
@ -175,3 +177,23 @@ def get_normalized_author(value):
value = re.sub('[^\w,\s]', '', value, flags=re.U)
value = " ".join(value.split(", ")[::-1])
return value
def update_dir_stucture(book_id):
db.session.connection().connection.connection.create_function("title_sort",1,db.title_sort)
book = db.session.query(db.Books).filter(db.Books.id == book_id).first()
path = os.path.join(config.DB_ROOT, book.path)
authordir = book.path.split("/")[0]
new_authordir=get_valid_filename(book.authors[0].name, False)
titledir = book.path.split("/")[1]
new_titledir = get_valid_filename(book.title, False) + " (" + str(book_id) + ")"
if titledir != new_titledir:
os.rename(path, os.path.join(os.path.dirname(path), new_titledir))
path = os.path.join(os.path.dirname(path), new_titledir)
book.path = book.path.split("/")[0] + "/" + new_titledir
if authordir != new_authordir:
os.renames(path, os.path.join(os.path.join(config.DB_ROOT, new_authordir), os.path.basename(path)))
book.path = new_authordir + "/" + book.path.split("/")[1]
db.session.commit()

View File

@ -27,4 +27,7 @@ span.glyphicon.glyphicon-tags {padding-right: 5px;color: #999;vertical-align: te
-webkit-box-shadow: 0 5px 8px -6px #777;
-moz-box-shadow: 0 5px 8px -6px #777;
box-shadow: 0 5px 8px -6px #777;
}
}
.btn-file {position: relative; overflow: hidden;}
.btn-file input[type=file] {position: absolute; top: 0; right: 0; min-width: 100%; min-height: 100%; font-size: 100px; text-align: right; filter: alpha(opacity=0); opacity: 0; outline: none; background: white; cursor: inherit; display: block;}

View File

@ -31,6 +31,13 @@
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
</head>
<body>
<script>
$(document).ready(function(){
$("#btn-upload").change(function() {
$("#form-upload").submit();
});
});
</script>
<!-- Static navbar -->
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container-fluid">
@ -56,6 +63,13 @@
</ul>
<ul class="nav navbar-nav navbar-right" id="main-nav">
{% if g.user.is_authenticated() %}
<li>
<form id="form-upload" class="navbar-form" action="{{ url_for('upload') }}" method="post" enctype="multipart/form-data">
<div class="form-group">
<span class="btn btn-default btn-file">Upload <input id="btn-upload" name="btn-upload" type="file"></span>
</div>
</form>
</li>
{% if g.user.role %}
<li><a href="{{url_for('user_list')}}"><span class="glyphicon glyphicon-dashboard"></span> Admin</a></li>
{% endif %}

View File

@ -20,6 +20,9 @@ from functools import wraps
import base64
from sqlalchemy.sql import *
import json
from wand.image import Image
import datetime
from uuid import uuid4
app = (Flask(__name__))
@ -226,12 +229,12 @@ def get_opds_download_link(book_id, format):
return response
@app.route("/get_authors_json", methods = ['GET', 'POST'])
def get_authors_json():
if request.method == "POST":
form = request.form.to_dict()
entries = db.session.execute("select name from authors where name like '%" + form['query'] + "%'")
return json.dumps([dict(r) for r in entries])
def get_authors_json():
if request.method == "POST":
form = request.form.to_dict()
entries = db.session.execute("select name from authors where name like '%" + form['query'] + "%'")
return json.dumps([dict(r) for r in entries])
@app.route("/", defaults={'page': 1})
@app.route('/page/<int:page>')
@ -662,28 +665,34 @@ def edit_book(book_id):
db.session.connection().connection.connection.create_function("title_sort",1,db.title_sort)
book = db.session.query(db.Books).filter(db.Books.id == book_id).first()
if request.method == 'POST':
edited_books_id = set()
to_save = request.form.to_dict()
book.title = to_save["book_title"]
author_id = book.authors[0].id
is_author = db.session.query(db.Authors).filter(db.Authors.name == to_save["author_name"].strip()).first()
if book.authors[0].name not in ("Unknown", "Unbekannt", "", " "):
if is_author:
book.authors.append(is_author)
if book.title != to_save["book_title"]:
book.title = to_save["book_title"]
edited_books_id.add(book.id)
author_id = book.authors[0].id
if book.authors[0].name != to_save["author_name"].strip():
is_author = db.session.query(db.Authors).filter(db.Authors.name == to_save["author_name"].strip()).first()
edited_books_id.add(book.id)
if book.authors[0].name not in ("Unknown", "Unbekannt", "", " "):
if is_author:
book.authors.append(is_author)
book.authors.remove(db.session.query(db.Authors).get(book.authors[0].id))
authors_books_count = db.session.query(db.Books).filter(db.Books.authors.any(db.Authors.id.is_(author_id))).count()
if authors_books_count == 0:
db.session.query(db.Authors).filter(db.Authors.id == author_id).delete()
else:
book.authors[0].name = to_save["author_name"].strip()
for linked_book in db.session.query(db.Books).filter(db.Books.authors.any(db.Authors.id.is_(author_id))).all():
edited_books_id.add(linked_book.id)
else:
if is_author:
book.authors.append(is_author)
else:
book.authors.append(db.Authors(to_save["author_name"].strip(), "", ""))
book.authors.remove(db.session.query(db.Authors).get(book.authors[0].id))
authors_books_count = db.session.query(db.Books).filter(db.Books.authors.any(db.Authors.id.is_(author_id))).count()
if authors_books_count == 0:
db.session.query(db.Authors).filter(db.Authors.id == author_id).delete()
else:
book.authors[0].name = to_save["author_name"].strip()
else:
if is_author:
book.authors.append(is_author)
else:
book.authors.append(db.Authors(to_save["author_name"].strip(), "", ""))
book.authors.remove(db.session.query(db.Authors).get(book.authors[0].id))
if to_save["cover_url"] and os.path.splitext(to_save["cover_url"])[1].lower() == ".jpg":
img = requests.get(to_save["cover_url"])
f = open(os.path.join(config.DB_ROOT, book.path, "cover.jpg"), "wb")
@ -720,9 +729,44 @@ def edit_book(book_id):
new_rating = db.Ratings(rating=int(to_save["rating"].strip()))
book.ratings[0] = new_rating
db.session.commit()
for b in edited_books_id:
helper.update_dir_stucture(b)
if "detail_view" in to_save:
return redirect(url_for('show_book', id=book.id))
else:
return render_template('edit_book.html', book=book)
else:
return render_template('edit_book.html', book=book)
@app.route("/upload", methods = ["GET", "POST"])
@login_required
def upload():
## create the function for sorting...
db.session.connection().connection.connection.create_function("title_sort",1,db.title_sort)
db.session.connection().connection.connection.create_function('uuid4', 0, lambda : str(uuid4()))
if request.method == 'POST' and 'btn-upload' in request.files:
file = request.files['btn-upload']
filename = file.filename
filename_root, fileextension = os.path.splitext(filename)
title_dir = helper.get_valid_filename(filename_root, False)
filepath = config.DB_ROOT + "/Unknown/" + title_dir
print filepath
if not os.path.exists(filepath):
os.makedirs(filepath)
file.save(os.path.join(filepath, filename))
with Image(filename=os.path.join(filepath, filename)+"[0]", resolution=150) as img:
img.compression_quality = 88
img.save(filename=os.path.join(filepath, "cover.jpg"))
is_author = db.session.query(db.Authors).filter(db.Authors.name.like("Unknown")).first()
if is_author:
db_author = is_author
else:
db_author = db.Authors("Unknown", "", "")
db.session.add(db_author)
db_book = db.Books(filename_root, "", "", datetime.datetime.now(), "", 1, datetime.datetime(101, 01,01), "Unknown/" + title_dir, 1, db_author, [])
db_book.authors.append(db_author)
#todo append data,...
db.session.add(db_book)
db.session.commit()
print filename
return render_template('search.html', searchterm="")