summaryrefslogtreecommitdiffstats
path: root/routes/uploads.py
diff options
context:
space:
mode:
authorFulgen301 <tokmajigeorge@gmail.com>2018-08-26 20:08:54 +0200
committerFulgen301 <tokmajigeorge@gmail.com>2018-08-26 20:08:54 +0200
commit305383c4b85dd6c826cb41faa42fd97015f33067 (patch)
treeead97e4c63de382a6ca20a026f2d9b12b21fc8a6 /routes/uploads.py
parent50622f038d63490277d610a83fe095ee000f2b98 (diff)
downloadparry-305383c4b85dd6c826cb41faa42fd97015f33067.tar.gz
parry-305383c4b85dd6c826cb41faa42fd97015f33067.zip
Rewrite database system with sqlalchemy, add /api/auth, add /api/uploads/<id>comments
Diffstat (limited to 'routes/uploads.py')
-rw-r--r--routes/uploads.py153
1 files changed, 144 insertions, 9 deletions
diff --git a/routes/uploads.py b/routes/uploads.py
index 703d3d1..391827d 100644
--- a/routes/uploads.py
+++ b/routes/uploads.py
@@ -13,6 +13,66 @@
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from ..helpers import *
+import string, magic
+
+def _add_upload(entry : Upload, session : DBSession):
+ return {
+ "voting" : {
+ "sum" : 0,
+ "count" : 0,
+ "votes" : None
+ },
+ "id" : entry.id,
+ "title" : entry.title,
+ "author" : {
+ "id" : entry.author.id if entry.author is not None else "0" * 24,
+ "username" : entry.author.username if entry.author is not None else "N/A"
+ },
+ "tags" : entry.tags,
+ "files" : [{
+ "metadata" : {
+ "hashes" : {
+ "sha1" : file.hash
+ }
+ },
+ "aliases" : None,
+ "deleted" : False,
+ "id" : file.id,
+ "filename" : file.name,
+ "content-type" : file.content_type,
+ "length" : file.length,
+ "chunkSize" : BLOCKSIZE,
+ "uploadData" : file.date.isoformat()
+ } for file in session.query(File).filter_by(upload=entry)
+ ],
+ "dependencies" : [], #TODO
+ "deleted" : False,
+ "description" : entry.description,
+ "pic" : None, #TODO
+ "slug" : entry.slug,
+ "createdAt" : entry.created_at.isoformat(),
+ "updatedAt" : entry.updated_at.isoformat(),
+ "__v" : entry._v,
+ "comments" : [{
+ "voting" : {
+ "sum" : 0,
+ "count" : 0,
+ "votes" : None
+ },
+ "deleted" : False,
+ "id" : comment.id,
+ "body" : comment.body,
+ "author" : {
+ "id" : comment.author.id,
+ "username" : comment.author.username
+ },
+ "upload" : comment.upload.id,
+ "createdAt" : comment.created_at.isoformat(),
+ "updatedAt" : comment.updated_at.isoformat()
+ } for comment in session.query(Comment).filter_by(upload=entry)
+ ]
+ }
+
@route("/api/uploads")
def get_uploads():
@@ -26,12 +86,10 @@ def get_uploads():
"uploads" : []
}
- for entry in database["entries"].values():
- if "__intern" in entry:
- entry = entry.copy()
- del entry["__intern"]
-
- ret["uploads"].append(entry)
+ session = DBSession()
+ for entry in session.query(Upload).order_by(Upload.updated_at.desc()):
+ ret["uploads"].append(_add_upload(entry, session))
+
ret["pagination"]["total"] = ret["pagination"]["limit"] = len(ret["uploads"])
@@ -39,11 +97,88 @@ def get_uploads():
@route("/api/uploads/<id>")
def get_upload(id):
- if id in database["entries"]:
- return database["entries"][id]
+ session = DBSession()
+ entry = session.query(Upload).get(id)
+ if entry is not None:
+ return _add_upload(entry, session)
else:
raise HTTPResponse(status=404)
@route("/api/uploads", method="POST")
+@auth_basic
def post_upload():
- raise HTTPResponse(status=501)
+ try:
+ session = DBSession()
+ if len(session.query(Upload).filter_by(title=requests.forms.title).all()):
+ raise HTTPResponse("An entry with the specified title already exists", 410)
+
+ entry = Upload(
+ title=request.forms.title,
+ author=session.query(User).filter_by(username=request.forms.username),
+ description=request.forms.description,
+ slug="".join(i for i in requests.forms.title.lower() if i in string.ascii_letters),
+ tags=request.forms.tags.split(";") if "tags" in request.forms else []
+ )
+
+ session.add(entry)
+
+ try:
+ os.mkdir(os.path.join(os.getcwd(), "media"))
+ except FileExistsError:
+ pass
+
+ for file in request.files.values():
+ f = File(
+ name=file.filename,
+ upload=entry
+ )
+
+ path = os.path.join(os.getcwd(), "media", f["id"])
+ file.save(path)
+
+ with open(path, "rb") as fobj:
+ f.hash = calculateHashForFile(fobj).hexdigest()
+ f.length = fobj.tell()
+
+ f.content_type = magic.from_file(path, mime=True)
+ session.add(f)
+
+ except KeyError as e:
+ session.rollback()
+ raise HTTPResponse(f"Missing form value: {e.args[0]}", 400)
+
+ session.commit()
+ return HTTPResponse(status=201)
+
+@route("/api/uploads/<id>/comments", method="POST")
+@auth_basic
+def post_comments(id):
+ session = DBSession()
+ try:
+ session.query(Upload).filter_by(id=id).one()
+ except db.orm.exc.NoResultFound:
+ raise HTTPResponse("Invalid upload id", 404)
+
+ try:
+ session.add(Comment(
+ body=request.forms.body,
+ author=session.query(User).filter_by(username=request.forms.username).one()
+ ))
+ except KeyError as e:
+ raise HTTPResponse(f"Missing form value: {e.args[0]}", 400)
+
+ session.commit()
+ return HTTPResponse(status=201)
+
+@route("/api/uploads/<id>/comments/<comment_id>", method="DELETE")
+@auth_basic
+def delete_comments(id, comment_id):
+ session = DBSession()
+ try:
+ comment = session.query(Comment).filter_by(id=comment_id, author=session.query(User).filter_by(username).one(), upload=session.query(Upload).filter_by(id=id).one()).one()
+ except db.orm.exc.NoResultFound:
+ raise HTTPResponse("Requested comment not found", 404)
+
+ session.delete(comment)
+ session.commit()
+ return HTTPResponse(status=204)