コード例 #1
0
	def connectBoxrouter(self, callback):
		try:
			boxrouterManager().boxrouter_connect()
			callback('connect_success')
		except Exception as e:
			self._logger.error('boxrouter can not connect', exc_info = True)
			callback('boxrouter_error', True)
コード例 #2
0
ファイル: setup.py プロジェクト: Ethereal-Machines/Ray
def login_astroprint():
    data = request.get_json()
    if data:
        machineId = data.get('machineId')
        accessCode = data.get('accessCode')
    else:
        return make_response('No Credentials given', 400)

    if machineId and accessCode:
        ap = astroprintCloud()
        try:
            if ap.signin(machineId, accessCode):
                s = settings()
                s.set(['setup', 'machineId'], machineId)
                s.set(['setup', 'accessCode'], accessCode)
                s.save()
                _logger.info("setting printer id to: %s", machineId)
                boxrouterManager()
                boxrouterManager().boxId = machineId

                _logger.info("Checking for updates")
                softwareManager().checkForcedUpdate()
                return make_response("OK", 200)
        except (AstroPrintCloudNoConnectionException, ConnectionError) as e:
            _logger.error(e)
            return make_response("AstroPrint.com can't be reached", 503)

    return make_response('Invalid Credentials', 400)
コード例 #3
0
ファイル: software.py プロジェクト: chris25640/AstroBox
	def restartServer(self):
		if platform == "linux" or platform == "linux2":
			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
					threading.Timer(1.0, subprocess.Popen, [a['command'].split(' ')]).start()
					self._logger.info('Restart command scheduled')

					from astroprint.boxrouter import boxrouterManager
					from astroprint.printer.manager import printerManager
					from astroprint.camera import cameraManager
					from astroprint.network.manager import networkManagerShutdown

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

					return True

			return False

		return True
コード例 #4
0
ファイル: cloud.py プロジェクト: TheUrbanWeb/3dbox
    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
コード例 #5
0
ファイル: __init__.py プロジェクト: TheUrbanWeb/3dbox
    def sendEventToPeer(self, type, data=None):
        try:
            boxrouterManager().sendEventToClient(self.clientId, type, data)

        except:
            self._logger.error('Error sending event [%s] to peer %s' %
                               (type, self.clientId),
                               exc_info=True)
コード例 #6
0
ファイル: __init__.py プロジェクト: IceForgTW/AstroBox
    def pingPongRounder(self, params=None):

        for key in self._connectedPeers.keys():
            if self._connectedPeers[key] != 'local':
                #sendRequestToClient(self, clientId, type, data, timeout, respCallback)
                boxrouterManager().sendRequestToClient(
                    self._connectedPeers[key].clientId, 'ping', None, 10,
                    self.pongCallback, [key])
コード例 #7
0
ファイル: software.py プロジェクト: AstroPrint/AstroBox
	def run(self):
		#We need to give the UI a chance to update before starting so that the message can be sent...
		self._progressCb("download", 0.0, "Starting...")
		#disconnect from the cloud during software upgrade. The reboot will take care of reconnect
		boxrouterManager().boxrouter_disconnect()

		time.sleep(2)
		self._installNextPackage()
コード例 #8
0
ファイル: software.py プロジェクト: italocjs/AstroBox
	def run(self):
		#We need to give the UI a chance to update before starting so that the message can be sent...
		self._progressCb("download", 0.0, "Starting...")
		#disconnect from the cloud during software upgrade. The reboot will take care of reconnect
		boxrouterManager().boxrouter_disconnect()

		time.sleep(2)
		self._installNextPackage()
コード例 #9
0
ファイル: cloud.py プロジェクト: AstroPrint/AstroBox
	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
コード例 #10
0
    def remove_logged_user(self):
        self.settings.set(["cloudSlicer", "loggedUser"], None)
        self.settings.save()
        boxrouterManager().boxrouter_disconnect()

        #let the singleton be recreated again, so credentials and print_files are forgotten
        global _instance
        _instance = None

        eventManager().fire(Events.LOCK_STATUS_CHANGED, None)
コード例 #11
0
ファイル: __init__.py プロジェクト: AstroPrint/AstroBox
	def pingPongRounder(self,params=None):
		for sessionId in self._connectedPeers.keys():
			peer = self._connectedPeers[sessionId]
			#if peer != 'local':
			if isinstance(peer, ConnectionPeer):
				try:
					boxrouterManager().sendRequestToClient(peer.clientId, 'ping', None, 10, self.pongCallback, [sessionId])

				except:
					self._logger.error('Error sending ping to peer %s' % peer.clientId, exc_info = True)
