2017-04-02 14:53:55 +00:00
|
|
|
from src.exceptions import BBJException, BBJParameterError, BBJUserError
|
|
|
|
from src import db, schema
|
2017-04-02 07:35:58 +00:00
|
|
|
from functools import wraps
|
2017-04-02 14:53:55 +00:00
|
|
|
from uuid import uuid1
|
|
|
|
import traceback
|
2017-04-02 07:35:58 +00:00
|
|
|
import cherrypy
|
|
|
|
import sqlite3
|
|
|
|
import json
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
dbname = "data.sqlite"
|
2017-04-02 19:26:49 +00:00
|
|
|
|
|
|
|
# user anonymity is achieved in the laziest possible way: a literal user
|
|
|
|
# named anonymous. may god have mercy on my soul.
|
2017-04-02 07:35:58 +00:00
|
|
|
with sqlite3.connect(dbname) as _c:
|
2017-04-02 19:26:49 +00:00
|
|
|
db.anon = db.user_resolve(_c, "anonymous")
|
|
|
|
if not db.anon:
|
|
|
|
db.anon = db.user_register(
|
|
|
|
_c, "anonymous", # this is the hash for "anon"
|
|
|
|
"5430eeed859cad61d925097ec4f53246"
|
|
|
|
"1ccf1ab6b9802b09a313be1478a4d614")
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
|
|
|
# creates a database connection for each thread
|
2017-04-02 08:34:52 +00:00
|
|
|
def db_connect(_):
|
2017-04-02 07:35:58 +00:00
|
|
|
cherrypy.thread_data.db = sqlite3.connect(dbname)
|
2017-04-02 08:34:52 +00:00
|
|
|
cherrypy.engine.subscribe('start_thread', db_connect)
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
def api_method(function):
|
2017-04-02 07:35:58 +00:00
|
|
|
"""
|
|
|
|
A wrapper that handles encoding of objects and errors to a
|
|
|
|
standard format for the API, resolves and authorizes users
|
2017-04-02 08:34:52 +00:00
|
|
|
from header data, and prepares cherrypy.thread_data so other
|
|
|
|
funtions can handle the request.
|
|
|
|
|
|
|
|
In the body of each api method and all the functions
|
|
|
|
they utilize, BBJExceptions are caught and their attached
|
|
|
|
schema is dispatched to the client. All other unhandled
|
|
|
|
exceptions will throw a code 1 back at the client and log
|
2017-04-02 14:53:55 +00:00
|
|
|
it for inspection. Errors related to JSON decoding are
|
|
|
|
caught as well and returned to the client as code 0.
|
2017-04-02 07:35:58 +00:00
|
|
|
"""
|
|
|
|
@wraps(function)
|
|
|
|
def wrapper(*args, **kwargs):
|
2017-04-02 08:34:52 +00:00
|
|
|
response = None
|
|
|
|
try:
|
2017-04-02 14:53:55 +00:00
|
|
|
# read in the body from the request to a string...
|
|
|
|
body = str(cherrypy.request.body.read(), "utf8")
|
2017-04-02 19:26:49 +00:00
|
|
|
# is it just empty bytes? not all methods require an input
|
2017-04-02 14:53:55 +00:00
|
|
|
if body:
|
|
|
|
body = json.loads(body)
|
|
|
|
if isinstance(body, dict):
|
|
|
|
# lowercase all of its keys
|
|
|
|
body = {str(key).lower(): value for key, value
|
|
|
|
in body.items()}
|
2017-04-02 19:26:49 +00:00
|
|
|
else: # would rather a NoneType than b""
|
|
|
|
body = None
|
2017-04-02 14:53:55 +00:00
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
username = cherrypy.request.headers.get("User")
|
|
|
|
auth = cherrypy.request.headers.get("Auth")
|
|
|
|
|
2017-04-02 19:26:49 +00:00
|
|
|
if (username and not auth) or (auth and not username):
|
2017-04-02 07:35:58 +00:00
|
|
|
return json.dumps(schema.error(5,
|
2017-04-02 08:34:52 +00:00
|
|
|
"User or Auth was given without the other."))
|
2017-04-02 07:35:58 +00:00
|
|
|
|
2017-04-02 19:26:49 +00:00
|
|
|
elif not username and not auth:
|
|
|
|
user = db.anon
|
|
|
|
|
|
|
|
else:
|
2017-04-02 08:34:52 +00:00
|
|
|
user = db.user_resolve(cherrypy.thread_data.db, username)
|
2017-04-02 14:53:55 +00:00
|
|
|
if not user:
|
|
|
|
raise BBJUserError("User %s is not registered" % username)
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
if auth != user["auth_hash"]:
|
|
|
|
return json.dumps(schema.error(5,
|
|
|
|
"Invalid authorization key for user."))
|
2017-04-02 07:35:58 +00:00
|
|
|
|
2017-04-02 19:26:49 +00:00
|
|
|
# api_methods may choose to bind a usermap into the thread_data
|
|
|
|
# which will send it off with the response
|
|
|
|
cherrypy.thread_data.usermap = {}
|
|
|
|
# TODO: Why in kek's name is self needing to be supplied a value positionally?
|
|
|
|
value = function(None, body, cherrypy.thread_data.db, user)
|
|
|
|
response = schema.response(value, cherrypy.thread_data.usermap)
|
2017-04-02 14:53:55 +00:00
|
|
|
|
2017-04-02 07:35:58 +00:00
|
|
|
except BBJException as e:
|
2017-04-02 08:34:52 +00:00
|
|
|
response = e.schema
|
2017-04-02 07:35:58 +00:00
|
|
|
|
2017-04-02 19:26:49 +00:00
|
|
|
except json.JSONDecodeError as e:
|
|
|
|
response = schema.error(0, str(e))
|
|
|
|
|
2017-04-02 07:35:58 +00:00
|
|
|
except Exception as e:
|
2017-04-02 14:53:55 +00:00
|
|
|
error_id = uuid1().hex
|
|
|
|
response = schema.error(1,
|
2017-04-02 19:26:49 +00:00
|
|
|
"Internal server error: code {}. {}"
|
|
|
|
.format(error_id, repr(e)))
|
2017-04-02 14:53:55 +00:00
|
|
|
with open("logs/exceptions/" + error_id, "a") as log:
|
|
|
|
traceback.print_tb(e.__traceback__, file=log)
|
|
|
|
log.write(repr(e))
|
2017-04-02 19:26:49 +00:00
|
|
|
print("logged code 1 exception " + error_id)
|
2017-04-02 08:34:52 +00:00
|
|
|
|
|
|
|
finally:
|
|
|
|
return json.dumps(response)
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
|
|
|
|
def create_usermap(connection, obj):
|
|
|
|
"""
|
|
|
|
Creates a mapping of all the user_ids that occur in OBJ to
|
|
|
|
their full user objects (names, profile info, etc). Can
|
|
|
|
be a thread_index or a messages object from one.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if isinstance(obj, dict):
|
2017-04-02 08:34:52 +00:00
|
|
|
# this is a message object for a thread, ditch the keys
|
|
|
|
obj = obj.values()
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
user_id: db.user_resolve(
|
|
|
|
connection,
|
|
|
|
user_id,
|
|
|
|
externalize=True,
|
|
|
|
return_false=False)
|
2017-04-02 19:26:49 +00:00
|
|
|
for user_id in {item["author"] for item in obj}
|
2017-04-02 07:35:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def validate(json, args):
|
|
|
|
"""
|
|
|
|
Ensure the json object contains all the keys needed to satisfy
|
2017-04-02 14:53:55 +00:00
|
|
|
its endpoint (and isnt empty)
|
2017-04-02 07:35:58 +00:00
|
|
|
"""
|
2017-04-02 14:53:55 +00:00
|
|
|
if not json:
|
|
|
|
raise BBJParameterError(
|
|
|
|
"JSON input is empty. This method requires the following "
|
|
|
|
"arguments: {}".format(", ".join(args)))
|
|
|
|
|
2017-04-02 07:35:58 +00:00
|
|
|
for arg in args:
|
|
|
|
if arg not in json.keys():
|
|
|
|
raise BBJParameterError(
|
2017-04-02 14:53:55 +00:00
|
|
|
"Required parameter {} is absent from the request. "
|
|
|
|
"This method requires the following arguments: {}"
|
|
|
|
.format(arg, ", ".join(args)))
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
|
|
|
APICONFIG = {
|
|
|
|
"/": {
|
|
|
|
"tools.response_headers.on": True,
|
|
|
|
"tools.response_headers.headers": [
|
|
|
|
("Content-Type", "application/json")
|
|
|
|
],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class API(object):
|
2017-04-02 08:34:52 +00:00
|
|
|
@api_method
|
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def user_register(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Register a new user into the system and return the new object.
|
|
|
|
Requires the string arguments `user_name` and `auth_hash`
|
|
|
|
"""
|
|
|
|
validate(args, ["user_name", "auth_hash"])
|
|
|
|
return db.user_register(
|
|
|
|
database, args["user_name"], args["auth_hash"])
|
|
|
|
|
|
|
|
|
|
|
|
@api_method
|
|
|
|
@cherrypy.expose
|
|
|
|
def user_update(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Receives new parameters and assigns them to the user_object
|
|
|
|
in the database. The following new parameters can be supplied:
|
|
|
|
`user_name`, `auth_hash`, `quip`, `bio`, and `color`. Any number
|
|
|
|
of them may be supplied.
|
|
|
|
|
|
|
|
The newly updated user object is returned on success.
|
|
|
|
"""
|
|
|
|
validate(args, []) # just make sure its not empty
|
|
|
|
return db.user_update(database, user, args)
|
|
|
|
|
|
|
|
|
|
|
|
@api_method
|
|
|
|
@cherrypy.expose
|
|
|
|
def get_me(self, args, database, user, **kwargs):
|
2017-04-02 08:34:52 +00:00
|
|
|
"""
|
|
|
|
Requires no arguments. Returns your internal user object,
|
|
|
|
including your authorization hash.
|
|
|
|
"""
|
2017-04-02 19:26:49 +00:00
|
|
|
return user
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
|
|
|
|
@api_method
|
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def user_get(self, args, database, user, **kwargs):
|
2017-04-02 08:34:52 +00:00
|
|
|
"""
|
|
|
|
Retreive an external user object for the given `user`.
|
|
|
|
Can be a user_id or user_name.
|
|
|
|
"""
|
2017-04-02 14:53:55 +00:00
|
|
|
validate(args, ["user"])
|
2017-04-02 19:26:49 +00:00
|
|
|
return db.user_resolve(
|
|
|
|
database, args["user"], return_false=False, externalize=True)
|
2017-04-02 08:34:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
@api_method
|
2017-04-02 07:35:58 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def thread_index(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Return an array with all the threads, ordered by most recent activity.
|
|
|
|
Requires no arguments.
|
|
|
|
"""
|
|
|
|
threads = db.thread_index(database)
|
|
|
|
cherrypy.thread_data.usermap = create_usermap(database, threads)
|
|
|
|
return threads
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
@api_method
|
2017-04-02 07:35:58 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def thread_create(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Creates a new thread and returns it. Requires the non-empty
|
|
|
|
string arguments `body` and `title`
|
|
|
|
"""
|
2017-04-02 07:35:58 +00:00
|
|
|
validate(args, ["body", "title"])
|
|
|
|
thread = db.thread_create(
|
2017-04-02 19:26:49 +00:00
|
|
|
database, user["user_id"], args["body"], args["title"])
|
|
|
|
cherrypy.thread_data.usermap = {user["user_id"]: user}
|
|
|
|
return thread
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
@api_method
|
2017-04-02 07:35:58 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def thread_reply(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Creates a new reply for the given thread and returns it.
|
|
|
|
Requires the string arguments `thread_id` and `body`
|
|
|
|
"""
|
2017-04-02 07:35:58 +00:00
|
|
|
validate(args, ["thread_id", "body"])
|
2017-04-02 19:26:49 +00:00
|
|
|
return db.thread_reply(
|
|
|
|
database, user["user_id"], args["thread_id"], args["body"])
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
@api_method
|
2017-04-02 07:35:58 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def thread_load(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Returns the thread object with all of its messages loaded.
|
|
|
|
Requires the argument `thread_id`
|
|
|
|
"""
|
2017-04-02 07:35:58 +00:00
|
|
|
validate(args, ["thread_id"])
|
2017-04-02 19:26:49 +00:00
|
|
|
thread = db.thread_get(database, args["thread_id"])
|
|
|
|
cherrypy.thread_data.usermap = \
|
|
|
|
create_usermap(database, thread["messages"])
|
|
|
|
return thread
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
@api_method
|
2017-04-02 07:35:58 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def edit_post(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Replace a post with a new body. Requires the arguments
|
|
|
|
`thread_id`, `post_id`, and `body`. This method verifies
|
|
|
|
that the user can edit a post before commiting the change,
|
|
|
|
otherwise an error object is returned whose description
|
|
|
|
should be shown to the user.
|
|
|
|
|
|
|
|
To perform sanity checks without actually attempting to
|
|
|
|
edit a post, use `edit_query`
|
|
|
|
|
|
|
|
Returns the new message object.
|
|
|
|
"""
|
|
|
|
if user == db.anon:
|
|
|
|
raise BBJUserError("Anons cannot edit messages.")
|
|
|
|
validate(args, ["body", "thread_id", "post_id"])
|
|
|
|
return message_edit_commit(
|
|
|
|
database, user["user_id"], args["thread_id"], args["post_id"], args["body"])
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 08:34:52 +00:00
|
|
|
@api_method
|
2017-04-02 07:35:58 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def edit_query(self, args, database, user, **kwargs):
|
|
|
|
"""
|
|
|
|
Queries the database to ensure the user can edit a given
|
|
|
|
message. Requires the arguments `thread_id` and `post_id`
|
|
|
|
(does not require a new body)
|
|
|
|
|
|
|
|
Returns either boolean true or the current message object
|
|
|
|
"""
|
|
|
|
if user == db.anon:
|
|
|
|
raise BBJUserError("Anons cannot edit messages.")
|
2017-04-02 07:35:58 +00:00
|
|
|
validate(args, ["thread_id", "post_id"])
|
2017-04-02 19:26:49 +00:00
|
|
|
return message_edit_query(
|
|
|
|
database, user["user_id"], args["thread_id"], args["post_id"])
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
|
2017-04-02 14:53:55 +00:00
|
|
|
@cherrypy.expose
|
2017-04-02 19:26:49 +00:00
|
|
|
def test(self, **kwargs):
|
2017-04-02 14:53:55 +00:00
|
|
|
print(cherrypy.request.body.read())
|
2017-04-02 19:26:49 +00:00
|
|
|
return "{\"wow\": \"jolly good show!\"}"
|
2017-04-02 14:53:55 +00:00
|
|
|
|
|
|
|
|
2017-04-02 07:35:58 +00:00
|
|
|
|
|
|
|
def run():
|
|
|
|
cherrypy.quickstart(API(), "/api")
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2017-04-02 19:26:49 +00:00
|
|
|
print("yo lets do that -i shit mang")
|