Beispiel #1
0
def handleWifiHotspot():
    nm = networkManager()
    if request.method == "GET":
        return jsonify({
            'hotspot': {
                'active':
                nm.isHotspotActive(),
                'name':
                nm.getHostname(),
                'hotspotOnlyOffline':
                settings().getBoolean(['wifi', 'hotspotOnlyOffline'])
            } if nm.isHotspotable() else False
        })

    elif request.method == "PUT":
        if "application/json" in request.headers["Content-Type"]:
            data = request.json

            if "hotspotOnlyOffline" in data:
                s = settings()
                s.setBoolean(['wifi', 'hotspotOnlyOffline'],
                             data["hotspotOnlyOffline"])
                s.save()
                return jsonify()

        return ("Invalid Request", 400)

    elif request.method == "DELETE":
        result = networkManager().stopHotspot()
        if result is True:
            return jsonify()
        else:
            return (result, 500)
Beispiel #2
0
def index():
    s = settings()
    loggedUsername = s.get(["cloudSlicer", "loggedUser"])

    if (s.getBoolean(["server", "firstRun"])):
        # we need to get the user to sign into their AstroPrint account
        return render_template("setup.jinja2",
                               debug=debug,
                               uiApiKey=UI_API_KEY,
                               version=VERSION,
                               variantData=variantManager().data,
                               astroboxName=networkManager().getHostname(),
                               settings=s)

    elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
        return render_template(
            "updating.jinja2",
            uiApiKey=UI_API_KEY,
            showForceUpdate=softwareManager.forceUpdateInfo != None,
            releaseInfo=softwareManager.updatingRelease
            or softwareManager.forceUpdateInfo,
            lastCompletionPercent=softwareManager.lastCompletionPercent,
            lastMessage=softwareManager.lastMessage,
            variantData=variantManager().data,
            astroboxName=networkManager().getHostname())

    elif loggedUsername and (current_user is None
                             or not current_user.is_authenticated()
                             or current_user.get_id() != loggedUsername):
        if current_user.is_authenticated():
            logout_user()

        return render_template("locked.jinja2",
                               username=loggedUsername,
                               uiApiKey=UI_API_KEY,
                               astroboxName=networkManager().getHostname(),
                               variantData=variantManager().data)

    else:
        pm = printerManager()
        nm = networkManager()

        paused = pm.isPaused()
        printing = pm.isPrinting()
        online = nm.isOnline()

        return render_template("app.jinja2",
                               user_email=loggedUsername,
                               version=VERSION,
                               printing=printing,
                               paused=paused,
                               online=online,
                               print_capture=cameraManager().timelapseInfo
                               if printing or paused else None,
                               printer_profile=printerProfileManager().data,
                               uiApiKey=UI_API_KEY,
                               astroboxName=nm.getHostname(),
                               variantData=variantManager().data,
                               serialLogActive=s.getBoolean(['serial', 'log']))
Beispiel #3
0
def resetFactorySettings():
    from astroprint.cloud import astroprintCloud
    from shutil import copy

    logger = logging.getLogger(__name__)
    logger.warning("Executing a Restore Factory Settings operation")

    #We log out first
    astroprintCloud().signout()

    s = settings()

    emptyFolder(s.get(['folder', 'uploads']) or s.getBaseFolder('uploads'))
    emptyFolder(s.get(['folder', 'timelapse']) or s.getBaseFolder('timelapse'))
    emptyFolder(
        s.get(['folder', 'timelapse_tmp']) or s.getBaseFolder('timelapse_tmp'))
    emptyFolder(s.get(['folder', 'virtualSd']) or s.getBaseFolder('virtualSd'))

    networkManager().forgetWifiNetworks()

    configFolder = s.getConfigFolder()

    #replace config.yaml with config.factory
    config_file = s._configfile
    config_factory = os.path.join(configFolder, "config.factory")
    if config_file and os.path.exists(config_file):
        if os.path.exists(config_factory):
            copy(config_factory, config_file)
        else:
            os.unlink(config_file)

    #replace printer-profile.yaml with printer-profile.factory
    p_profile_file = os.path.join(configFolder, "printer-profile.yaml")
    p_profile_factory = os.path.join(configFolder, "printer-profile.factory")
    if os.path.exists(p_profile_file):
        if os.path.exists(p_profile_factory):
            copy(p_profile_factory, p_profile_file)
        else:
            os.unlink(p_profile_file)

    #remove info about users
    user_file = s.get(["accessControl", "userfile"]) or os.path.join(
        configFolder, "users.yaml")
    if user_file and os.path.exists(user_file):
        os.unlink(user_file)

    logger.info("Restore completed, rebooting...")

    #We should reboot the whole device
    if softwareManager.restartServer():
        return jsonify()
    else:
        return ("There was an error rebooting.", 500)
Beispiel #4
0
	def _doRetry(self, silent=True):
		if self._retries < self.MAX_RETRIES:
			def retry():
				self._retries += 1
				self._logger.info('Retrying boxrouter connection. Retry #%d' % self._retries)
				self._silentReconnect = silent
				self.boxrouter_connect()

			threading.Timer(self.START_WAIT_BETWEEN_RETRIES * self.WAIT_MULTIPLIER_BETWEEN_RETRIES * (self._retries - 1) , retry ).start()

		else:
			self._logger.info('No more retries. Giving up...')
			self.status = self.STATUS_DISCONNECTED
			self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status);
			self._retries = 0

			#Are we offline?
			nm = networkManager()
			if not nm.checkOnline() and nm.isHotspotActive() is False: #isHotspotActive will return None if not possible
				#get the box hotspot up
				self._logger.info('AstroBox is offline. Starting hotspot...')
				result = nm.startHotspot()
				if result is True:
					self._logger.info('Hostspot started.')
				else:
					self._logger.error('Failed to start hostspot: %s' % result)
