Compare commits

..
7 Commits
Author SHA1 Message Date
Gina Häußge 0fd9b3354a Changed version... 2013-12-21 16:01:13 +01:00
Gina Häußge 765b941472 Merge branch 'master' into toMerge
Conflicts:
	octoprint/server.py
	setup.py
	src/octoprint/printer.py
	src/octoprint/static/js/app/main.js
	src/octoprint/util/__init__.py
2013-12-21 15:55:41 +01:00
Gina Häußge 64084bb628 A couple of manual merges... 2013-12-21 15:51:32 +01:00
Gina Häußge df269eb4f7 More intelligent handling of disabling and re-enabling the webcam stream.
See #314
(cherry picked from commit 1dd0aba)
2013-12-21 14:52:06 +01:00
Gina Häußge 722b03dca8 Disable webcam stream when control tab is not in focus.
Fixes #316
(cherry picked from commit 1b4a7c7)
2013-12-21 14:51:53 +01:00
Gina Häußge 3ddfc93c1b Use G28 for homing (G1 was a copy-paste-error)
Fixes #314
(cherry picked from commit 5b8126a)
2013-12-21 14:51:43 +01:00
Gina Häußge 5eb70fa57d Properly calculate time deltas (forgot the days)
(cherry picked from commit 84012d1)
2013-12-21 14:50:46 +01:00
27 changed files with 266 additions and 1322 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
1.1.0-dev
-177
View File
@@ -1,177 +0,0 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/OctoPrint.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/OctoPrint.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/OctoPrint"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/OctoPrint"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
-248
View File
@@ -1,248 +0,0 @@
# -*- coding: utf-8 -*-
#
# OctoPrint documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 02 17:08:50 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'OctoPrint'
copyright = u'2013, Gina Häußge'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = open("../VERSION").read().strip()
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'OctoPrintdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'OctoPrint.tex', u'OctoPrint Documentation',
u'Gina Häußge', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'octoprint', u'OctoPrint Documentation',
[u'Gina Häußge'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OctoPrint', u'OctoPrint Documentation',
u'Gina Häußge', 'OctoPrint', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
-22
View File
@@ -1,22 +0,0 @@
.. OctoPrint documentation master file, created by
sphinx-quickstart on Mon Dec 02 17:08:50 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to OctoPrint's documentation!
=====================================
Contents:
.. toctree::
:maxdepth: 2
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
-242
View File
@@ -1,242 +0,0 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\OctoPrint.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\OctoPrint.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end
+1 -1
View File
@@ -3,7 +3,7 @@
from setuptools import setup, find_packages from setuptools import setup, find_packages
VERSION = open("VERSION").read().strip() VERSION = "1.0.0-rc2"
def params(): def params():
name = "OctoPrint" name = "OctoPrint"
+5 -1
View File
@@ -14,6 +14,7 @@ import octoprint.util.gcodeInterpreter as gcodeInterpreter
from octoprint.settings import settings from octoprint.settings import settings
from octoprint.events import eventManager from octoprint.events import eventManager
from octoprint.filemanager.destinations import FileDestinations
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
@@ -195,6 +196,7 @@ class GcodeManager:
self.processStl(absolutePath, destination, uploadCallback) self.processStl(absolutePath, destination, uploadCallback)
return filename, False return filename, False
def getFutureFileName(self, file): def getFutureFileName(self, file):
if not file: if not file:
return None return None
@@ -205,6 +207,7 @@ class GcodeManager:
return self._getBasicFilename(absolutePath) return self._getBasicFilename(absolutePath)
def processStl(self, absolutePath, destination, uploadCallback=None): def processStl(self, absolutePath, destination, uploadCallback=None):
from octoprint.slicers.cura import CuraFactory from octoprint.slicers.cura import CuraFactory
@@ -227,6 +230,7 @@ class GcodeManager:
eventManager().fire("SlicingStarted", {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)}) eventManager().fire("SlicingStarted", {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)})
cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath]) cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath])
def processGcode(self, absolutePath, destination, uploadCallback=None): def processGcode(self, absolutePath, destination, uploadCallback=None):
if absolutePath is None: if absolutePath is None:
return None return None
@@ -243,7 +247,7 @@ class GcodeManager:
if uploadCallback is not None: if uploadCallback is not None:
uploadCallback(filename, absolutePath, destination) uploadCallback(filename, absolutePath, destination)
return filename return filename
def getFutureFilename(self, file): def getFutureFilename(self, file):
if not file: if not file:
+3 -8
View File
@@ -9,6 +9,8 @@ import copy
import os import os
import logging import logging
#import logging, logging.config
import octoprint.util.comm as comm import octoprint.util.comm as comm
import octoprint.util as util import octoprint.util as util
@@ -457,7 +459,7 @@ class Printer():
self._setProgressData(0.0, 0, 0, None) self._setProgressData(0.0, 0, 0, None)
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()}) self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
def mcFileTransferDone(self, filename): def mcFileTransferDone(self):
self._sdStreaming = False self._sdStreaming = False
if self._streamingFinishedCallback is not None: if self._streamingFinishedCallback is not None:
@@ -558,13 +560,6 @@ class Printer():
} }
} }
def getCurrentConnection(self):
if self._comm is None:
return "Closed", None, None
port, baudrate = self._comm.getConnection()
return self._comm.getStateString(), port, baudrate
def isClosedOrError(self): def isClosedOrError(self):
return self._comm is None or self._comm.isClosedOrError() return self._comm is None or self._comm.isClosedOrError()
+101 -183
View File
@@ -2,196 +2,148 @@
__author__ = "Gina Häußge <osd@foosel.net>" __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
from flask import request, jsonify, make_response from flask import request, jsonify
from octoprint.settings import settings, valid_boolean_trues from octoprint.settings import settings
from octoprint.printer import getConnectionOptions from octoprint.printer import getConnectionOptions
from octoprint.server import printer, restricted_access, SUCCESS from octoprint.server import printer, restricted_access, SUCCESS
from octoprint.server.ajax import ajax from octoprint.server.ajax import ajax
import octoprint.util as util
#~~ Printer control #~~ Printer control
@ajax.route("/control/connection", methods=["GET"]) @ajax.route("/control/connection/options", methods=["GET"])
def connectionOptions(): def connectionOptions():
state, port, baudrate = printer.getCurrentConnection() return jsonify(getConnectionOptions())
current = {
"state": state,
"port": port,
"baudrate": baudrate
}
return jsonify({"current": current, "options": getConnectionOptions()})
@ajax.route("/control/connection", methods=["POST"]) @ajax.route("/control/connection", methods=["POST"])
@restricted_access @restricted_access
def connectionCommand(): def connect():
valid_commands = { if "command" in request.values.keys() and request.values["command"] == "connect":
"connect": ["autoconnect"],
"disconnect": []
}
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
if response is not None:
return response
if command == "connect":
options = getConnectionOptions()
port = None port = None
baudrate = None baudrate = None
if "port" in data.keys(): if "port" in request.values.keys():
port = data["port"] port = request.values["port"]
if port not in options["ports"]: if "baudrate" in request.values.keys():
return make_response("Invalid port: %s" % port, 400) baudrate = request.values["baudrate"]
if "baudrate" in data.keys(): if "save" in request.values.keys():
baudrate = data["baudrate"]
if baudrate not in options["baudrates"]:
return make_response("Invalid baudrate: %d" % baudrate, 400)
if "save" in data.keys() and data["save"]:
settings().set(["serial", "port"], port) settings().set(["serial", "port"], port)
settings().setInt(["serial", "baudrate"], baudrate) settings().setInt(["serial", "baudrate"], baudrate)
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) settings().save()
settings().save() if "autoconnect" in request.values.keys():
settings().setBoolean(["serial", "autoconnect"], True)
settings().save()
printer.connect(port=port, baudrate=baudrate) printer.connect(port=port, baudrate=baudrate)
elif command == "disconnect": elif "command" in request.values.keys() and request.values["command"] == "disconnect":
printer.disconnect() printer.disconnect()
return jsonify(SUCCESS) return jsonify(SUCCESS)
@ajax.route("/control/printer/command", methods=["POST"]) @ajax.route("/control/command", methods=["POST"])
@restricted_access @restricted_access
def printerCommand(): def printerCommand():
if not printer.isOperational(): if "application/json" in request.headers["Content-Type"]:
return make_response("Printer is not operational", 403) data = request.json
if not "application/json" in request.headers["Content-Type"]: parameters = {}
return make_response("Expected content type JSON", 400) if "parameters" in data.keys(): parameters = data["parameters"]
data = request.json commands = []
if "command" in data.keys(): commands = [data["command"]]
elif "commands" in data.keys(): commands = data["commands"]
parameters = {} commandsToSend = []
if "parameters" in data.keys(): parameters = data["parameters"] for command in commands:
commandToSend = command
if len(parameters) > 0:
commandToSend = command % parameters
commandsToSend.append(commandToSend)
commands = [] printer.commands(commandsToSend)
if "command" in data.keys(): commands = [data["command"]]
elif "commands" in data.keys(): commands = data["commands"]
commandsToSend = []
for command in commands:
commandToSend = command
if len(parameters) > 0:
commandToSend = command % parameters
commandsToSend.append(commandToSend)
printer.commands(commandsToSend)
return jsonify(SUCCESS) return jsonify(SUCCESS)
@ajax.route("/control/job", methods=["POST"]) @ajax.route("/control/job", methods=["POST"])
@restricted_access @restricted_access
def controlJob(): def printJobControl():
if not printer.isOperational(): if "command" in request.values.keys():
return make_response("Printer is not operational", 403) if request.values["command"] == "start":
printer.startPrint()
valid_commands = { elif request.values["command"] == "pause":
"start": [], printer.togglePausePrint()
"pause": [], elif request.values["command"] == "cancel":
"cancel": [] printer.cancelPrint()
}
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
if response is not None:
return response
if command == "start":
printer.startPrint()
elif command == "pause":
printer.togglePausePrint()
elif command == "cancel":
printer.cancelPrint()
return jsonify(SUCCESS) return jsonify(SUCCESS)
@ajax.route("/control/printer/hotend", methods=["POST"]) @ajax.route("/control/temperature", methods=["POST"])
@restricted_access @restricted_access
def controlPrinterHotend(): def setTargetTemperature():
if not printer.isOperational(): if "temp" in request.values.keys():
return make_response("Printer is not operational", 403) # set target temperature
temp = request.values["temp"]
printer.command("M104 S" + temp)
valid_commands = { if "bedTemp" in request.values.keys():
"temp": ["temps"], # set target bed temperature
"offset": ["offsets"] bedTemp = request.values["bedTemp"]
} printer.command("M140 S" + bedTemp)
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
if response is not None:
return response
valid_targets = ["hotend", "bed"] if "tempOffset" in request.values.keys():
# set target temperature offset
try:
tempOffset = float(request.values["tempOffset"])
if tempOffset >= -50 and tempOffset <= 50:
printer.setTemperatureOffset(tempOffset, None)
except:
pass
##~~ temperature if "bedTempOffset" in request.values.keys():
if command == "temp": # set target bed temperature offset
temps = data["temps"] try:
bedTempOffset = float(request.values["bedTempOffset"])
# make sure the targets are valid and the values are numbers if bedTempOffset >= -50 and bedTempOffset <= 50:
validated_values = {} printer.setTemperatureOffset(None, bedTempOffset)
for type, value in temps.iteritems(): except:
if not type in valid_targets: pass
return make_response("Invalid target for setting temperature: %s" % type, 400)
if not isinstance(value, (int, long, float)):
return make_response("Not a number for %s: %r" % (type, value), 400)
validated_values[type] = value
# perform the actual temperature commands
# TODO make this a generic method call (printer.setTemperature(type, value)) to get rid of gcode here
if "hotend" in validated_values:
printer.command("M104 S%f" % validated_values["hotend"])
if "bed" in validated_values:
printer.command("M140 S%f" % validated_values["bed"])
##~~ temperature offset
elif command == "offset":
offsets = data["offsets"]
# make sure the targets are valid, the values are numbers and in the range [-50, 50]
validated_values = {}
for type, value in offsets.iteritems():
if not type in valid_targets:
return make_response("Invalid target for setting temperature: %s" % type, 400)
if not isinstance(value, (int, long, float)):
return make_response("Not a number for %s: %r" % (type, value), 400)
if not -50 <= value <= 50:
return make_response("Offset %s not in range [-50, 50]: %f" % (type, value), 400)
validated_values[type] = value
# set the offsets
if "hotend" in validated_values and "bed" in validated_values:
printer.setTemperatureOffset(validated_values["hotend"], validated_values["bed"])
elif "hotend" in validated_values:
printer.setTemperatureOffset(validated_values["hotend"], None)
elif "bed" in validated_values:
printer.setTemperatureOffset(None, validated_values["bed"])
return jsonify(SUCCESS) return jsonify(SUCCESS)
@ajax.route("/control/printer/printhead", methods=["POST"]) @ajax.route("/control/jog", methods=["POST"])
@restricted_access @restricted_access
def controlPrinterPrinthead(): def jog():
if not printer.isOperational() or printer.isPrinting(): if not printer.isOperational() or printer.isPrinting():
# do not jog when a print job is running or we don't have a connection # do not jog when a print job is running or we don't have a connection
return make_response("Printer is not operational or currently printing", 403) return jsonify(SUCCESS)
valid_commands = { (movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE) = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
"jog": [], if "x" in request.values.keys():
"home": ["axes"] # jog x
} x = request.values["x"]
command, data, response = util.getJsonCommandFromRequest(request, valid_commands) printer.commands(["G91", "G1 X%s F%d" % (x, movementSpeedX), "G90"])
if response is not None: if "y" in request.values.keys():
return response # jog y
y = request.values["y"]
printer.commands(["G91", "G1 Y%s F%d" % (y, movementSpeedY), "G90"])
if "z" in request.values.keys():
# jog z
z = request.values["z"]
printer.commands(["G91", "G1 Z%s F%d" % (z, movementSpeedZ), "G90"])
if "homeXY" in request.values.keys():
# home x/y
printer.command("G28 X0 Y0")
if "homeZ" in request.values.keys():
# home z
printer.command("G28 Z0")
if "extrude" in request.values.keys():
# extrude/retract
length = request.values["extrude"]
printer.commands(["G91", "G1 E%s F%d" % (length, movementSpeedE), "G90"])
movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True) movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
@@ -228,33 +180,6 @@ def controlPrinterPrinthead():
return jsonify(SUCCESS) return jsonify(SUCCESS)
@ajax.route("/control/printer/feeder", methods=["POST"])
@restricted_access
def controlPrinterFeeder():
if not printer.isOperational() or printer.isPrinting():
# do not jog when a print job is running or we don't have a connection
return make_response("Printer is not operational or currently printing", 403)
valid_commands = {
"extrude": ["amount"]
}
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
if response is not None:
return response
extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"])
if command == "extrude":
amount = data["amount"]
if not isinstance(amount, (int, long, float)):
return make_response("Not a number for extrusion amount: %r" % amount, 400)
# TODO make this a generic method call (printer.extruder([hotend,] amount)) to get rid of gcode here
printer.commands(["G91", "G1 E%s F%d" % (data["amount"], extrusionSpeed), "G90"])
return jsonify(SUCCESS)
@ajax.route("/control/custom", methods=["GET"]) @ajax.route("/control/custom", methods=["GET"])
def getCustomControls(): def getCustomControls():
customControls = settings().get(["controls"]) customControls = settings().get(["controls"])
@@ -265,23 +190,16 @@ def getCustomControls():
@restricted_access @restricted_access
def sdCommand(): def sdCommand():
if not settings().getBoolean(["feature", "sdSupport"]) or not printer.isOperational() or printer.isPrinting(): if not settings().getBoolean(["feature", "sdSupport"]) or not printer.isOperational() or printer.isPrinting():
return make_response("SD support is disabled", 403) return jsonify(SUCCESS)
valid_commands = { if "command" in request.values.keys():
"init": [], command = request.values["command"]
"refresh": [], if command == "init":
"release": [] printer.initSdCard()
} elif command == "refresh":
command, data, response = util.getJsonCommandFromRequest(request, valid_commands) printer.refreshSdFiles()
if response is not None: elif command == "release":
return response printer.releaseSdCard()
if command == "init":
printer.initSdCard()
elif command == "refresh":
printer.refreshSdFiles()
elif command == "release":
printer.releaseSdCard()
return jsonify(SUCCESS) return jsonify(SUCCESS)
+42 -85
View File
@@ -18,38 +18,21 @@ from octoprint.server.ajax import ajax
@ajax.route("/gcodefiles", methods=["GET"]) @ajax.route("/gcodefiles", methods=["GET"])
def readGcodeFiles(): def readGcodeFiles():
files = _getFileList(FileDestinations.LOCAL) files = gcodeManager.getAllFileData()
files.extend(_getFileList(FileDestinations.SDCARD))
sdFileList = printer.getSdFiles()
if sdFileList is not None:
for sdFile in sdFileList:
files.append({
"name": sdFile,
"size": "n/a",
"bytes": 0,
"date": "n/a",
"origin": "sd"
})
return jsonify(files=files, free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads")))) return jsonify(files=files, free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads"))))
@ajax.route("/gcodefiles/<string:target>", methods=["GET"])
def readGcodeFilesForTarget(target):
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Invalid target: %s" % target, 400)
return jsonify(files=_getFileList(target), free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads"))))
def _getFileList(target):
if target == FileDestinations.SDCARD:
sdFileList = printer.getSdFiles()
files = []
if sdFileList is not None:
for sdFile in sdFileList:
files.append({
"name": sdFile,
"size": "n/a",
"bytes": 0,
"date": "n/a",
"origin": FileDestinations.SDCARD
})
else:
files = gcodeManager.getAllFileData()
return files
@ajax.route("/gcodefiles/<string:target>", methods=["POST"]) @ajax.route("/gcodefiles/<string:target>", methods=["POST"])
@restricted_access @restricted_access
def uploadGcodeFile(target): def uploadGcodeFile(target):
@@ -118,78 +101,52 @@ def uploadGcodeFile(target):
return make_response("No gcode_file included", 400) return make_response("No gcode_file included", 400)
@ajax.route("/gcodefiles/local/<path:filename>", methods=["GET"]) @ajax.route("/gcodefiles/load", methods=["POST"])
def readGcodeFile(filename):
return redirectToTornado(request, url_for("index") + "downloads/gcode/" + filename)
@ajax.route("/gcodefiles/<string:target>/<path:filename>", methods=["POST"])
@restricted_access @restricted_access
def gcodeFileCommand(filename, target): def loadGcodeFile():
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: if "filename" in request.values.keys():
return make_response("Invalid target: %s" % target, 400)
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"load": []
}
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
if response is not None:
return response
if command == "load":
# selects/loads a file
printAfterLoading = False printAfterLoading = False
if "print" in data.keys() and data["print"]: if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues:
printAfterLoading = True printAfterLoading = True
sd = False sd = False
if target == FileDestinations.SDCARD: if "target" in request.values.keys() and request.values["target"] == "sd":
filenameToSelect = filename filename = request.values["filename"]
sd = True sd = True
else: else:
filenameToSelect = gcodeManager.getAbsolutePath(filename) filename = gcodeManager.getAbsolutePath(request.values["filename"])
printer.selectFile(filenameToSelect, sd, printAfterLoading) printer.selectFile(filename, sd, printAfterLoading)
return jsonify(SUCCESS) return jsonify(SUCCESS)
return make_response("Command %s is currently not implemented" % command, 400)
@ajax.route("/gcodefiles/<string:target>/<path:filename>", methods=["DELETE"]) @ajax.route("/gcodefiles/delete", methods=["POST"])
@restricted_access @restricted_access
def deleteGcodeFile(filename, target): def deleteGcodeFile():
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: if "filename" in request.values.keys():
return make_response("Invalid target: %s" % target, 400) filename = request.values["filename"]
sd = "target" in request.values.keys() and request.values["target"] == "sd"
sd = target == FileDestinations.SDCARD currentJob = printer.getCurrentJob()
currentFilename = None
currentSd = None
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
currentFilename = currentJob["filename"]
currentSd = currentJob["sd"]
currentJob = printer.getCurrentJob() if currentFilename is not None and filename == currentFilename and not (printer.isPrinting() or printer.isPaused()):
currentFilename = None printer.unselectFile()
currentSd = None
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
currentFilename = currentJob["filename"]
currentSd = currentJob["sd"]
if currentFilename is not None and filename == currentFilename and not (printer.isPrinting() or printer.isPaused()): if not (currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused())):
printer.unselectFile() if sd:
printer.deleteSdFile(filename)
if not (currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused())): else:
if sd: gcodeManager.removeFile(filename)
printer.deleteSdFile(filename)
else:
gcodeManager.removeFile(filename)
return readGcodeFiles() return readGcodeFiles()
@ajax.route("/gcodefiles/<string:target>/refresh", methods=["POST"]) @ajax.route("/gcodefiles/refresh", methods=["POST"])
@restricted_access @restricted_access
def refreshFiles(target): def refreshFiles():
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: printer.updateSdFiles()
return make_response("Invalid target: %s" % target, 400)
if target == FileDestinations.SDCARD:
printer.updateSdFiles()
return jsonify(SUCCESS) return jsonify(SUCCESS)
-31
View File
@@ -123,34 +123,3 @@ def changePasswordForUser(username):
else: else:
return make_response(("Forbidden", 403, [])) return make_response(("Forbidden", 403, []))
@ajax.route("/users/<username>/apikey", methods=["DELETE"])
@restricted_access
def deleteApikeyForUser(username):
if userManager is None:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
try:
userManager.deleteApikey(username)
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify(SUCCESS)
else:
return make_response(("Forbidden", 403, []))
@ajax.route("/users/<username>/apikey", methods=["POST"])
@restricted_access
def generateApikeyForUser(username):
if userManager is None:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
try:
apikey = userManager.generateApiKey(username)
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify({"apikey": apikey})
else:
return make_response(("Forbidden", 403, []))
+24 -10
View File
@@ -7,30 +7,36 @@ import logging
from flask import Blueprint, request, jsonify, abort from flask import Blueprint, request, jsonify, abort
from octoprint.server import printer, gcodeManager, SUCCESS from octoprint.server import printer, gcodeManager, SUCCESS
from octoprint.server.util import api_access from octoprint.settings import settings, valid_boolean_trues
from octoprint.settings import valid_boolean_trues
from octoprint.filemanager.destinations import FileDestinations from octoprint.filemanager.destinations import FileDestinations
import octoprint.gcodefiles as gcodefiles import octoprint.gcodefiles as gcodefiles
api = Blueprint("api", __name__) api = Blueprint("api", __name__)
#-- very simple api routines
@api.route("/load", methods=["POST"]) @api.route("/load", methods=["POST"])
@api_access
def apiLoad(): def apiLoad():
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
if not settings().get(["api", "enabled"]):
abort(401)
if not "apikey" in request.values.keys():
abort(401)
if request.values["apikey"] != settings().get(["api", "key"]):
abort(403)
if not "file" in request.files.keys(): if not "file" in request.files.keys():
abort(400) abort(400)
# Perform an upload # Perform an upload
f = request.files["file"] file = request.files["file"]
if not gcodefiles.isGcodeFileName(f.filename): if not gcodefiles.isGcodeFileName(file.filename):
abort(400) abort(400)
destination = FileDestinations.LOCAL destination = FileDestinations.LOCAL
filename, done = gcodeManager.addFile(f, destination) filename, done = gcodeManager.addFile(file, destination)
if filename is None: if filename is None:
logger.warn("Upload via API failed") logger.warn("Upload via API failed")
abort(500) abort(500)
@@ -45,11 +51,19 @@ def apiLoad():
return jsonify(SUCCESS) return jsonify(SUCCESS)
@api.route("/state", methods=["GET"]) @api.route("/state", methods=["GET"])
@api_access
def apiPrinterState(): def apiPrinterState():
if not settings().get(["api", "enabled"]):
abort(401)
if not "apikey" in request.values.keys():
abort(401)
if request.values["apikey"] != settings().get(["api", "key"]):
abort(403)
currentData = printer.getCurrentData() currentData = printer.getCurrentData()
currentData.update({ currentData.update({
"temperatures": printer.getCurrentTemperatures() "temperatures": printer.getCurrentTemperatures()
}) })
return jsonify(currentData) return jsonify(currentData)
+9 -47
View File
@@ -1,7 +1,7 @@
from flask.ext.principal import identity_changed, Identity
from tornado.web import StaticFileHandler, HTTPError from tornado.web import StaticFileHandler, HTTPError
from flask import url_for, make_response, request, current_app from flask import url_for, make_response
from flask.ext.login import login_required, login_user from flask.ext.login import login_required
from werkzeug.utils import redirect from werkzeug.utils import redirect
from sockjs.tornado import SockJSConnection from sockjs.tornado import SockJSConnection
@@ -15,70 +15,32 @@ import threading
import logging import logging
from functools import wraps from functools import wraps
from octoprint.server import userManager
from octoprint.settings import settings from octoprint.settings import settings
import octoprint.timelapse import octoprint.timelapse
import octoprint.server
from octoprint.users import ApiUser
def restricted_access(func, apiEnabled=True):
def restricted_access(func):
""" """
If you decorate a view with this, it will ensure that first setup has been 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 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 login_required decorator are met.
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" 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 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 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. 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. Otherwise the result of calling login_required will be returned.
""" """
@wraps(func) @wraps(func)
def decorated_view(*args, **kwargs): def decorated_view(*args, **kwargs):
# if OctoPrint hasn't been set up yet, abort if settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()):
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) return make_response("OctoPrint isn't setup yet", 403)
# if API is globally enabled, enabled for this request and an api key is provided, try to use that
if settings().get(["api", "enabled"]) and apiEnabled and "apikey" in request.values.keys():
apikey = request.values["apikey"]
user = None
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:
make_response("Invalid API key", 403)
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 login_required(func)(*args, **kwargs)
return decorated_view 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)
if not "apikey" in request.values.keys():
make_response("No API key provided", 401)
if request.values["apikey"] != settings().get(["api", "key"]):
make_response("Invalid API key", 403)
return func(args, kwargs)
return decorated_view
#~~ Printer state #~~ Printer state
@@ -324,7 +286,7 @@ class ReverseProxied(object):
def redirectToTornado(request, target): def redirectToTornado(request, target):
requestUrl = request.url requestUrl = request.url
appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "/ajax")] appBaseUrl = requestUrl[:requestUrl.find(url_for("ajax.base"))]
redirectUrl = appBaseUrl + target redirectUrl = appBaseUrl + target
if "?" in requestUrl: if "?" in requestUrl:
+6 -17
View File
@@ -187,7 +187,7 @@ class Settings(object):
#~~ getter #~~ getter
def get(self, path, asdict=False): def get(self, path):
if len(path) == 0: if len(path) == 0:
return None return None
@@ -211,28 +211,17 @@ class Settings(object):
else: else:
keys = k keys = k
if asdict: results = []
results = {}
else:
results = []
for key in keys: for key in keys:
if key in config.keys(): if key in config.keys():
value = config[key] results.append(config[key])
elif key in defaults: elif key in defaults:
value = defaults[key] results.append(defaults[key])
else: else:
value = None results.append(None)
if asdict:
results[key] = value
else:
results.append(value)
if not isinstance(k, (list, tuple)): if not isinstance(k, (list, tuple)):
if asdict: return results.pop()
return results.values().pop()
else:
return results.pop()
else: else:
return results return results
-4
View File
@@ -19,10 +19,6 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
//~~ item handling //~~ item handling
self.refresh = function() {
self._updateItems();
}
self.updateItems = function(items) { self.updateItems = function(items) {
self.allItems = items; self.allItems = items;
self._updateItems(); self._updateItems();
@@ -9,7 +9,6 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
self.selectedPort = ko.observable(undefined); self.selectedPort = ko.observable(undefined);
self.selectedBaudrate = ko.observable(undefined); self.selectedBaudrate = ko.observable(undefined);
self.saveSettings = ko.observable(undefined); self.saveSettings = ko.observable(undefined);
self.autoconnect = ko.observable(undefined);
self.isErrorOrClosed = ko.observable(undefined); self.isErrorOrClosed = ko.observable(undefined);
self.isOperational = ko.observable(undefined); self.isOperational = ko.observable(undefined);
@@ -30,7 +29,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
self.requestData = function() { self.requestData = function() {
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/connection", url: AJAX_BASEURL + "control/connection/options",
method: "GET", method: "GET",
dataType: "json", dataType: "json",
success: function(response) { success: function(response) {
@@ -40,18 +39,13 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
} }
self.fromResponse = function(response) { self.fromResponse = function(response) {
var ports = response.options.ports; self.portOptions(response.ports);
var baudrates = response.options.baudrates; self.baudrateOptions(response.baudrates);
var portPreference = response.options.portPreference;
var baudratePreference = response.options.baudratePreference;
self.portOptions(ports); if (!self.selectedPort() && response.ports && response.ports.indexOf(response.portPreference) >= 0)
self.baudrateOptions(baudrates); self.selectedPort(response.portPreference);
if (!self.selectedBaudrate() && response.baudrates && response.baudrates.indexOf(response.baudratePreference) >= 0)
if (!self.selectedPort() && ports && ports.indexOf(portPreference) >= 0) self.selectedBaudrate(response.baudratePreference);
self.selectedPort(portPreference);
if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0)
self.selectedBaudrate(baudratePreference);
self.saveSettings(false); self.saveSettings(false);
} }
@@ -92,8 +86,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
var data = { var data = {
"command": "connect", "command": "connect",
"port": self.selectedPort(), "port": self.selectedPort(),
"baudrate": self.selectedBaudrate(), "baudrate": self.selectedBaudrate()
"autoconnect": self.settings.serial_autoconnect()
}; };
if (self.saveSettings()) if (self.saveSettings())
@@ -103,20 +96,19 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
url: AJAX_BASEURL + "control/connection", url: AJAX_BASEURL + "control/connection",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: data
data: JSON.stringify(data), })
success: function(response) {
self.settings.requestData() self.settings.serial_port(self.selectedPort())
} self.settings.serial_baudrate(self.selectedBaudrate())
}); self.settings.saveData();
} else { } else {
self.requestData(); self.requestData();
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/connection", url: AJAX_BASEURL + "control/connection",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: {"command": "disconnect"}
data: JSON.stringify({"command": "disconnect"})
}) })
} }
} }
@@ -80,37 +80,26 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.sendJogCommand = function(axis, multiplier, distance) { self.sendJogCommand = function(axis, multiplier, distance) {
if (typeof distance === "undefined") if (typeof distance === "undefined")
distance = $('#jog_distance button.active').data('distance'); distance = $('#jog_distance button.active').data('distance');
if (self.settings.getPrinterInvertAxis(axis)) { if (self.settings.getPrinterInvertAxis(axis)) {
multiplier *= -1; multiplier *= -1;
} }
var data = {
"command": "jog"
}
data[axis] = distance * multiplier;
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/printer/printhead", url: AJAX_BASEURL + "control/jog",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: axis + "=" + ( distance * multiplier )
data: JSON.stringify(data) })
});
} }
self.sendHomeCommand = function(axis) { self.sendHomeCommand = function(axis) {
var data = {
"command": "home",
"axes": axis
}
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/printer/printhead", url: AJAX_BASEURL + "control/jog",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: "home" + axis
data: JSON.stringify(data) })
});
} }
self.sendExtrudeCommand = function() { self.sendExtrudeCommand = function() {
@@ -125,14 +114,12 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
var length = self.extrusionAmount(); var length = self.extrusionAmount();
if (!length) if (!length)
length = 5; length = 5;
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/printer/feeder", url: AJAX_BASEURL + "control/jog",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: "extrude=" + (dir * length)
data: JSON.stringify({command: "extrude", amount: (dir * length)}) })
});
} }
self.sendCustomCommand = function(command) { self.sendCustomCommand = function(command) {
@@ -156,11 +143,11 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
} }
} }
if (data === undefined) if (!data)
return; return;
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/printer/command", url: AJAX_BASEURL + "control/command",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", contentType: "application/json; charset=UTF-8",
@@ -127,19 +127,11 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
var file = self.listHelper.getItem(function(item) {return item.name == filename}); var file = self.listHelper.getItem(function(item) {return item.name == filename});
if (!file) return; if (!file) return;
var origin;
if (file.origin === undefined) {
origin = "local";
} else {
origin = file.origin;
}
$.ajax({ $.ajax({
url: AJAX_BASEURL + "gcodefiles/" + origin + "/" + filename, url: AJAX_BASEURL + "gcodefiles/load",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: {filename: filename, print: printAfterLoad, target: file.origin}
data: JSON.stringify({command: "load", print: printAfterLoad})
}) })
} }
@@ -147,16 +139,11 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
var file = self.listHelper.getItem(function(item) {return item.name == filename}); var file = self.listHelper.getItem(function(item) {return item.name == filename});
if (!file) return; if (!file) return;
var origin;
if (file.origin === undefined) {
origin = "local";
} else {
origin = file.origin;
}
$.ajax({ $.ajax({
url: AJAX_BASEURL + "gcodefiles/" + origin + "/" + filename, url: AJAX_BASEURL + "gcodefiles/delete",
type: "DELETE", type: "POST",
dataType: "json",
data: {filename: filename, target: file.origin},
success: self.fromResponse success: self.fromResponse
}) })
} }
@@ -147,8 +147,7 @@ function PrinterStateViewModel(loginStateViewModel) {
url: AJAX_BASEURL + "control/job", url: AJAX_BASEURL + "control/job",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", data: {command: command}
data: JSON.stringify({command: command})
}); });
} }
} }
@@ -167,64 +167,47 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
self.setTempFromProfile = function(profile) { self.setTempFromProfile = function(profile) {
if (!profile) if (!profile)
return; return;
self._sendHotendCommand("temp", "hotend", profile.extruder); self._updateTemperature(profile.extruder, "temp");
} }
self.setTemp = function() { self.setTemp = function() {
self._sendHotendCommand("temp", "hotend", self.newTemp(), function() {self.targetTemp(self.newTemp()); self.newTemp("");}); self._updateTemperature(self.newTemp(), "temp", function(){self.targetTemp(self.newTemp()); self.newTemp("");});
}; };
self.setTempToZero = function() { self.setTempToZero = function() {
self._sendHotendCommand("temp", "hotend", 0, function() {self.targetTemp(0); self.newTemp("");}); self._updateTemperature(0, "temp", function(){self.targetTemp(0); self.newTemp("");});
} }
self.setTempOffset = function() { self.setTempOffset = function() {
self._sendHotendCommand("offset", "hotend", self.newTempOffset(), function() {self.tempOffset(self.newTempOffset()); self.newTempOffset("");}); self._updateTemperature(self.newTempOffset(), "tempOffset", function() {self.tempOffset(self.newTempOffset()); self.newTempOffset("");});
} }
self.setBedTempFromProfile = function(profile) { self.setBedTempFromProfile = function(profile) {
if (!profile) self._updateTemperature(profile.bed, "bedTemp");
return;
self._sendHotendCommand("temp", "bed", profile.bed);
} }
self.setBedTemp = function() { self.setBedTemp = function() {
self._sendHotendCommand("temp", "bed", self.newBedTemp(), function() {self.bedTargetTemp(self.newBedTemp()); self.newBedTemp("");}); self._updateTemperature(self.newBedTemp(), "bedTemp", function() {self.bedTargetTemp(self.newBedTemp()); self.newBedTemp("");});
}; };
self.setBedTempToZero = function() { self.setBedTempToZero = function() {
self._sendHotendCommand("temp", "bed", 0, function() {self.bedTargetTemp(0); self.newBedTemp("");}); self._updateTemperature(0, "bedTemp", function() {self.bedTargetTemp(0); self.newBedTemp("");});
} }
self.setBedTempOffset = function() { self.setBedTempOffset = function() {
self._sendHotendCommand("offset", "bed", self.newBedTempOffset(), function() {self.bedTempOffset(self.newBedTempOffset()); self.newBedTempOffset("");}); self._updateTemperature(self.newBedTempOffset(), "bedTempOffset", function() {self.bedTempOffset(self.newBedTempOffset()); self.newBedTempOffset("");});
} }
self._sendHotendCommand = function(command, type, temp, callback) { self._updateTemperature = function(temp, type, callback) {
var group; var data = {};
if ("temp" == command) { data[type] = temp;
group = "temps";
} else if ("offset" == command) {
group = "offsets";
} else {
return;
}
var data = {
"command": command
};
data[group] = {};
data[group][type] = parseInt(temp);
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/printer/hotend", url: AJAX_BASEURL + "control/temperature",
type: "POST", type: "POST",
dataType: "json", data: data,
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data),
success: function() { if (callback !== undefined) callback(); } success: function() { if (callback !== undefined) callback(); }
}); });
} }
self.handleEnter = function(event, type) { self.handleEnter = function(event, type) {
@@ -89,17 +89,18 @@ function TerminalViewModel(loginStateViewModel, settingsViewModel) {
} }
self.sendCommand = function() { self.sendCommand = function() {
/*
var re = /^([gm][0-9]+)(\s.*)?/;
var commandMatch = command.match(re);
if (commandMatch != null) {
command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : "");
}
*/
var command = self.command(); var command = self.command();
var re = /^([gm][0-9]+)(\s.*)?/;
var commandMatch = command.match(re);
if (commandMatch != null) {
command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : "");
}
if (command) { if (command) {
$.ajax({ $.ajax({
url: AJAX_BASEURL + "control/printer/command", url: AJAX_BASEURL + "control/command",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
contentType: "application/json; charset=UTF-8", contentType: "application/json; charset=UTF-8",
@@ -28,7 +28,6 @@ function UsersViewModel(loginStateViewModel) {
self.editorUsername = ko.observable(undefined); self.editorUsername = ko.observable(undefined);
self.editorPassword = ko.observable(undefined); self.editorPassword = ko.observable(undefined);
self.editorRepeatedPassword = ko.observable(undefined); self.editorRepeatedPassword = ko.observable(undefined);
self.editorApikey = ko.observable(undefined);
self.editorAdmin = ko.observable(undefined); self.editorAdmin = ko.observable(undefined);
self.editorActive = ko.observable(undefined); self.editorActive = ko.observable(undefined);
@@ -37,12 +36,10 @@ function UsersViewModel(loginStateViewModel) {
self.editorUsername(undefined); self.editorUsername(undefined);
self.editorAdmin(undefined); self.editorAdmin(undefined);
self.editorActive(undefined); self.editorActive(undefined);
self.editorApikey(undefined);
} else { } else {
self.editorUsername(newValue.name); self.editorUsername(newValue.name);
self.editorAdmin(newValue.admin); self.editorAdmin(newValue.admin);
self.editorActive(newValue.active); self.editorActive(newValue.active);
self.editorApikey(newValue.apikey);
} }
self.editorPassword(undefined); self.editorPassword(undefined);
self.editorRepeatedPassword(undefined); self.editorRepeatedPassword(undefined);
@@ -125,27 +122,6 @@ function UsersViewModel(loginStateViewModel) {
}); });
} }
self.confirmGenerateApikey = function() {
if (!CONFIG_ACCESS_CONTROL) return;
self.generateApikey(self.currentUser().name, function(response) {
self._updateApikey(response.apikey);
})
}
self.confirmDeleteApikey = function() {
if (!CONFIG_ACCESS_CONTROL) return;
self.deleteApikey(self.currentUser().name, function() {
self._updateApikey(undefined);
})
}
self._updateApikey = function(apikey) {
self.editorApikey(apikey);
self.requestData();
}
//~~ AJAX calls //~~ AJAX calls
self.addUser = function(user, callback) { self.addUser = function(user, callback) {
@@ -211,24 +187,4 @@ function UsersViewModel(loginStateViewModel) {
success: callback success: callback
}); });
} }
self.generateApikey = function(username, callback) {
if (!CONFIG_ACCESS_CONTROL) return;
$.ajax({
url: AJAX_BASEURL + "users/" + username + "/apikey",
type: "POST",
success: callback
});
}
self.deleteApikey = function(username, callback) {
if (!CONFIG_ACCESS_CONTROL) return;
$.ajax({
url: AJAX_BASEURL + "users/" + username + "/apikey",
type: "DELETE",
success: callback
});
}
} }
+5 -5
View File
@@ -210,18 +210,18 @@
<span class="btn btn-primary fileinput-button span6" data-bind="css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px"> <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> <i class="icon-upload-alt icon-white"></i>
<span>Upload</span> <span>Upload</span>
<input id="gcode_upload" type="file" name="gcode_file" class="fileinput-button" data-bind="enable: loginState.isUser()"> <input id="gcode_upload" type="file" name="gcode_file" class="fileinput-button" data-url="/ajax/gcodefiles/upload" data-bind="enable: loginState.isUser()">
</span> </span>
<span class="btn btn-primary fileinput-button span6" data-bind="css: {disabled: !$root.loginState.isUser() || !$root.isSdReady()}" style="margin-bottom: 10px"> <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> <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="gcode_file" class="fileinput-button" data-bind="enable: loginState.isUser() && isSdReady()"> <input id="gcode_upload_sd" type="file" name="gcode_file" class="fileinput-button" data-url="/ajax/gcodefiles/upload" data-bind="enable: loginState.isUser() && isSdReady()">
</span> </span>
{% else %} {% else %}
<span class="btn btn-primary fileinput-button span12" data-bind="css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px"> <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> <i class="icon-upload-alt icon-white"></i>
<span>Upload</span> <span>Upload</span>
<input id="gcode_upload" type="file" name="gcode_file" class="fileinput-button" data-bind="enable: loginState.isUser()"> <input id="gcode_upload" type="file" name="gcode_file" class="fileinput-button" data-url="/ajax/gcodefiles/upload" data-bind="enable: loginState.isUser()">
</span> </span>
{% endif %} {% endif %}
</div> </div>
@@ -352,7 +352,7 @@
</div> </div>
<div> <div>
<button class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('x',-1) }"><i class="icon-arrow-left"></i></button> <button class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('x',-1) }"><i class="icon-arrow-left"></i></button>
<button class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendHomeCommand(['x', 'y']) }"><i class="icon-home"></i></button> <button class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendHomeCommand('XY') }"><i class="icon-home"></i></button>
<button class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('x',1) }"><i class="icon-arrow-right"></i></button> <button class="btn box pull-left" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('x',1) }"><i class="icon-arrow-right"></i></button>
</div> </div>
<div> <div>
@@ -366,7 +366,7 @@
<button class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('z',1) }"><i class="icon-arrow-up"></i></button> <button class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('z',1) }"><i class="icon-arrow-up"></i></button>
</div> </div>
<div> <div>
<button class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendHomeCommand(['z']) }"><i class="icon-home"></i></button> <button class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendHomeCommand('Z') }"><i class="icon-home"></i></button>
</div> </div>
<div> <div>
<button class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('z',-1) }"><i class="icon-arrow-down"></i></button> <button class="btn box" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { $root.sendJogCommand('z',-1) }"><i class="icon-arrow-down"></i></button>
+1 -16
View File
@@ -382,7 +382,7 @@
</thead> </thead>
<tbody data-bind="foreach: users.listHelper.paginatedItems"> <tbody data-bind="foreach: users.listHelper.paginatedItems">
<tr> <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" data-bind="text: name"></td>
<td class="settings_users_active"><i data-bind="css: { 'icon-check': active, 'icon-check-empty': !active }"></i></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_admin"><i data-bind="css: { 'icon-check': admin, 'icon-check-empty': !admin }"></i></td>
<td class="settings_users_actions" class="system_users_action"> <td class="settings_users_actions" class="system_users_action">
@@ -504,20 +504,6 @@
<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> </div>
<fieldset data-bind="visible: api_enabled">
<legend>Apikey</legend>
<div class="control-group">
<label class="control-label">Current Apikey</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'}">
<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>
</div>
</div>
</fieldset>
</form> </form>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
@@ -525,7 +511,6 @@
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">Confirm</button> <button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">Confirm</button>
</div> </div>
</div> </div>
</div> </div>
{% endif %} {% endif %}
+12 -51
View File
@@ -7,7 +7,6 @@ from flask.ext.principal import Identity
import hashlib import hashlib
import os import os
import yaml import yaml
import uuid
from octoprint.settings import settings from octoprint.settings import settings
@@ -71,10 +70,7 @@ class FilebasedUserManager(UserManager):
data = yaml.safe_load(f) data = yaml.safe_load(f)
for name in data.keys(): for name in data.keys():
attributes = data[name] attributes = data[name]
apikey = None self._users[name] = User(name, attributes["password"], attributes["active"], attributes["roles"])
if "apikey" in attributes:
apikey = attributes["apikey"]
self._users[name] = User(name, attributes["password"], attributes["active"], attributes["roles"], apikey)
else: else:
self._customized = False self._customized = False
@@ -88,8 +84,7 @@ class FilebasedUserManager(UserManager):
data[name] = { data[name] = {
"password": user._passwordHash, "password": user._passwordHash,
"active": user._active, "active": user._active,
"roles": user._roles, "roles": user._roles
"apikey": user._apikey
} }
with open(self._userfile, "wb") as f: with open(self._userfile, "wb") as f:
@@ -97,11 +92,11 @@ class FilebasedUserManager(UserManager):
self._dirty = False self._dirty = False
self._load() self._load()
def addUser(self, username, password, active=False, roles=["user"], apikey=None): def addUser(self, username, password, active=False, roles=["user"]):
if username in self._users.keys(): if username in self._users.keys():
raise UserAlreadyExists(username) raise UserAlreadyExists(username)
self._users[username] = User(username, UserManager.createPasswordHash(password), active, roles, apikey) self._users[username] = User(username, UserManager.createPasswordHash(password), active, roles)
self._dirty = True self._dirty = True
self._save() self._save()
@@ -159,25 +154,6 @@ class FilebasedUserManager(UserManager):
self._dirty = True self._dirty = True
self._save() self._save()
def generateApiKey(self, username):
if not username in self._users.keys():
raise UnknownUser(username)
user = self._users[username]
user._apikey = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
self._dirty = True
self._save()
return user._apikey
def deleteApikey(self, username):
if not username in self._users.keys():
raise UnknownUser(username)
user = self._users[username]
user._apikey = None
self._dirty = True
self._save()
def removeUser(self, username): def removeUser(self, username):
if not username in self._users.keys(): if not username in self._users.keys():
raise UnknownUser(username) raise UnknownUser(username)
@@ -186,20 +162,15 @@ class FilebasedUserManager(UserManager):
self._dirty = True self._dirty = True
self._save() self._save()
def findUser(self, username=None, apikey=None): def findUser(self, username=None):
if username is not None: if username is None:
if username not in self._users.keys(): return None
return None
return self._users[username] if username not in self._users.keys():
elif apikey is not None:
for user in self._users.values():
if apikey == user._apikey:
return user
return None
else:
return None return None
return self._users[username]
def getAllUsers(self): def getAllUsers(self):
return map(lambda x: x.asDict(), self._users.values()) return map(lambda x: x.asDict(), self._users.values())
@@ -223,20 +194,18 @@ class UnknownRole(Exception):
##~~ User object ##~~ User object
class User(UserMixin): class User(UserMixin):
def __init__(self, username, passwordHash, active, roles, apikey=None): def __init__(self, username, passwordHash, active, roles):
self._username = username self._username = username
self._passwordHash = passwordHash self._passwordHash = passwordHash
self._active = active self._active = active
self._roles = roles self._roles = roles
self._apikey = apikey
def asDict(self): def asDict(self):
return { return {
"name": self._username, "name": self._username,
"active": self.is_active(), "active": self.is_active(),
"admin": self.is_admin(), "admin": self.is_admin(),
"user": self.is_user(), "user": self.is_user()
"apikey": self._apikey
} }
def check_password(self, passwordHash): def check_password(self, passwordHash):
@@ -272,11 +241,3 @@ class DummyIdentity(Identity):
def dummy_identity_loader(): def dummy_identity_loader():
return DummyIdentity() return DummyIdentity()
##~~ Apiuser object to use when api key is used to access the API
class ApiUser(User):
def __init__(self):
User.__init__(self, "api", "", True, UserManager.valid_roles)
-18
View File
@@ -8,7 +8,6 @@ import sys
import time import time
import re import re
import tempfile import tempfile
from flask import make_response
from octoprint.settings import settings from octoprint.settings import settings
@@ -189,20 +188,3 @@ def silentRemove(file):
os.remove(file) os.remove(file)
except OSError: except OSError:
pass pass
def getJsonCommandFromRequest(request, valid_commands):
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
data = request.json
if not "command" in data.keys() or not data["command"] in valid_commands.keys():
return None, None, make_response("Expected valid command", 400)
command = data["command"]
for parameter in valid_commands[command]:
if not parameter in data:
return None, None, make_response("Mandatory parameter %s missing for command %s" % (parameter, command), 400)
return command, data, None
+1 -4
View File
@@ -291,9 +291,6 @@ class MachineCom(object):
def getOffsets(self): def getOffsets(self):
return (self._tempOffset, self._bedTempOffset) return (self._tempOffset, self._bedTempOffset)
def getConnection(self):
return self._port, self._baudrate
##~~ external interface ##~~ external interface
def close(self, isError = False): def close(self, isError = False):
@@ -829,8 +826,8 @@ class MachineCom(object):
self._sendCommand("M29") self._sendCommand("M29")
filename = self._currentFile.getFilename() filename = self._currentFile.getFilename()
self._currentFile = None self._currentFile = None
self._callback.mcFileTransferDone()
self._changeState(self.STATE_OPERATIONAL) self._changeState(self.STATE_OPERATIONAL)
self._callback.mcFileTransferDone(filename)
eventManager().fire("TransferDone", filename) eventManager().fire("TransferDone", filename)
self.refreshSdFiles() self.refreshSdFiles()
else: else: