Got app.py ready for pull request

This commit is contained in:
2017-02-09 00:44:02 +01:00
parent 0b5626ecdd
commit 2d0b26ed44

110
v1/app.py
View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Flask auth with HTTP '$ pip install flask_httpauth' # Flask auth with HTTP '$ pip install flask_httpauth'
# For https '$ pip install Flask-SSLify' # For https '$ pip install Flask-SSLify'
@@ -9,22 +8,23 @@ from json import loads, dumps
import requests import requests
from werkzeug.security import generate_password_hash, \ from werkzeug.security import generate_password_hash, \
check_password_hash check_password_hash
from diskusage import diskUsage from status.diskusage import diskUsage
from uptime import timeSinceBoot from status.uptime import timeSinceBoot
from cpuTemp import getCpuTemp from status.cpuTemp import getCpuTemp
from plex.tmdb import tmdbSearch
from plexMovies import getSpecificMovieInfo from plex.plexMovies import getSpecificMovieInfo
app = Flask(__name__, static_url_path = "") app = Flask(__name__, static_url_path = "")
auth = HTTPBasicAuth() auth = HTTPBasicAuth()
# Hardcoded users, the password is hashed with salt used by wekzeug # Hardcoded users, the password is hashed with salt used by wekzeug
users = { users = {
"kevin": "9f6c79bbb3b8bbc4e6aab32314afaf3c812df66b", "kevin": "9f6c79bbb3b8bbc4e6aab32314afaf3c812df66b",
"apollo": "BerryTree", "apollo": "BerryTree",
"test": "test" "test": "test"
} }
tmdbBaseURL = "https://api.themoviedb.org/3/" tmdbBaseURL = "https://api.themoviedb.org/3/"
@@ -37,8 +37,8 @@ tmdbBaseURL = "https://api.themoviedb.org/3/"
# # Costum function for hashing and verifying the sent password. # # Costum function for hashing and verifying the sent password.
# # TODO Read if ok to send in cleartext like this if use https # # TODO Read if ok to send in cleartext like this if use https
# def verifyHash(pw): # def verifyHash(pw):
# pw_hash = generate_password_hash(pw) # pw_hash = generate_password_hash(pw)
# return check_password_hash(pw_hash, pw) # return check_password_hash(pw_hash, pw)
# Flask function for getting password matching username sent by http request # Flask function for getting password matching username sent by http request
@auth.get_password @auth.get_password
@@ -51,7 +51,7 @@ def get_pw(username):
# to not match. # to not match.
@auth.error_handler @auth.error_handler
def unauthorized(): def unauthorized():
return make_response(jsonify({'error': 'Unauthorized access'}), 401) return make_response(jsonify({'error': 'Unauthorized access'}), 401)
# This would be replaced with a database, but single process and thread # This would be replaced with a database, but single process and thread
# can use local data like this for simplicity. # can use local data like this for simplicity.
@@ -60,10 +60,10 @@ def unauthorized():
# Want all return data to be JSON so create custom error response # Want all return data to be JSON so create custom error response
@app.errorhandler(404) @app.errorhandler(404)
def not_found(error): def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404) return make_response(jsonify({'error': 'Not found'}), 404)
@app.errorhandler(400) @app.errorhandler(400)
def bad_request(error): def bad_request(error):
return make_response(jsonify({'error': 'Bad request'}), 400) return make_response(jsonify({'error': 'Bad request'}), 400)
# --- Apollo Activity --- # # --- Apollo Activity --- #
@@ -71,90 +71,82 @@ def bad_request(error):
@app.route('/api/v1/disks', methods=['GET']) @app.route('/api/v1/disks', methods=['GET'])
@auth.login_required @auth.login_required
def get_diskUsage(): def get_diskUsage():
returningDiskUsage = diskUsage(request.args.get('dir')) returningDiskUsage = diskUsage(request.args.get('dir'))
if returningDiskUsage != None: if returningDiskUsage != None:
return jsonify(returningDiskUsage) return jsonify(returningDiskUsage)
else: else:
abort(404) abort(404)
@app.route('/api/v1/uptimes', methods=['GET']) @app.route('/api/v1/uptimes', methods=['GET'])
@auth.login_required @auth.login_required
def get_uptimes(): def get_uptimes():
try: try:
return jsonify({ 'uptime': timeSinceBoot() }) return jsonify({ 'uptime': timeSinceBoot() })
except: except:
abort(404) abort(404)
@app.route('/api/v1/temps', methods=['GET']) @app.route('/api/v1/temps', methods=['GET'])
def get_temps(): def get_temps():
cpuTemp = getCpuTemp() cpuTemp = getCpuTemp()
if cpuTemp != None: if cpuTemp != None:
return jsonify( {"Avg cpu temp": cpuTemp} ) return jsonify( {"Avg cpu temp": cpuTemp} )
else: else:
return jsonify( {"Error":"Temp reading not supported for host machine."} ) return jsonify( {"Error":"Temp reading not supported for host machine."} )
# TODO PLEX # TODO PLEX
# Search, watching, +photo # Search, watching, +photo
@app.route('/api/v1/plex/request', methods=['GET']) @app.route('/api/v1/plex/request', methods=['GET'])
def get_movieRequest(): def get_movieRequest():
if (request.args.get("query") != None): query = request.args.get("query")
requestType = "search/multi?" if (query != None):
requestAPI = "api_key=" + "9fa154f5355c37a1b9b57ac06e7d6712" # TODO if list is empty
requestQuery = "&query=" + str(request.args.get('query')) return jsonify(tmdbSearch(query))
requestLanguage = "&language=en.US"
url = tmdbBaseURL + requestType + requestAPI + requestQuery + requestLanguage else: return jsonify({ "Error": "Query not defined." })
# url = "https://api.themoviedb.org/3/search/multi?include_adult=false&query=home%20alone&language=en-US&api_key=9fa154f5355c37a1b9b57ac06e7d6712"
response = requests.get(url)
print(response.json)
return response.json
else: return jsonify ({ "Error": "Query not defined." })
@app.route('/api/v1/plex/movies', methods=['GET']) @app.route('/api/v1/plex/movies', methods=['GET'])
@auth.login_required @auth.login_required
def getPlexMovies(): def getPlexMovies():
title = request.args.get('title') title = request.args.get('title')
movieInfo = getSpecificMovieInfo(title) movieInfo = getSpecificMovieInfo(title)
if movieInfo != None: if movieInfo != None:
return jsonify(movieInfo) return jsonify(movieInfo)
abort(500) abort(500)
@app.route('/api/v1/plex/watchings', methods=['GET']) @app.route('/api/v1/plex/watchings', methods=['GET'])
@auth.login_required @auth.login_required
def getPlexWatchings(): def getPlexWatchings():
r = requests.get('http://10.0.0.41:32400/status/sessions') r = requests.get('http://10.0.0.41:32400/status/sessions')
return r.text return r.text
movieInfo = getSpecificMovieInfo(title) movieInfo = getSpecificMovieInfo(title)
if movieInfo != None: if movieInfo != None:
return jsonify(movieInfo) return jsonify(movieInfo)
@app.route('/api/v1/uptimes/duration', methods=['GET']) @app.route('/api/v1/uptimes/duration', methods=['GET'])
@auth.login_required @auth.login_required
def get_uptimesDuration(): def get_uptimesDuration():
up = uptime.uptime() up = uptime.uptime()
return jsonify( {'Duration': up.duration} ) return jsonify( {'Duration': up.duration} )
@app.route('/api/v1/uptimes/users', methods=['GET']) @app.route('/api/v1/uptimes/users', methods=['GET'])
@auth.login_required @auth.login_required
def get_uptimesUsers(): def get_uptimesUsers():
up = uptime.uptime() up = uptime.uptime()
return jsonify( {'Users': up.users} ) return jsonify( {'Users': up.users} )
@app.route('/api/v1/uptimes/load', methods=['GET']) @app.route('/api/v1/uptimes/load', methods=['GET'])
@auth.login_required @auth.login_required
def get_uptimesLoad(): def get_uptimesLoad():
up = uptime.uptime() up = uptime.uptime()
return jsonify( {'Load': up.load} ) return jsonify( {'Load': up.load} )
if __name__ == '__main__': if __name__ == '__main__':
app.run(host="0.0.0.0", port=63590, debug=True) app.run(host="0.0.0.0",port=63590, debug=True)