Beispiel #5
0
    def _ssdp_register(self):
        """
		Registers the AstroPrint instance as basic service with a presentation URL pointing to the web interface
		"""

        if self._ssdp_monitor_active:
            return

        time_since_last_unregister = time.time() - self._ssdp_last_unregister

        if time_since_last_unregister < (self._ssdp_notify_timeout + 1):
            wait_seconds = (self._ssdp_notify_timeout +
                            1) - time_since_last_unregister
            self.logger.info(
                "Waiting %s seconds before starting SSDP Service..." %
                wait_seconds)
            time.sleep(wait_seconds)

            #Make sure that the network is still after the wait
            if not networkManager().isOnline():
                return

        self._ssdp_monitor_active = True

        self._ssdp_monitor_thread = threading.Thread(
            target=self._ssdp_monitor,
            kwargs=dict(timeout=self._ssdp_notify_timeout))
        self._ssdp_monitor_thread.daemon = True
        self._ssdp_monitor_thread.start()
Beispiel #6
0
	def getStatus(self):
		printer = printerManager()
		cm = cameraManager()
		ppm = printerProfileManager()

		fileName = None

		if printer.isPrinting():
			currentJob = printer.getCurrentJob()
			fileName = currentJob["file"]["name"]

		return {
				'id': boxrouterManager().boxId,
				'name': networkManager().getHostname(),
				'printing': printer.isPrinting(),
				'fileName': fileName,
				'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None,
				'filament' : ppm.data['filament'],
				'material': None,
				'operational': printer.isOperational(),
				'paused': printer.isPaused(),
				'camera': cm.isCameraConnected(),
				#'printCapture': cm.timelapseInfo,
				'remotePrint': True,
				'capabilities': ['remotePrint'] + cm.capabilities
			}
Beispiel #7
0
    def wifiNetworks(self, data, sendMessage):
        networks = networkManager().getWifiNetworks()

        if networks:
            sendMessage(networks)
        else:
            sendMessage("unable_get_wifi_networks", True)
Beispiel #8
0
    def networkName(self, newName, sendMessage):
        nm = networkManager()

        if newName:
            nm.setHostname(newName)

        sendMessage({'name': nm.getHostname()})
Beispiel #9
0
def deleteStoredWiFiNetwork(networkId):
    nm = networkManager()

    if nm.deleteStoredWifiNetwork(networkId):
        return jsonify()
    else:
        return ("Network Not Found", 404)
Beispiel #10
0
    def processAuthenticate(self, data):
        if data:
            self._silentReconnect = False

            if 'error' in data:
                self._logger.warn(data['message'] if 'message' in
                                  data else 'Unkonwn authentication error')
                self.status = self.STATUS_ERROR
                self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
                self.close()
                if 'should_retry' in data and data['should_retry']:
                    self._doRetry()

            elif 'success' in data:
                self._logger.info("Connected to astroprint service")
                self.authenticated = True
                self._retries = 0
                self._retryTimer = None
                self.status = self.STATUS_CONNECTED
                self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

            return None

        else:
            from octoprint.server import VERSION
            from astroprint.printerprofile import printerProfileManager

            nm = networkManager()
            sm = softwareManager()
            ppm = printerProfileManager()

            authData = {
                'silentReconnect':
                self._silentReconnect,
                'boxId':
                self.boxId,
                'variantId':
                sm.variant['id'],
                'boxName':
                nm.getHostname(),
                'swVersion':
                VERSION,
                'platform':
                sm.platform,
                'localIpAddress':
                nm.activeIpAddress,
                'publicKey':
                self._publicKey,
                'privateKey':
                self._privateKey,
                'printerModel':
                ppm.data['printer_model']
                if ppm.data['printer_model']['id'] else None
            }

            pkgId = sm.mfPackageId
            if pkgId:
                authData['mfPackageId'] = pkgId

            return {'type': 'auth', 'data': authData}
Beispiel #11
0
def getWifiNetworks():
    networks = networkManager().getWifiNetworks()

    if networks:
        return jsonify(networks=networks)
    else:
        return jsonify({'message': "Unable to get WiFi networks"})
Beispiel #12
0
	def wifiNetworks(self, data, sendMessage):
		networks = networkManager().getWifiNetworks()

		if networks:
			sendMessage(networks)
		else:
			sendMessage("unable_get_wifi_networks",True)
Beispiel #13
0
	def networkName(self, newName, sendMessage):
		nm = networkManager()

		if newName :
				nm.setHostname(newName)

		sendMessage({'name':nm.getHostname()})
Beispiel #14
0
def getNetworkSettings():
    nm = networkManager()

    return jsonify({
        'networks': nm.getActiveConnections(),
        'hasWifi': nm.hasWifi()
    })
Beispiel #15
0
	def deleteStoredWiFiNetwork(self, data, sendMessage):
		nm = networkManager()

		if nm.deleteStoredWifiNetwork(data['id']):
			sendMessage({'success': 'no_error'})
		else:
			sendMessage("network_not_found",True)