コード例 #12
0
ファイル: cloud.py プロジェクト: daftscience/AstroBox
	def signout(self):
		self.settings.set(["cloudSlicer", "privateKey"], None)
		self.settings.set(["cloudSlicer", "publicKey"], None)
		self.settings.set(["cloudSlicer", "email"], None)
		self.settings.save()
		boxrouterManager().boxrouter_disconnect()

		#let the singleton be recreated again, so credentials and print_files are forgotten
		global _instance
		_instance = None
コード例 #13
0
ファイル: cloud.py プロジェクト: IceForgTW/AstroBox
	def remove_logged_user(self):
		self.settings.set(["cloudSlicer", "loggedUser"], None)
		self.settings.save()
		boxrouterManager().boxrouter_disconnect()

		#let the singleton be recreated again, so credentials and print_files are forgotten
		global _instance
		_instance = None

		eventManager().fire(Events.LOCK_STATUS_CHANGED, None)
コード例 #14
0
	def cleanup(self):
		global discoveryManager
		
		discoveryManager.shutdown()
		discoveryManager = None
		boxrouterManager().shutdown()
		cameraManager().shutdown()

		from astroprint.network.manager import networkManagerShutdown
		networkManagerShutdown()
コード例 #15
0
	def cleanup(self):
		global discoveryManager
		
		discoveryManager.shutdown()
		discoveryManager = None
		boxrouterManager().shutdown()
		cameraManager().shutdown()

		from astroprint.network.manager import networkManagerShutdown
		networkManagerShutdown()
		
		logging.getLogger(__name__).info("Goodbye!")
コード例 #16
0
ファイル: cloud.py プロジェクト: nerginer/AstroBox
	def signout(self):
		self.settings.set(["cloudSlicer", "loggedUser"], None)
		self.settings.save()
		boxrouterManager().boxrouter_disconnect()
		
		logout_user()

		#let the singleton be recreated again, so credentials and print_files are forgotten
		global _instance
		_instance = None

		identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
		eventManager().fire(Events.LOCK_STATUS_CHANGED, None)
コード例 #17
0
    def signout(self):
        self.settings.set(["cloudSlicer", "loggedUser"], None)
        self.settings.save()
        boxrouterManager().boxrouter_disconnect()

        logout_user()

        #let the singleton be recreated again, so credentials and print_files are forgotten
        global _instance
        _instance = None

        identity_changed.send(current_app._get_current_object(),
                              identity=AnonymousIdentity())
        eventManager().fire(Events.LOCK_STATUS_CHANGED, None)
コード例 #18
0
    def cleanup(self):
        global discoveryManager

        pluginManager().shutdown()
        downloadManager().shutdown()
        printerManager().rampdown()
        discoveryManager.shutdown()
        discoveryManager = None
        boxrouterManager().shutdown()
        cameraManager().shutdown()
        externalDriveManager().shutdown()

        from astroprint.network.manager import networkManagerShutdown
        networkManagerShutdown()
コード例 #19
0
ファイル: __init__.py プロジェクト: TheUrbanWeb/3dbox
    def pingPongRounder(self, params=None):
        for sessionId in self._connectedPeers.keys():
            peer = self._connectedPeers[sessionId]
            #if peer != 'local':
            if isinstance(peer, ConnectionPeer):
                try:
                    boxrouterManager().sendRequestToClient(
                        peer.clientId, 'ping', None, 10, self.pongCallback,
                        [sessionId])

                except:
                    self._logger.error('Error sending ping to peer %s' %
                                       peer.clientId,
                                       exc_info=True)
コード例 #20
0
ファイル: printer.py プロジェクト: AstroPrint/AstroBox
	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
			}
コード例 #21
0
ファイル: boxrouter.py プロジェクト: nerginer/AstroBox
def connect_boxrouter():
	br = boxrouterManager()

	if br.boxrouter_connect():
		return jsonify()
	else:
		return abort(400)
コード例 #22
0
ファイル: boxrouter.py プロジェクト: nerginer/AstroBox
def connect_boxrouter():
    br = boxrouterManager()

    if br.boxrouter_connect():
        return jsonify()
    else:
        return abort(400)
コード例 #23
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
	)
