예제 #1
0
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)
예제 #2
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}
예제 #3
0
파일: cloud.py 프로젝트: IceForgTW/AstroBox
	def __call__(self, r):
		r.headers['User-Agent'] = softwareManager().userAgent
		sig_base = '&'.join((r.method, r.headers['User-Agent']))
		hashed = hmac.new(self.privateKey, sig_base, sha256)

		r.headers['X-Public'] = self.publicKey
		r.headers['X-Hash'] = binascii.b2a_base64(hashed.digest())[:-1]

		return r
예제 #4
0
파일: cloud.py 프로젝트: shumybest/AstroBox
	def __init__(self):
		self.settings = settings()

		publicKey = self.settings.get(['cloudSlicer', 'publicKey'])
		privateKey = self.settings.get(['cloudSlicer', 'privateKey'])

		self.hmacAuth = HMACAuth(publicKey, privateKey,)
		self.apiHost = self.settings.get(['cloudSlicer', 'apiHost'])
		self._sm = softwareManager()
예제 #5
0
    def __call__(self, r):
        r.headers['User-Agent'] = softwareManager().userAgent
        sig_base = '&'.join((r.method, r.headers['User-Agent']))
        hashed = hmac.new(self.privateKey, sig_base, sha256)

        r.headers['X-Public'] = self.publicKey
        r.headers['X-Hash'] = binascii.b2a_base64(hashed.digest())[:-1]

        return r
예제 #6
0
파일: ssl.py 프로젝트: italocjs/AstroBox
	def enable(self):
		if not self.isSslActive():
			disabledPath = self.sslCertPath.replace('ssl', 'ssl_disabled')
			if os.path.isfile(disabledPath):
				os.rename(os.path.dirname(disabledPath), os.path.dirname(self.sslCertPath))

			else:
				from astroprint.cloud import astroprintCloud

				astroprint = astroprintCloud()
				cert = astroprint.get_local_certificate()
				if cert is not None:
					mkpath(os.path.dirname(self.sslCertPath))
					with open(self.sslCertPath, 'w') as f:
						f.write(cert)
				else:
					raise NoCertException()

			softwareManager().restartServer()
예제 #7
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
                }
            }
예제 #8
0
파일: cloud.py 프로젝트: pamxy/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
예제 #9
0
	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
예제 #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()

			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
			}
예제 #11
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
			 	}
			}
예제 #12
0
파일: cloud.py 프로젝트: italocjs/AstroBox
	def __call__(self, r):

		r.headers['User-Agent'] = softwareManager().userAgent
		sig_base = '&'.join((r.method, r.headers['User-Agent']))

		hashed = hmac.new(self.privateKey, sig_base, sha256)

		r.headers['X-Public'] = self.publicKey
		r.headers['X-Hash'] = binascii.b2a_base64(hashed.digest())[:-1]
		r.headers['X-Box-Id'] = self.boxId
		if self.isOnFleet:
			r.headers['X-Org-Id'] = self.orgId
			r.headers['X-Group-Id'] = self.groupId

		return r
예제 #13
0
    def __init__(self, hostname, router):
        self._systemListener = None
        self._lastReceived = 0
        self._lineCheck = None
        self._error = False
        self._closing = False

        self._weakRefRouter = weakref.ref(router)
        self._logger = logging.getLogger(__name__)
        self._condition = threading.Condition()
        self._messageHandler = BoxRouterMessageHandler(self._weakRefRouter,
                                                       self)
        super(AstroprintBoxRouterClient,
              self).__init__(hostname,
                             headers=[('user-agent',
                                       softwareManager().userAgent)])
예제 #14
0
파일: cloud.py 프로젝트: acrive82/AstroBox
    def __init__(self):
        self.settings = settings()
        self.hmacAuth = None

        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.apiHost = self.settings.get(['cloudSlicer', 'apiHost'])
        self._print_file_store = None
        self._sm = softwareManager()
        self._logger = logging.getLogger(__name__)
예제 #15
0
파일: cloud.py 프로젝트: IceForgTW/AstroBox
	def __init__(self):
		self.settings = settings()
		self.hmacAuth = None

		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.apiHost = self.settings.get(['cloudSlicer', 'apiHost'])
		self._print_file_store = None
		self._sm = softwareManager()
		self._logger = logging.getLogger(__name__)
예제 #16
0
	def __init__(self):
		self._eventManager = eventManager()

		self.logger = logging.getLogger(__name__)

		self.variantMgr = variantManager()
		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)
예제 #17
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)
예제 #18
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)
예제 #19
0
파일: ssl.py 프로젝트: italocjs/AstroBox
	def disable(self):
		if self.isSslActive():
			dirname = os.path.dirname(self.sslCertPath)
			os.rename(dirname, dirname.replace('ssl', 'ssl_disabled'))
			softwareManager().restartServer()