Beispiel #16
0
    def boxrouter_connect(self):
        if not networkManager().isOnline():
            return False

        if not self.connected:
            from octoprint.server import userManager

            loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
            if loggedUser and userManager:
                user = userManager.findUser(loggedUser)

                if user:
                    self._publicKey = user.publicKey
                    self._privateKey = user.privateKey

                    if self._publicKey and self._privateKey:
                        self.status = self.STATUS_CONNECTING
                        self._eventManager.fire(Events.ASTROPRINT_STATUS,
                                                self.status)

                        try:
                            self._ws = AstroprintBoxRouterClient(
                                self._address, self)
                            self._ws.connect()
                            self.connected = True

                        except Exception as e:
                            self._logger.error(
                                "Error connecting to boxrouter: %s" % e)
                            self._doRetry(
                                False)  #This one should not be silent

                        return True

        return False
Beispiel #17
0
    def _doRetry(self, silent=True):
        if self._retries < self.MAX_RETRIES:
            self._retries += 1
            sleep(self.START_WAIT_BETWEEN_RETRIES *
                  self.WAIT_MULTIPLIER_BETWEEN_RETRIES * (self._retries - 1))
            self._logger.info('Retrying boxrouter connection. Retry #%d' %
                              self._retries)
            self._silentReconnect = silent
            self.boxrouter_connect()

        else:
            self._logger.info('No more retries. Giving up...')
            self.status = self.STATUS_DISCONNECTED
            self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
            self._retries = 0

            #Are we offline?
            nm = networkManager()
            if not nm.checkOnline() and nm.isHotspotActive(
            ) is False:  #isHotspotActive will return None if not possible
                #get the box hotspot up
                self._logger.info('AstroBox is offline. Starting hotspot...')
                result = nm.startHotspot()
                if result is True:
                    self._logger.info('Hostspot started.')
                else:
                    self._logger.error('Failed to start hostspot: %s' % result)
Beispiel #18
0
    def deleteStoredWiFiNetwork(self, data, sendMessage):
        nm = networkManager()

        if nm.deleteStoredWifiNetwork(data['id']):
            sendMessage({'success': 'no_error'})
        else:
            sendMessage("network_not_found", True)
Beispiel #19
0
    def signin(self, email, password, hasSessionContext=True):
        from octoprint.server import userManager
        from astroprint.network.manager import networkManager
        user = None
        userLoggedIn = False

        online = networkManager().isOnline()

        if online:
            private_key = self.get_private_key(email, password)

            if private_key:
                public_key = self.get_public_key(email, private_key)

                if public_key:
                    #Let's protect the box now:
                    user = userManager.findUser(email)

                    if user:
                        userManager.changeUserPassword(email, password)
                        userManager.changeCloudAccessKeys(
                            email, public_key, private_key)
                    else:
                        user = userManager.addUser(email, password, public_key,
                                                   private_key, True)

                    userLoggedIn = True

        else:
            user = userManager.findUser(email)
            userLoggedIn = user and user.check_password(
                userManager.createPasswordHash(password))

        if userLoggedIn:
            if hasSessionContext:
                login_user(user, remember=True)

            userId = user.get_id()

            self.settings.set(["cloudSlicer", "loggedUser"], userId)
            self.settings.save()

            boxrouterManager().boxrouter_connect()

            if hasSessionContext:
                identity_changed.send(current_app._get_current_object(),
                                      identity=Identity(userId))

            #let the singleton be recreated again, so new credentials are taken into use
            global _instance
            _instance = None

            eventManager().fire(Events.LOCK_STATUS_CHANGED, userId)

            return True

        elif not online:
            raise AstroPrintCloudNoConnectionException()

        return False
Beispiel #20
0
def getStatus():
	printer = printerManager()
	cm = cameraManager()
	softwareManager = swManager()
	ppm = printerProfileManager()

	fileName = None

	if printer.isPrinting():
		currentJob = printer.getCurrentJob()
		fileName = currentJob["file"]["name"]

	return Response(
		json.dumps({
			'id': boxrouterManager().boxId,
			'name': networkManager().getHostname(),
			'printing': printer.isPrinting(),
			'fileName': fileName,
			'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None,
			'filament' : ppm.data['filament'],
			'material': None,
			'operational': printer.isOperational(),
			'paused': printer.isPaused(),
			'camera': cm.isCameraConnected(),
			#'printCapture': cm.timelapseInfo,
			'remotePrint': True,
			'capabilities': softwareManager.capabilities() + cm.capabilities
		}),
		mimetype= 'application/json',
		headers= {
			'Access-Control-Allow-Origin': '*'
		} if settings().getBoolean(['api', 'allowCrossOrigin']) else None
	)
Beispiel #21
0
def getNetworkSettings():
    nm = networkManager()

    return jsonify({
        'networks': nm.getActiveConnections(),
        'hasWifi': bool(nm.getWifiDevice())
    })