コード例 #24
0
ファイル: util.py プロジェクト: TheUrbanWeb/3dbox
	def on_open(self, request):
		s = settings()
		loggedUsername = s.get(["cloudSlicer", "loggedUser"])

		if loggedUsername:
			token = request.arguments.get("token")
			token = token[0] if token else None
			tokenContents = octoprint.server.read_ws_token(token)
			if not tokenContents or tokenContents['public_key'] != self._userManager.findUser(loggedUsername).publicKey:
				return False

		remoteAddress = self._getRemoteAddress(request)
		self._logger.info("New connection from client [IP address: %s, Session id: %s]", remoteAddress, self.session.session_id)

		# connected => update the API key, might be necessary if the client was left open while the server restarted
		self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "sessionId": self.session.session_id})
		self.sendEvent(Events.ASTROPRINT_STATUS, boxrouterManager().status)

		printer = printerManager()

		printer.registerCallback(self)
		printer.fileManager.registerCallback(self)

		self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
		for event in PrinterStateConnection.EVENTS:
			self._eventManager.subscribe(event, self._onEvent)
コード例 #25
0
ファイル: cloud.py プロジェクト: italocjs/AstroBox
	def remove_logged_user(self):
		loggedUser = self.settings.get(['cloudSlicer', 'loggedUser'])
		from octoprint.server import userManager
		#Method could be call twice (boxrouter, touch), and now user is deleted
		if loggedUser:
			userManager.removeUser(loggedUser)
		self.settings.set(["cloudSlicer", "loggedUser"], None)
		self.settings.set(["materialSelected"], None)
		self.settings.set(["printerSelected"], None)
		self.settings.set(["qualitySelected"], None)
		self.settings.set(["customQualitySelected"], None)
		self.settings.save()
		boxrouterManager().boxrouter_disconnect()

		#let the singleton be recreated again, so credentials and print_files are forgotten
		global _instance
		_instance = None

		eventManager().fire(Events.LOCK_STATUS_CHANGED, None)
コード例 #26
0
ファイル: cloud.py プロジェクト: daftscience/AstroBox
	def signin(self, email, password):
		private_key = self.get_private_key(email, password)

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

			if public_key:
				self.settings.set(["cloudSlicer", "privateKey"], private_key)
				self.settings.set(["cloudSlicer", "publicKey"], public_key)
				self.settings.set(["cloudSlicer", "email"], email)
				self.settings.save()
				boxrouterManager().boxrouter_connect()

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

				return True

		return False
コード例 #27
0
ファイル: __init__.py プロジェクト: Ethereal-Machines/Ray
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)
コード例 #28
0
ファイル: cloud.py プロジェクト: acrive82/AstroBox
    def print_job(self,
                  id=None,
                  print_file_id=None,
                  print_file_name=None,
                  status='started'):
        if self.cloud_enabled():
            try:
                if id:
                    r = requests.put(
                        "%s/printjobs/%s" % (self.apiHost, id),
                        data=json.dumps({'status': status}),
                        auth=self.hmacAuth,
                        headers={'Content-Type': 'application/json'})

                else:
                    #create a print job
                    data = {'box_id': boxrouterManager().boxId}

                    if not print_file_id and not print_file_name:
                        self._logger.error(
                            'print_file_id and name are both missing in print_job'
                        )
                        return False

                    if print_file_id:
                        data['print_file_id'] = print_file_id

                    if print_file_name:
                        data['name'] = print_file_name

                    r = requests.post(
                        "%s/printjobs" % self.apiHost,
                        data=json.dumps(data),
                        auth=self.hmacAuth,
                        headers={'Content-Type': 'application/json'})

                if r.status_code == 200:
                    return r.json()

                if r.status_code == 400:
                    self._logger.error(
                        "Bad print_job request (400). Response: %s" % r.text)

                else:
                    self._logger.error(
                        "print_job request failed with status: %d" %
                        r.status_code)

            except Exception as e:
                self._logger.error("Failed to send print_job request: %s" % e)

        return False
コード例 #29
0
ファイル: software.py プロジェクト: cronos45/AstroBox
	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
コード例 #30
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
コード例 #31
0
def box_identify():
    nm = networkManager()
    s = settings()

    return Response(json.dumps({
        'id': boxrouterManager().boxId,
        'name': nm.getHostname(),
        'version': VERSION,
        'firstRun': s.getBoolean(["server", "firstRun"]),
        'online': nm.isOnline()
    }),
                    headers={'Access-Control-Allow-Origin': '*'}
                    if s.getBoolean(['api', 'allowCrossOrigin']) else None)
