Merge branch 'devel' into commRefactoring

This commit is contained in:
Gina Häußge committed 2014-08-30 20:02:36 +02:00
commit de9dd77b50
65 files changed
+6355 -1120

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
[main]
host = https://www.transifex.com
[octoprint.messages]
file_filter = src/octoprint/translations/<lang>/LC_MESSAGES/messages.po
source_file = src/octoprint/translations/messages.pot
source_lang = en
+6
View File
@@ -0,0 +1,6 @@
[python: src/octoprint/**.py]
[jinja2: src/octoprint/templates/**.jinja2]
extensions=jinja2.ext.autoescape, jinja2.ext.with_
[javascript: src/octoprint/static/js/app/**.js]
extract_messages = gettext, ngettext
+4
View File
@@ -164,6 +164,10 @@ Job information
- 0..1
- Integer
- The estimated print time for the file, in seconds.
* - ``lastPrintTime``
- 0..1
- Integer
- The print time of the last print of the file, in seconds.
* - ``filament``
- 0..1
- Object
+5
View File
@@ -0,0 +1,5 @@
mock>=1.0.1
nose>=1.3.0
sphinxcontrib-httpdomain
sphinx_rtd_theme
po2json
+4 -8
View File
@@ -1,16 +1,12 @@
flask==0.9
werkzeug==0.8.3
tornado==3.0.2
tornado==4.0.1
sockjs-tornado>=1.0.0
PyYAML==3.10
Flask-Login==0.2.2
Flask-Principal==0.3.5
pyserial>=2.6
netaddr>=0.7.10
mock>=1.0.1
nose>=1.3.0
Flask-Babel==0.9
pyserial
netaddr
watchdog
sarge
sphinxcontrib-httpdomain
sphinx_rtd_theme
+1 -1
View File
@@ -18,7 +18,7 @@
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Octoprint Daemon"
NAME="Octoprint"
DAEMON=/usr/bin/octoprint
DAEMON=/usr/local/bin/octoprint
PIDFILE=/var/run/$NAME.pid
PKGNAME=octoprint
SCRIPTNAME=/etc/init.d/$PKGNAME
+102 -1
View File
@@ -13,6 +13,12 @@ import os
import shutil
import glob
I18N_MAPPING_FILE = "babel.cfg"
I18N_DOMAIN = "messages"
I18N_INPUT_DIRS = "."
I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations")
I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n")
I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot")
def package_data_dirs(source, sub_folders):
dirs = []
@@ -47,10 +53,105 @@ class CleanCommand(Command):
shutil.rmtree(egg)
class NewTranslation(Command):
description = "create a new translation"
user_options = [
('locale=', 'l', 'locale for the new translation'),
]
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_init_messages = babel.init_catalog(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.locale = None
self.babel_init_messages.initialize_options()
def finalize_options(self):
self.babel_init_messages.locale = self.locale
self.babel_init_messages.input_file = I18N_POT_FILE
self.babel_init_messages.output_dir = I18N_OUTPUT_DIR_PY
self.babel_init_messages.finalize_options()
def run(self):
self.babel_init_messages.run()
class RefreshTranslation(Command):
description = "refresh translations"
user_options = []
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_extract_messages = babel.extract_messages(dist)
self.babel_update_messages = babel.update_catalog(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.babel_extract_messages.initialize_options()
self.babel_update_messages.initialize_options()
def finalize_options(self):
self.babel_extract_messages.mapping_file = I18N_MAPPING_FILE
self.babel_extract_messages.output_file = I18N_POT_FILE
self.babel_extract_messages.input_dirs = I18N_INPUT_DIRS
self.babel_extract_messages.msgid_bugs_address = "i18n@octoprint.org"
self.babel_extract_messages.copyright_holder = "The OctoPrint Project"
self.babel_extract_messages.finalize_options()
self.babel_update_messages.input_file = I18N_MAPPING_FILE
self.babel_update_messages.output_dir = I18N_OUTPUT_DIR_PY
def run(self):
self.babel_extract_messages.run()
self.babel_update_messages.run()
class CompileTranslation(Command):
description = "compile translations"
user_options = []
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_compile_messages = babel.compile_catalog(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.babel_compile_messages.initialize_options()
def finalize_options(self):
self.babel_compile_messages.directory = I18N_OUTPUT_DIR_PY
def run(self):
self.babel_compile_messages.run()
import po2json
for lang_code in os.listdir(I18N_OUTPUT_DIR_PY):
full_path = os.path.join(I18N_OUTPUT_DIR_PY, lang_code)
if os.path.isdir(full_path):
client_po_dir = os.path.join(full_path, "LC_MESSAGES")
po2json.update_js_file(
"%s/%s.po" % (client_po_dir, I18N_DOMAIN),
lang_code,
I18N_OUTPUT_DIR_JS,
I18N_DOMAIN
)
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
cmdclass.update({
'clean': CleanCommand
'clean': CleanCommand,
'babel_new': NewTranslation,
'babel_refresh': RefreshTranslation,
'babel_compile': CompileTranslation
})
return cmdclass
+3 -3
View File
@@ -293,7 +293,7 @@ class CommandTrigger(GenericEventListener):
def _executeGcodeCommand(self, command):
commands = [command]
if isinstance(command, (list, tuple, set)):
self.logger.debug("Executing GCode commands: %r" % command)
self._logger.debug("Executing GCode commands: %r" % command)
commands = list(command)
else:
self._logger.debug("Executing GCode command: %s" % command)
@@ -330,8 +330,8 @@ class CommandTrigger(GenericEventListener):
if "job" in currentData.keys() and currentData["job"] is not None:
params["__filename"] = currentData["job"]["file"]["name"]
if "progress" in currentData.keys() and currentData["progress"] is not None \
and "progress" in currentData["progress"].keys() and currentData["progress"]["progress"] is not None:
params["__progress"] = str(round(currentData["progress"]["progress"] * 100))
and "completion" in currentData["progress"].keys() and currentData["progress"]["completion"] is not None:
params["__progress"] = str(round(currentData["progress"]["completion"] * 100))
# now add the payload keys as well
if isinstance(payload, dict):
+3
View File
@@ -0,0 +1,3 @@
# coding=utf-8
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -1,3 +1,6 @@
# coding=utf-8
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
class FileDestinations(object):
SDCARD = "sdcard"
-6
View File
@@ -1,6 +0,0 @@
class FileTypes(object):
STL = "stl"
GCODE = "gcode"
+25 -16
View File
@@ -100,6 +100,7 @@ class Printer():
"date": None
},
"estimatedPrintTime": None,
"lastPrintTime": None,
"filament": {
"length": None,
"volume": None
@@ -504,6 +505,7 @@ class Printer():
self._selectedFile = None
estimatedPrintTime = None
lastPrintTime = None
date = None
filament = None
if filename:
@@ -513,11 +515,14 @@ class Printer():
date = int(os.stat(filename).st_ctime)
fileData = self._gcodeManager.getFileData(filename)
if fileData is not None and "gcodeAnalysis" in fileData.keys():
if "estimatedPrintTime" in fileData["gcodeAnalysis"].keys():
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
if "filament" in fileData["gcodeAnalysis"].keys():
filament = fileData["gcodeAnalysis"]["filament"]
if fileData is not None:
if "gcodeAnalysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]:
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
if "filament" in fileData["gcodeAnalysis"].keys():
filament = fileData["gcodeAnalysis"]["filament"]
if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]:
lastPrintTime = fileData["prints"]["last"]["lastPrintTime"]
self._stateMonitor.setJobData({
"file": {
@@ -527,6 +532,7 @@ class Printer():
"date": date
},
"estimatedPrintTime": estimatedPrintTime,
"lastPrintTime": lastPrintTime,
"filament": filament,
})
@@ -685,6 +691,7 @@ class StateMonitor(object):
self._offsets = {}
self._changeEvent = threading.Event()
self._stateMutex = threading.Lock()
self._lastUpdate = time.time()
self._worker = threading.Thread(target=self._work)
@@ -714,8 +721,9 @@ class StateMonitor(object):
self._changeEvent.set()
def setState(self, state):
self._state = state
self._changeEvent.set()
with self._stateMutex:
self._state = state
self._changeEvent.set()
def setJobData(self, jobData):
self._jobData = jobData
@@ -733,16 +741,17 @@ class StateMonitor(object):
while True:
self._changeEvent.wait()
now = time.time()
delta = now - self._lastUpdate
additionalWaitTime = self._ratelimit - delta
if additionalWaitTime > 0:
time.sleep(additionalWaitTime)
with self._stateMutex:
now = time.time()
delta = now - self._lastUpdate
additionalWaitTime = self._ratelimit - delta
if additionalWaitTime > 0:
time.sleep(additionalWaitTime)
data = self.getCurrentData()
self._updateCallback(data)
self._lastUpdate = time.time()
self._changeEvent.clear()
data = self.getCurrentData()
self._updateCallback(data)
self._lastUpdate = time.time()
self._changeEvent.clear()
def getCurrentData(self):
return {
+65 -46
View File
@@ -1,15 +1,17 @@
# coding=utf-8
import uuid
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
import tornado.wsgi
import uuid
from sockjs.tornado import SockJSRouter
from flask import Flask, render_template, send_from_directory, make_response
from flask import Flask, render_template, send_from_directory, g, request
from flask.ext.login import LoginManager
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
from flask.ext.babel import Babel
from babel import Locale
from watchdog.observers import Observer
import os
@@ -20,6 +22,7 @@ SUCCESS = {}
NO_CONTENT = ("", 204)
app = Flask("octoprint")
babel = Babel(app)
debug = False
printer = None
@@ -33,22 +36,51 @@ admin_permission = Permission(RoleNeed("admin"))
user_permission = Permission(RoleNeed("user"))
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator, \
UrlForwardHandler, user_validator, GcodeWatchdogHandler, UploadCleanupWatchdogHandler
from octoprint.printer import Printer, getConnectionOptions
from octoprint.settings import settings
import octoprint.gcodefiles as gcodefiles
import octoprint.util as util
import octoprint.users as users
import octoprint.events as events
import octoprint.timelapse
import octoprint._version
import octoprint.util
from . import util
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
VERSION = octoprint._version.get_versions()['version']
def get_available_locale_identifiers(locales):
result = set()
# add available translations
for locale in locales:
result.add(locale.language)
if locale.territory:
# if a territory is specified, add that too
result.add("%s_%s" % (locale.language, locale.territory))
return result
LOCALES = [Locale.parse("en")] + babel.list_translations()
LANGUAGES = get_available_locale_identifiers(LOCALES)
@app.before_request
def before_request():
g.locale = get_locale()
@babel.localeselector
def get_locale():
if "l10n" in request.values:
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
return request.accept_languages.best_match(LANGUAGES)
@app.route("/")
def index():
return render_template(
@@ -106,8 +138,8 @@ class Server():
self._debug = debug
self._allowRoot = allowRoot
self._logConf = logConf
self._server = None
def run(self):
if not self._allowRoot:
self._checkForRoot()
@@ -119,10 +151,8 @@ class Server():
global loginManager
global debug
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, FallbackHandler
from tornado.web import Application
debug = self._debug
@@ -150,12 +180,18 @@ class Server():
if settings().getBoolean(["accessControl", "enabled"]):
userManagerName = settings().get(["accessControl", "userManager"])
try:
clazz = util.getClass(userManagerName)
clazz = octoprint.util.getClass(userManagerName)
userManager = clazz()
except AttributeError, e:
logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
app.wsgi_app = ReverseProxied(app.wsgi_app)
app.wsgi_app = util.ReverseProxied(
app.wsgi_app,
settings().get(["server", "reverseProxy", "prefixHeader"]),
settings().get(["server", "reverseProxy", "schemeHeader"]),
settings().get(["server", "reverseProxy", "prefixFallback"]),
settings().get(["server", "reverseProxy", "prefixScheme"])
)
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
loginManager = LoginManager()
@@ -180,35 +216,18 @@ class Server():
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
def access_validation_factory(validator):
"""
Creates an access validation wrapper using the supplied validator.
:param validator: the access validator to use inside the validation wrapper
:return: an access validation wrapper taking a request as parameter and performing the request validation
"""
def f(request):
"""
Creates a custom wsgi and Flask request context in order to be able to process user information
stored in the current session.
:param request: The Tornado request for which to create the environment and context
"""
wsgi_environ = tornado.wsgi.WSGIContainer.environ(request)
with app.request_context(wsgi_environ):
app.session_interface.open_session(app, flask.request)
loginManager.reload_user()
validator(flask.request)
return f
upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"]))
self._tornado_app = Application(self._router.urls + [
(r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": settings().getBaseFolder("timelapse"), "as_attachment": True}),
(r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}),
(r"/downloads/logs/([^/]*)", LargeResponseHandler, {"path": settings().getBaseFolder("logs"), "as_attachment": True, "access_validation": access_validation_factory(admin_validator)}),
(r"/downloads/camera/current", UrlForwardHandler, {"url": settings().get(["webcam", "snapshot"]), "as_attachment": True, "access_validation": access_validation_factory(user_validator)}),
(r".*", FallbackHandler, {"fallback": WSGIContainer(app.wsgi_app)})
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)),
(r"/downloads/files/local/([^/]*\.(gco|gcode))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)),
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
(r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes))
])
self._server = HTTPServer(self._tornado_app)
max_body_sizes = [
("POST", r"/api/files/([^/]*)", settings().getInt(["server", "uploads", "maxSize"]))
]
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=settings().getInt(["server", "maxSize"]))
self._server.listen(self._port, address=self._host)
eventManager.fire(events.Events.STARTUP)
@@ -220,8 +239,8 @@ class Server():
# start up watchdogs
observer = Observer()
observer.schedule(GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched"))
observer.schedule(UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads"))
observer.schedule(util.watchdog.GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched"))
observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads"))
observer.start()
try:
@@ -237,7 +256,7 @@ class Server():
def _createSocketConnection(self, session):
global printer, gcodeManager, userManager, eventManager
return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
return util.sockjs.PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
def _checkForRoot(self):
if "geteuid" in dir(os) and os.geteuid() == 0:
@@ -302,7 +321,7 @@ class Server():
with open(logConf, "r") as f:
configFromFile = yaml.safe_load(f)
config = util.dict_merge(defaultConfig, configFromFile)
config = octoprint.util.dict_merge(defaultConfig, configFromFile)
logging.config.dictConfig(config)
if settings().getBoolean(["serial", "log"]):
@@ -311,5 +330,5 @@ class Server():
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
if __name__ == "__main__":
octoprint = Server()
octoprint.run()
server = Server()
server.run()
+19 -9
View File
@@ -1,8 +1,9 @@
# coding=utf-8
from octoprint.server.util import getApiKey, getUserForApiKey
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import netaddr
@@ -15,8 +16,11 @@ 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, UI_API_KEY
from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.server.util import get_api_key, get_user_for_apikey
from octoprint.server.util.flask import restricted_access
#~~ init api blueprint, including sub modules
@@ -32,7 +36,7 @@ from . import users as api_users
from . import log as api_logs
VERSION = "1.0"
VERSION = "0.1"
def optionsAllowOrigin(request):
@@ -67,7 +71,7 @@ def beforeApiRequests():
if request.method == 'OPTIONS' and s().getBoolean(["api", "allowCrossOrigin"]):
return optionsAllowOrigin(request)
apikey = getApiKey(request)
apikey = get_api_key(request)
if apikey is None:
# no api key => 401
return make_response("No API key provided", 401)
@@ -84,7 +88,7 @@ def beforeApiRequests():
# global api key => continue regular request processing
return
user = getUserForApiKey(apikey)
user = get_user_for_apikey(apikey)
if user is not None:
# user specific api key => continue regular request processing
return
@@ -143,7 +147,7 @@ def apiPrinterState():
def apiVersion():
return jsonify({
"server": octoprint.server.VERSION,
"api": octoprint.server.api.VERSION
"api": VERSION
})
#~~ system control
@@ -161,7 +165,12 @@ def performSystemAction():
if availableAction["action"] == action:
logger.info("Performing command: %s" % availableAction["command"])
try:
p = sarge.run(availableAction["command"], stderr=sarge.Capture())
# Note: we put the command in brackets since sarge (up to the most recently released version) has
# a bug concerning shell=True commands. Once sarge 0.1.4 we can upgrade to that and remove this
# workaround again
#
# See https://bitbucket.org/vinay.sajip/sarge/issue/21/behavior-is-not-like-popen-using-shell
p = sarge.run([availableAction["command"]], stderr=sarge.Capture(), shell=True)
if p.returncode != 0:
returncode = p.returncode
stderr_text = p.stderr.text
@@ -226,8 +235,9 @@ def login():
@restricted_access
def logout():
# Remove session keys set by Flask-Principal
for key in ('identity.id', 'identity.auth_type'):
del session[key]
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
if key in session:
del session[key]
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
logout_user()
+5 -1
View File
@@ -1,13 +1,17 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, make_response
from octoprint.settings import settings
from octoprint.printer import getConnectionOptions
from octoprint.server import printer, restricted_access, NO_CONTENT
from octoprint.server import printer, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
import octoprint.util as util
+20 -8
View File
@@ -1,8 +1,9 @@
# coding=utf-8
from octoprint.events import Events
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, make_response, url_for
@@ -10,8 +11,10 @@ import octoprint.gcodefiles as gcodefiles
import octoprint.util as util
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, gcodeManager, eventManager, restricted_access, NO_CONTENT
from octoprint.server import printer, gcodeManager, eventManager, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.server.api import api
from octoprint.events import Events
#~~ GCODE file handling
@@ -89,13 +92,22 @@ def uploadGcodeFile(target):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
if not "file" in request.files.keys():
input_name = "file"
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
if input_upload_name in request.values and input_upload_path in request.values:
import shutil
upload = util.Object()
upload.filename = request.values[input_upload_name]
upload.save = lambda new_path: shutil.move(request.values[input_upload_path], new_path)
elif input_name in request.files:
upload = request.files[input_name]
else:
return make_response("No file included", 400)
if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD card support is disabled", 404)
file = request.files["file"]
sd = target == FileDestinations.SDCARD
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
@@ -118,9 +130,9 @@ def uploadGcodeFile(target):
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
futureFilename = gcodeManager.getFutureFilename(file)
futureFilename = gcodeManager.getFutureFilename(upload)
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
return make_response("Can not upload file %s, wrong format?" % file.filename, 415)
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused():
@@ -151,9 +163,9 @@ def uploadGcodeFile(target):
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination):
printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
filename, done = gcodeManager.addFile(file, target, fileProcessingFinished)
filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished)
if filename is None:
return make_response("Could not upload the file %s" % file.filename, 500)
return make_response("Could not upload the file %s" % upload.filename, 500)
sdFilename = None
if isinstance(filename, tuple):
+5 -1
View File
@@ -1,10 +1,14 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, make_response, jsonify
from octoprint.server import printer, restricted_access, NO_CONTENT
from octoprint.server import printer, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.server.api import api
import octoprint.util as util
+6 -3
View File
@@ -1,6 +1,9 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Marc Hannappel Salandora"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
@@ -9,8 +12,8 @@ from werkzeug.utils import secure_filename
from octoprint.settings import settings
from octoprint.server import restricted_access, NO_CONTENT, admin_permission
from octoprint.server.util import redirectToTornado
from octoprint.server import NO_CONTENT, admin_permission
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from octoprint.server.api import api
from octoprint.util import getFreeBytes
@@ -27,7 +30,7 @@ def getLogFiles():
@restricted_access
@admin_permission.require(403)
def downloadLog(filename):
return redirectToTornado(request, url_for("index") + "downloads/logs/" + filename)
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
@api.route("/logs/<path:filename>", methods=["DELETE"])
+17 -3
View File
@@ -1,13 +1,17 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, make_response
from flask import request, jsonify, make_response, Response
import re
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, restricted_access, NO_CONTENT
from octoprint.server import printer, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
import octoprint.util as util
#~~ Printer
@@ -125,6 +129,9 @@ def printerToolCommand():
@api.route("/printer/tool", methods=["GET"])
def printerToolState():
if not printer.isOperational():
return make_response("Printer is not operational", 409)
def deleteBed(x):
data = dict(x)
@@ -181,6 +188,9 @@ def printerBedCommand():
@api.route("/printer/bed", methods=["GET"])
def printerBedState():
if not printer.isOperational():
return make_response("Printer is not operational", 409)
def deleteTools(x):
data = dict(x)
@@ -189,7 +199,11 @@ def printerBedState():
del data[k]
return data
return jsonify(_getTemperatureData(deleteTools))
data = _getTemperatureData(deleteTools)
if isinstance(data, Response):
return data
else:
return jsonify(data)
##~~ Print head
+11 -3
View File
@@ -1,6 +1,9 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
@@ -9,8 +12,9 @@ from flask import request, jsonify
from octoprint.settings import settings
from octoprint.printer import getConnectionOptions
from octoprint.server import restricted_access, admin_permission
from octoprint.server import admin_permission
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
#~~ settings
@@ -43,7 +47,8 @@ def getSettings():
"invertAxes": s.get(["printerParameters", "invertAxes"]),
"numExtruders": s.get(["printerParameters", "numExtruders"]),
"extruderOffsets": s.get(["printerParameters", "extruderOffsets"]),
"bedDimensions": s.get(["printerParameters", "bedDimensions"])
"bedDimensions": s.get(["printerParameters", "bedDimensions"]),
"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
},
"webcam": {
"streamUrl": s.get(["webcam", "stream"]),
@@ -81,7 +86,8 @@ def getSettings():
"uploads": s.getBaseFolder("uploads"),
"timelapse": s.getBaseFolder("timelapse"),
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
"logs": s.getBaseFolder("logs")
"logs": s.getBaseFolder("logs"),
"watched": s.getBaseFolder("watched")
},
"temperature": {
"profiles": s.get(["temperature", "profiles"])
@@ -125,6 +131,7 @@ def setSettings():
if "numExtruders" in data["printer"].keys(): s.setInt(["printerParameters", "numExtruders"], data["printer"]["numExtruders"])
if "extruderOffsets" in data["printer"].keys(): s.set(["printerParameters", "extruderOffsets"], data["printer"]["extruderOffsets"])
if "bedDimensions" in data["printer"].keys(): s.set(["printerParameters", "bedDimensions"], data["printer"]["bedDimensions"])
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
if "webcam" in data.keys():
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
@@ -171,6 +178,7 @@ def setSettings():
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
if "temperature" in data.keys():
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
+6 -3
View File
@@ -1,6 +1,9 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
@@ -11,8 +14,8 @@ import octoprint.timelapse
import octoprint.util as util
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import restricted_access, admin_permission
from octoprint.server.util import redirectToTornado
from octoprint.server import admin_permission
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from octoprint.server.api import api
@@ -46,7 +49,7 @@ def getTimelapseData():
@api.route("/timelapse/<filename>", methods=["GET"])
def downloadTimelapse(filename):
return redirectToTornado(request, url_for("index") + "downloads/timelapse/" + filename)
return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename)
@api.route("/timelapse/<filename>", methods=["DELETE"])
+5 -1
View File
@@ -1,14 +1,18 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, abort, make_response
from flask.ext.login import current_user
import octoprint.users as users
from octoprint.server import restricted_access, SUCCESS, admin_permission, userManager
from octoprint.server import SUCCESS, admin_permission, userManager
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
#~~ user settings
-565
View File
@@ -1,565 +0,0 @@
# coding=utf-8
from octoprint.filemanager.destinations import FileDestinations
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
from flask.ext.principal import identity_changed, Identity
from tornado.web import StaticFileHandler, HTTPError, RequestHandler, asynchronous
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from flask import url_for, make_response, request, current_app
from flask.ext.login import login_required, login_user, current_user
from werkzeug.utils import redirect
from sockjs.tornado import SockJSConnection
import datetime
import stat
import mimetypes
import email
import time
import os
import threading
import logging
from functools import wraps
from watchdog.events import PatternMatchingEventHandler
from octoprint.settings import settings
import octoprint.timelapse
import octoprint.server
from octoprint.users import ApiUser
from octoprint.events import Events
from octoprint import gcodefiles
import octoprint.util as util
def restricted_access(func, apiEnabled=True):
"""
If you decorate a view with this, it will ensure that first setup has been
done for OctoPrint's Access Control plus that any conditions of the
login_required decorator are met. It also allows to login using the masterkey or any
of the user's apikeys if API access is enabled globally and for the decorated view.
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
flag from the settings being set to True and the userManager not indicating
that it's user database has been customized from default), the decorator
will cause a HTTP 403 status code to be returned by the decorated resource.
If an API key is provided and it matches a known key, the user will be logged in and
the view will be called directly. If the provided key doesn't match any known key,
a HTTP 403 status code will be returned by the decorated resource.
Otherwise the result of calling login_required will be returned.
"""
@wraps(func)
def decorated_view(*args, **kwargs):
# if OctoPrint hasn't been set up yet, abort
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 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()
else:
# user key might have been used
user = octoprint.server.userManager.findUser(apikey=apikey)
if user is None:
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)
# call regular login_required decorator
return login_required(func)(*args, **kwargs)
return decorated_view
def api_access(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not settings().get(["api", "enabled"]):
make_response("API disabled", 401)
apikey = getApiKey(request)
if apikey is None:
make_response("No API key provided", 401)
if apikey != settings().get(["api", "key"]):
make_response("Invalid API key", 403)
return func(*args, **kwargs)
return decorated_view
def getUserForApiKey(apikey):
if settings().get(["api", "enabled"]) and apikey is not None:
if apikey == settings().get(["api", "key"]):
# master key was used
return ApiUser()
else:
# user key might have been used
return octoprint.server.userManager.findUser(apikey=apikey)
else:
return None
def getApiKey(request):
# Check Flask GET/POST arguments
if hasattr(request, "values") and "apikey" in request.values:
return request.values["apikey"]
# Check Tornado GET/POST arguments
if hasattr(request, "arguments") and "apikey" in request.arguments \
and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0:
return request.arguments["apikey"]
# Check Tornado and Flask headers
if "X-Api-Key" in request.headers.keys():
return request.headers.get("X-Api-Key")
return None
#~~ Printer state
class PrinterStateConnection(SockJSConnection):
EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE,
Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED,
Events.TRANSFER_STARTED, Events.TRANSFER_DONE]
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
SockJSConnection.__init__(self, session)
self._logger = logging.getLogger(__name__)
self._temperatureBacklog = []
self._temperatureBacklogMutex = threading.Lock()
self._logBacklog = []
self._logBacklogMutex = threading.Lock()
self._messageBacklog = []
self._messageBacklogMutex = threading.Lock()
self._printer = printer
self._gcodeManager = gcodeManager
self._userManager = userManager
self._eventManager = eventManager
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
return forwardedFor.split(",")[0]
return info.ip
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, "version": octoprint.server.VERSION})
self._printer.registerCallback(self)
self._gcodeManager.registerCallback(self)
octoprint.timelapse.registerCallback(self)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
for event in PrinterStateConnection.EVENTS:
self._eventManager.subscribe(event, self._onEvent)
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
def on_close(self):
self._logger.info("Client connection closed")
self._printer.unregisterCallback(self)
self._gcodeManager.unregisterCallback(self)
octoprint.timelapse.unregisterCallback(self)
self._eventManager.fire(Events.CLIENT_CLOSED)
for event in PrinterStateConnection.EVENTS:
self._eventManager.unsubscribe(event, self._onEvent)
def on_message(self, message):
pass
def sendCurrentData(self, data):
# add current temperature, log and message backlogs to sent data
with self._temperatureBacklogMutex:
temperatures = self._temperatureBacklog
self._temperatureBacklog = []
with self._logBacklogMutex:
logs = self._logBacklog
self._logBacklog = []
with self._messageBacklogMutex:
messages = self._messageBacklog
self._messageBacklog = []
data.update({
"temps": temperatures,
"logs": logs,
"messages": messages
})
self._emit("current", data)
def sendHistoryData(self, data):
self._emit("history", data)
def sendEvent(self, type, payload=None):
self._emit("event", {"type": type, "payload": payload})
def sendFeedbackCommandOutput(self, name, output):
self._emit("feedbackCommandOutput", {"name": name, "output": output})
def sendTimelapseConfig(self, timelapseConfig):
self._emit("timelapse", timelapseConfig)
def addLog(self, data):
with self._logBacklogMutex:
self._logBacklog.append(data)
def addMessage(self, data):
with self._messageBacklogMutex:
self._messageBacklog.append(data)
def addTemperature(self, data):
with self._temperatureBacklogMutex:
self._temperatureBacklog.append(data)
def _onEvent(self, event, payload):
self.sendEvent(event, payload)
def _emit(self, type, payload):
self.send({type: payload})
#~~ customized large response handler
class LargeResponseHandler(StaticFileHandler):
CHUNK_SIZE = 16 * 1024
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
StaticFileHandler.initialize(self, path, default_filename)
self._as_attachment = as_attachment
self._access_validation = access_validation
def get(self, path, include_body=True):
if self._access_validation is not None:
self._access_validation(self.request)
path = self.parse_url_path(path)
abspath = os.path.abspath(os.path.join(self.root, path))
# os.path.abspath strips a trailing /
# it needs to be temporarily added back for requests to root/
if not (abspath + os.path.sep).startswith(self.root):
raise HTTPError(403, "%s is not in root static directory", path)
if os.path.isdir(abspath) and self.default_filename is not None:
# need to look at the request.path here for when path is empty
# but there is some prefix to the path that was already
# trimmed by the routing
if not self.request.path.endswith("/"):
self.redirect(self.request.path + "/")
return
abspath = os.path.join(abspath, self.default_filename)
if not os.path.exists(abspath):
raise HTTPError(404)
if not os.path.isfile(abspath):
raise HTTPError(403, "%s is not a file", path)
stat_result = os.stat(abspath)
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
self.set_header("Last-Modified", modified)
mime_type, encoding = mimetypes.guess_type(abspath)
if mime_type:
self.set_header("Content-Type", mime_type)
cache_time = self.get_cache_time(path, modified, mime_type)
if cache_time > 0:
self.set_header("Expires", datetime.datetime.utcnow() +
datetime.timedelta(seconds=cache_time))
self.set_header("Cache-Control", "max-age=" + str(cache_time))
self.set_extra_headers(path)
# Check the If-Modified-Since, and don't send the result if the
# content has not been modified
ims_value = self.request.headers.get("If-Modified-Since")
if ims_value is not None:
date_tuple = email.utils.parsedate(ims_value)
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
if if_since >= modified:
self.set_status(304)
return
if not include_body:
assert self.request.method == "HEAD"
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
else:
with open(abspath, "rb") as file:
while True:
data = file.read(LargeResponseHandler.CHUNK_SIZE)
if not data:
break
self.write(data)
self.flush()
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment")
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
class UrlForwardHandler(RequestHandler):
def initialize(self, url=None, as_attachment=False, basename=None, access_validation=None):
RequestHandler.initialize(self)
self._url = url
self._as_attachment = as_attachment
self._basename = basename
self._access_validation = access_validation
@asynchronous
def get(self, *args, **kwargs):
if self._access_validation is not None:
self._access_validation(self.request)
if self._url is None:
raise HTTPError(404)
client = AsyncHTTPClient()
r = HTTPRequest(url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True)
try:
return client.fetch(r, self.handle_response)
except HTTPError as e:
if hasattr(e, "response") and e.response:
self.handle_response(e.response)
else:
raise HTTPError(500)
def handle_response(self, response):
if response.error and not isinstance(response.error, HTTPError):
raise HTTPError(500)
filename = None
self.set_status(response.code)
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
value = response.headers.get(name)
if value:
self.set_header(name, value)
if name == "Content-Type":
filename = self.get_filename(value)
if self._as_attachment:
if filename is not None:
self.set_header("Content-Disposition", "attachment; filename=%s" % filename)
else:
self.set_header("Content-Disposition", "attachment")
if response.body:
self.write(response.body)
self.finish()
def get_filename(self, content_type):
if not self._basename:
return None
typeValue = map(str.strip, content_type.split(";"))
if len(typeValue) == 0:
return None
extension = mimetypes.guess_extension(typeValue[0])
if not extension:
return None
return "%s%s" % (self._basename, extension)
#~~ admin access validator for use with tornado
def admin_validator(request):
"""
Validates that the given request is made by an admin user, identified either by API key or existing Flask
session.
Must be executed in an existing Flask request context!
:param request: The Flask request object
"""
apikey = getApiKey(request)
if settings().get(["api", "enabled"]) and apikey is not None:
user = getUserForApiKey(apikey)
else:
user = current_user
if user is None or not user.is_authenticated() or not user.is_admin():
raise HTTPError(403)
#~~ user access validator for use with tornado
def user_validator(request):
"""
Validates that the given request is made by an authenticated user, identified either by API key or existing Flask
session.
Must be executed in an existing Flask request context!
:param request: The Flask request object
"""
apikey = getApiKey(request)
if settings().get(["api", "enabled"]) and apikey is not None:
user = getUserForApiKey(apikey)
else:
user = current_user
if user is None or not user.is_authenticated():
raise HTTPError(403)
#~~ reverse proxy compatible wsgi middleware
class ReverseProxied(object):
"""
Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
Alternatively define prefix and scheme via config.yaml:
server:
baseUrl: /myprefix
scheme: http
:param app: the WSGI application
"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if not script_name:
script_name = settings().get(["server", "baseUrl"])
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if not scheme:
scheme = settings().get(["server", "scheme"])
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
def redirectToTornado(request, target):
requestUrl = request.url
appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "api")]
redirectUrl = appBaseUrl + target
if "?" in requestUrl:
fragment = requestUrl[requestUrl.rfind("?"):]
redirectUrl += fragment
return redirect(redirectUrl)
class UploadCleanupWatchdogHandler(PatternMatchingEventHandler):
"""
Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder
"""
patterns = map(lambda x: "*.%s" % x, gcodefiles.GCODE_EXTENSIONS)
def __init__(self, gcode_manager):
PatternMatchingEventHandler.__init__(self)
self._gcode_manager = gcode_manager
def on_deleted(self, event):
filename = self._gcode_manager._getBasicFilename(event.src_path)
if not filename:
return
self._gcode_manager.removeFileFromMetadata(filename)
class GcodeWatchdogHandler(PatternMatchingEventHandler):
"""
Takes care of automatically "uploading" files that get added to the watched folder.
"""
patterns = map(lambda x: "*.%s" % x, gcodefiles.SUPPORTED_EXTENSIONS)
def __init__(self, gcodeManager, printer):
PatternMatchingEventHandler.__init__(self)
self._logger = logging.getLogger(__name__)
self._gcodeManager = gcodeManager
self._printer = printer
def _upload(self, path):
class WatchdogFileWrapper(object):
def __init__(self, path):
self._path = path
self.filename = os.path.basename(self._path)
def save(self, target):
util.safeRename(self._path, target)
fileWrapper = WatchdogFileWrapper(path)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = self._printer.getCurrentJob()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
futureFilename = self._gcodeManager.getFutureFilename(fileWrapper)
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename)
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and not currentOrigin == FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused():
self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename)
return
self._gcodeManager.addFile(fileWrapper, FileDestinations.LOCAL)
def on_created(self, event):
self._upload(event.src_path)
+114
View File
@@ -0,0 +1,114 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.settings import settings
import octoprint.timelapse
import octoprint.server
from octoprint.users import ApiUser
from . import flask
from . import sockjs
from . import tornado
from . import watchdog
def get_user_for_apikey(apikey):
if settings().get(["api", "enabled"]) and apikey is not None:
if apikey == settings().get(["api", "key"]):
# master key was used
return ApiUser()
else:
# user key might have been used
return octoprint.server.userManager.findUser(apikey=apikey)
else:
return None
def get_api_key(request):
# Check Flask GET/POST arguments
if hasattr(request, "values") and "apikey" in request.values:
return request.values["apikey"]
# Check Tornado GET/POST arguments
if hasattr(request, "arguments") and "apikey" in request.arguments \
and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0:
return request.arguments["apikey"]
# Check Tornado and Flask headers
if "X-Api-Key" in request.headers.keys():
return request.headers.get("X-Api-Key")
return None
#~~ reverse proxy compatible WSGI middleware
class ReverseProxied(object):
"""
Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
Alternatively define prefix and scheme via config.yaml:
server:
baseUrl: /myprefix
scheme: http
:param app: the WSGI application
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
:param base_url: the prefix to use as fallback if headers are not set
"""
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""):
self.app = app
# headers for prefix & scheme, converted to conform to WSGI format
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
self._header_prefix = to_wsgi_format(header_prefix)
self._header_scheme = to_wsgi_format(header_scheme)
# fallback prefix & scheme from config
self._fallback_prefix = base_url
self._fallback_scheme = scheme
def __call__(self, environ, start_response):
# determine prefix
prefix = environ.get(self._header_prefix, "")
if not prefix:
prefix = self._fallback_prefix
# rewrite SCRIPT_NAME and if necessary also PATH_INFO based on prefix
if prefix:
environ["SCRIPT_NAME"] = prefix
path_info = environ["PATH_INFO"]
if path_info.startswith(prefix):
environ["PATH_INFO"] = path_info[len(prefix):]
# determine scheme
scheme = environ.get(self._header_scheme, "")
if not scheme:
scheme = self._fallback_scheme
# rewrite wsgi.url_scheme based on scheme
if scheme:
environ["wsgi.url_scheme"] = scheme
# call wrapped app with rewritten environment
return self.app(environ, start_response)
+154
View File
@@ -0,0 +1,154 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import tornado.web
import flask
import flask.ext.login
import flask.ext.principal
import functools
from octoprint.settings import settings
import octoprint.server
import octoprint.users
#~~ access validators for use with tornado
def admin_validator(request):
"""
Validates that the given request is made by an admin user, identified either by API key or existing Flask
session.
Must be executed in an existing Flask request context!
:param request: The Flask request object
"""
user = _get_flask_user_from_request(request)
if user is None or not user.is_authenticated() or not user.is_admin():
raise tornado.web.HTTPError(403)
def user_validator(request):
"""
Validates that the given request is made by an authenticated user, identified either by API key or existing Flask
session.
Must be executed in an existing Flask request context!
:param request: The Flask request object
"""
user = _get_flask_user_from_request(request)
if user is None or not user.is_authenticated():
raise tornado.web.HTTPError(403)
def _get_flask_user_from_request(request):
"""
Retrieves the current flask user from the request context. Uses API key if available, otherwise the current
user session if available.
:param request: flask request from which to retrieve the current user
:return: the user or None if no user could be determined
"""
import octoprint.server.util
import flask.ext.login
from octoprint.settings import settings
apikey = octoprint.server.util.get_api_key(request)
if settings().get(["api", "enabled"]) and apikey is not None:
user = octoprint.server.util.get_user_for_apikey(apikey)
else:
user = flask.ext.login.current_user
return user
def redirect_to_tornado(request, target, code=302):
"""
Redirects from flask to tornado, flask request context must exist.
:param request:
:param target:
:param code:
:return:
"""
import flask
requestUrl = request.url
appBaseUrl = requestUrl[:requestUrl.find(flask.url_for("index") + "api")]
redirectUrl = appBaseUrl + target
if "?" in requestUrl:
fragment = requestUrl[requestUrl.rfind("?"):]
redirectUrl += fragment
return flask.redirect(redirectUrl, code=code)
def restricted_access(func, api_enabled=True):
"""
If you decorate a view with this, it will ensure that first setup has been
done for OctoPrint's Access Control plus that any conditions of the
login_required decorator are met. It also allows to login using the masterkey or any
of the user's apikeys if API access is enabled globally and for the decorated view.
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
flag from the settings being set to True and the userManager not indicating
that it's user database has been customized from default), the decorator
will cause a HTTP 403 status code to be returned by the decorated resource.
If an API key is provided and it matches a known key, the user will be logged in and
the view will be called directly. If the provided key doesn't match any known key,
a HTTP 403 status code will be returned by the decorated resource.
Otherwise the result of calling login_required will be returned.
"""
@functools.wraps(func)
def decorated_view(*args, **kwargs):
# if OctoPrint hasn't been set up yet, abort
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
return flask.make_response("OctoPrint isn't setup yet", 403)
# 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 = octoprint.server.util.get_api_key(flask.request)
if settings().get(["api", "enabled"]) and api_enabled and apikey is not None and apikey != octoprint.server.UI_API_KEY:
if apikey == settings().get(["api", "key"]):
# master key was used
user = octoprint.users.ApiUser()
else:
# user key might have been used
user = octoprint.server.userManager.findUser(apikey=apikey)
if user is None:
return flask.make_response("Invalid API key", 401)
if flask.ext.login.login_user(user, remember=False):
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
return func(*args, **kwargs)
# call regular login_required decorator
return flask.ext.login.login_required(func)(*args, **kwargs)
return decorated_view
def api_access(func):
@functools.wraps(func)
def decorated_view(*args, **kwargs):
if not settings().get(["api", "enabled"]):
flask.make_response("API disabled", 401)
apikey = octoprint.server.util.get_api_key(flask.request)
if apikey is None:
flask.make_response("No API key provided", 401)
if apikey != settings().get(["api", "key"]):
flask.make_response("Invalid API key", 403)
return func(*args, **kwargs)
return decorated_view
+124
View File
@@ -0,0 +1,124 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import threading
import sockjs.tornado
import octoprint.timelapse
import octoprint.server
from octoprint.events import Events
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE,
Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED,
Events.TRANSFER_STARTED, Events.TRANSFER_DONE]
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
sockjs.tornado.SockJSConnection.__init__(self, session)
self._logger = logging.getLogger(__name__)
self._temperatureBacklog = []
self._temperatureBacklogMutex = threading.Lock()
self._logBacklog = []
self._logBacklogMutex = threading.Lock()
self._messageBacklog = []
self._messageBacklogMutex = threading.Lock()
self._printer = printer
self._gcodeManager = gcodeManager
self._userManager = userManager
self._eventManager = eventManager
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
return forwardedFor.split(",")[0]
return info.ip
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, "version": octoprint.server.VERSION})
self._printer.registerCallback(self)
self._gcodeManager.registerCallback(self)
octoprint.timelapse.registerCallback(self)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
for event in PrinterStateConnection.EVENTS:
self._eventManager.subscribe(event, self._onEvent)
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
def on_close(self):
self._logger.info("Client connection closed")
self._printer.unregisterCallback(self)
self._gcodeManager.unregisterCallback(self)
octoprint.timelapse.unregisterCallback(self)
self._eventManager.fire(Events.CLIENT_CLOSED)
for event in PrinterStateConnection.EVENTS:
self._eventManager.unsubscribe(event, self._onEvent)
def on_message(self, message):
pass
def sendCurrentData(self, data):
# add current temperature, log and message backlogs to sent data
with self._temperatureBacklogMutex:
temperatures = self._temperatureBacklog
self._temperatureBacklog = []
with self._logBacklogMutex:
logs = self._logBacklog
self._logBacklog = []
with self._messageBacklogMutex:
messages = self._messageBacklog
self._messageBacklog = []
data.update({
"temps": temperatures,
"logs": logs,
"messages": messages
})
self._emit("current", data)
def sendHistoryData(self, data):
self._emit("history", data)
def sendEvent(self, type, payload=None):
self._emit("event", {"type": type, "payload": payload})
def sendFeedbackCommandOutput(self, name, output):
self._emit("feedbackCommandOutput", {"name": name, "output": output})
def sendTimelapseConfig(self, timelapseConfig):
self._emit("timelapse", timelapseConfig)
def addLog(self, data):
with self._logBacklogMutex:
self._logBacklog.append(data)
def addMessage(self, data):
with self._messageBacklogMutex:
self._messageBacklog.append(data)
def addTemperature(self, data):
with self._temperatureBacklogMutex:
self._temperatureBacklog.append(data)
def _onEvent(self, event, payload):
self.sendEvent(event, payload)
def _emit(self, type, payload):
self.send({type: payload})
+880
View File
@@ -0,0 +1,880 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import datetime
import stat
import mimetypes
import email
import time
import re
import tornado
import tornado.web
import tornado.gen
import tornado.escape
import tornado.httputil
import tornado.httpserver
import tornado.httpclient
import tornado.http1connection
import tornado.iostream
import tornado.tcpserver
import octoprint.util
#~~ WSGI middleware
@tornado.web.stream_request_body
class UploadStorageFallbackHandler(tornado.web.RequestHandler):
"""
A `RequestHandler` similar to `tornado.web.FallbackHandler` which fetches any files contained in the request bodies
of content type `multipart`, stores them in temporary files and supplies the `fallback` with the file's `name`,
`content_type`, `path` and `size` instead via a rewritten body.
Basically similar to what the nginx upload module does.
Basic request body example:
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file"; filename="test.gcode"
Content-Type: application/octet-stream
...
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="apikey"
my_funny_apikey
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="select"
true
------WebKitFormBoundarypYiSUx63abAmhT5C--
That would get turned into:
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="apikey"
my_funny_apikey
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="select"
true
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.path"
/tmp/tmpzupkro
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.name"
test.gcode
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.content_type"
application/octet-stream
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.size"
349182
------WebKitFormBoundarypYiSUx63abAmhT5C--
The underlying application can then access the contained files via their respective paths and just move them
where necessary.
"""
# the request methods that may contain a request body
BODY_METHODS = ("POST", "PATCH", "PUT")
def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None):
if not suffixes:
suffixes = dict()
self._fallback = fallback
self._file_prefix = file_prefix
self._file_suffix = file_suffix
self._path = path
self._suffixes = dict((key, key) for key in ("name", "path", "content_type", "size"))
for suffix_type, suffix in suffixes.iteritems():
if suffix_type in self._suffixes and suffix is not None:
self._suffixes[suffix_type] = suffix
# Parts, files and values will be stored here
self._parts = dict()
self._files = []
# Part currently being processed
self._current_part = None
# content type of request body
self._content_type = None
# bytes left to read according to content_length of request body
self._bytes_left = 0
# buffer needed for identifying form data parts
self._buffer = b""
# buffer for new body
self._new_body = b""
# logger
self._logger = logging.getLogger(__name__)
def prepare(self):
"""
Prepares the processing of the request. If it's a request that may contain a request body (as defined in
`UploadStorageFallbackHandler.BODY_METHODS) prepares the multipart parsing if content type fits. If it's a
body-less request, just calls the `fallback` with an empty body and finishes the request.
"""
if self.request.method in UploadStorageFallbackHandler.BODY_METHODS:
self._bytes_left = self.request.headers.get("Content-Length", 0)
self._content_type = self.request.headers.get("Content-Type", None)
# request might contain a body
if self.is_multipart():
if not self._bytes_left:
# we don't support requests without a content-length
raise tornado.web.HTTPError(400, reason="No Content-Length supplied")
# extract the multipart boundary
fields = self._content_type.split(";")
for field in fields:
k, sep, v = field.strip().partition("=")
if k == "boundary" and v:
if v.startswith(b'"') and v.endswith(b'"'):
self._multipart_boundary = tornado.escape.utf8(v[1:-1])
else:
self._multipart_boundary = tornado.escape.utf8(v)
break
else:
self._multipart_boundary = None
else:
self._fallback(self.request, b"")
self._finished = True
def data_received(self, chunk):
"""
Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of
processing the multipart data structure via `self._process_multipart_data`. If not, just adds the chunk to
internal in-memory buffer.
:param chunk: chunk of data received from Tornado
"""
data = self._buffer + chunk
if self.is_multipart():
self._process_multipart_data(data)
else:
self._buffer = data
def is_multipart(self):
"""Checks whether this request is a `multipart` request"""
return self._content_type is not None and self._content_type.startswith("multipart")
def _process_multipart_data(self, data):
"""
Processes the given data, parsing it for multipart definitions and calling the appropriate methods.
:param data: the data to process as a string
"""
# check for boundary
delimiter = b"--%s" % self._multipart_boundary
delimiter_loc = data.find(delimiter)
delimiter_len = len(delimiter)
end_of_header = None
if delimiter_loc != -1:
# found the delimiter in the currently available data
data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:]
end_of_header = self._buffer.find("\r\n\r\n")
else:
# make sure any boundary (with single or double ==) contained at the end of chunk does not get
# truncated by this processing round => save it to the buffer for next round
endlen = len(self._multipart_boundary) + 4
data, self._buffer = data[0:-endlen], data[-endlen:]
# stream data to part handler
if data and self._current_part:
self._on_part_data(self._current_part, data)
if end_of_header >= 0:
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
self._buffer = self._buffer[end_of_header + 4:]
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
# we saw the last boundary and are at the end of our request
if self._current_part:
self._on_part_finish(self._current_part)
self._current_part = None
self._buffer = b""
self._on_request_body_finish()
def _on_part_header(self, header):
"""
Called for a new multipart header, takes care of parsing the header and calling `self._on_part` with the
relevant data, setting the current part in the process.
:param header: header to parse
"""
# close any open parts
if self._current_part:
self._on_part_finish(self._current_part)
self._current_part = None
header_check = header.find(self._multipart_boundary)
if header_check != -1:
self._logger.warn("Header still contained multipart boundary, stripping it...")
header = header[header_check:]
# convert to dict
header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8"))
disp_header = header.get("Content-Disposition", "")
disposition, disp_params = tornado.httputil._parse_header(disp_header)
if disposition != "form-data":
self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one")
return
if not disp_params.get("name"):
self._logger.warn("Got a multipart header without name, ignoring that one")
return
self._current_part = self._on_part_start(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None)
def _on_part_start(self, name, content_type, filename=None):
"""
Called for new parts in the multipart stream. If `filename` is given creates new `file` part (which leads
to storage of the data as temporary file on disk), if not creates a new `data` part (which stores
incoming data in memory).
Structure of `file` parts:
* `name`: name of the part
* `filename`: filename associated with the part
* `path`: path to the temporary file storing the file's data
* `content_type`: content type of the part
* `file`: file handle for the temporary file (mode "wb", not deleted on close!)
Structure of `data` parts:
* `name`: name of the part
* `content_type`: content type of the part
* `data`: bytes of the part (initialized to "")
:param name: name of the part
:param content_type: content type of the part
:param filename: filename associated with the part.
:return: dict describing the new part
"""
if filename is not None:
# this is a file
import tempfile
handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False)
return dict(name=tornado.escape.utf8(name),
filename=tornado.escape.utf8(filename),
path=tornado.escape.utf8(handle.name),
content_type=tornado.escape.utf8(content_type),
file=handle)
else:
return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"")
def _on_part_data(self, part, data):
"""
Called when new bytes are received for the given `part`, takes care of writing them to their storage.
:param part: part for which data was received
:param data: data chunk which was received
"""
if "file" in part:
part["file"].write(data)
else:
part["data"] += data
def _on_part_finish(self, part):
"""
Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for
`file` parts closing the temporary file and storing the part in the internal files storage.
:param part: part which was closed
"""
name = part["name"]
self._parts[name] = part
if "file" in part:
self._files.append(part["path"])
part["file"].close()
del part["file"]
def _on_request_body_finish(self):
"""
Called when the request body has been read completely. Takes care of creating the replacement body out of the
logged parts, turning `file` parts into new
:return:
"""
self._new_body = b""
for name, part in self._parts.iteritems():
if "filename" in part:
# add form fields for filename, path, size and content_type for all files contained in the request
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
for n, p in fields.iteritems():
key = name + "." + n
self._new_body += b"--%s\r\n" % self._multipart_boundary
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
self._new_body += b"\r\n"
self._new_body += p + b"\r\n"
elif "data" in part:
self._new_body += b"--%s\r\n" % self._multipart_boundary
value = part["data"]
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % name
if "content_type" in part and part["content_type"] is not None:
self._new_body += b"Content-Type: %s\r\n" % part["content_type"]
self._new_body += b"\r\n"
self._new_body += value
self._new_body += b"--%s--\r\n" % self._multipart_boundary
def _handle_method(self, *args, **kwargs):
"""
Handler for any request method, takes care of defining the new request body if necessary and forwarding
the current request and changed body to the `fallback`.
"""
# determine which body to supply
body = b""
if self.is_multipart():
# make sure we really processed all data in the buffer
while len(self._buffer):
self._process_multipart_data(self._buffer)
# use rewritten body
body = self._new_body
elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS:
# directly use data from buffer
body = self._buffer
# rewrite content length
self.request.headers["Content-Length"] = len(body)
try:
# call the configured fallback with request and body to use
self._fallback(self.request, body)
self._headers_written = True
finally:
# make sure the temporary files are removed again
for f in self._files:
octoprint.util.silentRemove(f)
# make all http methods trigger _handle_method
get = _handle_method
post = _handle_method
put = _handle_method
patch = _handle_method
delete = _handle_method
head = _handle_method
options = _handle_method
class WsgiInputContainer(object):
"""
A WSGI container for use with Tornado that allows supplying the request body to be used for `wsgi.input` in the
generated WSGI environment upon call.
A `RequestHandler` can thus provide the WSGI application with a stream for the request body, or a modified body.
Example usage:
wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app)
application = tornado.web.Application([
(r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app),
])
The implementation logic is basically the same as `tornado.wsgi.WSGIContainer` but the `__call__` and `environ`
methods have been adjusted to for an optionally supplied `body` argument which is then used for `wsgi.input`.
"""
def __init__(self, wsgi_application):
self.wsgi_application = wsgi_application
def __call__(self, request, body=None):
"""
Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado `HTTPServerRequest`.
:param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from
:param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream
"""
data = {}
response = []
def start_response(status, response_headers, exc_info=None):
data["status"] = status
data["headers"] = response_headers
return response.append
app_response = self.wsgi_application(
WsgiInputContainer.environ(request, body), start_response)
try:
response.extend(app_response)
body = b"".join(response)
finally:
if hasattr(app_response, "close"):
app_response.close()
if not data:
raise Exception("WSGI app did not call start_response")
status_code = int(data["status"].split()[0])
headers = data["headers"]
header_set = set(k.lower() for (k, v) in headers)
body = tornado.escape.utf8(body)
if status_code != 304:
if "content-length" not in header_set:
headers.append(("Content-Length", str(len(body))))
if "content-type" not in header_set:
headers.append(("Content-Type", "text/html; charset=UTF-8"))
if "server" not in header_set:
headers.append(("Server", "TornadoServer/%s" % tornado.version))
parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
for key, value in headers:
parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n")
parts.append(b"\r\n")
parts.append(body)
request.write(b"".join(parts))
request.finish()
self._log(status_code, request)
@staticmethod
def environ(request, body=None):
"""
Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
An optional `body` to be used for populating `wsgi.input` can be supplied (either a string or a stream). If not
supplied, `request.body` will be wrapped into a `io.BytesIO` stream and used instead.
:param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from
:param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream
"""
from tornado.wsgi import to_wsgi_str
import sys
import io
# determine the request_body to supply as wsgi.input
if body is not None:
if isinstance(body, (bytes, str)):
request_body = io.BytesIO(tornado.escape.utf8(body))
else:
request_body = body
else:
request_body = io.BytesIO(tornado.escape.utf8(request.body))
hostport = request.host.split(":")
if len(hostport) == 2:
host = hostport[0]
port = int(hostport[1])
else:
host = request.host
port = 443 if request.protocol == "https" else 80
environ = {
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": "",
"PATH_INFO": to_wsgi_str(tornado.escape.url_unescape(
request.path, encoding=None, plus=False)),
"QUERY_STRING": request.query,
"REMOTE_ADDR": request.remote_ip,
"SERVER_NAME": host,
"SERVER_PORT": str(port),
"SERVER_PROTOCOL": request.version,
"wsgi.version": (1, 0),
"wsgi.url_scheme": request.protocol,
"wsgi.input": request_body,
"wsgi.errors": sys.stderr,
"wsgi.multithread": False,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
}
if "Content-Type" in request.headers:
environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
if "Content-Length" in request.headers:
environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
for key, value in request.headers.items():
environ["HTTP_" + key.replace("-", "_").upper()] = value
return environ
def _log(self, status_code, request):
access_log = logging.getLogger("tornado.access")
if status_code < 400:
log_method = access_log.info
elif status_code < 500:
log_method = access_log.warning
else:
log_method = access_log.error
request_time = 1000.0 * request.request_time()
summary = request.method + " " + request.uri + " (" + \
request.remote_ip + ")"
log_method("%d %s %.2fms", status_code, summary, request_time)
#~~ customized HTTP1Connection implementation
class CustomHTTPServer(tornado.httpserver.HTTPServer):
"""
Custom implementation of `tornado.httpserver.HTTPServer` that allows defining max body sizes depending on path and
method.
The implementation is mostly taken from `tornado.httpserver.HTTPServer`, the only difference is the creation
of a `CustomHTTP1ConnectionParameters` instance instead of `tornado.http1connection.HTTP1ConnectionParameters`
which is supplied with the two new constructor arguments `max_body_sizes` and `max_default_body_size` and the
creation of a `CustomHTTP1ServerConnection` instead of a `tornado.http1connection.HTTP1ServerConnection` upon
connection by a client.
`max_body_sizes` is expected to be an iterable containing tuples of the form (method, path regex, maximum body size),
with method and path regex having to match in order for maximum body size to take affect.
`default_max_body_size` is the default maximum body size to apply if no specific one from `max_body_sizes` matches.
"""
def __init__(self, request_callback, no_keep_alive=False, io_loop=None,
xheaders=False, ssl_options=None, protocol=None,
decompress_request=False,
chunk_size=None, max_header_size=None,
idle_connection_timeout=None, body_timeout=None,
max_body_sizes=None, default_max_body_size=None, max_buffer_size=None):
self.request_callback = request_callback
self.no_keep_alive = no_keep_alive
self.xheaders = xheaders
self.protocol = protocol
self.conn_params = CustomHTTP1ConnectionParameters(
decompress=decompress_request,
chunk_size=chunk_size,
max_header_size=max_header_size,
header_timeout=idle_connection_timeout or 3600,
max_body_sizes=max_body_sizes,
default_max_body_size=default_max_body_size,
body_timeout=body_timeout)
tornado.tcpserver.TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,
max_buffer_size=max_buffer_size,
read_chunk_size=chunk_size)
self._connections = set()
def handle_stream(self, stream, address):
context = tornado.httpserver._HTTPRequestContext(stream, address,
self.protocol)
conn = CustomHTTP1ServerConnection(
stream, self.conn_params, context)
self._connections.add(conn)
conn.start_serving(self)
class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection):
"""
A custom implementation of `tornado.http1connection.HTTP1ServerConnection` which utilizes a `CustomHTTP1Connection`
instead of a `tornado.http1connection.HTTP1Connection` in `_server_request_loop`. The implementation logic is
otherwise the same as `tornado.http1connection.HTTP1ServerConnection`.
"""
@tornado.gen.coroutine
def _server_request_loop(self, delegate):
try:
while True:
conn = CustomHTTP1Connection(self.stream, False,
self.params, self.context)
request_delegate = delegate.start_request(self, conn)
try:
ret = yield conn.read_response(request_delegate)
except (tornado.iostream.StreamClosedError,
tornado.iostream.UnsatisfiableReadError):
return
except tornado.http1connection._QuietException:
# This exception was already logged.
conn.close()
return
except Exception:
tornado.http1connection.gen_log.error("Uncaught exception", exc_info=True)
conn.close()
return
if not ret:
return
yield tornado.gen.moment
finally:
delegate.on_close(self)
class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
"""
A custom implementation of `tornado.http1connection.HTTP1Connection` which upon checking the `Content-Length` of
the request against the configured maximum utilizes `max_body_sizes` and `default_max_body_size` as a fallback.
"""
def __init__(self, stream, is_client, params=None, context=None):
tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context)
import re
self._max_body_sizes = map(lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or dict())
self._default_max_body_size = self.params.default_max_body_size or self.stream.max_buffer_size
def _read_body(self, code, headers, delegate):
"""
Basically the same as `tornado.http1connection.HTTP1Connection._read_body`, but determines the maximum
content length individually for the request (utilizing `._get_max_content_length`).
If the individual max content length is 0 or smaller no content length is checked. If the content length of the
current request exceeds the individual max content length, the request processing is aborted and an
`HTTPInputError` is raised.
"""
content_length = headers.get("Content-Length")
if "Content-Length" in headers:
if "," in headers["Content-Length"]:
# Proxies sometimes cause Content-Length headers to get
# duplicated. If all the values are identical then we can
# use them but if they differ it's an error.
pieces = re.split(r',\s*', headers["Content-Length"])
if any(i != pieces[0] for i in pieces):
raise tornado.httputil.HTTPInputError(
"Multiple unequal Content-Lengths: %r" %
headers["Content-Length"])
headers["Content-Length"] = pieces[0]
content_length = int(headers["Content-Length"])
content_length = int(content_length)
max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path)
if 0 <= max_content_length < content_length:
raise tornado.httputil.HTTPInputError("Content-Length too long")
else:
content_length = None
if code == 204:
# This response code is not allowed to have a non-empty body,
# and has an implicit length of zero instead of read-until-close.
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
if ("Transfer-Encoding" in headers or
content_length not in (None, 0)):
raise tornado.httputil.HTTPInputError(
"Response with code %d should not have body" % code)
content_length = 0
if content_length is not None:
return self._read_fixed_body(content_length, delegate)
if headers.get("Transfer-Encoding") == "chunked":
return self._read_chunked_body(delegate)
if self.is_client:
return self._read_body_until_close(delegate)
return None
def _get_max_content_length(self, method, path):
"""
Gets the max content length for the given method and path. Checks whether method and path match against any
of the specific maximum content lengths supplied in `max_body_sizes` and returns that as the maximum content
length if available, otherwise returns `default_max_body_size`.
:param method: method of the request to match against
:param path: path od the request to match against
:return: determine maximum content length to apply to this request, max return 0 for unlimited allowed content
length
"""
for m, p, s in self._max_body_sizes:
if method == m and p.match(path):
return s
return self._default_max_body_size
class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionParameters):
"""
An implementation of `tornado.http1connection.HTTP1ConnectionParameters` that adds to new parameters
`max_body_sizes` and `default_max_body_size`.
For a description of these please see the documentation of `CustomHTTPServer` above.
"""
def __init__(self, *args, **kwargs):
tornado.http1connection.HTTP1ConnectionParameters.__init__(self, args, kwargs)
self.max_body_sizes = kwargs["max_body_sizes"] if "max_body_sizes" in kwargs else dict()
self.default_max_body_size = kwargs["default_max_body_size"] if "default_max_body_size" in kwargs else dict()
#~~ customized large response handler
class LargeResponseHandler(tornado.web.StaticFileHandler):
CHUNK_SIZE = 16 * 1024
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
tornado.web.StaticFileHandler.initialize(self, path, default_filename)
self._as_attachment = as_attachment
self._access_validation = access_validation
def get(self, path, include_body=True):
if self._access_validation is not None:
self._access_validation(self.request)
path = self.parse_url_path(path)
abspath = os.path.abspath(os.path.join(self.root, path))
# os.path.abspath strips a trailing /
# it needs to be temporarily added back for requests to root/
if not (abspath + os.path.sep).startswith(self.root):
raise tornado.web.HTTPError(403, "%s is not in root static directory", path)
if os.path.isdir(abspath) and self.default_filename is not None:
# need to look at the request.path here for when path is empty
# but there is some prefix to the path that was already
# trimmed by the routing
if not self.request.path.endswith("/"):
self.redirect(self.request.path + "/")
return
abspath = os.path.join(abspath, self.default_filename)
if not os.path.exists(abspath):
raise tornado.web.HTTPError(404)
if not os.path.isfile(abspath):
raise tornado.web.HTTPError(403, "%s is not a file", path)
stat_result = os.stat(abspath)
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
self.set_header("Last-Modified", modified)
mime_type, encoding = mimetypes.guess_type(abspath)
if mime_type:
self.set_header("Content-Type", mime_type)
cache_time = self.get_cache_time(path, modified, mime_type)
if cache_time > 0:
self.set_header("Expires", datetime.datetime.utcnow() +
datetime.timedelta(seconds=cache_time))
self.set_header("Cache-Control", "max-age=" + str(cache_time))
self.set_extra_headers(path)
# Check the If-Modified-Since, and don't send the result if the
# content has not been modified
ims_value = self.request.headers.get("If-Modified-Since")
if ims_value is not None:
date_tuple = email.utils.parsedate(ims_value)
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
if if_since >= modified:
self.set_status(304)
return
if not include_body:
assert self.request.method == "HEAD"
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
else:
with open(abspath, "rb") as file:
while True:
data = file.read(LargeResponseHandler.CHUNK_SIZE)
if not data:
break
self.write(data)
self.flush()
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment")
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
class UrlForwardHandler(tornado.web.RequestHandler):
def initialize(self, url=None, as_attachment=False, basename=None, access_validation=None):
tornado.web.RequestHandler.initialize(self)
self._url = url
self._as_attachment = as_attachment
self._basename = basename
self._access_validation = access_validation
@tornado.web.asynchronous
def get(self, *args, **kwargs):
if self._access_validation is not None:
self._access_validation(self.request)
if self._url is None:
raise tornado.web.HTTPError(404)
client = tornado.httpclient.AsyncHTTPClient()
r = tornado.httpclient.HTTPRequest(url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True)
try:
return client.fetch(r, self.handle_response)
except tornado.web.HTTPError as e:
if hasattr(e, "response") and e.response:
self.handle_response(e.response)
else:
raise tornado.web.HTTPError(500)
def handle_response(self, response):
if response.error and not isinstance(response.error, tornado.web.HTTPError):
raise tornado.web.HTTPError(500)
filename = None
self.set_status(response.code)
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
value = response.headers.get(name)
if value:
self.set_header(name, value)
if name == "Content-Type":
filename = self.get_filename(value)
if self._as_attachment:
if filename is not None:
self.set_header("Content-Disposition", "attachment; filename=%s" % filename)
else:
self.set_header("Content-Disposition", "attachment")
if response.body:
self.write(response.body)
self.finish()
def get_filename(self, content_type):
if not self._basename:
return None
typeValue = map(str.strip, content_type.split(";"))
if len(typeValue) == 0:
return None
extension = mimetypes.guess_extension(typeValue[0])
if not extension:
return None
return "%s%s" % (self._basename, extension)
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
def access_validation_factory(app, login_manager, validator):
"""
Creates an access validation wrapper using the supplied validator.
:param validator: the access validator to use inside the validation wrapper
:return: an access validation wrapper taking a request as parameter and performing the request validation
"""
def f(request):
"""
Creates a custom wsgi and Flask request context in order to be able to process user information
stored in the current session.
:param request: The Tornado request for which to create the environment and context
"""
import flask
wsgi_environ = WsgiInputContainer.environ(request)
with app.request_context(wsgi_environ):
app.session_interface.open_session(app, flask.request)
login_manager.reload_user()
validator(flask.request)
return f
+87
View File
@@ -0,0 +1,87 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import watchdog.events
import octoprint.gcodefiles
import octoprint.util
from octoprint.settings import settings
class UploadCleanupWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""
Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder
"""
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.GCODE_EXTENSIONS)
def __init__(self, gcode_manager):
watchdog.events.PatternMatchingEventHandler.__init__(self)
self._gcode_manager = gcode_manager
def on_deleted(self, event):
filename = self._gcode_manager._getBasicFilename(event.src_path)
if not filename:
return
self._gcode_manager.removeFileFromMetadata(filename)
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""
Takes care of automatically "uploading" files that get added to the watched folder.
"""
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.SUPPORTED_EXTENSIONS)
def __init__(self, gcodeManager, printer):
watchdog.events.PatternMatchingEventHandler.__init__(self)
self._logger = logging.getLogger(__name__)
self._gcodeManager = gcodeManager
self._printer = printer
def _upload(self, path):
class WatchdogFileWrapper(object):
def __init__(self, path):
self._path = path
self.filename = os.path.basename(self._path)
def save(self, target):
octoprint.util.safeRename(self._path, target)
fileWrapper = WatchdogFileWrapper(path)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = self._printer.getCurrentJob()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
futureFilename = self._gcodeManager.getFutureFilename(fileWrapper)
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not octoprint.gcodefiles.isGcodeFileName(futureFilename)):
self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename)
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and not currentOrigin == octoprint.gcodefiles.FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused():
self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename)
return
self._gcodeManager.addFile(fileWrapper, octoprint.gcodefiles.FileDestinations.LOCAL)
def on_created(self, event):
self._upload(event.src_path)
+56 -6
View File
@@ -60,8 +60,18 @@ default_settings = {
"host": "0.0.0.0",
"port": 5000,
"firstRun": True,
"baseUrl": "",
"scheme": ""
"reverseProxy": {
"prefixHeader": "X-Script-Name",
"schemeHeader": "X-Scheme",
"prefixFallback": "",
"schemeFallback": ""
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
"nameSuffix": ".name",
"pathSuffix": ".path"
},
"maxSize": 100 * 1024, # 100 KB
},
"webcam": {
"stream": None,
@@ -82,6 +92,9 @@ default_settings = {
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
"sizeThreshold": 20 * 1024 * 1024, # 20MB
},
"gcodeAnalysis": {
"maxExtruders": 10
},
"feature": {
"temperatureGraph": True,
"waitForStartOnConnect": False,
@@ -121,7 +134,8 @@ default_settings = {
],
"bedDimensions": {
"x": 200.0, "y": 200.0, "r": 100
}
},
"defaultExtrusionLength": 5
},
"appearance": {
"name": "",
@@ -219,7 +233,7 @@ class Settings(object):
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
with open(self._configfile, "r") as f:
self._config = yaml.safe_load(f)
# chamged from else to handle cases where the file exists, but is empty / 0 bytes
# changed from else to handle cases where the file exists, but is empty / 0 bytes
if not self._config:
self._config = {}
@@ -230,6 +244,36 @@ class Settings(object):
if not self._config:
return
dirty = False
for migrate in (self._migrate_event_config, self._migrate_reverse_proxy_config):
dirty = migrate() or dirty
if dirty:
self.save(force=True)
def _migrate_reverse_proxy_config(self):
if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]):
prefix = ""
if "baseUrl" in self._config["server"]:
prefix = self._config["server"]["baseUrl"]
del self._config["server"]["baseUrl"]
scheme = ""
if "scheme" in self._config["server"]:
scheme = self._config["server"]["scheme"]
del self._config["server"]["scheme"]
if not "reverseProxy" in self._config["server"] or not isinstance(self._config["server"]["reverseProxy"], dict):
self._config["server"]["reverseProxy"] = dict()
if prefix:
self._config["server"]["reverseProxy"]["prefixFallback"] = prefix
if scheme:
self._config["server"]["reverseProxy"]["schemeFallback"] = scheme
self._logger.info("Migrated reverse proxy configuration to new structure")
return True
else:
return False
def _migrate_event_config(self):
if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]):
self._logger.info("Migrating config (event subscriptions)...")
@@ -311,8 +355,10 @@ class Settings(object):
newEvents["subscriptions"].append(newTrigger)
self._config["events"] = newEvents
self.save(force=True)
self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"]))
return True
else:
return False
def save(self, force=False):
if not self._dirty and not force:
@@ -402,7 +448,11 @@ class Settings(object):
return None
if isinstance(value, bool):
return value
return value.lower() in valid_boolean_trues
if isinstance(value, (int, float)):
return value != 0
if isinstance(value, (str, unicode)):
return value.lower() in valid_boolean_trues
return value is not None
def getBaseFolder(self, type):
if type not in default_settings["folder"].keys():
+13 -6
View File
@@ -1,3 +1,5 @@
import sarge
__author__ = "Ross Hendrickson savorywatt"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -49,14 +51,19 @@ class Cura(object):
import threading
def start_thread(call_back, call_back_args, call_args, cwd):
import subprocess
self._logger.info("Running %r in %s" % (call_args, cwd))
command = " ".join(call_args)
try:
subprocess.check_call(call_args, cwd=cwd)
call_back(*call_back_args)
except subprocess.CalledProcessError as (e):
self._logger.warn("Could not slice via Cura, got return code %r" % e.returncode)
call_back_args.append("Got returncode %r" % e.returncode)
p = sarge.run(command, cwd=cwd)
if p.returncode == 0:
call_back(*call_back_args)
else:
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
call_back_args.append("Got returncode %r" % p.returncode)
call_back(*call_back_args)
except:
self._logger.exception("Could not slice via Cura, got an unknown error")
call_back_args.append("Unknown error, please consult the log file")
call_back(*call_back_args)
executable = self.cura_path
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
+99 -23
View File
@@ -47,7 +47,9 @@ GCODE.renderer = (function(){
invertAxes: {x: false, y: false},
bed: {x: 200, y: 200},
container: undefined
container: undefined,
onInternalOptionChange: undefined
};
var offsetModelX = 0, offsetModelY = 0;
@@ -142,45 +144,107 @@ GCODE.renderer = (function(){
ctx.lineCap = 'round';
trackTransforms(ctx);
canvas.addEventListener('mousedown',function(evt){
// dragging => translating
canvas.addEventListener('mousedown', function(event){
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragStart = ctx.transformedPoint(lastX,lastY);
// remember starting point of dragging gesture
lastX = event.offsetX || (event.pageX - canvas.offsetLeft);
lastY = event.offsetY || (event.pageY - canvas.offsetTop);
dragStart = ctx.transformedPoint(lastX, lastY);
// not yet dragged anything
dragged = false;
},false);
canvas.addEventListener('mousemove',function(evt){
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
}, false);
canvas.addEventListener('mousemove', function(event){
// save current mouse coordinates
lastX = event.offsetX || (event.pageX - canvas.offsetLeft);
lastY = event.offsetY || (event.pageY - canvas.offsetTop);
// mouse movement => dragged
dragged = true;
if (dragStart){
if (dragStart !== undefined){
// translate
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
reRender();
renderOptions["centerViewport"] = false;
renderOptions["zoomInOnModel"] = false;
renderOptions["zoomInOnBed"] = false;
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
offsetBedY = 0;
scaleX = 1;
scaleY = 1;
if (renderOptions["onInternalOptionChange"] !== undefined) {
renderOptions["onInternalOptionChange"]({
centerViewport: false,
moveModel: false,
zoomInOnModel: false,
zoomInOnBed: false
});
}
}
},false);
canvas.addEventListener('mouseup',function(evt){
dragStart = null;
if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
},false);
}, false);
canvas.addEventListener('mouseup', function(event){
// reset dragStart
dragStart = undefined;
}, false);
// mouse wheel => zooming
var zoom = function(clicks){
var pt = ctx.transformedPoint(lastX,lastY);
// focus on last mouse position prior to zoom
var pt = ctx.transformedPoint(lastX, lastY);
ctx.translate(pt.x,pt.y);
// determine zooming factor and perform zoom
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
// return to old position
ctx.translate(-pt.x,-pt.y);
// render
reRender();
// disable conflicting options
renderOptions["zoomInOnModel"] = false;
renderOptions["zoomInOnBed"] = false;
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
offsetBedY = 0;
scaleX = 1;
scaleY = 1;
if (renderOptions["onInternalOptionChange"] !== undefined) {
renderOptions["onInternalOptionChange"]({
zoomInOnModel: false,
zoomInOnBed: false
});
}
};
var handleScroll = function(evt){
var handleScroll = function(event){
var delta;
if(evt.detail<0 || evt.wheelDelta>0)delta=zoomFactorDelta;
else delta=-1*zoomFactorDelta;
// determine zoom direction & delta
if (event.detail < 0 || event.wheelDelta > 0) {
delta = zoomFactorDelta;
} else {
delta = -1 * zoomFactorDelta;
}
if (delta) zoom(delta);
return evt.preventDefault() && false;
return event.preventDefault() && false;
};
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
canvas.addEventListener('mousewheel',handleScroll,false);
};
var drawGrid = function() {
@@ -448,8 +512,13 @@ GCODE.renderer = (function(){
};
var applyZoom = function(mdlInfo) {
// get middle of canvas
var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2);
// get current transform
var transform = ctx.getTransform();
// move to middle of canvas, reset scale, move back
if (scaleX && scaleY && transform.a && transform.d) {
ctx.translate(pt.x, pt.y);
ctx.scale(1 / scaleX, 1 / scaleY);
@@ -458,6 +527,7 @@ GCODE.renderer = (function(){
}
if (mdlInfo && renderOptions["zoomInOnModel"]) {
// if we need to zoom in on model, scale factor is calculated by longer side of object in relation to that axis of canvas
var scaleF = mdlInfo.modelSize.x > mdlInfo.modelSize.y ? (canvas.width - 10) / mdlInfo.modelSize.x : (canvas.height - 10) / mdlInfo.modelSize.y;
scaleF /= zoomFactor;
if (transform.a && transform.d) {
@@ -468,6 +538,7 @@ GCODE.renderer = (function(){
ctx.translate(-pt.x, -pt.y);
}
} else {
// reset scale to 1
scaleX = 1;
scaleY = 1;
}
@@ -477,18 +548,23 @@ GCODE.renderer = (function(){
var width = canvas.width - 10;
var height = canvas.height - 10;
// de-invert
if (currentInvertX || currentInvertY) {
ctx.scale(currentInvertX ? -1 : 1, currentInvertY ? -1 : 1);
ctx.translate(currentInvertX ? -width : 0, currentInvertY ? height : 0);
}
// get settings
var invertX = renderOptions["invertAxes"]["x"];
var invertY = renderOptions["invertAxes"]["y"];
// invert
if (invertX || invertY) {
ctx.translate(invertX ? width : 0, invertY ? -height : 0);
ctx.scale(invertX ? -1 : 1, invertY ? -1 : 1);
}
// save for later
currentInvertX = invertX;
currentInvertY = invertY;
};
@@ -530,7 +606,7 @@ GCODE.renderer = (function(){
dirty = true;
renderOptions[opt] = options[opt];
if ($.inArray(opt, ["moveModel", "centerViewport", "zoomInOnModel", "bed", "invertAxes"])) {
if ($.inArray(opt, ["moveModel", "centerViewport", "zoomInOnModel", "bed", "invertAxes"]) > -1) {
mustRefresh = true;
}
}
+12 -19
View File
@@ -40,11 +40,7 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
};
self._onclose = function() {
$("#offline_overlay_message").html(
"The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect " +
"automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect " +
"anytime using the button below."
);
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."));
if (!$("#offline_overlay").is(":visible"))
$("#offline_overlay").show();
@@ -59,10 +55,7 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
};
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."
);
$("#offline_overlay_message").html(gettext("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) {
@@ -129,40 +122,40 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
if ((type == "UpdatedFiles" && payload.type == "gcode") || type == "MetadataAnalysisFinished") {
gcodeFilesViewModel.requestData();
} else if (type == "MovieRendering") {
new PNotify({title: "Rendering timelapse", text: "Now rendering timelapse " + payload.movie_basename});
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
} else if (type == "MovieDone") {
new PNotify({title: "Timelapse ready", text: "New timelapse " + payload.movie_basename + " is done rendering."});
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
timelapseViewModel.requestData();
} else if (type == "MovieFailed") {
html = "<p>Rendering of timelapse " + payload.movie_basename + " failed with return code " + payload.returncode + "</p>";
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s"), payload) + "</p>";
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
new PNotify({title: "Rendering failed", text: html, type: "error", hide: false});
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
} else if (type == "SlicingStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
gcodeUploadProgressBar.text("Slicing ...");
gcodeUploadProgressBar.text(gettext("Slicing ..."));
} else if (type == "SlicingDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({title: "Slicing done", text: "Sliced " + payload.stl + " to " + payload.gcode + ", took " + _.sprintf("%.2f", payload.time) + " seconds"});
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload)});
gcodeFilesViewModel.requestData(payload.gcode);
} else if (type == "SlicingFailed") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
html = "Could not slice " + payload.stl + " to " + payload.gcode + ": " + payload.reason;
new PNotify({title: "Slicing failed", text: html, type: "error", hide: false});
html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
} else if (type == "TransferStarted") {
gcodeUploadProgress.addClass("progress-striped").addClass("active");
gcodeUploadProgressBar.css("width", "100%");
gcodeUploadProgressBar.text("Streaming ...");
gcodeUploadProgressBar.text(gettext("Streaming ..."));
} else if (type == "TransferDone") {
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
gcodeUploadProgressBar.css("width", "0%");
gcodeUploadProgressBar.text("");
new PNotify({title: "Streaming done", text: "Streamed " + payload.local + " to " + payload.remote + " on SD, took " + _.sprintf("%.2f", payload.time) + " seconds"});
new PNotify({title: gettext("Streaming done"), text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload)});
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
}
break;
+8 -8
View File
@@ -11,7 +11,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
self.searchFunction = undefined;
self.allItems = [];
0
self.items = ko.observableArray([]);
self.pageSize = ko.observable(filesPerPage);
self.currentPage = ko.observable(0);
@@ -321,12 +321,12 @@ function formatDuration(seconds) {
var m = (seconds % 3600) / 60;
var h = seconds / 3600;
return _.sprintf("%02d:%02d:%02d", h, m, s);
return _.sprintf(gettext(/* L10N: duration format */ "%(hour)02d:%(minute)02d:%(second)02d"), {hour: h, minute: m, second: s});
}
function formatDate(unixTimestamp) {
if (!unixTimestamp) return "-";
return moment.unix(unixTimestamp).format("YYYY-MM-DD HH:mm");
return moment.unix(unixTimestamp).format(gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm"));
}
function formatTimeAgo(unixTimestamp) {
@@ -336,20 +336,20 @@ function formatTimeAgo(unixTimestamp) {
function formatFilament(filament) {
if (!filament || !filament["length"]) return "-";
var result = _.sprintf("%.02fm", (filament["length"] / 1000));
var result = "%(length).02fm";
if (filament.hasOwnProperty("volume") && filament.volume) {
result += " / " + _.sprintf("%.02fcm³", filament["volume"]);
result += " / " + "%(volume).02fcm³";
}
return result;
return _.sprintf(result, {length: filament["length"] / 1000, volume: filament["volume"]});
}
function cleanTemperature(temp) {
if (!temp || temp < 10) return "off";
if (!temp || temp < 10) return gettext("off");
return temp;
}
function formatTemperature(temp) {
if (!temp || temp < 10) return "off";
if (!temp || temp < 10) return gettext("off");
return _.sprintf("%.1f&deg;C", temp);
}
+38 -4
View File
@@ -1,4 +1,30 @@
$(function() {
//~~ Initialize i18n
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
if (catalog === undefined) {
catalog = {messages: undefined, plural_expr: undefined, locale: undefined, domain: undefined}
}
babel.Translations.load(catalog).install();
moment.locale(LOCALE);
// Dummy translation requests for dynamic strings supplied by the backend
var dummyTranslations = [
// printer states
gettext("Offline"),
gettext("Opening serial port"),
gettext("Detecting serial port"),
gettext("Detecting baudrate"),
gettext("Connecting"),
gettext("Operational"),
gettext("Printing from SD"),
gettext("Sending file to SD"),
gettext("Printing"),
gettext("Paused"),
gettext("Closed"),
gettext("Transfering file to SD")
];
//~~ Initialize view models
var loginStateViewModel = new LoginStateViewModel();
var usersViewModel = new UsersViewModel(loginStateViewModel);
@@ -92,7 +118,7 @@ $(function() {
}
function gcode_upload_fail(e, data) {
var error = "<p>Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.</p>";
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.") + "</p>";
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
new PNotify({
title: "Upload failed",
@@ -108,10 +134,10 @@ $(function() {
function gcode_upload_progress(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$("#gcode_upload_progress .bar").css("width", progress + "%");
$("#gcode_upload_progress .bar").text("Uploading ...");
$("#gcode_upload_progress .bar").text(gettext("Uploading ..."));
if (progress >= 100) {
$("#gcode_upload_progress").addClass("progress-striped").addClass("active");
$("#gcode_upload_progress .bar").text("Saving ...");
$("#gcode_upload_progress .bar").text(gettext("Saving ..."));
}
}
@@ -361,7 +387,15 @@ $(function() {
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
if (currentSrc === undefined || currentSrc.trim() == "") {
webcamImage.attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
var newSrc = CONFIG_WEBCAM_STREAM;
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
webcamImage.attr("src", newSrc);
}
} else if (previous.hash == "#control") {
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
@@ -6,15 +6,15 @@ function AppearanceViewModel(settingsViewModel) {
self.brand = ko.computed(function() {
if (self.name())
return "OctoPrint: " + self.name();
return gettext("OctoPrint") + ": " + self.name();
else
return "OctoPrint";
})
return gettext("OctoPrint");
});
self.title = ko.computed(function() {
if (self.name())
return self.name() + " [OctoPrint]";
return self.name() + " [" + gettext("OctoPrint") + "]";
else
return "OctoPrint";
})
return gettext("OctoPrint");
});
}
@@ -21,9 +21,9 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
self.buttonText = ko.computed(function() {
if (self.isErrorOrClosed())
return "Connect";
return gettext("Connect");
else
return "Disconnect";
return gettext("Disconnect");
})
self.previousIsOperational = undefined;
@@ -34,13 +34,13 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
// multiple extruders
for (var extruder = 0; extruder < numExtruders; extruder++) {
tools[extruder] = self._createToolEntry();
tools[extruder]["name"]("Tool " + extruder);
tools[extruder]["name"](gettext("Tool") + " " + extruder);
tools[extruder]["key"]("tool" + extruder);
}
} else {
// only one extruder, no need to add numbers
tools[0] = self._createToolEntry();
tools[0]["name"]("Hotend");
tools[0]["name"](gettext("Hotend"));
tools[0]["key"]("tool0");
}
@@ -49,11 +49,11 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.fromCurrentData = function(data) {
self._processStateData(data.state);
}
};
self.fromHistoryData = function(data) {
self._processStateData(data.state);
}
};
self._processStateData = function(data) {
self.isErrorOrClosed(data.flags.closedOrError);
@@ -63,13 +63,13 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.isError(data.flags.error);
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
}
};
self.fromFeedbackCommandData = function(data) {
if (data.name in self.feedbackControlLookup) {
self.feedbackControlLookup[data.name](data.output);
}
}
};
self.requestData = function() {
$.ajax({
@@ -80,18 +80,18 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self._fromResponse(response);
}
});
}
};
self._fromResponse = function(response) {
self.controls(self._processControls(response.controls));
}
};
self._processControls = function(controls) {
for (var i = 0; i < controls.length; i++) {
controls[i] = self._processControl(controls[i]);
}
return controls;
}
};
self._processControl = function(control) {
if (control.type == "parametric_command" || control.type == "parametric_commands") {
@@ -105,7 +105,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
control.children = self._processControls(control.children);
}
return control;
}
};
self.sendJogCommand = function(axis, multiplier, distance) {
if (typeof distance === "undefined")
@@ -116,7 +116,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
var data = {
"command": "jog"
}
};
data[axis] = distance * multiplier;
$.ajax({
@@ -126,13 +126,13 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
});
}
};
self.sendHomeCommand = function(axis) {
var data = {
"command": "home",
"axes": axis
}
};
$.ajax({
url: API_BASEURL + "printer/printhead",
@@ -141,7 +141,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
});
}
};
self.sendExtrudeCommand = function() {
self._sendECommand(1);
@@ -153,7 +153,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self._sendECommand = function(dir) {
var length = self.extrusionAmount();
if (!length) length = 5;
if (!length) length = self.settings.printer_defaultExtrusionLength();
var data = {
command: "extrude",
@@ -217,7 +217,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
})
}
};
self.displayMode = function(customControl) {
switch (customControl.type) {
+18 -10
View File
@@ -106,13 +106,21 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
self.isSdReady(data.flags.sdReady);
};
self._otherRequestInProgress = false;
self.requestData = function(filenameToFocus, locationToFocus) {
if (self._otherRequestInProgress) return;
self._otherRequestInProgress = true;
$.ajax({
url: API_BASEURL + "files",
method: "GET",
dataType: "json",
success: function(response) {
self.fromResponse(response, filenameToFocus, locationToFocus);
self._otherRequestInProgress = false;
},
error: function() {
self._otherRequestInProgress = false;
}
});
};
@@ -265,21 +273,21 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") {
var filament = data["gcodeAnalysis"]["filament"];
if (_.keys(filament).length == 1) {
output += "Filament: " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "<br>";
} else {
var i = 0;
do {
output += "Filament (Tool " + i + "): " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + i]) + "<br>";
i++;
} while (filament.hasOwnProperty("tool" + i));
output += gettext("Filament") + ": " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "<br>";
} else if (_.keys(filament).length > 1) {
for (var toolKey in filament) {
if (!_.startsWith(toolKey, "tool") || !filament[toolKey] || !filament[toolKey].hasOwnProperty("length") || filament[toolKey]["length"] <= 0) continue;
output += gettext("Filament") + " (" + gettext("Tool") + " " + toolKey.substr("tool".length) + "): " + formatFilament(filament[toolKey]) + "<br>";
}
}
}
output += "Estimated Print Time: " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]);
output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
}
if (data["prints"] && data["prints"]["last"]) {
output += "<br>Last Printed: " + formatTimeAgo(data["prints"]["last"]["date"]);
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
if (data["prints"]["last"]["lastPrintTime"]) {
output += "<br>Last Print Time: " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
}
}
return output;
@@ -34,9 +34,7 @@ function FirstRunViewModel() {
};
self.disableAccessControl = function() {
$("#confirmation_dialog .confirmation_dialog_message").html("If you disable Access Control <strong>and</strong> your OctoPrint " +
"installation is accessible from the internet, your printer <strong>will be accessible by everyone - " +
"that also includes the bad guys!</strong>");
$("#confirmation_dialog .confirmation_dialog_message").html(gettext("If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"));
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
e.preventDefault();
+33 -17
View File
@@ -10,15 +10,15 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
var text = "";
switch (self.ui_progress_type()) {
case "loading": {
text = "Loading... (" + self.ui_progress_percentage().toFixed(0) + "%)";
text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
break;
}
case "analyzing": {
text = "Analyzing... (" + self.ui_progress_percentage().toFixed(0) + "%)";
text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
break;
}
case "done": {
text = "Analyzed";
text = gettext("Analyzed");
break;
}
}
@@ -60,7 +60,8 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
showNextLayer: self.renderer_showNext(),
showPreviousLayer: self.renderer_showPrevious(),
zoomInOnModel: self.renderer_zoomOnModel()
zoomInOnModel: self.renderer_zoomOnModel(),
onInternalOptionChange: self._onInternalRendererOptionChange
};
if (additionalRendererOptions) {
_.extend(renderer, additionalRendererOptions);
@@ -172,7 +173,7 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.clear = function() {
GCODE.ui.clear();
}
};
self._configureLayerSlider = function() {
self.layerSlider = $("#gcode_slider_layers").slider({
@@ -321,17 +322,17 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.currentLayer = 0;
} else {
var output = [];
output.push("Model size is: " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
if (model.filament.length == 0) {
output.push("Total filament used: " + model.filament.toFixed(2) + "mm");
output.push(gettext("Total filament used") + ": " + model.filament.toFixed(2) + gettext("mm"));
} else {
for (var i = 0; i < model.filament.length; i++) {
output.push("Total filament used (Tool " + i + "): " + model.filament[i].toFixed(2) + "mm");
output.push(gettext("Total filament used") + " (" + gettext("Tool") + " " + i + "): " + model.filament[i].toFixed(2) + gettext("mm"));
}
}
output.push("Estimated print time: " + formatDuration(model.printTime));
output.push("Estimated layer height: " + model.layerHeight.toFixed(2) + "mm");
output.push("Layer count: " + model.layersPrinted.toFixed(0) + " printed, " + model.layersTotal.toFixed(0) + " visited");
output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime));
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext(printed) + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
self.ui_modelInfo(output.join("<br>"));
@@ -350,17 +351,17 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.currentCommand = [0, 1];
} else {
var output = [];
output.push("Layer number: " + (layer.number + 1));
output.push("Layer height (mm): " + layer.height);
output.push("GCODE commands in layer: " + layer.commands);
output.push(gettext("Layer number") + ": " + (layer.number + 1));
output.push(gettext("Layer height") + " (mm): " + layer.height);
output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
if (layer.filament.length == 1) {
output.push("Filament used by layer: " + layer.filament[0].toFixed(2) + "mm");
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
} else {
for (var i = 0; i < layer.filament.length; i++) {
output.push("Filament used by layer (Tool " + i + "): " + layer.filament[i].toFixed(2) + "mm");
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
}
}
output.push("Print time for layer: " + formatDuration(layer.printTime));
output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));
self.ui_layerInfo(output.join("<br>"));
@@ -370,6 +371,20 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
}
};
self._onInternalRendererOptionChange = function(options) {
if (!options) return;
for (var opt in options) {
if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) {
self.renderer_zoomOnModel(false);
} else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) {
self.renderer_centerViewport(false);
} else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) {
self.renderer_centerModel(false);
}
}
};
self.changeLayer = function(event) {
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
@@ -389,4 +404,5 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
};
}
@@ -12,15 +12,15 @@ function LoginStateViewModel() {
if (self.loggedIn()) {
return "\"" + self.username() + "\"";
} else {
return "Login";
return gettext("Login");
}
})
});
self.subscribers = [];
self.subscribe = function(callback) {
if (callback === undefined) return;
self.subscribers.push(callback);
}
};
self.requestData = function() {
$.ajax({
@@ -51,7 +51,7 @@ function LoginStateViewModel() {
_.each(self.subscribers, function(callback) { callback("logout", {}); });
}
}
};
self.login = function() {
var username = $("#login_user").val();
@@ -67,21 +67,21 @@ function LoginStateViewModel() {
type: "POST",
data: {"user": username, "pass": password, "remember": remember},
success: function(response) {
new PNotify({title: "Login successful", text: "You are now logged in as \"" + response.name + "\"", type: "success"});
new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"});
self.fromResponse(response);
},
error: function(jqXHR, textStatus, errorThrown) {
new PNotify({title: "Login failed", text: "User unknown or wrong password", type: "error"});
new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"});
}
})
}
};
self.logout = function() {
$.ajax({
url: API_BASEURL + "logout",
type: "POST",
success: function(response) {
new PNotify({title: "Logout successful", text: "You are now logged out", type: "success"});
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
self.fromResponse(response);
}
})
@@ -14,15 +14,15 @@ function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsV
dataType: "json",
data: "action=" + action.action,
success: function() {
new PNotify({title: "Success", text: "The command \""+ action.name +"\" executed successfully", type: "success"});
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"});
},
error: function(jqXHR, textStatus, errorThrown) {
var error = "<p>The command \"" + action.name + "\" could not be executed.</p>";
var error = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
new PNotify({title: "Error", text: error, type: "error", hide: false});
new PNotify({title: gettext("Error"), text: error, type: "error", hide: false});
}
})
}
};
if (action.confirm) {
var confirmationDialog = $("#confirmation_dialog");
var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog);
@@ -24,13 +24,16 @@ function PrinterStateViewModel(loginStateViewModel) {
self.filament = ko.observableArray([]);
self.estimatedPrintTime = ko.observable(undefined);
self.lastPrintTime = ko.observable(undefined);
self.currentHeight = ko.observable(undefined);
self.estimatedPrintTimeString = ko.computed(function() {
if (!self.estimatedPrintTime())
return "-";
return formatDuration(self.estimatedPrintTime());
if (self.lastPrintTime())
return formatDuration(self.lastPrintTime());
if (self.estimatedPrintTime())
return formatDuration(self.estimatedPrintTime());
return "-";
});
self.byteString = ko.computed(function() {
if (!self.filesize())
@@ -60,9 +63,9 @@ function PrinterStateViewModel(loginStateViewModel) {
});
self.pauseString = ko.computed(function() {
if (self.isPaused())
return "Continue";
return gettext("Continue");
else
return "Pause";
return gettext("Pause");
});
self.timelapseString = ko.computed(function() {
@@ -73,9 +76,9 @@ function PrinterStateViewModel(loginStateViewModel) {
var type = timelapse["type"];
if (type == "zchange") {
return "On Z Change";
return gettext("On Z Change");
} else if (type == "timed") {
return "Timed (" + timelapse["options"]["interval"] + "s)";
return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")";
} else {
return "-";
}
@@ -101,7 +104,7 @@ function PrinterStateViewModel(loginStateViewModel) {
};
self._processStateData = function(data) {
self.stateString(data.text);
self.stateString(gettext(data.text));
self.isErrorOrClosed(data.flags.closedOrError);
self.isOperational(data.flags.operational);
self.isPaused(data.flags.paused);
@@ -123,18 +126,18 @@ function PrinterStateViewModel(loginStateViewModel) {
}
self.estimatedPrintTime(data.estimatedPrintTime);
self.lastPrintTime(data.lastPrintTime);
var result = [];
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
var i = 0;
do {
var key = "tool" + i;
result[i] = {
name: ko.observable("Tool " + i),
for (var key in data.filament) {
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue;
result.push({
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
data: ko.observable(data.filament[key])
};
i++;
} while (data.filament.hasOwnProperty("tool" + i));
});
}
}
self.filament(result);
};
@@ -160,7 +163,7 @@ function PrinterStateViewModel(loginStateViewModel) {
};
if (self.isPaused()) {
$("#confirmation_dialog .confirmation_dialog_message").text("This will restart the print job from the beginning.");
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will restart the print job from the beginning."));
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); restartCommand(); });
$("#confirmation_dialog").modal("show");
@@ -11,7 +11,38 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.appearance_name = ko.observable(undefined);
self.appearance_color = ko.observable(undefined);
self.appearance_available_colors = ko.observable(["default", "red", "orange", "yellow", "green", "blue", "violet", "black"]);
self.appearance_available_colors = ko.observable([
{key: "default", name: gettext("default")},
{key: "red", name: gettext("red")},
{key: "orange", name: gettext("orange")},
{key: "yellow", name: gettext("yellow")},
{key: "green", name: gettext("green")},
{key: "blue", name: gettext("blue")},
{key: "violet", name: gettext("violet")},
{key: "black", name: gettext("black")},
]);
self.appearance_colorName = function(color) {
switch (color) {
case "red":
return gettext("red");
case "orange":
return gettext("orange");
case "yellow":
return gettext("yellow");
case "green":
return gettext("green");
case "blue":
return gettext("blue");
case "violet":
return gettext("violet");
case "black":
return gettext("black");
case "default":
return gettext("default");
default:
return color;
}
};
self.printer_movementSpeedX = ko.observable(undefined);
self.printer_movementSpeedY = ko.observable(undefined);
@@ -19,6 +50,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.printer_movementSpeedE = ko.observable(undefined);
self.printer_invertAxes = ko.observable(undefined);
self.printer_numExtruders = ko.observable(undefined);
self.printer_defaultExtrusionLength = ko.observable(undefined);
self._printer_extruderOffsets = ko.observableArray([]);
self.printer_extruderOffsets = ko.computed({
@@ -122,6 +154,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.folder_timelapse = ko.observable(undefined);
self.folder_timelapseTmp = ko.observable(undefined);
self.folder_logs = ko.observable(undefined);
self.folder_watched = ko.observable(undefined);
self.cura_enabled = ko.observable(undefined);
self.cura_path = ko.observable(undefined);
@@ -202,6 +235,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.printer_numExtruders(response.printer.numExtruders);
self.printer_extruderOffsets(response.printer.extruderOffsets);
self.printer_bedDimensions(response.printer.bedDimensions);
self.printer_defaultExtrusionLength(response.printer.defaultExtrusionLength);
self.webcam_streamUrl(response.webcam.streamUrl);
self.webcam_snapshotUrl(response.webcam.snapshotUrl);
@@ -236,6 +270,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
self.folder_timelapse(response.folder.timelapse);
self.folder_timelapseTmp(response.folder.timelapseTmp);
self.folder_logs(response.folder.logs);
self.folder_watched(response.folder.watched);
self.cura_enabled(response.cura.enabled);
self.cura_path(response.cura.path);
@@ -267,7 +302,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
"invertAxes": self.printer_invertAxes(),
"numExtruders": self.printer_numExtruders(),
"extruderOffsets": self.printer_extruderOffsets(),
"bedDimensions": self.printer_bedDimensions()
"bedDimensions": self.printer_bedDimensions(),
"defaultExtrusionLength": self.printer_defaultExtrusionLength()
},
"webcam": {
"streamUrl": self.webcam_streamUrl(),
@@ -303,7 +339,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
"uploads": self.folder_uploads(),
"timelapse": self.folder_timelapse(),
"timelapseTmp": self.folder_timelapseTmp(),
"logs": self.folder_logs()
"logs": self.folder_logs(),
"watched": self.folder_watched()
},
"temperature": {
"profiles": self.temperature_profiles()
@@ -19,7 +19,7 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
self.tools = ko.observableArray([]);
self.hasBed = ko.observable(true);
self.bedTemp = self._createToolEntry();
self.bedTemp["name"]("Bed");
self.bedTemp["name"](gettext("Bed"));
self.bedTemp["key"]("bed");
self.isErrorOrClosed = ko.observable(undefined);
@@ -51,7 +51,7 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
if (tools.length <= extruder || !tools[extruder]) {
tools[extruder] = self._createToolEntry();
}
tools[extruder]["name"]("Tool " + extruder);
tools[extruder]["name"](gettext("Tool") + " " + extruder);
tools[extruder]["key"]("tool" + extruder);
}
} else {
@@ -62,12 +62,12 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
if (tools.length < 1 || !tools[0]) {
tools[0] = self._createToolEntry();
}
tools[0]["name"]("Hotend");
tools[0]["name"](gettext("Hotend"));
tools[0]["key"]("tool0");
}
// print bed
heaterOptions["bed"] = {name: "Bed", color: "blue"};
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
// write back
self.heaterOptions(heaterOptions);
@@ -98,9 +98,9 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins == 0)
return "just now";
return gettext("just now");
else
return "- " + diffInMins + " min";
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
@@ -238,12 +238,12 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1]) : "-";
data.push({
label: "Actual " + heaterOptions[type].name + ": " + actualTemp,
label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp,
color: heaterOptions[type].color,
data: actuals
});
data.push({
label: "Target " + heaterOptions[type].name + ": " + targetTemp,
label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp,
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
data: targets
});
+7
View File
@@ -0,0 +1,7 @@
Note to developers
------------------
Do not edit the files in this directory directly, they are auto generated from the i18n PO files. If you want to
change any translations in here, please follow the translation guide on the Wiki:
https://github.com/foosel/OctoPrint/wiki/Translating-OctoPrint
+1
View File
@@ -0,0 +1 @@
window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 15:56+0100\nLast-Translator: Gina H\u00e4u\u00dfge <osd@foosel.net>\nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Title": "Titel", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "yellow": "Gelb", "Path to Cura": "Pfad zu Cura", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Cura": "Cura", "Files": "Dateien", "Bed Size": "Bettdimensionen", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde <strong>\u00fcber die n\u00e4chsten Minuten</strong> versuchen, zu reconnecten, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Upload Folder": "Uploadverzeichnis", "descending": "absteigend", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckzeit", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "default": "Standard", "API": "API", "Printing from SD": "Drucke von SD", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Tool": "Werkzeug", "Settings": "Einstellungen", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Printed": "Gedruckt", "Layer number": "Schichtnummer", "Sync with job progress": "Job mit Fortschritt synchronisieren", "Circular": "Rund", "Total filament used": "Gesamtmenge genutzten Filaments", "red": "Rot", "Save as default": "Als Standard speichern", "Slicing ...": "Slice ...", "Last Print Time": "Letzte Druckdauer", "Target": "Soll", "Streaming ...": "Streame ...", "Logout successful": "Logout erfolgreich", "Now rendering timelapse %(movie_basename)s": "Rendere Zeitrafferaufnahme %(movie_basename)s", "Documentation": "Dokumentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "aufsteigend", "Model size": "Modelgr\u00f6\u00dfe", "Temperatures": "Temperaturen", "visited": "besucht", "Timed": "Nach Zeit", "Edit user \"%(user)s\"": "Editiere Nutzer \"%(user)s\"", "Snapshot URL": "Snapshot-URL", "Release SD card": "SD-KLine truncated
+1
View File
@@ -0,0 +1 @@
window.BABEL_TO_LOAD_fr = {"locale": "fr", "domain": "messages", "plural_expr": "(n > 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 13:54+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\nPlural-Forms: nplurals=2; plural=(n > 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Temps d'impression restant", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Title": "Titre", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "yellow": "jaune", "Path to Cura": "Chemin vers Cura", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Cura": "Cura", "Files": "Fichiers", "Bed Size": "Taille du lit", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement <strong>dans les minutes qui suivent</strong>. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Upload Folder": "R\u00e9pertoire des chargements", "descending": "descendant", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "default": "Par d\u00e9faut", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Tool": "Outil", "Settings": "Param\u00e8tres", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to SD": "Chargement vers la carte SD", "The command \"%(command)s\" could not be executed.": "La commande \"%(command)s\" n'a pas pu \u00eatre ex\u00e9cut\u00e9e", "Printed": "Imprim\u00e9", "Layer number": "Couche num\u00e9ro", "Sync with job progress": "Synchroniser avec le progr\u00e8s du job", "Circular": "Circulaire", "Total filament used": "Quantit\u00e9 de filament utilis\u00e9", "red": "rouge", "Save as default": "Sauver en tant que d\u00e9faut", "Slicing ...": "Tranchage en cours...", "Last Print Time": "Temps d'impression pr\u00e9c\u00e9dent", "Target": "Cible", "Streaming ...": "Diffusion en direct en cours...", "Logout successful": "Fermeture de session r\u00e9ussie", "Now rendering timelapse %(movieLine truncated
+160
View File
@@ -0,0 +1,160 @@
/**
* Babel JavaScript Support
*
* Copyright (C) 2008-2011 Edgewall Software
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://babel.edgewall.org/wiki/License.
*
* This software consists of voluntary contributions made by many
* individuals. For the exact contribution history, see the revision
* history and logs, available at http://babel.edgewall.org/log/.
*/
/**
* A simple module that provides a gettext like translation interface.
* The catalog passed to load() must be a object conforming to this
* interface::
*
* {
* messages: an object of {msgid: translations} items where
* translations is an array of messages or a single
* string if the message is not pluralizable.
* plural_expr: the plural expression for the language.
* locale: the identifier for this locale.
* domain: the name of the domain.
* }
*
* Missing elements in the object are ignored.
*
* Typical usage::
*
* var translations = babel.Translations.load(...).install();
*/
var babel = new function() {
var defaultPluralExpr = function(n) { return n == 1 ? 0 : 1; };
var formatRegex = /%?%(?:\(([^\)]+)\))?([disr])/g;
/**
* A translations object implementing the gettext interface
*/
var Translations = this.Translations = function(locale, domain) {
this.messages = {};
this.locale = locale || 'unknown';
this.domain = domain || 'messages';
this.pluralexpr = defaultPluralExpr;
};
/**
* Create a new translations object from the catalog and return it.
* See the babel-module comment for more details.
*/
Translations.load = function(catalog) {
var rv = new Translations();
rv.load(catalog);
return rv;
};
Translations.prototype = {
/**
* translate a single string.
*/
gettext: function(string) {
var translated = this.messages[string];
if (typeof translated == 'undefined')
return string;
return (typeof translated == 'string') ? translated : translated[0];
},
/**
* translate a pluralizable string
*/
ngettext: function(singular, plural, n) {
var translated = this.messages[singular];
if (typeof translated == 'undefined')
return (n == 1) ? singular : plural;
return translated[this.pluralexpr(n)];
},
/**
* Install this translation document wide. After this call, there are
* three new methods on the window object: _, gettext and ngettext
*/
install: function() {
var self = this;
window.gettext = function(string) {
return self.gettext(string);
};
window.ngettext = function(singular, plural, n) {
return self.ngettext(singular, plural, n);
};
return this;
},
/**
* Works like Translations.load but updates the instance rather
* then creating a new one.
*/
load: function(catalog) {
if (catalog.messages)
this.update(catalog.messages);
if (catalog.plural_expr)
this.setPluralExpr(catalog.plural_expr);
if (catalog.locale)
this.locale = catalog.locale;
if (catalog.domain)
this.domain = catalog.domain;
return this;
},
/**
* Updates the translations with the object of messages.
*/
update: function(mapping) {
for (var key in mapping)
if (mapping.hasOwnProperty(key))
this.messages[key] = mapping[key];
return this;
},
/**
* Sets the plural expression
*/
setPluralExpr: function(expr) {
this.pluralexpr = new Function('n', 'return +(' + expr + ')');
return this;
}
};
/**
* A python inspired string formatting function. Supports named and
* positional placeholders and "s", "d" and "i" as type characters
* without any formatting specifications.
*
* Examples::
*
* babel.format(_('Hello %s'), name)
* babel.format(_('Progress: %(percent)s%%'), {percent: 100})
*/
this.format = function() {
var arg, string = arguments[0], idx = 0;
if (arguments.length == 1)
return string;
else if (arguments.length == 2 && typeof arguments[1] == 'object')
arg = arguments[1];
else {
arg = [];
for (var i = 1, n = arguments.length; i != n; ++i)
arg[i - 1] = arguments[i];
}
return string.replace(formatRegex, function(all, name, type) {
if (all[0] == all[1]) return all.substring(1);
var value = arg[name || idx++];
return (type == 'i' || type == 'd') ? +value : value;
});
}
};
+10
View File
@@ -0,0 +1,10 @@
//! moment.js
//! version : 2.8.2
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
(function(a){function b(a,b,c){switch(arguments.length){case 2:return null!=a?a:b;case 3:return null!=a?a:null!=b?b:c;default:throw new Error("Implement me")}}function c(a,b){return yb.call(a,b)}function d(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function e(a){sb.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+a)}function f(a,b){var c=!0;return m(function(){return c&&(e(a),c=!1),b.apply(this,arguments)},b)}function g(a,b){pc[a]||(e(b),pc[a]=!0)}function h(a,b){return function(c){return p(a.call(this,c),b)}}function i(a,b){return function(c){return this.localeData().ordinal(a.call(this,c),b)}}function j(){}function k(a,b){b!==!1&&F(a),n(this,a),this._d=new Date(+a._d)}function l(a){var b=y(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=sb.localeData(),this._bubble()}function m(a,b){for(var d in b)c(b,d)&&(a[d]=b[d]);return c(b,"toString")&&(a.toString=b.toString),c(b,"valueOf")&&(a.valueOf=b.valueOf),a}function n(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=b._pf),"undefined"!=typeof b._locale&&(a._locale=b._locale),Hb.length>0)for(c in Hb)d=Hb[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function o(a){return 0>a?Math.ceil(a):Math.floor(a)}function p(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.length<b;)d="0"+d;return(e?c?"+":"":"-")+d}function q(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function r(a,b){var c;return b=K(b,a),a.isBefore(b)?c=q(a,b):(c=q(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function s(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(g(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=sb.duration(c,d),t(this,e,a),this}}function t(a,b,c,d){var e=b._milliseconds,f=b._days,g=b._months;d=null==d?!0:d,e&&a._d.setTime(+a._d+e*c),f&&mb(a,"Date",lb(a,"Date")+f*c),g&&kb(a,lb(a,"Month")+g*c),d&&sb.updateOffset(a,f||g)}function u(a){return"[object Array]"===Object.prototype.toString.call(a)}function v(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function w(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&A(a[d])!==A(b[d]))&&g++;return g+f}function x(a){if(a){var b=a.toLowerCase().replace(/(.)s$/,"$1");a=ic[a]||jc[b]||b}return a}function y(a){var b,d,e={};for(d in a)c(a,d)&&(b=x(d),b&&(e[b]=a[d]));return e}function z(b){var c,d;if(0===b.indexOf("week"))c=7,d="day";else{if(0!==b.indexOf("month"))return;c=12,d="month"}sb[b]=function(e,f){var g,h,i=sb._locale[b],j=[];if("number"==typeof e&&(f=e,e=a),h=function(a){var b=sb().utc().set(d,a);return i.call(sb._locale,b,e||"")},null!=f)return h(f);for(g=0;c>g;g++)j.push(h(g));return j}}function A(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function B(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function C(a,b,c){return gb(sb([a,11,31+b-c]),b,c).week}function D(a){return E(a)?366:365}function E(a){return a%4===0&&a%100!==0||a%400===0}function F(a){var b;a._a&&-2===a._pf.overflow&&(b=a._a[Ab]<0||a._a[Ab]>11?Ab:a._a[Bb]<1||a._a[Bb]>B(a._a[zb],a._a[Ab])?Bb:a._a[Cb]<0||a._a[Cb]>23?Cb:a._a[Db]<0||a._a[Db]>59?Db:a._a[Eb]<0||a._a[Eb]>59?Eb:a._a[Fb]<0||a._a[Fb]>999?Fb:-1,a._pf._overflowDayOfYear&&(zb>b||b>Bb)&&(b=Bb),a._pf.overflow=b)}function G(a){return null==a._isValid&&(a._isValid=!isNaN(a._d.getTime())&&a._pf.overflow<0&&!a._pf.empty&&!a._pf.invalidMonth&&!a._pf.nullInput&&!a._pf.invalidFormat&&!a._pf.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===a._pf.charsLeftOver&&0===a._pf.unusedTokens.length)),a._isValid}function H(a){return a?a.toLowerCase().replace("_","-"):a}function I(a){for(var b,c,d,e,f=0;f<a.length;){for(e=H(a[f]).split("-"),b=e.length,c=H(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=J(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&w(e,c,!0)>=b-1)break;b--}f++}return null}function J(a){var b=null;if(!Gb[a]&&Ib)try{b=sb.locale(),require("./locale/"+a),sb.locale(b)}catch(c){}return Gb[a]}function K(a,b){return b._isUTC?sb(a).zone(b._offset||0):sb(a).local()}function L(a){return a.mLine truncated
},week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){return a.defineLocale("ar-ma",{months:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),weekdays:"الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:6,doy:12}})}),function(a){a(sb)}(function(a){var b={1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"},c={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"};return a.defineLocale("ar-sa",{months:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},meridiem:function(a){return 12>a?"ص":"م"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},preparse:function(a){return a.replace(/[۰-۹]/g,function(a){return c[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return b[a]}).replace(/,/g,"،")},week:{dow:6,doy:12}})}),function(a){a(sb)}(function(a){var b={1:"١",2:"٢",3:"٣",4:"٤",5:"٥",6:"٦",7:"٧",8:"٨",9:"٩",0:"٠"},c={"١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","٠":"0"};return a.defineLocale("ar",{months:"يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"),monthsShort:"يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"),weekdays:"الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},meridiem:function(a){return 12>a?"ص":"م"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},preparse:function(a){return a.replace(/[۰-۹]/g,function(a){return c[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return b[a]}).replace(/,/g,"،")},week:{dow:6,doy:12}})}),function(a){a(sb)}(function(a){var b={1:"-inci",5:"-inci",8:"-inci",70:"-inci",80:"-inci",2:"-nci",7:"-nci",20:"-nci",50:"-nci",3:"-üncü",4:"-üncü",1Line truncated
}),function(a){a(sb)}(function(a){var b={1:"۱",2:"۲",3:"۳",4:"۴",5:"۵",6:"۶",7:"۷",8:"۸",9:"۹",0:"۰"},c={"۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9","۰":"0"};return a.defineLocale("fa",{months:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),monthsShort:"ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر".split("_"),weekdays:"یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه".split("_"),weekdaysShort:"یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه".split("_"),weekdaysMin:"ی_د_س_چ_پ_ج_ش".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},meridiem:function(a){return 12>a?"قبل از ظهر":"بعد از ظهر"},calendar:{sameDay:"[امروز ساعت] LT",nextDay:"[فردا ساعت] LT",nextWeek:"dddd [ساعت] LT",lastDay:"[دیروز ساعت] LT",lastWeek:"dddd [پیش] [ساعت] LT",sameElse:"L"},relativeTime:{future:"در %s",past:"%s پیش",s:"چندین ثانیه",m:"یک دقیقه",mm:"%d دقیقه",h:"یک ساعت",hh:"%d ساعت",d:"یک روز",dd:"%d روز",M:"یک ماه",MM:"%d ماه",y:"یک سال",yy:"%d سال"},preparse:function(a){return a.replace(/[۰-۹]/g,function(a){return c[a]}).replace(/،/g,",")},postformat:function(a){return a.replace(/\d/g,function(a){return b[a]}).replace(/,/g,"،")},ordinal:"%dم",week:{dow:6,doy:12}})}),function(a){a(sb)}(function(a){function b(a,b,d,e){var f="";switch(d){case"s":return e?"muutaman sekunnin":"muutama sekunti";case"m":return e?"minuutin":"minuutti";case"mm":f=e?"minuutin":"minuuttia";break;case"h":return e?"tunnin":"tunti";case"hh":f=e?"tunnin":"tuntia";break;case"d":return e?"päivän":"päivä";case"dd":f=e?"päivän":"päivää";break;case"M":return e?"kuukauden":"kuukausi";case"MM":f=e?"kuukauden":"kuukautta";break;case"y":return e?"vuoden":"vuosi";case"yy":f=e?"vuoden":"vuotta"}return f=c(a,e)+" "+f}function c(a,b){return 10>a?b?e[a]:d[a]:a}var d="nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän".split(" "),e=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",d[7],d[8],d[9]];return a.defineLocale("fi",{months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"su_ma_ti_ke_to_pe_la".split("_"),longDateFormat:{LT:"HH.mm",L:"DD.MM.YYYY",LL:"Do MMMM[ta] YYYY",LLL:"Do MMMM[ta] YYYY, [klo] LT",LLLL:"dddd, Do MMMM[ta] YYYY, [klo] LT",l:"D.M.YYYY",ll:"Do MMM YYYY",lll:"Do MMM YYYY, [klo] LT",llll:"ddd, Do MMM YYYY, [klo] LT"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:b,m:b,mm:b,h:b,hh:b,d:b,dd:b,M:b,MM:b,y:b,yy:b},ordinal:"%d.",week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){return a.defineLocale("fo",{months:"januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"),weekdaysShort:"sun_mán_týs_mik_hós_frí_ley".split("_"),weekdaysMin:"su_má_tý_mi_hó_fr_le".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D. MMMM, YYYY LT"},calendar:{sameDay:"[Í dag kl.] LT",nextDay:"[Í morgin kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[Í gjár kl.] LT",lastWeek:"[síðstu] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"um %s",past:"%s síðani",s:"fá sekund",m:"ein minutt",mm:"%d minuttir",h:"ein tími",hh:"%d tímar",d:"ein dagur",dd:"%d dagar",M:"ein mánaði",MM:"%d mánaðir",y:"eitt ár",yy:"%d ár"},ordinal:"%d.",week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){return a.defineLocale("fr-ca",{months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [Line truncated
})},week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){return a.defineLocale("nb",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tirs_ons_tors_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"H.mm",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] LT",LLLL:"dddd D. MMMM YYYY [kl.] LT"},calendar:{sameDay:"[i dag kl.] LT",nextDay:"[i morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[i går kl.] LT",lastWeek:"[forrige] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinal:"%d.",week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){var b={1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"},c={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"};return a.defineLocale("ne",{months:"जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर".split("_"),monthsShort:"जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.".split("_"),weekdays:"आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार".split("_"),weekdaysShort:"आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.".split("_"),weekdaysMin:"आइ._सो._मङ्_बु._बि._शु._श.".split("_"),longDateFormat:{LT:"Aको h:mm बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, LT",LLLL:"dddd, D MMMM YYYY, LT"},preparse:function(a){return a.replace(/[१२३४५६७८९०]/g,function(a){return c[a]})},postformat:function(a){return a.replace(/\d/g,function(a){return b[a]})},meridiem:function(a){return 3>a?"राती":10>a?"बिहान":15>a?"दिउँसो":18>a?"बेलुका":20>a?"साँझ":"राती"},calendar:{sameDay:"[आज] LT",nextDay:"[भोली] LT",nextWeek:"[आउँदो] dddd[,] LT",lastDay:"[हिजो] LT",lastWeek:"[गएको] dddd[,] LT",sameElse:"L"},relativeTime:{future:"%sमा",past:"%s अगाडी",s:"केही समय",m:"एक मिनेट",mm:"%d मिनेट",h:"एक घण्टा",hh:"%d घण्टा",d:"एक दिन",dd:"%d दिन",M:"एक महिना",MM:"%d महिना",y:"एक बर्ष",yy:"%d बर्ष"},week:{dow:1,doy:7}})}),function(a){a(sb)}(function(a){var b="jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"),c="jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_");return a.defineLocale("nl",{months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:function(a,d){return/-MMM-/.test(d)?c[a.month()]:b[a.month()]},weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[vandaag om] LT",nextDay:"[morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinal:function(a){return a+(1===a||8===a||a>=20?"ste":"de")},week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){return a.defineLocale("nn",{months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"),weekdaysShort:"sun_mån_tys_ons_tor_fre_lau".split("_"),weekdaysMin:"su_må_ty_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[I dag klokka] LT",nextDay:"[I morgon klokka] LT",nextWeek:"dddd [klokka] LT",lastDay:"[I går klokka] LT",lastWeek:"[Føregåande] dddd [klokka] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s sidan",s:"nokre sekund",m:"eit minutt",mm:"%d minutt",h:"ein time",hh:"%d timar",d:"ein dag",ddLine truncated
},sameElse:"LL"},ordinal:function(a,b){switch(b){case"d":case"D":case"DDD":return a+"日";case"M":return a+"月";case"w":case"W":return a+"周";default:return a}},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1分钟",mm:"%d分钟",h:"1小时",hh:"%d小时",d:"1天",dd:"%d天",M:"1个月",MM:"%d个月",y:"1年",yy:"%d年"},week:{dow:1,doy:4}})}),function(a){a(sb)}(function(a){return a.defineLocale("zh-tw",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT",l:"YYYY年MMMD日",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日LT",llll:"YYYY年MMMD日ddddLT"},meridiem:function(a,b){var c=100*a+b;return 900>c?"早上":1130>c?"上午":1230>c?"中午":1800>c?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},ordinal:function(a,b){switch(b){case"d":case"D":case"DDD":return a+"日";case"M":return a+"月";case"w":case"W":return a+"週";default:return a}},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"}})}),sb.locale("en"),Ib?module.exports=sb:"function"==typeof define&&define.amd?(define("moment",function(a,b,c){return c.config&&c.config()&&c.config().noGlobal===!0&&(wb.moment=tb),sb}),rb(!0)):rb()}).call(this);
-6
View File
@@ -1,6 +0,0 @@
//! moment.js
//! version : 2.4.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
(function(a){function b(a,b){return function(c){return i(a.call(this,c),b)}}function c(a,b){return function(c){return this.lang().ordinal(a.call(this,c),b)}}function d(){}function e(a){u(a),g(this,a)}function f(a){var b=o(a),c=b.year||0,d=b.month||0,e=b.week||0,f=b.day||0,g=b.hour||0,h=b.minute||0,i=b.second||0,j=b.millisecond||0;this._input=a,this._milliseconds=+j+1e3*i+6e4*h+36e5*g,this._days=+f+7*e,this._months=+d+12*c,this._data={},this._bubble()}function g(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return b.hasOwnProperty("toString")&&(a.toString=b.toString),b.hasOwnProperty("valueOf")&&(a.valueOf=b.valueOf),a}function h(a){return 0>a?Math.ceil(a):Math.floor(a)}function i(a,b){for(var c=a+"";c.length<b;)c="0"+c;return c}function j(a,b,c,d){var e,f,g=b._milliseconds,h=b._days,i=b._months;g&&a._d.setTime(+a._d+g*c),(h||i)&&(e=a.minute(),f=a.hour()),h&&a.date(a.date()+h*c),i&&a.month(a.month()+i*c),g&&!d&&bb.updateOffset(a),(h||i)&&(a.minute(e),a.hour(f))}function k(a){return"[object Array]"===Object.prototype.toString.call(a)}function l(a){return"[object Date]"===Object.prototype.toString.call(a)||a instanceof Date}function m(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&q(a[d])!==q(b[d]))&&g++;return g+f}function n(a){if(a){var b=a.toLowerCase().replace(/(.)s$/,"$1");a=Kb[a]||Lb[b]||b}return a}function o(a){var b,c,d={};for(c in a)a.hasOwnProperty(c)&&(b=n(c),b&&(d[b]=a[c]));return d}function p(b){var c,d;if(0===b.indexOf("week"))c=7,d="day";else{if(0!==b.indexOf("month"))return;c=12,d="month"}bb[b]=function(e,f){var g,h,i=bb.fn._lang[b],j=[];if("number"==typeof e&&(f=e,e=a),h=function(a){var b=bb().utc().set(d,a);return i.call(bb.fn._lang,b,e||"")},null!=f)return h(f);for(g=0;c>g;g++)j.push(h(g));return j}}function q(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function r(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function s(a){return t(a)?366:365}function t(a){return 0===a%4&&0!==a%100||0===a%400}function u(a){var b;a._a&&-2===a._pf.overflow&&(b=a._a[gb]<0||a._a[gb]>11?gb:a._a[hb]<1||a._a[hb]>r(a._a[fb],a._a[gb])?hb:a._a[ib]<0||a._a[ib]>23?ib:a._a[jb]<0||a._a[jb]>59?jb:a._a[kb]<0||a._a[kb]>59?kb:a._a[lb]<0||a._a[lb]>999?lb:-1,a._pf._overflowDayOfYear&&(fb>b||b>hb)&&(b=hb),a._pf.overflow=b)}function v(a){a._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function w(a){return null==a._isValid&&(a._isValid=!isNaN(a._d.getTime())&&a._pf.overflow<0&&!a._pf.empty&&!a._pf.invalidMonth&&!a._pf.nullInput&&!a._pf.invalidFormat&&!a._pf.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===a._pf.charsLeftOver&&0===a._pf.unusedTokens.length)),a._isValid}function x(a){return a?a.toLowerCase().replace("_","-"):a}function y(a,b){return b.abbr=a,mb[a]||(mb[a]=new d),mb[a].set(b),mb[a]}function z(a){delete mb[a]}function A(a){var b,c,d,e,f=0,g=function(a){if(!mb[a]&&nb)try{require("./lang/"+a)}catch(b){}return mb[a]};if(!a)return bb.fn._lang;if(!k(a)){if(c=g(a))return c;a=[a]}for(;f<a.length;){for(e=x(a[f]).split("-"),b=e.length,d=x(a[f+1]),d=d?d.split("-"):null;b>0;){if(c=g(e.slice(0,b).join("-")))return c;if(d&&d.length>=b&&m(e,d,!0)>=b-1)break;b--}f++}return bb.fn._lang}function B(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function C(a){var b,c,d=a.match(rb);for(b=0,c=d.length;c>b;b++)d[b]=Pb[d[b]]?Pb[d[b]]:B(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function D(a,b){return a.isValid()?(b=E(b,a.lang()),Mb[b]||(Mb[b]=C(b)),Mb[b](a)):a.lang().invalidDate()}function E(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(sb.lastIndex=0;d>=0&&sb.test(a);)a=a.replace(sb,c),sb.lastIndex=0,d-=1;return a}function F(a,b){var c;switch(a){case"DDDD":return vb;case"YYYY":case"GGGG":case"gggg":return wb;case"YYYYY":case"GGGGG":case"ggggg":return xb;case"S":case"SS":case"SSS":case"DDD":return ub;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return zb;case"a":case"A":return A(b._l)._meridiemParse;case"X":return Cb;case"Z":case"ZZ":return Ab;case"T":return Bb;case"SSSS":return yb;case"MM":case"DD":case"YY":case"GG":case"gg":case"HH":case"hh":case"mm":case"ss":case"M":case"D":case"d":case"H":case"h":case"m":case"s":case"w":case"ww":case"W":case"WW":case"e":case"E":return tb;default:return c=new RegExp(N(M(a.replace("\\","")),"i"))}}function G(a){var b=(Ab.exec(a)||[])[0],c=(b+"").match(Hb)||["-",0,0],d=+(60*c[1])+q(c[2]);return"+"===c[0]?-d:d}function H(a,b,c){var d,e=c._a;switch(a){case"M":case"MM":null!=b&&(e[gb]=q(b)-1);break;case"MMM":case"MMMM":d=A(c._l).monthsParse(b),null!=d?e[gb]=d:c._pf.invalidMonth=b;break;case"D":case"DD":null!=b&&(e[hb]=q(b));break;case"DDD":case"DDDD":null!=b&&(c._dayOfYear=q(b));break;case"YY":e[fb]=q(b)+(q(b)>68?1900:2e3);break;case"YYYY":case"YYYYY":e[fb]=q(b);break;case"a"Line truncated
+6 -7
View File
@@ -6,7 +6,7 @@
// Body
body {
padding-top: 60px;
//padding-top: 60px;
}
// Navigation bar
@@ -113,9 +113,11 @@ body {
}
}
/** OctoPrint application tabs */
.octoprint-container {
margin-top: 20px;
/** OctoPrint application tabs */
.tab-content {
padding: 9px 15px;
border-left: 1px solid #DDD;
@@ -143,12 +145,9 @@ body {
border-bottom: 1px solid #E5E5E5;
font-weight: normal;
}
}
/** Accordions */
/** Accordions */
.octoprint-container {
.accordion-heading {
.accordion-heading-button {
float: right;
+21 -25
View File
@@ -3,14 +3,10 @@
<div id="offline_overlay_wrapper">
<div class="container">
<div class="hero-unit">
<h1>Server is offline</h1>
<p id="offline_overlay_message">
The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect
automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect
anytime using the button below.
</p>
<h1>{{ _('Server is offline') }}</h1>
<p id="offline_overlay_message"></p>
<p>
<a class="btn btn-primary btn-large" id="offline_overlay_reconnect">Attempt to reconnect</a>
<a class="btn btn-primary btn-large" id="offline_overlay_reconnect">{{ _('Attempt to reconnect') }}</a>
</p>
</div>
</div>
@@ -21,12 +17,12 @@
<div id="drop_overlay_background"></div>
<div id="drop_overlay_wrapper">
{% if enableSdSupport %}
<div class="dropzone" id="drop_locally"><span class="centered"><i class="icon-upload-alt"></i><br>Upload locally</span></div>
<div class="dropzone" id="drop_locally"><span class="centered"><i class="icon-upload-alt"></i><br>{{ _('Upload locally') }}</span></div>
<div class="dropzone_background" id="drop_locally_background"></div>
<div class="dropzone" id="drop_sd"><span class="centered"><i class="icon-upload-alt"></i><br>Upload to SD<br><small data-bind="visible: !isSdReady()">(SD not initialized)</small></span></div>
<div class="dropzone" id="drop_sd"><span class="centered"><i class="icon-upload-alt"></i><br>{{ _('Upload to SD') }}<br><small data-bind="visible: !isSdReady()">({{ _('SD not initialized') }})</small></span></div>
<div class="dropzone_background" id="drop_sd_background"></div>
{% else %}
<div class="dropzone" id="drop"><span class="centered"><i class="icon-upload-alt"></i><br>Upload</span></div>
<div class="dropzone" id="drop"><span class="centered"><i class="icon-upload-alt"></i><br>{{ _('Upload') }}</span></div>
<div class="dropzone_background" id="drop_background"></div>
{% endif %}
</div>
@@ -35,24 +31,24 @@
<div id="confirmation_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>Are you sure?</h3>
<h3>{{ _('Are you sure?') }}</h3>
</div>
<div class="modal-body">
<p class="confirmation_dialog_message"></p>
<p>Are you sure you want to proceed?</p>
<p>{{ _('Are you sure you want to proceed?') }}</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</a>
<a href="#" class="btn btn-danger confirmation_dialog_acknowledge">Proceed</a>
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-danger confirmation_dialog_acknowledge">{{ _('Proceed') }}</a>
</div>
</div>
<div id="first_run_dialog" class="modal hide fade" data-backdrop="static" data-keyboard="false">
<div class="modal-header">
<h3><i class="icon-warning-sign"></i> Configure Access Control</h3>
<h3><i class="icon-warning-sign"></i> {{ _('Configure Access Control') }}</h3>
</div>
<div class="modal-body">
<p>
{% trans %}<p>
<strong>Please read the following, it is very important for your printer's health!</strong>
</p>
<p>
@@ -65,39 +61,39 @@
It looks like you haven't configured access control yet. Please <strong>set up an username and password</strong> for the
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
on "Keep Access Control Enabled":
</p>
</p>{% endtrans %}
<form class="form-horizontal">
<div class="control-group" data-bind="css: {success: validUsername()}">
<label class="control-label" for="first_run_username">Username</label>
<label class="control-label" for="first_run_username">{{ _('Username') }}</label>
<div class="controls">
<input type="text" class="input-medium" data-bind="value: username, valueUpdate: 'afterkeydown'">
</div>
</div>
<div class="control-group" data-bind="css: {success: validPassword()}">
<label class="control-label" for="first_run_username">Password</label>
<label class="control-label" for="first_run_username">{{ _('Password') }}</label>
<div class="controls">
<input type="password" class="input-medium" data-bind="value: password, valueUpdate: 'afterkeydown'">
</div>
</div>
<div class="control-group" data-bind="css: {error: passwordMismatch(), success: validPassword() && !passwordMismatch()}">
<label class="control-label" for="first_run_username">Confirm Password</label>
<label class="control-label" for="first_run_username">{{ _('Confirm Password') }}</label>
<div class="controls">
<input type="password" class="input-medium" data-bind="value: confirmedPassword, valueUpdate: 'afterkeydown'">
<span class="help-inline" data-bind="visible: passwordMismatch()">Passwords don't match</span>
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
</div>
</div>
</form>
<p>
{% trans %}<p>
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
need Access Control for other reasons, you may alternatively disable Access Control. You should only
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
</p>
<p>
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
</p>
</p>{% endtrans %}
</div>
<div class="modal-footer">
<a href="#" class="btn btn-danger" data-bind="click: disableAccessControl">Disable Access Control</a>
<a href="#" class="btn btn-primary" data-bind="click: keepAccessControl, enable: validData(), css: {disabled: !validData()}">Keep Access Control Enabled</a>
<a href="#" class="btn btn-danger" data-bind="click: disableAccessControl">{{ _('Disable Access Control') }}</a>
<a href="#" class="btn btn-primary" data-bind="click: keepAccessControl, enable: validData(), css: {disabled: !validData()}">{{ _('Keep Access Control Enabled') }}</a>
</div>
</div>
+113 -106
View File
@@ -37,15 +37,16 @@
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + "/sockjs";
var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + BASEURL + "sockjs";
var SOCKJS_DEBUG = {% if debug -%} true; {% else %} false; {%- endif %}
var UI_API_KEY = "{{ uiApiKey }}";
var VERSION = "{{ version }}";
var LOCALE = "{{ g.locale }}";
</script>
</head>
<body>
<div id="navbar" class="navbar navbar-fixed-top">
<div id="navbar" class="navbar navbar-static-top">
<div class="navbar-inner" data-bind="css: appearance.color">
<div class="container">
<a class="brand" href="#"> <span data-bind="text: appearance.brand">OctoPrint</span></a>
@@ -53,13 +54,13 @@
<ul class="nav pull-right">
<li style="display: none;" data-bind="visible: loginState.isAdmin">
<a id="navbar_show_settings" class="pull-right" href="#settings_dialog">
<i class="icon-wrench"></i> Settings
<i class="icon-wrench"></i> {{ _('Settings') }}
</a>
</li>
{% if enableSystemMenu %}
<li class="dropdown" style="display: none" data-bind="visible: loginState.isAdmin">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-off"></i> System
<i class="icon-off"></i> {{ _('System') }}
<b class="caret"></b>
</a>
<ul class="dropdown-menu" data-bind="foreach: systemActions">
@@ -70,22 +71,22 @@
{% if enableAccessControl %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-user"></i> <span data-bind="text: loginState.userMenuText">Login</span>
<i class="icon-user"></i> <span data-bind="text: loginState.userMenuText">{{ _('Login') }}</span>
<b class="caret"></b>
</a>
<div id="login_dropdown_loggedout" style="padding: 15px" class="dropdown-menu" data-bind="css: {hide: loginState.loggedIn(), 'dropdown-menu': !loginState.loggedIn()}">
<label for="login_user">Username</label>
<input type="text" id="login_user" placeholder="Username">
<label for="login_pass">Password</label>
<input type="password" id="login_pass" placeholder="Password">
<label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" placeholder="{{ _('Username') }}">
<label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" placeholder="{{ _('Password') }}">
<label class="checkbox">
<input type="checkbox" id="login_remember"> Remember me
<input type="checkbox" id="login_remember"> {{ _('Remember me') }}
</label>
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: loginState.login">Login</button>
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: loginState.login">{{ _('Login') }}</button>
</div>
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
<li><a href="#" id="change_password_button" data-bind="click: function() { users.showChangePasswordDialog(loginState.currentUser()); }">Change Password</a></li>
<li><a href="#" id="logout_button" data-bind="click: loginState.logout">Logout</a></li>
<li><a href="#" id="change_password_button" data-bind="click: function() { users.showChangePasswordDialog(loginState.currentUser()); }">{{ _('Change Password') }}</a></li>
<li><a href="#" id="logout_button" data-bind="click: loginState.logout">{{ _('Logout') }}</a></li>
</ul>
</li>
{% endif %}
@@ -99,73 +100,72 @@
<div class="accordion span4">
<div class="accordion-group" data-bind="visible: loginState.isUser" id="connection_accordion">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" href="#connection"><i class="icon-signal"></i> Connection</a>
<a class="accordion-toggle" data-toggle="collapse" href="#connection"><i class="icon-signal"></i> {{ _('Connection') }}</a>
</div>
<div class="accordion-body collapse in" id="connection">
<div class="accordion-inner">
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">Serial Port</label>
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Serial Port') }}</label>
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">Baudrate</label>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"></select>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"> Save connection settings
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"> {{ _('Save connection settings') }}
</label>
<label class="checkbox">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"> Auto-connect on server startup
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed() && loginState.isUser()"> {{ _('Auto-connect on server startup') }}
</label>
<button class="btn btn-block" id="printer_connect" data-bind="click: connect, text: buttonText(), enable: loginState.isUser()">Connect</button>
<button class="btn btn-block" id="printer_connect" data-bind="click: connect, text: buttonText(), enable: loginState.isUser()">{{ _('Connect') }}</button>
</div>
</div>
</div>
<div class="accordion-group" id="state_accordion">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" href="#state"><i class="icon-info-sign"></i> State</a>
<a class="accordion-toggle" data-toggle="collapse" href="#state"><i class="icon-info-sign"></i> {{ _('State') }}</a>
</div>
<div class="accordion-body collapse in" id="state">
<div class="accordion-inner">
Machine State: <strong data-bind="text: stateString"></strong><br>
File: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
{{ _('Machine State') }}: <strong data-bind="text: stateString"></strong><br>
{{ _('File') }}: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
{{ _('Timelapse') }}: <strong data-bind="text: timelapseString"></strong><br>
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): '"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<span data-bind="text: 'Filament (' + name() + '): '"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<!-- /ko -->
Estimated Print Time: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
Timelapse: <strong data-bind="text: timelapseString"></strong><br>
Height: <strong data-bind="text: heightString"></strong><br>
Print Time: <strong data-bind="text: printTimeString"></strong><br>
Print Time Left: <strong data-bind="text: printTimeLeftString"></strong><br>
Printed: <strong data-bind="text: byteString"></strong><br>
{{ _('Approx. Total Print Time') }}: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
{{ _('Print Time') }}: <strong data-bind="text: printTimeString"></strong><br>
{{ _('Print Time Left') }}: <strong data-bind="text: printTimeLeftString"></strong><br>
{{ _('Printed') }}: <strong data-bind="text: byteString"></strong><br>
<div class="progress">
<div class="bar" id="job_progressBar" data-bind="style: { width: progressString() + '%' }"></div>
</div>
<div class="row-fluid print-control" style="display: none;" data-bind="visible: loginState.isUser">
<button class="btn btn-primary span4" data-bind="click: print, enable: isOperational() && isReady() && !isPrinting() && loginState.isUser(), css: {'btn-danger': isPaused()}" id="job_print"><i class="icon-white" data-bind="css: {'icon-print': !isPaused(), 'icon-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? 'Restart' : 'Print')">Print</span></button>
<button class="btn span4" id="job_pause" data-bind="click: pause, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser(), css: {active: isPaused()}"><i class="icon-pause"></i> <span>Pause</span></button>
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser()"><i class="icon-stop"></i> Cancel</button>
<button class="btn btn-primary span4" data-bind="click: print, enable: isOperational() && isReady() && !isPrinting() && loginState.isUser(), css: {'btn-danger': isPaused()}" id="job_print"><i class="icon-white" data-bind="css: {'icon-print': !isPaused(), 'icon-undo': isPaused()}"></i> <span data-bind="text: (isPaused() ? '{{ _('Restart') }}' : '{{ _('Print') }}')">{{ _('Print') }}</span></button>
<button class="btn span4" id="job_pause" data-bind="click: pause, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser(), css: {active: isPaused()}"><i class="icon-pause"></i> <span>{{ _('Pause') }}</span></button>
<button class="btn span4" id="job_cancel" data-bind="click: cancel, enable: isOperational() && (isPrinting() || isPaused()) && loginState.isUser()"><i class="icon-stop"></i> {{ _('Cancel') }}</button>
</div>
</div>
</div>
</div>
<div class="accordion-group" id="files_accordion">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" href="#files"><i class="icon-list"></i> Files</a>
<a class="accordion-toggle" data-toggle="collapse" href="#files"><i class="icon-list"></i> {{ _('Files') }}</a>
<div class="settings-trigger accordion-heading-button btn-group">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="icon-wrench"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('name'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> Sort by name (ascending)</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('upload'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'upload' ? 'visible' : 'hidden'}"></i> Sort by upload date (descending)</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('size'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> Sort by file size (descending)</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('name'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('upload'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'upload' ? 'visible' : 'hidden'}"></i> {{ _('Sort by upload date') }} ({{ _('descending') }})</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('size'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
{% if enableSdSupport %}
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('local'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'local') ? 'visible' : 'hidden'}"></i> Only show files stored locally</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('sd'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'sd') ? 'visible' : 'hidden'}"></i> Only show files stored on SD</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('local'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'local') ? 'visible' : 'hidden'}"></i> {{ _('Only show files stored locally') }}</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('sd'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'sd') ? 'visible' : 'hidden'}"></i> {{ _('Only show files stored on SD') }}</a></li>
{% endif %}
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('printed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'printed') ? 'visible' : 'hidden'}"></i> Hide successfully printed files</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('printed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'printed') ? 'visible' : 'hidden'}"></i> {{ _('Hide successfully printed files') }}</a></li>
</ul>
</div>
@@ -175,9 +175,9 @@
<span class="icon-sd-black-14"></span>
</a>
<ul class="dropdown-menu">
<li data-bind="visible: !isSdReady()"><a href="#" data-bind="click: function() { $root.initSdCard(); }"><i class="icon-flag"></i> Initialize SD card</a></li>
<li data-bind="visible: isSdReady()"><a href="#" data-bind="click: function() { $root.refreshSdFiles(); }"><i class="icon-refresh"></i> Refresh SD files</a></li>
<li data-bind="visible: isSdReady()"><a href="#" data-bind="click: function() { $root.releaseSdCard(); }"><i class="icon-eject"></i> Release SD card</a></li>
<li data-bind="visible: !isSdReady()"><a href="#" data-bind="click: function() { $root.initSdCard(); }"><i class="icon-flag"></i> {{ _('Initialize SD card') }}</a></li>
<li data-bind="visible: isSdReady()"><a href="#" data-bind="click: function() { $root.refreshSdFiles(); }"><i class="icon-refresh"></i> {{ _('Refresh SD files') }}</a></li>
<li data-bind="visible: isSdReady()"><a href="#" data-bind="click: function() { $root.releaseSdCard(); }"><i class="icon-eject"></i> {{ _('Release SD card') }}</a></li>
</ul>
</div>
{% endif %}
@@ -185,43 +185,43 @@
<div class="accordion-body collapse in overflow_visible" id="files">
<div class="accordion-inner">
<form class="form-search">
<input type="text" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="Search...">
<input type="text" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
</form>
<div class="gcode_files" data-bind="slimScrolledForeach: listHelper.paginatedItems">
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }">
<div class="title" data-bind="css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: name"></div>
<div class="uploaded">Uploaded: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">Size: <span data-bind="text: formatSize(size)"></span></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="Download"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data.name); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="Remove"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="Load"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="Load and Print"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data.name); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
</div>
</div>
</div>
<div class="muted text-right">
<small>Free: <span data-bind="text: freeSpaceString"></span></small>
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span></small>
</div>
<div style="display: none;" data-bind="visible: loginState.isUser">
<div class="row-fluid upload-buttons">
{% if enableSdSupport %}
<span class="btn btn-primary fileinput-button span6" data-bind="css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px">
<i class="icon-upload-alt icon-white"></i>
<span>Upload</span>
<span>{{ _('Upload') }}</span>
<input id="gcode_upload" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
</span>
<span class="btn btn-primary fileinput-button span6" data-bind="css: {disabled: !$root.loginState.isUser() || !$root.isSdReady()}" style="margin-bottom: 10px">
<i class="icon-upload-alt icon-white"></i>
<span>Upload to SD</span>
<span>{{ _('Upload to SD') }}</span>
<input id="gcode_upload_sd" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser() && isSdReady()">
</span>
{% else %}
<span class="btn btn-primary fileinput-button span12" data-bind="css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px">
<i class="icon-upload-alt icon-white"></i>
<span>Upload</span>
<span>{{ _('Upload') }}</span>
<input id="gcode_upload" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
</span>
{% endif %}
@@ -230,7 +230,7 @@
<div class="bar" style="width: 0%"></div>
</div>
<div>
<small>Hint: You can also drag and drop files on this page to upload them.</small>
<small>{{ _('Hint: You can also drag and drop files on this page to upload them.') }}</small>
</div>
</div>
</div>
@@ -240,11 +240,11 @@
<div class="span8 tabbable">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a href="#temp" data-toggle="tab">Temperature</a></li>
<li><a href="#control" data-toggle="tab">Control</a></li>
{% if enableGCodeVisualizer %}<li><a href="#gcode" data-toggle="tab">GCode Viewer</a></li>{% endif %}
<li><a href="#term" data-toggle="tab">Terminal</a></li>
{% if enableTimelapse %}<li><a href="#timelapse" data-toggle="tab">Timelapse</a></li>{% endif %}
<li class="active"><a href="#temp" data-toggle="tab">{{ _('Temperature') }}</a></li>
<li><a href="#control" data-toggle="tab">{{ _('Control') }}</a></li>
{% if enableGCodeVisualizer %}<li><a href="#gcode" data-toggle="tab">{{ _('GCode Viewer') }}</a></li>{% endif %}
<li><a href="#term" data-toggle="tab">{{ _('Terminal') }}</a></li>
{% if enableTimelapse %}<li><a href="#timelapse" data-toggle="tab">{{ _('Timelapse') }}</a></li>{% endif %}
</ul>
<div class="tab-content">
@@ -259,9 +259,9 @@
<table class="table table-bordered table-hover" style="table-layout: fixed; width: 100%; margin-top: 20px">
<tr>
<th style="width: 18%"></th>
<th style="width: 12%; text-align: right">Actual</th>
<th style="width: 35%">Target</th>
<th style="width: 35%">Offset</th>
<th style="width: 12%; text-align: right">{{ _('Actual') }}</th>
<th style="width: 35%">{{ _('Target') }}</th>
<th style="width: 35%">{{ _('Offset') }}</th>
</tr>
<!-- ko foreach: tools -->
<tr data-bind="template: { name: 'temprow-template' }"></tr>
@@ -277,7 +277,7 @@
<input type="text" class="input-mini text-right tempInput" data-bind="attr: {placeholder: cleanTemperature(target()) }, value: newTarget, enable: $root.isOperational() && $root.loginState.isUser(), event: { keyup: function(d, e) {$root.handleEnter(e, 'target', $data);} }">
<span class="add-on">&deg;C</span>
<div class="btn-group">
<button type="submit" data-bind="click: $parent.setTarget, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">Set</button>
<button type="submit" data-bind="click: $parent.setTarget, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">{{ _('Set') }}</button>
<button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.isUser()">
<span class="caret"></span>
</button>
@@ -289,7 +289,7 @@
<!-- /ko -->
<li class="divider"></li>
<li>
<a href="#" data-bind="click: $root.setTargetToZero">Off</a>
<a href="#" data-bind="click: $root.setTargetToZero">{{ _('Off') }}</a>
</li>
</ul>
</div>
@@ -299,7 +299,7 @@
<div class="input-append">
<input type="number" min="-50" max="50" class="input-mini text-right tempInput" data-bind="attr: {placeholder: offset}, value: newOffset, enable: $root.isOperational() && $root.loginState.isUser(), event: { keyup: function(d, e) {$root.handleEnter(e, 'offset', $data);} }">
<span class="add-on">&deg;C</span>
<button type="submit" data-bind="click: $root.setOffset, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">Set</button>
<button type="submit" data-bind="click: $root.setOffset, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">{{ _('Set') }}</button>
</div>
</td>
</script>
@@ -357,28 +357,28 @@
<div>
<div class="btn-group control-box">
<button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: isOperational() && !isPrinting() && !isPaused() && loginState.isUser()">
Select Tool...
{{ _('Select Tool...') }}
<span class="caret"></span>
</button>
<ul class="dropdown-menu" data-bind="foreach: tools">
<li><a href="#" data-bind="click: $root.sendSelectToolCommand, text: 'Select ' + name(), enable: $root.isOperational() && !$root.isPrinting() && !$root.isPaused() && $root.loginState.isUser()"></a></li>
<li><a href="#" data-bind="click: $root.sendSelectToolCommand, text: name(), enable: $root.isOperational() && !$root.isPrinting() && !$root.isPaused() && $root.loginState.isUser()"></a></li>
</ul>
</div>
<div class="input-append control-box">
<input type="text" class="input-mini text-right" data-bind="value: extrusionAmount, enable: isOperational() && !isPrinting() && loginState.isUser(), attr: {placeholder: 5}">
<input type="text" class="input-mini text-right" data-bind="value: extrusionAmount, enable: isOperational() && !isPrinting() && loginState.isUser(), attr: {placeholder: settings.printer_defaultExtrusionLength}">
<span class="add-on">mm</span>
</div>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendExtrudeCommand() }">Extrude</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendRetractCommand() }">Retract</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendExtrudeCommand() }">{{ _('Extrude') }}</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendRetractCommand() }">{{ _('Retract') }}</button>
</div>
</div>
<!-- General control panel -->
<div class="jog-panel" style="display: none;" data-bind="visible: loginState.isUser">
<h1>General</h1>
<h1>{{ _('General') }}</h1>
<div>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M18'}) }">Motors off</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M106'}) }">Fans on</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M106 S0'}) }">Fans off</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M18'}) }">{{ _('Motors off') }}</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M106'}) }">{{ _('Fans on') }}</button>
<button class="btn btn-block control-box" data-bind="enable: isOperational() && loginState.isUser(), click: function() { $root.sendCustomCommand({type:'command',command:'M106 S0'}) }">{{ _('Fans off') }}</button>
</div>
</div>
@@ -442,38 +442,38 @@
<p>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_syncProgress">Sync with job progress
<input type="checkbox" data-bind="checked: renderer_syncProgress">{{ _('Sync with job progress') }}
</label>
</p>
<p>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_centerViewport">Center viewport on model
<input type="checkbox" data-bind="checked: renderer_centerViewport">{{ _('Center viewport on model') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_zoomOnModel">Zoom in on model
<input type="checkbox" data-bind="checked: renderer_zoomOnModel">{{ _('Zoom in on model') }}
</label>
</p>
<p>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showMoves">Show moves
<input type="checkbox" data-bind="checked: renderer_showMoves">{{ _('Show moves') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showRetracts">Show retracts
<input type="checkbox" data-bind="checked: renderer_showRetracts">{{ _('Show retracts') }}
</label>
</p>
<p>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showPrevious">Also show previous layer
<input type="checkbox" data-bind="checked: renderer_showPrevious">{{ _('Also show previous layer') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showNext">Also show next layer
<input type="checkbox" data-bind="checked: renderer_showNext">{{ _('Also show next layer') }}
</label>
</p>
<p>
<button class="btn btn-block" data-bind="click: reload, enable: enableReload">Reload</button>
<button class="btn btn-block" data-bind="click: reload, enable: enableReload">{{ _('Reload') }}</button>
</p>
</div>
</div>
@@ -500,7 +500,7 @@
<div class="tab-pane" id="term">
<pre id="terminal-output" class="pre-scrollable"></pre>
<label class="checkbox">
<input type="checkbox" id="terminal-autoscroll" data-bind="checked: autoscrollEnabled"> Autoscroll
<input type="checkbox" id="terminal-autoscroll" data-bind="checked: autoscrollEnabled"> {{ _('Autoscroll') }}
</label>
<div data-bind="foreach: filters">
<label class="checkbox">
@@ -510,57 +510,57 @@
<div class="input-append" style="display: none;" data-bind="visible: loginState.isUser">
<input type="text" id="terminal-command" data-bind="value: command, event: { keyup: function(d,e) { return handleKeyUp(e); }, keydown: function(d,e) { return handleKeyDown(e); } }, enable: isOperational() && loginState.isUser()">
<button class="btn" type="button" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">Send</button>
<button class="btn" type="button" id="terminal-send" data-bind="click: sendCommand, enable: isOperational() && loginState.isUser()">{{ _('Send') }}</button>
</div>
</div>
{% if enableTimelapse %}
<div class="tab-pane" id="timelapse">
<div style="display: none;" data-bind="visible: loginState.isUser">
<h1>Timelapse Configuration</h1>
<h1>{{ _('Timelapse Configuration') }}</h1>
<label for="webcam_timelapse_mode">Timelapse Mode</label>
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
<option value="off">Off</option>
<option value="zchange">On Z Change</option>
<option value="timed">Timed</option>
<option value="off">{{ _('Off') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
<option value="timed">{{ _('Timed') }}</option>
</select>
<label for="webcam_timelapse_postRoll">Timelapse post roll (in rendered seconds)</label>
<label for="webcam_timelapse_postRoll">{{ _('Timelapse post roll (in rendered seconds)') }}</label>
<div class="input-append">
<input type="text" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<span class="add-on">sec</span>
<span class="add-on">{{ _('sec') }}</span>
</div>
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
<label for="webcam_timelapse_interval">Interval</label>
<label for="webcam_timelapse_interval">{{ _('Interval') }}</label>
<div class="input-append">
<input type="text" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()">
<span class="add-on">sec</span>
<span class="add-on">{{ _('sec') }}</span>
</div>
</div>
<div data-bind="visible: loginState.isAdmin">
<label class="checkbox">
<input type="checkbox" data-bind="checked: persist"> Save as default
<input type="checkbox" data-bind="checked: persist"> {{ _('Save as default') }}
</label>
</div>
<div>
<button class="btn" data-bind="click: save, enable: saveButtonEnabled">Save config</button>
<button class="btn" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save config') }}</button>
</div>
</div>
<h1>Finished Timelapses</h1>
<h1>{{ _('Finished Timelapses') }}</h1>
<div class="pull-right">
<small>Sort by: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">Name (ascending)</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('creation'); }">Creation date (descending)</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">Size (descending)</a></small>
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('creation'); }">{{ _('Creation date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_files">
<thead>
<tr>
<th class="timelapse_files_name">Name</th>
<th class="timelapse_files_size">Size</th>
<th class="timelapse_files_action">Action</th>
<th class="timelapse_files_name">{{ _('Name') }}</th>
<th class="timelapse_files_size">{{ _('Size') }}</th>
<th class="timelapse_files_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
@@ -589,13 +589,13 @@
</div>
<div class="footer">
<ul class="pull-left muted">
<li><small>Version: <span class="version">{{ version }}</span></small></li>
<li><small>{{ _('Version') }}: <span class="version">{{ version }}</span></small></li>
</ul>
<ul class="pull-right">
<li><a href="http://octoprint.org"><i class="icon-home"></i> Homepage</a></li>
<li><a href="https://github.com/foosel/OctoPrint/"><i class="icon-download"></i> Sourcecode</a></li>
<li><a href="https://github.com/foosel/OctoPrint/wiki"><i class="icon-book"></i> Documentation</a></li>
<li><a href="https://github.com/foosel/OctoPrint/issues"><i class="icon-flag"></i> Bugs and Requests</a></li>
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/"><i class="icon-download"></i> {{ _('Sourcecode') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/wiki"><i class="icon-book"></i> {{ _('Documentation') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/issues"><i class="icon-flag"></i> {{ _('Bugs and Requests') }}</a></li>
</ul>
</div>
</div>
@@ -608,6 +608,7 @@
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/underscore-min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/underscore.string.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/knockout.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/babel.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/avltree.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/bootstrap/bootstrap.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/bootstrap/bootstrap-modalmanager.js') }}"></script>
@@ -621,7 +622,7 @@
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.fileupload.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/jquery/jquery.slimscroll.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/sockjs-0.3.4.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/moment.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/moment-with-locales.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/pusher.color.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/detectmobilebrowser.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/md5.min.js') }}"></script>
@@ -651,6 +652,12 @@
<script type="text/javascript" src="{{ url_for('static', filename='js/app/main.js') }}"></script>
<!-- /Include OctoPrint files -->
<!-- Include i18n language files -->
{% if g.locale != 'en' %}
<script type="text/javascript" src="{{ url_for('static', filename='js/i18n/%s.js' % g.locale) }}"></script>
{% endif %}
<!-- /Include i18n language files -->
<script type="text/javascript" src="{{ url_for('static', filename='gcodeviewer/js/ui.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='gcodeviewer/js/gCodeReader.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='gcodeviewer/js/renderer.js') }}"></script>
+120 -108
View File
@@ -1,39 +1,39 @@
<div id="settings_dialog" class="modal hide fade container" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="settings_dialog_label">OctoPrint Settings</h3>
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
</div>
<div class="modal-body">
<div class="tabbable">
<ul class="nav nav-list span4" id="settingsTabs">
<li class="nav-header">Printer</li>
<li class="active"><a href="#settings_serialConnection" data-toggle="tab">Serial Connection</a></li>
<li><a href="#settings_printerParameters" data-toggle="tab">Printer Parameters</a></li>
<li><a href="#settings_temperature" data-toggle="tab">Temperatures</a></li>
<li><a href="#settings_terminalFilters" data-toggle="tab">Terminal filters</a></li>
<li class="nav-header">Features</li>
<li><a href="#settings_features" data-toggle="tab">Features</a></li>
<li><a href="#settings_webcam" data-toggle="tab">Webcam</a></li>
<li><a href="#settings_cura" data-toggle="tab">Cura</a></li>
{% if enableAccessControl %}<li><a href="#settings_users" data-toggle="tab">Access Control</a></li>{% endif %}
<li><a href="#settings_api" data-toggle="tab">Api</a></li>
<li class="nav-header">{{ _('Printer') }}</li>
<li class="active"><a href="#settings_serialConnection" data-toggle="tab">{{ _('Serial Connection') }}</a></li>
<li><a href="#settings_printerParameters" data-toggle="tab">{{ _('Printer Parameters') }}</a></li>
<li><a href="#settings_temperature" data-toggle="tab">{{ _('Temperatures') }}</a></li>
<li><a href="#settings_terminalFilters" data-toggle="tab">{{ _('Terminal filters') }}</a></li>
<li class="nav-header">{{ _('Features') }}</li>
<li><a href="#settings_features" data-toggle="tab">{{ _('Features') }}</a></li>
<li><a href="#settings_webcam" data-toggle="tab">{{ _('Webcam') }}</a></li>
<li><a href="#settings_cura" data-toggle="tab">{{ _('Cura') }}</a></li>
{% if enableAccessControl %}<li><a href="#settings_users" data-toggle="tab">{{ _('Access Control') }}</a></li>{% endif %}
<li><a href="#settings_api" data-toggle="tab">{{ _('API') }}</a></li>
<li class="nav-header">OctoPrint</li>
<li><a href="#settings_folder" data-toggle="tab">Folders</a></li>
<li><a href="#settings_appearance" data-toggle="tab">Appearance</a></li>
<li><a href="#settings_logs" data-toggle="tab">Logs</a></li>
<li><a href="#settings_folder" data-toggle="tab">{{ _('Folders') }}</a></li>
<li><a href="#settings_appearance" data-toggle="tab">{{ _('Appearance') }}</a></li>
<li><a href="#settings_logs" data-toggle="tab">{{ _('Logs') }}</a></li>
</ul>
<div class="tab-content span8">
<div class="tab-pane active" id="settings_serialConnection">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-serialPort">Serial Port</label>
<label class="control-label" for="settings-serialPort">{{ _('Serial Port') }}</label>
<div class="controls">
<select id="settings-serialPort" data-bind="options: serial_portOptions, optionsCaption: 'AUTO', value: serial_port"></select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-baudrate">Baudrate</label>
<label class="control-label" for="settings-baudrate">{{ _('Baudrate') }}</label>
<div class="controls">
<select id="settings-baudrate" data-bind="options: serial_baudrateOptions, optionsCaption: 'AUTO', value: serial_baudrate"></select>
</div>
@@ -41,12 +41,12 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_autoconnect" id="settings-serialAutoconnect"> Auto-connect to printer on server start
<input type="checkbox" data-bind="checked: serial_autoconnect" id="settings-serialAutoconnect"> {{ _('Auto-connect to printer on server start') }}
</label>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialTimeoutCommunication">Communication timeout</label>
<label class="control-label" for="settings-serialTimeoutCommunication">{{ _('Communication timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutCommunication" id="settings-serialTimeoutCommunication">
@@ -55,7 +55,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-movementSpeedE">Temperature timeout</label>
<label class="control-label" for="settings-movementSpeedE">{{ _('Temperature timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
@@ -64,7 +64,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialTimeoutSdStatus">SD status timeout</label>
<label class="control-label" for="settings-serialTimeoutSdStatus">{{ _('SD status timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutSdStatus" id="settings-serialTimeoutSdStatus">
@@ -73,7 +73,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialTimeoutConnection">Connection timeout</label>
<label class="control-label" for="settings-serialTimeoutConnection">{{ _('Connection timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutConnection" id="settings-serialTimeoutConnection">
@@ -82,7 +82,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialTimeoutDetection">Autodetection timeout</label>
<label class="control-label" for="settings-serialTimeoutDetection">{{ _('Autodetection timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutDetection" id="settings-serialTimeoutDetection">
@@ -93,7 +93,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_log" id="settings-serialLog"> Log communication to serial.log (might negatively impact performance) <span class="label label-important">Warning</span>
<input type="checkbox" data-bind="checked: serial_log" id="settings-serialLog"> {{ _('Log communication to serial.log (might negatively impact performance)') }} <span class="label label-important">{{ _('Warning') }}</span>
</label>
</div>
</div>
@@ -102,39 +102,39 @@
<div class="tab-pane" id="settings_printerParameters">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">Axis</label>
<label class="control-label">{{ _('Axis') }}</label>
<div class="controls form-inline">
<label>X:</label>
<label>{{ _('X') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedX" id="settings-movementSpeedX">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_invertX" id="settings-printerInvertX"> Invert control
<input type="checkbox" data-bind="checked: printer_invertX" id="settings-printerInvertX"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>Y:</label>
<label>{{ _('Y') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedY" id="settings-movementSpeedY">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_invertY" id="settings-printerInvertY"> Invert control
<input type="checkbox" data-bind="checked: printer_invertY" id="settings-printerInvertY"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>Z:</label>
<label>{{ _('Z') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedZ" id="settings-movementSpeedZ">
<span class="add-on">mm/min</span>
</div>
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_invertZ" id="settings-printerInvertZ"> Invert control
<input type="checkbox" data-bind="checked: printer_invertZ" id="settings-printerInvertZ"> {{ _('Invert control') }}
</label>
</div>
<div class="controls form-inline">
<label>E:</label>
<label>{{ _('E') }}:</label>
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: printer_movementSpeedE" id="settings-movementSpeedE">
<span class="add-on">mm/min</span>
@@ -142,13 +142,19 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-numExtruders">Number of Extruders</label>
<label class="control-label" for="settings-defaultExtrusionLength">{{ _('Default extrusion length') }}</label>
<div class="controls">
<input type="number" class="input-mini text-right" min="1" data-bind="value: printer_defaultExtrusionLength" id="settings-defaultExtrusionLength">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-numExtruders">{{ _('Number of Extruders') }}</label>
<div class="controls">
<input type="number" class="input-mini text-right" min="1" max="5" data-bind="value: printer_numExtruders" id="settings-numExtruders">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-extruderOffsets">Extruder Offsets</label>
<label class="control-label" for="settings-extruderOffsets">{{ _('Extruder Offsets') }}</label>
<!-- ko foreach: ko_printer_extruderOffsets -->
<div class="controls form-inline">
<label>X:</label>
@@ -165,21 +171,21 @@
<!-- /ko -->
</div>
<div class="control-group">
<label class="control-label" for="settings-bedSize">Bed Size</label>
<label class="control-label" for="settings-bedSize">{{ _('Bed Size') }}</label>
<div class="controls form-inline" data-bind="ifnot: printer_bedCircular">
<label>X:</label>
<label>{{ _('X') }}:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printer_bedDimensionX" id="settings-bedX">
<span class="add-on">mm</span>
</div>
<label>Y:</label>
<label>{{ _('Y') }}:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printer_bedDimensionY" id="settings-bedY">
<span class="add-on">mm</span>
</div>
</div>
<div class="controls form-inline" data-bind="if: printer_bedCircular">
<label>Radius:</label>
<label>{{ _('Radius') }}:</label>
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printer_bedDimensionR" id="settings-bedR">
<span class="add-on">mm</span>
@@ -187,7 +193,7 @@
</div>
<div class="controls form-inline">
<label class="checkbox">
<input type="checkbox" data-bind="checked: printer_bedCircular" id="settings-bedCircular">Circular
<input type="checkbox" data-bind="checked: printer_bedCircular" id="settings-bedCircular"> {{ _('Circular') }}
</label>
</div>
</div>
@@ -196,25 +202,25 @@
<div class="tab-pane" id="settings_webcam">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-webcamStreamUrl">Stream URL</label>
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Stream URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: webcam_streamUrl" id="settings-webcamStreamUrl">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-webcamStreamUrl">Snapshot URL</label>
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Snapshot URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: webcam_snapshotUrl" id="settings-webcamSnapshotUrl">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-webcamStreamUrl">Path to FFMPEG</label>
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Path to FFMPEG') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: webcam_ffmpegPath" id="settings-webcamFfmpegPath">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-webcamBitrate">Timelapse bitrate</label>
<label class="control-label" for="settings-webcamBitrate">{{ _('Timelapse bitrate') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: webcam_bitrate" id="settings-webcamBitrate">
</div>
@@ -222,19 +228,19 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_watermark" id="settings-webcamWatermark"> Enable OctoPrint watermark in timelapse movies
<input type="checkbox" data-bind="checked: webcam_watermark" id="settings-webcamWatermark"> {{ _('Enable OctoPrint watermark in timelapse movies') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_flipH" id="settings-webcamFlipH"> Flip webcam horizontally
<input type="checkbox" data-bind="checked: webcam_flipH" id="settings-webcamFlipH"> {{ _('Flip webcam horizontally') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_flipV" id="settings-webcamFlipV"> Flip webcam vertically
<input type="checkbox" data-bind="checked: webcam_flipV" id="settings-webcamFlipV"> {{ _('Flip webcam vertically') }}
</label>
</div>
</div>
@@ -245,56 +251,56 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_temperatureGraph" id="settings-featureTemperatureGraph"> Enable Temperature Graph
<input type="checkbox" data-bind="checked: feature_temperatureGraph" id="settings-featureTemperatureGraph"> {{ _('Enable Temperature Graph') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_gcodeViewer" id="settings-featureGcodeViewer"> Enable GCode Visualizer
<input type="checkbox" data-bind="checked: feature_gcodeViewer" id="settings-featureGcodeViewer"> {{ _('Enable GCode Visualizer') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdSupport" id="settings-featureSdSupport"> Enable SD support
<input type="checkbox" data-bind="checked: feature_sdSupport" id="settings-featureSdSupport"> {{ _('Enable SD support') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> Always assume SD card is present <span class="label">Repetier</span>
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_waitForStart" id="settings-featureWaitForStart"> Wait for <code>start</code> on connect
<input type="checkbox" data-bind="checked: feature_waitForStart" id="settings-featureWaitForStart"> {{ _('Wait for <code>start</code> on connect') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> Send a checksum with <strong>every</strong> command <span class="label">Repetier</span>
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> {{ _('Send a checksum with <strong>every</strong> command') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> Support <code>TargetExtr%n</code>/<code>TargetBed</code> target temperature format <span class="label">Repetier</span>
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> Swallow the first "ok" after a resend response
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> {{ _('Swallow the first "ok" after a resend response') }}
</label>
</div>
</div>
@@ -303,36 +309,42 @@
<div class="tab-pane" id="settings_folder">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-folderUploads">Upload Folder</label>
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_uploads" id="settings-folderUploads">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-folderTimelapse">Timelapse Folder</label>
<label class="control-label" for="settings-folderTimelapse">{{ _('Timelapse Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-folderTimelapseTemp">Timelapse Temp Folder</label>
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-folderLogs">Logs Folder</label>
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_logs" id="settings-folderLogs">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-watchedLogs">{{ _('Watched Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
</div>
</div>
</form>
</div>
<div class="tab-pane" id="settings_temperature">
<form class="form-horizontal">
<div class="row-fluid">
<div class="offset3 span3"><h4>Extruder</h4></div>
<div class="span3"><h4>Bed</h4></div>
<div class="offset3 span3"><h4>{{ _('Extruder') }}</h4></div>
<div class="span3"><h4>{{ _('Bed') }}</h4></div>
</div>
<div data-bind="foreach: temperature_profiles">
<div class="row-fluid" style="margin-bottom: 5px">
@@ -362,8 +374,8 @@
<div class="tab-pane" id="settings_terminalFilters">
<form class="form-horizontal">
<div class="row-fluid">
<div class="span4"><h4>Name</h4></div>
<div class="span6"><h4>RegExp <small><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions">?</a></small></h4></div>
<div class="span4"><h4>{{ _('Name') }}</h4></div>
<div class="span6"><h4>{{ _('RegExp') }} <small><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions">?</a></small></h4></div>
</div>
<div data-bind="foreach: terminalFilters">
<div class="row-fluid" style="margin-bottom: 5px">
@@ -388,15 +400,15 @@
<div class="tab-pane" id="settings_appearance">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-appearanceName">Title</label>
<label class="control-label" for="settings-appearanceName">{{ _('Title') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: appearance_name" id="settings-appearanceName">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-appearanceColor">Color</label>
<label class="control-label" for="settings-appearanceColor">{{ _('Color') }}</label>
<div class="controls">
<select id="settings-appearanceColor" data-bind="value: appearance_color, options: appearance_available_colors">
<select id="settings-appearanceColor" data-bind="value: appearance_color, options: appearance_available_colors, optionsText: 'name', optionsValue: 'key'">
</select>
</div>
</div>
@@ -405,19 +417,19 @@
<div class="tab-pane" id="settings_cura">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-curaEnabled">Enable slicing via Cura</label>
<label class="control-label" for="settings-curaEnabled">{{ _('Enable slicing via Cura') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: cura_enabled">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-curaPath">Path to Cura</label>
<label class="control-label" for="settings-curaPath">{{ _('Path to Cura') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: cura_path">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-curaConfig">Path to Cura config</label>
<label class="control-label" for="settings-curaConfig">{{ _('Path to Cura config') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: cura_config">
</div>
@@ -429,19 +441,19 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-apiEnabled" data-bind="checked: api_enabled"> Enable
<input type="checkbox" id="settings-apiEnabled" data-bind="checked: api_enabled"> {{ _('Enable') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> Allow <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">Cross Origin Resource Sharing (CORS)</a>
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> {{ _('Allow <a href="%(url)s">Cross Origin Resource Sharing (CORS)</a>', url = "https://en.wikipedia.org/wiki/Cross-origin_resource_sharing") }}
</label>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-apiKey">Apikey</label>
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: api_key" id="settings-apikey">
</div>
@@ -454,19 +466,19 @@
<table class="table table-condensed table-hover" id="system_users">
<thead>
<tr>
<th class="settings_users_name">Name</th>
<th class="settings_users_active">Active</th>
<th class="settings_users_admin">Admin</th>
<th class="settings_users_actions">Action</th>
<th class="settings_users_name">{{ _('Name') }}</th>
<th class="settings_users_active">{{ _('Active') }}</th>
<th class="settings_users_admin">{{ _('Admin') }}</th>
<th class="settings_users_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: users.listHelper.paginatedItems">
<tr>
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>Apikey: <span data-bind="text: apikey"></span></small></span></td>
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span></small></span></td>
<td class="settings_users_active"><i data-bind="css: { 'icon-check': active, 'icon-check-empty': !active }"></i></td>
<td class="settings_users_admin"><i data-bind="css: { 'icon-check': admin, 'icon-check-empty': !admin }"></i></td>
<td class="settings_users_actions" class="system_users_action">
<a href="#" class="icon-pencil" title="Update User" data-bind="click: function() { $root.users.showEditUserDialog($data); }"></a>&nbsp;|&nbsp;<a href="#" class="icon-key" title="Change password" data-bind="click: function() { $root.users.showChangePasswordDialog($data); }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="Delete user" data-bind="click: function() { $root.users.removeUser($data); }"></a>
<a href="#" class="icon-pencil" title="{{ _('Update User') }}" data-bind="click: function() { $root.users.showEditUserDialog($data); }"></a>&nbsp;|&nbsp;<a href="#" class="icon-key" title="{{ _('Change password') }}" data-bind="click: function() { $root.users.showChangePasswordDialog($data); }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete user') }}" data-bind="click: function() { $root.users.removeUser($data); }"></a>
</td>
</tr>
</tbody>
@@ -483,114 +495,114 @@
</ul>
</div>
<button title="Add user" class="btn" data-bind="click: $root.users.showAddUserDialog"><i class="icon-plus"></i> Create new user</button>
<button title="Add user" class="btn" data-bind="click: $root.users.showAddUserDialog"><i class="icon-plus"></i> {{ _('Add user') }}</button>
<!-- Modals for user management -->
<div id="settings-usersDialogAddUser" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>Create new user</h3>
<h3>{{ _('Add user') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-usersDialogAddUserName">Username</label>
<label class="control-label" for="settings-usersDialogAddUserName">{{ _('Username') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-usersDialogAddUserName" data-bind="value: $root.users.editorUsername" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-usersDialogAddUserPassword1">Password</label>
<label class="control-label" for="settings-usersDialogAddUserPassword1">{{ _('Password') }}</label>
<div class="controls">
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword1" data-bind="value: $root.users.editorPassword" required>
</div>
</div>
<div class="control-group" data-bind="css: {error: $root.users.editorPasswordMismatch()}">
<label class="control-label" for="settings-usersDialogAddUserPassword2">Repeat Password</label>
<label class="control-label" for="settings-usersDialogAddUserPassword2">{{ _('Repeat Password') }}</label>
<div class="controls">
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword2" data-bind="value: $root.users.editorRepeatedPassword, valueUpdate: 'afterkeydown'" required>
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">Passwords do not match</span>
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-usersDialogAddUserActive" data-bind="checked: $root.users.editorActive"> Active
<input type="checkbox" id="settings-usersDialogAddUserActive" data-bind="checked: $root.users.editorActive"> {{ _('Active') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-usersDialogAddUserAdmin" data-bind="checked: $root.users.editorAdmin"> Admin
<input type="checkbox" id="settings-usersDialogAddUserAdmin" data-bind="checked: $root.users.editorAdmin"> {{ _('Admin') }}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Abort</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmAddUser(); }, enable: !$root.users.editorPasswordMismatch()">Confirm</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmAddUser(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
</div>
</div>
<div id="settings-usersDialogEditUser" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>Edit user "<span data-bind="text: $root.users.editorUsername"></span>"</h3>
<h3>{{ _('Edit user "%(user)s"', user = '<span data-bind="text: $root.users.editorUsername"></span>') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-usersDialogEditUserActive" data-bind="checked: $root.users.editorActive"> Active
<input type="checkbox" id="settings-usersDialogEditUserActive" data-bind="checked: $root.users.editorActive"> {{ _('Active') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-usersDialogEditUserAdmin" data-bind="checked: $root.users.editorAdmin"> Admin
<input type="checkbox" id="settings-usersDialogEditUserAdmin" data-bind="checked: $root.users.editorAdmin"> {{ _('Admin') }}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Abort</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmEditUser(); }">Confirm</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmEditUser(); }">{{ _('Confirm') }}</button>
</div>
</div>
<div id="settings-usersDialogChangePassword" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>Change password for user "<span data-bind="text: $root.users.editorUsername"></span>"</h3>
<h3>{{ _('Change password for user "%(user)s"', user='<span data-bind="text: $root.users.editorUsername"></span>') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-usersDialogChangePasswordPassword1">New Password</label>
<label class="control-label" for="settings-usersDialogChangePasswordPassword1">{{ _('New Password') }}</label>
<div class="controls">
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword1" data-bind="value: $root.users.editorPassword" required>
</div>
</div>
<div class="control-group" data-bind="css: {error: $root.users.editorPasswordMismatch()}">
<label class="control-label" for="settings-usersDialogChangePasswordPassword2">Repeat Password</label>
<label class="control-label" for="settings-usersDialogChangePasswordPassword2">{{ _('Repeat Password') }}</label>
<div class="controls">
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword2" data-bind="value: $root.users.editorRepeatedPassword, valueUpdate: 'afterkeydown'" required>
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">Passwords do not match</span>
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
</div>
</div>
<fieldset data-bind="visible: api_enabled">
<legend>Apikey</legend>
<div class="control-group">
<label class="control-label">Current Apikey</label>
<label class="control-label">{{ _('Current API Key') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level uneditable-input" data-bind="value: $root.users.editorApikey, attr: {placeholder: 'N/A'}">
<input type="text" class="input-block-level uneditable-input" data-bind="value: $root.users.editorApikey, attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn" title="Generate new Apikey" data-bind="click: function() { $root.users.confirmGenerateApikey(); }"><i class="icon-refresh"></i></a>
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: function() { $root.users.confirmDeleteApikey(); }"><i class="icon-trash"></i></a>
</div>
@@ -601,8 +613,8 @@
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Abort</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">Confirm</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
</div>
</div>
@@ -611,20 +623,20 @@
<div class="tab-pane" id="settings_logs" data-bind="allowBindings: false">
<div id="logs">
<h1>Logs</h1>
<h1>{{ _('Logs') }}</h1>
<div class="pull-right">
<small>
Sort by: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">Name (ascending)</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">Modification date (descending)</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">Size (descending)</a>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_name">Name</th>
<th class="settings_logs_size">Size</th>
<th class="settings_logs_date">Date</th>
<th class="settings_logs_action">Action</th>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
<th class="settings_logs_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
@@ -661,7 +673,7 @@
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button class="btn btn-primary" data-bind="click: saveData">Save</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
<button class="btn btn-primary" data-bind="click: saveData">{{ _('Save') }}</button>
</div>
</div>
+12 -8
View File
@@ -305,14 +305,18 @@ class Timelapse(object):
command_str = " ".join(command)
self._logger.debug("Executing command: %s" % command_str)
p = sarge.run(command_str, stderr=sarge.Capture())
if p.returncode == 0:
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
else:
returncode = p.returncode
stderr_text = p.stderr.text
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
try:
p = sarge.run(command_str, stderr=sarge.Capture())
if p.returncode == 0:
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
else:
returncode = p.returncode
stderr_text = p.stderr.text
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
except:
self._logger.exception("Could not render movie due to unknown error")
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
def cleanCaptureDir(self):
if not os.path.isdir(self._captureDir):
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4
View File
@@ -248,3 +248,7 @@ def dict_merge(a, b):
else:
result[k] = deepcopy(v)
return result
class Object(object):
pass
+9 -7
View File
@@ -48,6 +48,7 @@ def serialList():
+ glob.glob("/dev/ttyAMA*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/cuaU*") \
+ glob.glob("/dev/rfcomm*")
additionalPorts = settings().get(["serial", "additionalPorts"])
@@ -340,11 +341,11 @@ class MachineCom(object):
def close(self, isError = False):
printing = self.isPrinting() or self.isPaused()
if self._serial is not None:
self._serial.close()
if isError:
self._changeState(self.STATE_CLOSED_WITH_ERROR)
else:
self._changeState(self.STATE_CLOSED)
self._serial.close()
self._serial = None
if settings().get(["feature", "sdSupport"]):
@@ -631,19 +632,20 @@ class MachineCom(object):
##~~ SD file list
# if we are currently receiving an sd file list, each line is just a filename, so just read it and abort processing
if self._sdFileList and not "End file list" in line:
fileinfo = line.strip().split(None, 2)
preprocessed_line = line.strip().lower()
fileinfo = preprocessed_line.rsplit(None, 1)
if len(fileinfo) > 1:
# we got extended file information here, so let's split filename and size and try to make them a bit nicer
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
filename, size = fileinfo
filename = filename.lower()
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just ignore it and set size to None
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
filename = preprocessed_line
size = None
else:
# no extended file information, so only the filename is there and we set size to None
filename = fileinfo[0].lower()
filename = preprocessed_line
size = None
if isGcodeFileName(filename):
@@ -944,7 +946,7 @@ class MachineCom(object):
try:
self._log("Connecting to: %s" % self._port)
if self._baudrate == 0:
self._serial = serial.Serial(str(self._port), 115200, timeout=0.1, writeTimeout=10000)
self._serial = serial.Serial(str(self._port), 115200, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000)
else:
self._serial = serial.Serial(str(self._port), self._baudrate, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000)
except:
+17 -14
View File
@@ -195,23 +195,26 @@ class gcode(object):
absoluteE = False
elif T is not None:
posOffset[0] -= offsets[currentExtruder]["x"] if currentExtruder < len(offsets) else 0
posOffset[1] -= offsets[currentExtruder]["y"] if currentExtruder < len(offsets) else 0
if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]):
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
else:
posOffset[0] -= offsets[currentExtruder]["x"] if currentExtruder < len(offsets) else 0
posOffset[1] -= offsets[currentExtruder]["y"] if currentExtruder < len(offsets) else 0
currentExtruder = T
currentExtruder = T
posOffset[0] += offsets[currentExtruder]["x"] if currentExtruder < len(offsets) else 0
posOffset[1] += offsets[currentExtruder]["y"] if currentExtruder < len(offsets) else 0
posOffset[0] += offsets[currentExtruder]["x"] if currentExtruder < len(offsets) else 0
posOffset[1] += offsets[currentExtruder]["y"] if currentExtruder < len(offsets) else 0
if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1):
currentE.append(0.0)
if len(maxExtrusion) <= currentExtruder:
for i in range(len(maxExtrusion), currentExtruder + 1):
maxExtrusion.append(0.0)
if len(totalExtrusion) <= currentExtruder:
for i in range(len(totalExtrusion), currentExtruder + 1):
totalExtrusion.append(0.0)
if len(currentE) <= currentExtruder:
for i in range(len(currentE), currentExtruder + 1):
currentE.append(0.0)
if len(maxExtrusion) <= currentExtruder:
for i in range(len(maxExtrusion), currentExtruder + 1):
maxExtrusion.append(0.0)
if len(totalExtrusion) <= currentExtruder:
for i in range(len(totalExtrusion), currentExtruder + 1):
totalExtrusion.append(0.0)
if self.progressCallback is not None:
self.progressCallback(100.0)