Beispiel #22
0
	def _doRetry(self, silent=True):
		if self._retries < len(self.RETRY_SCHEDULE):
			def retry():
				self._retries += 1
				self._logger.info('Retrying boxrouter connection. Retry #%d' % self._retries)
				self._silentReconnect = silent
				self._retryTimer = None
				self.boxrouter_connect()

			if not self._retryTimer:
				self._logger.info('Waiting %d secs before retrying...' % self.RETRY_SCHEDULE[self._retries])
				self._retryTimer = threading.Timer(self.RETRY_SCHEDULE[self._retries] , retry )
				self._retryTimer.start()

		else:
			self._logger.info('No more retries. Giving up...')
			self.status = self.STATUS_DISCONNECTED
			self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
			self._retries = 0
			self._retryTimer = None

			#Are we offline?
			nm = networkManager()
			if not nm.checkOnline() and nm.isHotspotActive() is False: #isHotspotActive will return None if not possible
				#get the box hotspot up
				self._logger.info('AstroBox is offline. Starting hotspot...')
				result = nm.startHotspot()
				if result is True:
					self._logger.info('Hostspot started.')
				else:
					self._logger.error('Failed to start hostspot: %s' % result)
Beispiel #23
0
def stopWifiHotspot():
    result = networkManager().stopHotspot()

    if result is True:
        return jsonify()
    else:
        return (result, 500)
Beispiel #24
0
def startWifiHotspot():
	result = networkManager().startHotspot()

	if result is True:
		return jsonify()
	else:
		return (result, 500)
Beispiel #25
0
def getNetworkSettings():
	nm = networkManager()

	return jsonify({
		'networks': nm.getActiveConnections(),
		'hasWifi': bool(nm.getWifiDevice())
	})
Beispiel #26
0
	def boxrouter_connect(self):
		if not networkManager().isOnline():
			return False

		if not self.connected:
			from octoprint.server import userManager
			
			loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
			if loggedUser and userManager:
				user = userManager.findUser(loggedUser)

				if user:
					self._publicKey = user.publicKey
					self._privateKey = user.privateKey

					if self._publicKey and self._privateKey:
						self.status = self.STATUS_CONNECTING
						self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status);

						try:
							self._ws = AstroprintBoxRouterClient(self._address, self)
							self._ws.connect()
							self.connected = True

						except Exception as e:
							self._logger.error("Error connecting to boxrouter: %s" % e)
							self._doRetry(False) #This one should not be silent

						return True

		return False
Beispiel #27
0
def getWifiNetworks():
	networks = networkManager().getWifiNetworks()

	if networks:
		return jsonify(networks = networks)
	else:
		return jsonify({'message': "Unable to get WiFi networks"})
Beispiel #28
0
	def _doRetry(self, silent=True):
		if self._retries < len(self.RETRY_SCHEDULE):
			def retry():
				self._retries += 1
				self._logger.info('Retrying boxrouter connection. Retry #%d' % self._retries)
				self._silentReconnect = silent
				self._retryTimer = None
				self.boxrouter_connect()

			if not self._retryTimer:
				self._logger.info('Waiting %d secs before retrying...' % self.RETRY_SCHEDULE[self._retries])
				self._retryTimer = threading.Timer(self.RETRY_SCHEDULE[self._retries] , retry )
				self._retryTimer.start()

		else:
			self._logger.info('No more retries. Giving up...')
			self.status = self.STATUS_DISCONNECTED
			self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
			self._retries = 0
			self._retryTimer = None

			#Are we offline?
			nm = networkManager()
			if not nm.checkOnline() and nm.isHotspotActive() is False: #isHotspotActive will return None if not possible
				#get the box hotspot up
				self._logger.info('AstroBox is offline. Starting hotspot...')
				result = nm.startHotspot()
				if result is True:
					self._logger.info('Hostspot started.')
				else:
					self._logger.error('Failed to start hostspot: %s' % result)
Beispiel #29
0
    def networkSettings(self, data, sendMessage):
        nm = networkManager()

        sendMessage({
            'networks': nm.getActiveConnections(),
            'hasWifi': nm.hasWifi(),
            'storedWifiNetworks': nm.storedWifiNetworks()
        })
Beispiel #30
0
def getNetworkSettings():
    nm = networkManager()

    return jsonify({
        'networks': nm.getActiveConnections(),
        'networkDeviceInfo': nm.networkDeviceInfo,
        'hasWifi': nm.hasWifi(),
        'storedWifiNetworks': nm.storedWifiNetworks()
    })
Beispiel #31
0
	def networkSettings(self, data, sendMessage):
		nm = networkManager()

		sendMessage({
			'networks': nm.getActiveConnections(),
			'hasWifi': nm.hasWifi(),
			'networkDeviceInfo': nm.networkDeviceInfo,
			'storedWifiNetworks': nm.storedWifiNetworks()
		})
Beispiel #32
0
	def signin(self, email, password, hasSessionContext = True):
		from octoprint.server import userManager
		from astroprint.network.manager import networkManager
		user = None
		userLoggedIn = False

		online = networkManager().isOnline()

		if online:
			private_key = self.get_private_key(email, password)

			if private_key:
				public_key = self.get_public_key(email, private_key)

				if public_key:
					#Let's protect the box now:
					user = userManager.findUser(email)

					if user:
						userManager.changeUserPassword(email, password)
						userManager.changeCloudAccessKeys(email, public_key, private_key)
					else:
						user = userManager.addUser(email, password, public_key, private_key, True)

					userLoggedIn = True

		else:
			user = userManager.findUser(email)
			userLoggedIn = user and user.check_password(userManager.createPasswordHash(password))

		if userLoggedIn:
			if hasSessionContext:
				login_user(user, remember=True)

			userId = user.get_id()

			self.settings.set(["cloudSlicer", "loggedUser"], userId)
			self.settings.save()

			boxrouterManager().boxrouter_connect()

			if hasSessionContext:
				identity_changed.send(current_app._get_current_object(), identity=Identity(userId))

			#let the singleton be recreated again, so new credentials are taken into use
			global _instance
			_instance = None

			eventManager().fire(Events.LOCK_STATUS_CHANGED, userId)

			return True

		elif not online:
			raise AstroPrintCloudNoConnectionException()

		return False