コード例 #32
0
ファイル: cloud.py プロジェクト: AstroPrint/AstroBox
	def print_job(self, id= None, print_file_id= None, print_file_name= None, status= 'started', reason= None, materialUsed= None ):
		if self.cloud_enabled():
			try:
				if id:

					data = {'status': status}

					if reason:
						data['reason'] = reason

					if materialUsed:
						data['material_used'] = materialUsed

					r = requests.put("%s/printjobs/%s" % (self.apiHost, id),
						data=json.dumps(data),
						auth=self.hmacAuth,
						headers={'Content-Type': 'application/json'}
					)

				else:
					#create a print job
					data = {
						'box_id': boxrouterManager().boxId,
						'product_variant_id': softwareManager().data['variant']['id']
					}

					if not print_file_id and not print_file_name:
						self._logger.error('print_file_id and name are both missing in print_job')
						return False

					if print_file_id:
						data['print_file_id'] = print_file_id

					if print_file_name:
						data['name'] = print_file_name

					r = requests.post( "%s/printjobs" % self.apiHost, data= json.dumps(data), auth=self.hmacAuth, headers={'Content-Type': 'application/json'} )

				if r.status_code == 200:
					return r.json()

				if r.status_code == 400:
					self._logger.error("Bad print_job request (400). Response: %s" % r.text)

				else:
					self._logger.error("print_job request failed with status: %d" % r.status_code)

			except Exception as e:
				self._logger.error("Failed to send print_job request: %s" % e)

		return False
コード例 #33
0
ファイル: __init__.py プロジェクト: InaZuma3/AstroBoxFYP
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
コード例 #34
0
ファイル: software.py プロジェクト: acrive82/AstroBox
    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
コード例 #35
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
コード例 #36
0
	def getStatus(self, callback):
		try:
			sets = settings()
			user = sets.get(["cloudSlicer", "loggedUser"])

			payload = {
				'userLogged': user if user else None,
				'boxrouterStatus' :  boxrouterManager().status
			}
			callback(payload)

		except Exception as e:
			self._logger.error('unsuccessfully user status got', exc_info = True)
			callback('getting_status_error')
コード例 #37
0
ファイル: util.py プロジェクト: daftscience/AstroBox
	def on_open(self, info):
		remoteAddress = self._getRemoteAddress(info)
		self._logger.info("New connection from client: %s" % remoteAddress)

		# connected => update the API key, might be necessary if the client was left open while the server restarted
		self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION})
		self.sendEvent(Events.ASTROPRINT_STATUS, boxrouterManager().status)

		self._printer.registerCallback(self)
		self._gcodeManager.registerCallback(self)
		#octoprint.timelapse.registerCallback(self)

		self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
		for event in PrinterStateConnection.EVENTS:
			self._eventManager.subscribe(event, self._onEvent)
コード例 #38
0
    def sendLogs(self, ticketNo=None, message=None):
        import zipfile

        from astroprint.boxrouter import boxrouterManager
        from tempfile import gettempdir

        try:
            boxId = boxrouterManager().boxId

            #Create the zip file
            zipFilename = '%s/%s-logs.zip' % (gettempdir(), boxId)
            zipf = zipfile.ZipFile(zipFilename, 'w')

            for root, dirs, files in os.walk(
                    self._settings.getBaseFolder("logs")):
                for file in files:
                    zipf.write(os.path.join(root, file), file)

            zipf.close()

        except Exception as e:
            self._logger.error('Error while zipping logs: %s' % e)
            return False

        zipf = open(zipFilename, 'rb')

        #send the file to the server
        r = requests.post('%s/astrobox/software/logs' %
                          (self._settings.get(['cloudSlicer', 'apiHost'])),
                          data={
                              'ticket': ticketNo,
                              'message': message,
                              'boxId': boxId
                          },
                          files={'file': (zipFilename, zipf)},
                          auth=self._checkAuth(),
                          headers=self._requestHeaders)

        zipf.close()

        #remove the file
        os.remove(zipFilename)

        if r.status_code == 200:
            return True
        else:
            self._logger.error('Error while sending logs: %d' % r.status_code)
            return False
