mirror of
https://github.com/simon987/nyaa.git
synced 2025-12-14 15:49:02 +00:00
@@ -6,13 +6,39 @@ from nyaa import models, forms
|
||||
from nyaa import bencode, backend, utils
|
||||
from nyaa import torrents
|
||||
|
||||
import functools
|
||||
import json
|
||||
import os.path
|
||||
#from orderedset import OrderedSet
|
||||
#from werkzeug import secure_filename
|
||||
|
||||
# #################################### API HELPERS ####################################
|
||||
api_blueprint = flask.Blueprint('api', __name__)
|
||||
|
||||
# #################################### API HELPERS ####################################
|
||||
def basic_auth_user(f):
|
||||
''' A decorator that will try to validate the user into g.user from basic auth.
|
||||
Note: this does not set user to None on failure, so users can also authorize
|
||||
themselves with the cookie (handled in routes.before_request). '''
|
||||
@functools.wraps(f)
|
||||
def decorator(*args, **kwargs):
|
||||
auth = flask.request.authorization
|
||||
if auth:
|
||||
user = models.User.by_username_or_email(auth.get('username'))
|
||||
if user and user.validate_authorization(auth.get('password')):
|
||||
flask.g.user = user
|
||||
|
||||
return f(*args, **kwargs)
|
||||
return decorator
|
||||
|
||||
def api_require_user(f):
|
||||
''' Returns an error message if flask.g.user is None.
|
||||
Remember to put after basic_auth_user. '''
|
||||
@functools.wraps(f)
|
||||
def decorator(*args, **kwargs):
|
||||
if flask.g.user is None:
|
||||
return flask.jsonify({'errors':['Bad authorization']}), 403
|
||||
return f(*args, **kwargs)
|
||||
return decorator
|
||||
|
||||
def validate_user(upload_request):
|
||||
auth_info = None
|
||||
@@ -90,3 +116,68 @@ def api_upload(upload_request, user):
|
||||
return_error_messages.extend(error_messages)
|
||||
|
||||
return flask.make_response(flask.jsonify({'Failure': return_error_messages}), 400)
|
||||
|
||||
# V2 below
|
||||
|
||||
# Map UploadForm fields to API keys
|
||||
UPLOAD_API_FORM_KEYMAP = {
|
||||
'torrent_file' : 'torrent',
|
||||
|
||||
'display_name' : 'name',
|
||||
|
||||
'is_anonymous' : 'anonymous',
|
||||
'is_hidden' : 'hidden',
|
||||
'is_complete' : 'complete',
|
||||
'is_remake' : 'remake'
|
||||
}
|
||||
UPLOAD_API_FORM_KEYMAP_REVERSE = {v:k for k,v in UPLOAD_API_FORM_KEYMAP.items()}
|
||||
UPLOAD_API_KEYS = [
|
||||
'name',
|
||||
'category',
|
||||
'anonymous',
|
||||
'hidden',
|
||||
'complete',
|
||||
'remake',
|
||||
'information',
|
||||
'description'
|
||||
]
|
||||
|
||||
@api_blueprint.route('/v2/upload', methods=['POST'])
|
||||
@basic_auth_user
|
||||
@api_require_user
|
||||
def v2_api_upload():
|
||||
mapped_dict = {
|
||||
'torrent_file' : flask.request.files.get('torrent')
|
||||
}
|
||||
|
||||
request_data_field = flask.request.form.get('torrent_data')
|
||||
if request_data_field is None:
|
||||
return flask.jsonify({'errors' : ['missing torrent_data field']}), 400
|
||||
request_data = json.loads(request_data_field)
|
||||
|
||||
# Map api keys to upload form fields
|
||||
for key in UPLOAD_API_KEYS:
|
||||
mapped_key = UPLOAD_API_FORM_KEYMAP_REVERSE.get(key, key)
|
||||
mapped_dict[mapped_key] = request_data.get(key)
|
||||
|
||||
# Flask-WTF (very helpfully!!) automatically grabs the request form, so force a None formdata
|
||||
upload_form = forms.UploadForm(None, data=mapped_dict)
|
||||
upload_form.category.choices = _create_upload_category_choices()
|
||||
|
||||
if upload_form.validate():
|
||||
torrent = backend.handle_torrent_upload(upload_form, flask.g.user)
|
||||
|
||||
# Create a response dict with relevant data
|
||||
torrent_metadata = {
|
||||
'url' : flask.url_for('view_torrent', torrent_id=torrent.id, _external=True),
|
||||
'id' : torrent.id,
|
||||
'name' : torrent.display_name,
|
||||
'hash' : torrent.info_hash.hex(),
|
||||
'magnet' : torrent.magnet_uri
|
||||
}
|
||||
|
||||
return flask.jsonify(torrent_metadata)
|
||||
else:
|
||||
# Map errors back from form fields into the api keys
|
||||
mapped_errors = { UPLOAD_API_FORM_KEYMAP.get(k, k) : v for k,v in upload_form.errors.items() }
|
||||
return flask.jsonify({'errors' : mapped_errors}), 400
|
||||
|
||||
@@ -343,6 +343,16 @@ class User(db.Model):
|
||||
def __repr__(self):
|
||||
return '<User %r>' % self.username
|
||||
|
||||
def validate_authorization(self, password):
|
||||
''' Returns a boolean for whether the user can be logged in '''
|
||||
checks = [
|
||||
# Password must match
|
||||
password == self.password_hash,
|
||||
# Reject inactive and banned users
|
||||
self.status == UserStatusType.ACTIVE
|
||||
]
|
||||
return all(checks)
|
||||
|
||||
@classmethod
|
||||
def by_id(cls, id):
|
||||
return cls.query.get(id)
|
||||
@@ -357,6 +367,10 @@ class User(db.Model):
|
||||
user = cls.query.filter_by(email=email).first()
|
||||
return user
|
||||
|
||||
@classmethod
|
||||
def by_username_or_email(cls, username_or_email):
|
||||
return cls.by_username(username_or_email) or cls.by_email(username_or_email)
|
||||
|
||||
@property
|
||||
def is_admin(self):
|
||||
return self.level is UserLevelType.ADMIN or self.level is UserLevelType.SUPERADMIN
|
||||
|
||||
@@ -110,6 +110,9 @@ def get_utc_timestamp(datetime_str):
|
||||
def get_display_time(datetime_str):
|
||||
return datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S').strftime('%Y-%m-%d %H:%M')
|
||||
|
||||
# Routes start here #
|
||||
|
||||
app.register_blueprint(api_handler.api_blueprint, url_prefix='/api')
|
||||
|
||||
@app.route('/rss', defaults={'rss': True})
|
||||
@app.route('/', defaults={'rss': False})
|
||||
|
||||
Reference in New Issue
Block a user