Beispiel #33
0
def handleNetworkName():
    nm = networkManager()

    if request.method == "POST":
        if "application/json" in request.headers["Content-Type"]:
            data = request.json
            nm.setHostname(data['name'])
        else:
            return ("Invalid Request", 400)
    return jsonify(name=nm.getHostname())
Beispiel #34
0
    def boxrouter_connect(self):
        if not networkManager().isOnline():
            return False

        if not self.connected:
            from octoprint.server import userManager

            loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
            if loggedUser and userManager:
                user = userManager.findUser(loggedUser)

                if user and user.is_authenticated:
                    self._publicKey = user.publicKey
                    self._privateKey = user.privateKey

                    if self._publicKey and self._privateKey:
                        self.status = self.STATUS_CONNECTING
                        self._eventManager.fire(Events.ASTROPRINT_STATUS,
                                                self.status)

                        try:
                            if self._retryTimer:
                                #This is in case the user tried to connect and there was a pending retry
                                self._retryTimer.cancel()
                                self._retryTimer = None
                                #If it fails, the retry sequence should restart
                                self._retries = 0

                            if self._ws and not self._ws.terminated:
                                self._ws.terminate()

                            self._ws = AstroprintBoxRouterClient(
                                self._address, self)
                            self._ws.connect()
                            self.connected = True

                        except Exception as e:
                            self._logger.error(
                                "Error connecting to boxrouter [%s]: %s" %
                                (self._address, e))
                            self.connected = False
                            self.status = self.STATUS_ERROR
                            self._eventManager.fire(Events.ASTROPRINT_STATUS,
                                                    self.status)

                            if self._ws:
                                self._ws.terminate()
                                self._ws = None

                            self._doRetry(
                                False)  #This one should not be silent

                        return True

        return False
Beispiel #35
0
def setWifiNetwork():
	if "application/json" in request.headers["Content-Type"]:
		data = request.json
		result = networkManager().setWifiNetwork(data['id'], data['password'])

		if result:
			return jsonify(result)
		else:
			return ("Network %s not found" % data['id'], 404)

	return ("Invalid Request", 400)
Beispiel #36
0
def setWifiNetwork():
    if "application/json" in request.headers["Content-Type"]:
        data = request.json
        if 'id' in data:
            result = networkManager().setWifiNetwork(data['id'],
                                                     data.get('password'))
            if result:
                return jsonify(result)
            else:
                return ("Network %s not found" % data['id'], 404)
    return ("Invalid Request", 400)
Beispiel #37
0
    def processAuthenticate(self, data):
        if data:
            self._silentReconnect = False

            if 'error' in data:
                self._logger.warn(data['message'] if 'message' in
                                  data else 'Unkonwn authentication error')
                self.status = self.STATUS_ERROR
                self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
                self.close()

            elif 'success' in data:
                self._logger.info("Connected to astroprint service")
                self.authenticated = True
                self._retries = 0
                self._retryTimer = None
                self.status = self.STATUS_CONNECTED
                self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

            return None

        else:
            from octoprint.server import VERSION

            nm = networkManager()

            activeConnections = nm.getActiveConnections()

            if activeConnections and (
                activeConnections['wired'] or activeConnections['wireless'] \
                or activeConnections['manual']):
                preferredConn = (activeConnections['wired'] or \
                                 activeConnections['wireless'] or \
                                 activeConnections['manual'])
                localIpAddress = preferredConn['ip']
            else:
                localIpAddress = None

            sm = softwareManager()

            return {
                'type': 'auth',
                'data': {
                    'silentReconnect': self._silentReconnect,
                    'boxId': self.boxId,
                    'variantId': sm.variant['id'],
                    'boxName': nm.getHostname(),
                    'swVersion': VERSION,
                    'platform': sm.platform,
                    'localIpAddress': localIpAddress,
                    'publicKey': self._publicKey,
                    'privateKey': self._privateKey
                }
            }
Beispiel #38
0
def box_identify():
    br = boxrouterManager()
    nm = networkManager()

    return Response(
        json.dumps({
            'id': br.boxId,
            'name': nm.getHostname(),
            'version': VERSION
        }),
        headers={'Access-Control-Allow-Origin': '*'}
        if settings().getBoolean(['api', 'allowCrossOrigin']) else None)
Beispiel #39
0
def sslSettings():
    nm = networkManager()
    sslm = nm.sslManager
    s = settings()

    if request.method == 'POST':
        if "application/json" in request.headers["Content-Type"]:
            data = request.json
            action = data.get('action')

            if action == 'toggle':
                if sslm.isSslActive():
                    sslm.disable()
                else:
                    sslm.enable()
                    if not s.get(['network', 'ssl', 'domain']):
                        ips = [
                            v.get('ip')
                            for _, v in nm.getActiveConnections().items()
                            if v is not None
                        ]
                        if len(ips) > 0:
                            s.set(['network', 'ssl', 'domain'],
                                  "%s.xip.astroprint.com" %
                                  ips[0].split(':')[0].replace('.', '-'))
                            s.save()

                return jsonify(True)

            elif action == 'save':
                values = data.get('values')
                if values:
                    domain = values.get('domain')
                    s.set(['network', 'ssl', 'domain'], domain)
                    s.save()

                    return jsonify(True)

        return ("Invalid Request", 400)

    else:
        ips = [
            v.get('ip') for _, v in nm.getActiveConnections().items()
            if v is not None
        ]
        domains = set([
            '%s.xip.astroprint.com' % (i.split(':')[0].replace('.', '-'))
            for i in ips if i is not None
        ] + ['%s.ssl.local' % nm.getHostname()])

        return jsonify(enabled=sslm.isSslActive(),
                       active_domain=sslm.getDomain(),
                       domains=list(domains))