コード例 #39
0
ファイル: util.py プロジェクト: IceForgTW/AstroBox
	def on_open(self, info):
		remoteAddress = self._getRemoteAddress(info)
		self._logger.info("New connection from client [IP address: %s, Session id: %s]", remoteAddress, self.session.session_id)

		# connected => update the API key, might be necessary if the client was left open while the server restarted
		self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "sessionId": self.session.session_id})
		self.sendEvent(Events.ASTROPRINT_STATUS, boxrouterManager().status)

		printer = printerManager()

		printer.registerCallback(self)
		printer.fileManager.registerCallback(self)
		#octoprint.timelapse.registerCallback(self)

		self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
		for event in PrinterStateConnection.EVENTS:
			self._eventManager.subscribe(event, self._onEvent)
コード例 #40
0
ファイル: printer.py プロジェクト: italocjs/AstroBox
    def getStatus(self):
        printer = printerManager()
        cm = cameraManager()
        ppm = printerProfileManager()
        cloudInstance = astroprintCloud()

        fileName = None

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

        return {
            'id':
            boxrouterManager().boxId,
            'name':
            networkManager().getHostname(),
            'orgId':
            cloudInstance.orgId,
            'groupId':
            cloudInstance.groupId,
            '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(),
            'isBedClear':
            printer.isBedClear,
            #'printCapture': cm.timelapseInfo,
            'remotePrint':
            True,
            'capabilities': ['remotePrint'] + cm.capabilities
        }
コード例 #41
0
ファイル: cloud.py プロジェクト: jeffatrembley/AstroBox
    def print_job(self, id=None, print_file_id=None, print_file_name=None, status="started"):
        if self.cloud_enabled():
            try:
                if id:
                    r = requests.put(
                        "%s/printjobs/%s" % (self.apiHost, id),
                        data=json.dumps({"status": status}),
                        auth=self.hmacAuth,
                        headers={"Content-Type": "application/json"},
                    )

                else:
                    # create a print job
                    data = {"box_id": boxrouterManager().boxId}

                    if not print_file_id and not print_file_name:
                        self._logger.error("print_file_id and name are both missing in print_job")
                        return False

                    if print_file_id:
                        data["print_file_id"] = print_file_id

                    if print_file_name:
                        data["name"] = print_file_name

                    r = requests.post(
                        "%s/printjobs" % self.apiHost,
                        data=json.dumps(data),
                        auth=self.hmacAuth,
                        headers={"Content-Type": "application/json"},
                    )

                if r.status_code == 200:
                    return r.json()

                if r.status_code == 400:
                    self._logger.error("Bad print_job request (400). Response: %s" % r.text)

                else:
                    self._logger.error("print_job request failed with status: %d" % r.status_code)

            except Exception as e:
                self._logger.error("Failed to send print_job request: %s" % e)

        return False
コード例 #42
0
ファイル: software.py プロジェクト: TramALot/AstroBox
	def sendLogs(self, ticketNo=None, message=None):
		import zipfile

		from astroprint.boxrouter import boxrouterManager
		from tempfile import gettempdir

		try:
			boxId = boxrouterManager().boxId

			#Create the zip file
			zipFilename = '%s/%s-logs.zip' % (gettempdir(), boxId)
			zipf = zipfile.ZipFile(zipFilename, 'w')

			for root, dirs, files in os.walk(self._settings.getBaseFolder("logs")):
				for file in files:
					zipf.write(os.path.join(root, file), file)

			zipf.close()

		except Exception as e:
			self._logger.error('Error while zipping logs: %s' % e)
			return False

		zipf = open(zipFilename, 'rb')

		#send the file to the server
		r = requests.post(
			'%s/astrobox/software/logs' % (self._settings.get(['cloudSlicer','apiHost'])),
			data = { 'ticket': ticketNo, 'message': message, 'boxId': boxId},
			files = {'file': (zipFilename, zipf)},
			auth = self._checkAuth(),
			headers = self._requestHeaders
		)

		zipf.close()

		#remove the file
		os.remove(zipFilename)

		if r.status_code == 200:
			return True
		else:
			self._logger.error('Error while sending logs: %d' % r.status_code)
			return False
