Further work on the REST API, documented most of /api/printer and while at it also fixed #365

This commit is contained in:
Gina Häußge committed 2014-03-24 18:27:43 +01:00
1 parent 22614f09a0
commit 072079df05
10 files changed
+783 -130

No files matched your search

+7 -1
View File
@@ -1,4 +1,6 @@
# coding=utf-8
import uuid
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -40,6 +42,9 @@ import octoprint.events as events
import octoprint.timelapse
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
@app.route("/")
def index():
branch = None
@@ -64,7 +69,8 @@ def index():
gitCommit=commit,
stylesheet=settings().get(["devel", "stylesheet"]),
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"])
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
uiApiKey=UI_API_KEY
)
+38 -1
View File
@@ -1,4 +1,6 @@
# coding=utf-8
from octoprint.server.util import getApiKey, getUserForApiKey
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -13,7 +15,7 @@ from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
import octoprint.util as util
import octoprint.users
import octoprint.server
from octoprint.server import restricted_access, admin_permission, NO_CONTENT
from octoprint.server import restricted_access, admin_permission, NO_CONTENT, UI_API_KEY
from octoprint.settings import settings as s, valid_boolean_trues
#~~ init api blueprint, including sub modules
@@ -30,6 +32,41 @@ from . import users as api_users
from . import log as api_logs
@api.before_request
def beforeApiRequests():
"""
All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case
the underlying request processing will directly take place, or it may be the global or a user specific case. In any
case it has to be present and must be valid, so anything other than the above three types will result in denying
the request.
"""
apikey = getApiKey(request)
if apikey is None:
# no api key => 401
return make_response("No API key provided", 401)
if apikey == UI_API_KEY:
# ui api key => continue regular request processing
return
if not s().get(["api", "enabled"]):
# api disabled => 401
return make_response("API disabled", 401)
if apikey == s().get(["api", "key"]):
# global api key => continue regular request processing
return
user = getUserForApiKey(apikey)
if user is not None:
# user specific api key => continue regular request processing
return
# invalid api key => 401
return make_response("Invalid API key", 401)
#~~ first run setup
+32 -9
View File
@@ -12,13 +12,36 @@ import octoprint.util as util
#~~ Printer
@api.route("/printer", methods=["GET"])
def printerState():
if not printer.isOperational():
return make_response("Printer is not operational", 409)
# process excludes
excludes = []
if "exclude" in request.values:
excludeStr = request.values["exclude"]
if len(excludeStr.strip()) > 0:
excludes = filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(",")))
result = {}
result.update(_getTemperatureData(lambda x: x))
# add temperature information
if not "temperature" in excludes:
result.update({"temperature": _getTemperatureData(lambda x: x)})
# add sd information
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
result.update({"sd": {"ready": printer.isSdReady()}})
# add state information
if not "state" in excludes:
state = printer.getCurrentData()["state"]
result.update({"state": {
"text": state["stateString"],
"flags": state["flags"]
}})
return jsonify(result)
@@ -276,11 +299,14 @@ def printerCommand():
data = request.json
parameters = {}
if "parameters" in data.keys(): parameters = data["parameters"]
if "parameters" in data.keys():
parameters = data["parameters"]
commands = []
if "command" in data.keys(): commands = [data["command"]]
elif "commands" in data.keys(): commands = data["commands"]
if "command" in data.keys():
commands = [data["command"]]
elif "commands" in data.keys():
commands = data["commands"]
commandsToSend = []
for command in commands:
@@ -306,9 +332,6 @@ def _getTemperatureData(filter):
return make_response("Printer is not operational", 409)
tempData = printer.getCurrentTemperatures()
result = {
"temps": filter(tempData)
}
if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues:
tempHistory = printer.getTemperatureHistory()
@@ -320,9 +343,9 @@ def _getTemperatureData(filter):
history = list(tempHistory)
limit = min(limit, len(history))
result.update({
tempData.update({
"history": map(lambda x: filter(x), history[-limit:])
})
return result
return filter(tempData)
+13 -9
View File
@@ -50,9 +50,9 @@ def restricted_access(func, apiEnabled=True):
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
return make_response("OctoPrint isn't setup yet", 403)
# if API is globally enabled, enabled for this request and an api key is provided, try to use that
apikey = _getApiKey(request)
if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None:
# if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that
apikey = getApiKey(request)
if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None and apikey != octoprint.server.UI_API_KEY:
if apikey == settings().get(["api", "key"]):
# master key was used
user = ApiUser()
@@ -61,7 +61,7 @@ def restricted_access(func, apiEnabled=True):
user = octoprint.server.userManager.findUser(apikey=apikey)
if user is None:
make_response("Invalid API key", 401)
return make_response("Invalid API key", 401)
if login_user(user, remember=False):
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
return func(*args, **kwargs)
@@ -76,7 +76,7 @@ def api_access(func):
def decorated_view(*args, **kwargs):
if not settings().get(["api", "enabled"]):
make_response("API disabled", 401)
apikey = _getApiKey(request)
apikey = getApiKey(request)
if apikey is None:
make_response("No API key provided", 401)
if apikey != settings().get(["api", "key"]):
@@ -85,7 +85,7 @@ def api_access(func):
return decorated_view
def _getUserForApiKey(apikey):
def getUserForApiKey(apikey):
if settings().get(["api", "enabled"]) and apikey is not None:
if apikey == settings().get(["api", "key"]):
# master key was used
@@ -97,7 +97,7 @@ def _getUserForApiKey(apikey):
return None
def _getApiKey(request):
def getApiKey(request):
# Check Flask GET/POST arguments
if hasattr(request, "values") and "apikey" in request.values:
return request.values["apikey"]
@@ -148,6 +148,10 @@ class PrinterStateConnection(SockJSConnection):
def on_open(self, info):
remoteAddress = self._getRemoteAddress(info)
self._logger.info("New connection from client: %s" % remoteAddress)
# connected => update the API key, might be necessary if the client was left open while the server restarted
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY})
self._printer.registerCallback(self)
self._gcodeManager.registerCallback(self)
octoprint.timelapse.registerCallback(self)
@@ -316,9 +320,9 @@ def admin_validator(request):
:param request: The Flask request object
"""
apikey = _getApiKey(request)
apikey = getApiKey(request)
if settings().get(["api", "enabled"]) and apikey is not None:
user = _getUserForApiKey(apikey)
user = getUserForApiKey(apikey)
else:
user = current_user
+29 -20
View File
@@ -27,31 +27,17 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
self._socket.onopen = self._onconnect;
self._socket.onclose = self._onclose;
self._socket.onmessage = self._onmessage;
}
};
self.reconnect = function() {
delete self._socket;
self.connect();
}
};
self._onconnect = function() {
self._autoReconnecting = false;
self._autoReconnectTrial = 0;
if ($("#offline_overlay").is(":visible")) {
$("#offline_overlay").hide();
self.logViewModel.requestData();
self.timelapseViewModel.requestData();
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
self.loginStateViewModel.requestData();
self.gcodeFilesViewModel.requestData();
self.gcodeViewModel.reset();
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
}
}
}
};
self._onclose = function() {
$("#offline_overlay_message").html(
@@ -70,20 +56,43 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
} else {
self._onreconnectfailed();
}
}
};
self._onreconnectfailed = function() {
$("#offline_overlay_message").html(
"The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, " +
"but you may try a manual reconnect using the button below."
);
}
};
self._onmessage = function(e) {
for (var prop in e.data) {
var data = e.data[prop];
switch (prop) {
case "connected": {
// update the current UI API key and send it with any request
UI_API_KEY = data["apikey"];
$.ajaxSetup({
headers: {"X-Api-Key": UI_API_KEY}
});
if ($("#offline_overlay").is(":visible")) {
$("#offline_overlay").hide();
self.logViewModel.requestData();
self.timelapseViewModel.requestData();
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
self.loginStateViewModel.requestData();
self.gcodeFilesViewModel.requestData();
self.gcodeViewModel.reset();
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
}
}
break;
}
case "history": {
self.connectionViewModel.fromHistoryData(data);
self.printerStateViewModel.fromHistoryData(data);
@@ -160,7 +169,7 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
}
}
}
}
};
self.connect();
}
+6 -1
View File
@@ -25,7 +25,7 @@ $(function() {
gcodeFilesViewModel,
timelapseViewModel,
gcodeViewModel,
logViewModel
logViewModel
);
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
@@ -35,6 +35,11 @@ $(function() {
headers: { "cache-control": "no-cache" }
});
// send the current UI API key with any request
$.ajaxSetup({
headers: {"X-Api-Key": UI_API_KEY}
});
//~~ Show settings - to ensure centered
$('#navbar_show_settings').click(function() {
$('#settings_dialog').modal()
+2
View File
@@ -39,6 +39,8 @@
var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + "/sockjs";
var SOCKJS_DEBUG = {% if debug -%} true; {% else %} false; {%- endif %}
var UI_API_KEY = "{{ uiApiKey }}";
</script>
</head>
<body>