Beispiel #40
0
def check_internet():
	nm = networkManager()

	if nm.isAstroprintReachable():
		return jsonify(connected = True)
	else:
		networks = nm.getWifiNetworks()

		if networks:
			return jsonify(networks = networks, connected = False)
		else:
			return make_response("Unable to get WiFi networks", 500)
Beispiel #41
0
def connect_internet():
	if "application/json" in request.headers["Content-Type"]:
		data = request.json
		if 'id' in data and 'password' in data:
			result = networkManager().setWifiNetwork(data['id'], data['password'])

			if result:
				return jsonify(result)
			else:
				return make_response("Network %s not found" % data['id'], 404)

	return make_response("Invalid Request", 400)
Beispiel #42
0
def check_internet():
    nm = networkManager()

    if nm.isAstroprintReachable():
        return jsonify(connected=True)
    else:
        networks = nm.getWifiNetworks()

        if networks:
            return jsonify(networks=networks, connected=False)
        else:
            return make_response("Unable to get WiFi networks", 500)
Beispiel #43
0
    def validatePassword(self, email, password):
        from octoprint.server import userManager
        from astroprint.network.manager import networkManager
        user = None
        userValidated = False

        online = networkManager().isOnline()

        if online:
            try:
                private_key = self.get_private_key(email, password)

                if private_key:
                    public_key = self.get_public_key(email, private_key)

                    if public_key:
                        #Let's update the box now:
                        user = userManager.findUser(email)
                        if user:
                            userManager.changeUserPassword(email, password)
                            userManager.changeCloudAccessKeys(
                                email, public_key, private_key)
                        else:
                            user = userManager.addUser(email, password,
                                                       public_key, private_key,
                                                       True)

                        userValidated = True

                    else:
                        return False

                else:
                    return False

            except ConnectionError as e:
                self._logger.error(
                    'Connection error when trying to validate password: %s' %
                    e)

        # was offline or couldn't reach astroprint.com
        if not userValidated:
            user = userManager.findUser(email)
            userValidated = user and user.check_password(
                userManager.createPasswordHash(password))

        if userValidated:
            userId = user.get_id()
            self.settings.set(["cloudSlicer", "loggedUser"], userId)
            self.settings.save()

        return userValidated
Beispiel #44
0
def handleNetworkName():
	nm = networkManager()

	if request.method == "POST":
		if "application/json" in request.headers["Content-Type"]:
			data = request.json

			nm.setHostname(data['name'])

		else:
			return ("Invalid Request", 400)

	return jsonify(name=nm.getHostname())
Beispiel #45
0
def save_name():
    name = request.values.get('name', None)

    if not name or not re.search(r"^[a-zA-Z0-9\-_]+$", name):
        return make_response('Invalid Name', 400)
    else:
        if platform == "linux" or platform == "linux2":
            if networkManager().setHostname(name):
                return jsonify()
            else:
                return (500, "There was an error saving the hostname")
        else:
            return NO_CONTENT
Beispiel #46
0
def handleWifiHotspot():
	nm = networkManager()

	if request.method == "GET":
		return jsonify({
			'hotspot': {
				'active': nm.isHotspotActive(),
				'name': nm.getHostname(),
				'hotspotOnlyOffline': settings().getBoolean(['wifi', 'hotspotOnlyOffline'])	
			} if nm.isHotspotable() else False
		})

	elif request.method == "PUT":
		if "application/json" in request.headers["Content-Type"]:
			data = request.json

			if "hotspotOnlyOffline" in data:
				s = settings()
				s.setBoolean(['wifi', 'hotspotOnlyOffline'], data["hotspotOnlyOffline"])
				s.save()
				return jsonify()

		return ("Invalid Request", 400)

	elif request.method == "DELETE":
		result = networkManager().stopHotspot()

		if result is True:
			return jsonify()
		else:
			return (result, 500)

	else: #POST
		result = nm.startHotspot()

		if result is True:
			return jsonify()
		else:
			return (result, 500)
Beispiel #47
0
def save_name():
	name = request.values.get('name', None)

	if not name or not re.search(r"^[a-zA-Z0-9\-_]+$", name):
		return make_response('Invalid Name', 400)
	else:
		if platform == "linux" or platform == "linux2":
			if networkManager().setHostname(name):
				return jsonify()
			else:
				return (500, "There was an error saving the hostname")
		else:
			return NO_CONTENT
Beispiel #48
0
	def restartServer(self):
		if platform == "linux" or platform == "linux2":
			from astroprint.boxrouter import boxrouterManager
			from astroprint.printer.manager import printerManager
			from astroprint.camera import cameraManager
			from astroprint.network.manager import networkManager

			#let's be nice about shutthing things down
			boxrouterManager().boxrouter_disconnect()
			printerManager().disconnect()
			cameraManager().close_camera()
			networkManager().close()

			actions = self._settings.get(["system", "actions"])
			for a in actions:
				if a['action'] == 'astrobox-restart':
					subprocess.call(a['command'].split(' '))
					return True

			subprocess.call(['restart', 'astrobox'])

		return True