コード例 #43
0
ファイル: cloud.py プロジェクト: Yzhao1125/AstroBox
	def updateBoxrouterData(self, data):
		if self.cloud_enabled():
			try:
				if data:
					r = requests.put("%s/astrobox/%s/update-boxrouter-data" % (self.apiHost, boxrouterManager().boxId),
						data=json.dumps(data),
						auth=self.hmacAuth,
						headers={'Content-Type': 'application/json'}
					)

					if r.status_code == 200:
						return r.json()
					if r.status_code == 400:
						self._logger.error("Bad updateBoxrouterData request (400). Response: %s" % r.text)
					if r.status_code == 404:
						self._logger.error("Request updateBoxrouterData not found (404). Response: %s" % r.text)
			except Exception as e:
				self._logger.error("Failed to send updateBoxrouterData request: %s" % e)
		return False
コード例 #44
0
ファイル: cloud.py プロジェクト: italocjs/AstroBox
	def __init__(self):
		self.settings = settings()
		self._eventManager = eventManager()
		self.hmacAuth = None
		self.boxId = boxrouterManager().boxId

		self.tryingLoggingTimes = 0

		self.apiHost = roConfig('cloud.apiHost')
		self._print_file_store = None
		self._sm = softwareManager()
		self._logger = logging.getLogger(__name__)

		loggedUser = self.settings.get(['cloudSlicer', 'loggedUser'])
		if loggedUser:
			from octoprint.server import userManager

			user = userManager.findUser(loggedUser)

			if user and user.publicKey and user.privateKey:
				self.hmacAuth = HMACAuth(user.publicKey, user.privateKey, self.boxId, user.orgId, user.groupId)
コード例 #45
0
def box_identify():
    nm = networkManager()
    s = settings()

    sslEnabled = request.headers.get('x-https-configured') == '1'

    r = {
        'id': boxrouterManager().boxId,
        'name': nm.getHostname(),
        'version': VERSION,
        'firstRun': s.getBoolean(["server", "firstRun"]),
        'online': nm.isOnline(),
        'ssl': sslEnabled
    }

    if sslEnabled:
        r['ssl_domain'] = s.get(['network', 'ssl', 'domain'])

    return Response(json.dumps(r),
                    headers={'Access-Control-Allow-Origin': '*'}
                    if s.getBoolean(['api', 'allowCrossOrigin']) else None)
コード例 #46
0
ファイル: printer.py プロジェクト: bula87/AstroBox
    def getStatus(self):
        printer = printerManager()
        cm = cameraManager()

        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': None,
            'material': None,
            'operational': printer.isOperational(),
            'paused': printer.isPaused(),
            'camera': cm.isCameraConnected(),
            #'printCapture': cm.timelapseInfo,
            'remotePrint': True,
            'capabilities': ['remotePrint'] + cm.capabilities
        }
コード例 #47
0
ファイル: __init__.py プロジェクト: IceForgTW/AstroBox
	def pingPongRounder(self,params=None):
		
		for key in self._connectedPeers.keys():
			if self._connectedPeers[key] != 'local':
				#sendRequestToClient(self, clientId, type, data, timeout, respCallback)
				boxrouterManager().sendRequestToClient(self._connectedPeers[key].clientId, 'ping',None,10, self.pongCallback, [key])
コード例 #48
0
ファイル: users.py プロジェクト: AstroPrint/AstroBox
	def createPasswordHash(password):
		if password is not None:
			return hashlib.sha512(password + boxrouterManager().boxId).hexdigest()
		return None
コード例 #49
0
ファイル: account.py プロジェクト: AstroPrint/AstroBox
	def _onBoxrouterStateChange(self,event,value):
			data = {
				'boxrouterStatus' :  boxrouterManager().status
			}
			self.publishEvent('boxrouter_state_change',data)
コード例 #50
0
ファイル: __init__.py プロジェクト: AstroPrint/AstroBox
	def sendEventToPeer(self, type, data= None):
		try:
			boxrouterManager().sendEventToClient(self.clientId, type, data)

		except:
			self._logger.error('Error sending event [%s] to peer %s' % (type, self.clientId), exc_info = True)
コード例 #51
0
ファイル: __init__.py プロジェクト: IceForgTW/AstroBox
	def sendEventToPeer(self, type, data= None):
		boxrouterManager().sendEventToClient(self.clientId, type, data)
コード例 #52
0
ファイル: boxrouter.py プロジェクト: daftscience/AstroBox
def connect_boxrouter():
	br = boxrouterManager()

	br.boxrouter_connect()

	return jsonify()
コード例 #53
0
ファイル: __init__.py プロジェクト: AstroPrint/AstroBox
	def get_uuid(self):
		return boxrouterManager().boxId