Adding unfinished upload function

pull/8/head
Cervinko Cera 9 years ago
parent cb2ac4d142
commit 3ddecc007c

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

@ -154,7 +154,7 @@ def get_attachment(file_path):
'permissions?') 'permissions?')
return None 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 Returns the given string converted to a string that can be used for a clean
filename. Limits num characters to 128 max. filename. Limits num characters to 128 max.
@ -164,7 +164,9 @@ def get_valid_filename(value):
value = unicodedata.normalize('NFKD', value) value = unicodedata.normalize('NFKD', value)
re_slugify = re.compile('[^\w\s-]', re.UNICODE) re_slugify = re.compile('[^\w\s-]', re.UNICODE)
value = unicode(re_slugify.sub('', value).strip()) 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 return value
def get_normalized_author(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 = re.sub('[^\w,\s]', '', value, flags=re.U)
value = " ".join(value.split(", ")[::-1]) value = " ".join(value.split(", ")[::-1])
return value 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()

@ -28,3 +28,6 @@ span.glyphicon.glyphicon-tags {padding-right: 5px;color: #999;vertical-align: te
-moz-box-shadow: 0 5px 8px -6px #777; -moz-box-shadow: 0 5px 8px -6px #777;
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;}

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

@ -20,6 +20,9 @@ from functools import wraps
import base64 import base64
from sqlalchemy.sql import * from sqlalchemy.sql import *
import json import json
from wand.image import Image
import datetime
from uuid import uuid4
app = (Flask(__name__)) app = (Flask(__name__))
@ -227,10 +230,10 @@ def get_opds_download_link(book_id, format):
@app.route("/get_authors_json", methods = ['GET', 'POST']) @app.route("/get_authors_json", methods = ['GET', 'POST'])
def get_authors_json(): def get_authors_json():
if request.method == "POST": if request.method == "POST":
form = request.form.to_dict() form = request.form.to_dict()
entries = db.session.execute("select name from authors where name like '%" + form['query'] + "%'") entries = db.session.execute("select name from authors where name like '%" + form['query'] + "%'")
return json.dumps([dict(r) for r in entries]) return json.dumps([dict(r) for r in entries])
@app.route("/", defaults={'page': 1}) @app.route("/", defaults={'page': 1})
@ -662,27 +665,33 @@ def edit_book(book_id):
db.session.connection().connection.connection.create_function("title_sort",1,db.title_sort) 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() book = db.session.query(db.Books).filter(db.Books.id == book_id).first()
if request.method == 'POST': if request.method == 'POST':
edited_books_id = set()
to_save = request.form.to_dict() to_save = request.form.to_dict()
book.title = to_save["book_title"] 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 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() 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", "", " "): edited_books_id.add(book.id)
if is_author: if book.authors[0].name not in ("Unknown", "Unbekannt", "", " "):
book.authors.append(is_author) if is_author:
book.authors.remove(db.session.query(db.Authors).get(book.authors[0].id)) book.authors.append(is_author)
authors_books_count = db.session.query(db.Books).filter(db.Books.authors.any(db.Authors.id.is_(author_id))).count() book.authors.remove(db.session.query(db.Authors).get(book.authors[0].id))
if authors_books_count == 0: authors_books_count = db.session.query(db.Books).filter(db.Books.authors.any(db.Authors.id.is_(author_id))).count()
db.session.query(db.Authors).filter(db.Authors.id == author_id).delete() if authors_books_count == 0:
else: db.session.query(db.Authors).filter(db.Authors.id == author_id).delete()
book.authors[0].name = to_save["author_name"].strip() else:
else: book.authors[0].name = to_save["author_name"].strip()
if is_author: for linked_book in db.session.query(db.Books).filter(db.Books.authors.any(db.Authors.id.is_(author_id))).all():
book.authors.append(is_author) edited_books_id.add(linked_book.id)
else: else:
book.authors.append(db.Authors(to_save["author_name"].strip(), "", "")) if is_author:
book.authors.remove(db.session.query(db.Authors).get(book.authors[0].id)) 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": if to_save["cover_url"] and os.path.splitext(to_save["cover_url"])[1].lower() == ".jpg":
img = requests.get(to_save["cover_url"]) img = requests.get(to_save["cover_url"])
@ -720,9 +729,44 @@ def edit_book(book_id):
new_rating = db.Ratings(rating=int(to_save["rating"].strip())) new_rating = db.Ratings(rating=int(to_save["rating"].strip()))
book.ratings[0] = new_rating book.ratings[0] = new_rating
db.session.commit() db.session.commit()
for b in edited_books_id:
helper.update_dir_stucture(b)
if "detail_view" in to_save: if "detail_view" in to_save:
return redirect(url_for('show_book', id=book.id)) return redirect(url_for('show_book', id=book.id))
else: else:
return render_template('edit_book.html', book=book) return render_template('edit_book.html', book=book)
else: else:
return render_template('edit_book.html', book=book) 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="")

Loading…
Cancel
Save