Beispiel #49
0
def box_identify():
	br = boxrouterManager()
	nm = networkManager()

	response = Response()

	response.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
	response.data = json.dumps({
		'id': br.boxId,
		'name': nm.getHostname(),
		'version': VERSION
	})

	return response
Beispiel #50
0
def getInternetSettings():
	nm = networkManager()

	isHotspotable = nm.isHotspotable()

	return jsonify({
		'networks': nm.getActiveConnections(),
		'hasWifi': bool(nm.getWifiDevice()),
		'hotspot': {
			'active': nm.isHotspotActive(),
			'name': nm.getHostname(),
			'hotspotOnlyOffline': settings().getBoolean(['wifi', 'hotspotOnlyOffline'])	
		} if isHotspotable else False
	})
Beispiel #51
0
	def restartServer(self):
		if platform == "linux" or platform == "linux2":
			from astroprint.boxrouter import boxrouterManager
			from astroprint.printer.manager import printerManager
			from astroprint.camera import cameraManager
			from astroprint.network.manager import networkManager

			#let's be nice about shutthing things down
			boxrouterManager().boxrouter_disconnect()
			printerManager().disconnect()
			cameraManager().close_camera()
			networkManager().close()

			actions = self._settings.get(["system", "actions"])
			for a in actions:
				if a['action'] == 'astrobox-restart':
					#Call to Popen will start the restart command but return inmediately before it completes
					subprocess.Popen(a['command'].split(' '))
					return True

			return False

		return True
Beispiel #52
0
	def processAuthenticate(self, data):
		if data:
			self._silentReconnect = False

			if 'error' in data:
				self._logger.warn(data['message'] if 'message' in data else 'Unkonwn authentication error')
				self.status = self.STATUS_ERROR
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
				self.close()

			elif 'success' in data:
				self._logger.info("Connected to astroprint service")
				self.authenticated = True
				self._retries = 0
				self._retryTimer = None
				self.status = self.STATUS_CONNECTED
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

			return None

		else:
			from octoprint.server import VERSION
			from astroprint.printerprofile import printerProfileManager

			nm = networkManager()
			sm = softwareManager()
			ppm = printerProfileManager()

			authData = {
				'silentReconnect': self._silentReconnect,
				'boxId': self.boxId,
				'variantId': sm.variant['id'],
				'boxName': nm.getHostname(),
				'swVersion': VERSION,
				'platform': sm.platform,
				'localIpAddress': nm.activeIpAddress,
				'publicKey': self._publicKey,
				'privateKey': self._privateKey,
				'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None
			}

			pkgId = sm.mfPackageId
			if pkgId:
				authData['mfPackageId'] = pkgId

			return {
				'type': 'auth',
				'data': authData
			}
Beispiel #53
0
	def boxrouter_connect(self):
		if not networkManager().isOnline():
			return False

		if not self.connected:
			from octoprint.server import userManager

			loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
			if loggedUser and userManager:
				user = userManager.findUser(loggedUser)

				if user and user.is_authenticated:
					self._publicKey = user.publicKey
					self._privateKey = user.privateKey

					if self._publicKey and self._privateKey:
						self.status = self.STATUS_CONNECTING
						self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

						try:
							if self._retryTimer:
								#This is in case the user tried to connect and there was a pending retry
								self._retryTimer.cancel()
								self._retryTimer = None
								#If it fails, the retry sequence should restart
								self._retries = 0

							if self._ws and not self._ws.terminated:
								self._ws.terminate()

							self._ws = AstroprintBoxRouterClient(self._address, self)
							self._ws.connect()
							self.connected = True

						except Exception as e:
							self._logger.error("Error connecting to boxrouter: %s" % e)
							self.connected = False
							self.status = self.STATUS_ERROR
							self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

							if self._ws:
								self._ws.terminate()
								self._ws = None

							self._doRetry(False) #This one should not be silent

						return True

		return False
Beispiel #54
0
	def processAuthenticate(self, data):
		if data:
			self._silentReconnect = False

			if 'error' in data:
				self._logger.warn(data['message'] if 'message' in data else 'Unkonwn authentication error')
				self.status = self.STATUS_ERROR
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
				self.close()

			elif 'success' in data:
				self._logger.info("Connected to astroprint service")
				self.authenticated = True
				self._retries = 0
				self._retryTimer = None
				self.status = self.STATUS_CONNECTED
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

			return None

		else:
			from octoprint.server import VERSION

			nm = networkManager()

			activeConnections = nm.getActiveConnections()

			if activeConnections and ( activeConnections['wired'] or activeConnections['wireless']):
				preferredConn = activeConnections['wired'] or activeConnections['wireless']
				localIpAddress = preferredConn['ip']
			else:
				localIpAddress = None

			sm = softwareManager()

			return {
			 	'type': 'auth',
			 	'data': {
			 		'silentReconnect': self._silentReconnect,
			 		'boxId': self.boxId,
			 		'variantId': sm.variant['id'],
			 		'boxName': nm.getHostname(),
			 		'swVersion': VERSION,
			 		'platform': sm.platform,
			 		'localIpAddress': localIpAddress,
			 		'publicKey': self._publicKey,
			 		'privateKey': self._privateKey
			 	}
			}
Beispiel #55
0
	def setWifiNetwork(self, data, sendMessage):
		if 'id' in data and 'password' in data:
			result = networkManager().setWifiNetwork(data['id'], data['password'])

			if result:
				if 'err_code' in result:
					sendMessage(result['err_code'], True)
				else:
					sendMessage(result)
			else:
				sendMessage('network_not_found',True)

			return

		sendMessage('incorrect_data',True)
Beispiel #56
0
	def validatePassword(self, email, password):
		from octoprint.server import userManager
		from astroprint.network.manager import networkManager
		user = None
		userValidated = False

		online = networkManager().isOnline()

		if online:
			try:
				private_key = self.get_private_key(email, password)

				if private_key:
					public_key = self.get_public_key(email, private_key)

					if public_key:
						#Let's update the box now:
						user = userManager.findUser(email)
						if user:
							userManager.changeUserPassword(email, password)
							userManager.changeCloudAccessKeys(email, public_key, private_key)
						else:
							user = userManager.addUser(email, password, public_key, private_key, True)

						userValidated = True

					else:
						return False

				else:
					return False

			except ConnectionError as e:
				self._logger.error('Connection error when trying to validate password: %s' % e)

		# was offline or couldn't reach astroprint.com
		if not userValidated:
			user = userManager.findUser(email)
			userValidated = user and user.check_password(userManager.createPasswordHash(password))

		if userValidated:
			userId = user.get_id()
			self.settings.set(["cloudSlicer", "loggedUser"], userId)
			self.settings.save()

		return userValidated
Beispiel #57
0
	def checkInternet(self, data, sendResponse):
		nm = networkManager()

		if nm.isAstroprintReachable():
		#if False:
			return sendResponse({'connected':True})
		else:
			networks = nm.getWifiNetworks()

			if networks:
				return sendResponse(
					{
						'networks':networks,
						'connected':False
					}
				)
			else:
				return sendResponse("unable_get_wifi",True)
Beispiel #58
0
	def __init__(self):
		self._eventManager = eventManager()

		self.logger = logging.getLogger(__name__)

		self.mfDefinition = manufacturerPkgManager()
		self.softwareMgr = softwareManager()

		# upnp/ssdp
		self._ssdp_monitor_active = False
		self._ssdp_monitor_thread = None
		self._ssdp_notify_timeout = 10
		self._ssdp_last_notify = 0
		self._ssdp_last_unregister = 0

		# SSDP
		if networkManager().isOnline():
			self._ssdp_register()

		self._eventManager.subscribe(Events.NETWORK_STATUS, self._onNetworkStateChanged)
Beispiel #59
0
	def _ssdp_register(self):
		"""
		Registers the AstroPrint instance as basic service with a presentation URL pointing to the web interface
		"""

		time_since_last_unregister = time.time() - self._ssdp_last_unregister

		if time_since_last_unregister < ( self._ssdp_notify_timeout + 1 ):
			wait_seconds = ( self._ssdp_notify_timeout + 1) - time_since_last_unregister
			self.logger.info("Waiting %s seconds before starting SSDP Service..." % wait_seconds)
			time.sleep(wait_seconds)

			#Make sure that the network is still after the wait
			if not networkManager().isOnline():
				return

		self._ssdp_monitor_active = True

		self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor, kwargs=dict(timeout=self._ssdp_notify_timeout))
		self._ssdp_monitor_thread.daemon = True
		self._ssdp_monitor_thread.start()
Beispiel #60
0
def index():
	s = settings()
	loggedUsername = s.get(["cloudSlicer", "loggedUser"])

	if (s.getBoolean(["server", "firstRun"])):
		swm = swManager()

		# we need to get the user to sign into their AstroPrint account
		return render_template(
			"setup.jinja2",
			debug= debug,
			uiApiKey= UI_API_KEY,
			version= VERSION,
			commit= swm.commit,
			variantData= variantManager().data,
			astroboxName= networkManager().getHostname(),
			checkSoftware= swm.shouldCheckForNew,
			settings=s
		)

	elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
		return render_template(
			"updating.jinja2",
			uiApiKey= UI_API_KEY,
			showForceUpdate=  softwareManager.forceUpdateInfo != None,
			releaseInfo= softwareManager.updatingRelease or softwareManager.forceUpdateInfo,
			lastCompletionPercent= softwareManager.lastCompletionPercent,
			lastMessage= softwareManager.lastMessage,
			variantData= variantManager().data,
			astroboxName= networkManager().getHostname()
		)

	elif loggedUsername and (current_user is None or not current_user.is_authenticated() or current_user.get_id() != loggedUsername):
		if current_user.is_authenticated():
			logout_user()

		return render_template(
			"locked.jinja2",
			username= loggedUsername,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager().getHostname(),
			variantData= variantManager().data
		)

	else:
		pm = printerManager()
		nm = networkManager()
		swm = swManager()

		paused = pm.isPaused()
		printing = pm.isPrinting()
		online = nm.isOnline()

		return render_template(
			"app.jinja2",
			user_email= loggedUsername,
			version= VERSION,
			commit= swm.commit,
			printing= printing,
			paused= paused,
			online= online,
			print_capture= cameraManager().timelapseInfo if printing or paused else None,
			printer_profile= printerProfileManager().data,
			uiApiKey= UI_API_KEY,
			astroboxName= nm.getHostname(),
			variantData= variantManager().data,
			checkSoftware= swm.shouldCheckForNew,
			serialLogActive= s.getBoolean(['serial', 'log'])
		)