def start_camera_process(self, camera_name=None, token=None): if not token: token = self.token if not config.get_settings()["camera"]["enabled"]: self.logger.info("Can't launch camera - disabled in config") return False self.logger.info("Launching camera subprocess") if not camera_name: camera_name = config.get_settings()["camera"]["default"] module_name = self.CAMERA_MODULES[camera_name] if module_name: cam_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), module_name) if cam_path and cam_path.endswith(".py"): start_command = [sys.executable, cam_path, token] elif camera_name == self.HD_CAMERA_NAME: start_command = [os.path.basename(cam_path)] if sys.platform.startswith("linux"): start_command[0] = "./" + start_command[0] start_command += [self.HD_CAMERA_URL, self.HD_CAMERA_PORT, token] else: self.logger.warning("Unable to launch camera: unknown module - " + os.path.basename(cam_path)) return False try: self.camera_process = subprocess.Popen(start_command) except Exception as e: self.logger.warning("Could not launch camera due to error:\n" + str(e)) else: self.current_camera_name = camera_name self.token = token self.logger.info("Camera started: " + camera_name) return True
def __init__(self): self.logger = log.create_logger('camera') self.stop_flag = False paths.init_path_to_libs() import numpy as np import cv2 as cv2 self.np = np self.cv2 = cv2 signal.signal(signal.SIGINT, self.intercept_signal) signal.signal(signal.SIGTERM, self.intercept_signal) if len(sys.argv) > 2: self.user_token = sys.argv[1] mac = sys.argv[2] else: ul = user_login.UserLogin(self) ul.wait() self.user_token = ul.user_token mac = None self.image_extension = config.get_settings()["camera"]["img_ext"] self.image_quality = config.get_settings()["camera"]["img_qual"] self.hardware_resize = config.get_settings( )["camera"]["hardware_resize"] self.min_loop_time = config.get_settings()["camera"]["min_loop_time"] self.search_cameras() self.http_client = http_client.HTTPClient(self, keep_connection_flag=True) if mac: self.http_client.mac = mac #we need to use MAC from client to ensure that it's not changed on camera restart self.main_loop()
class DB(object): DB_SERVER = get_settings("DB_SERVER", "127.0.0.1") DB_SERVER_PORT = get_settings("DB_SERVER_PORT", 27017) DB_NAME = get_settings("DB_NAME", "blog") def __init__(self): self._opened = False def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_value, traceback): self.close() return False def open(self): if self._opened: return self._opened = True self._conn = Connection(host=self.DB_SERVER, port=self.DB_SERVER_PORT) self._db = self._conn[self.DB_NAME] def close(self): if not self._opened: return self._opened = False self._conn.disconnect() def __getattr__(self, name): return getattr(self._db, name, None)
def update(self): if self.update_flag: self.logger.info('Updating client...') update_file_name = config.get_settings( )['update']['update_file_name'] try: urllib.urlretrieve( config.get_settings()['update']['update_file_url'] + update_file_name, update_file_name) except Exception as e: error_message = 'Update failed!\nReason: error while downloading.\nDetails: ' + str( e) config.create_error_report(0, error_message, None, self.logger, is_blocking=True) return error_message else: error = self.extract_update(update_file_name) if error: return error self.logger.info('...client successfully updated!') self.update_flag = False log.send_logs() log.clear_logs()
def __init__(self): self.logger = log.create_logger('camera') self.stop_flag = False paths.init_path_to_libs() import numpy as np import cv2 as cv2 self.np = np self.cv2 = cv2 signal.signal(signal.SIGINT, self.intercept_signal) signal.signal(signal.SIGTERM, self.intercept_signal) if len(sys.argv) > 2: self.user_token = sys.argv[1] mac = sys.argv[2] else: ul = user_login.UserLogin(self) ul.wait() self.user_token = ul.user_token mac = None self.image_extension = config.get_settings()["camera"]["img_ext"] self.image_quality = config.get_settings()["camera"]["img_qual"] self.hardware_resize = config.get_settings()["camera"]["hardware_resize"] self.min_loop_time = config.get_settings()["camera"]["min_loop_time"] self.search_cameras() self.http_client = http_client.HTTPClient(self, keep_connection_flag=True) if mac: self.http_client.mac = mac #we need to use MAC from client to ensure that it's not changed on camera restart self.main_loop()
def deliver_message(message: str) -> str: """ Введенное пользователем сообщение отправляется в сокет - для сервиса MQTT publisher. Возвращаемое значение: признак успеха отправки. """ socket.setdefaulttimeout(SOCKET_TIMEOUT) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if get_settings("use_ssl"): server_socket = ssl.wrap_socket( server_socket, cert_reqs=ssl.CERT_REQUIRED, ca_certs=get_settings("SSL_KEYFILE_PATH")) try: server_socket.connect((get_settings("host"), get_settings("port"))) if message: server_socket.send(message.encode()) answer = server_socket.recv(1024).decode("utf-8") server_socket.close() return answer except socket.timeout: server_socket.close() return "Превышено время ожидания ответа" server_socket.close() return "Неизвестная ошибка отправки сообщения"
async def healthcheck_post(response: Response): response.status_code = 201 # change status code return { "Endpoint": "POST /api/healthcheck", "App": get_settings().APP, "Version": get_settings().VERSION }
def set_model_path(filename: str): realpath = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.abspath( os.path.join(realpath, "..", get_settings().APP, get_settings().MODEL_FOLDER, filename)) # relative to app return file_path
def get_upload_folder(): realpath = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.abspath( os.path.join(realpath, "..", get_settings().APP, get_settings().UPLOAD_FOLDER)) # relative to app print(file_path) return file_path
def _chooseBackgroundColorSlot(self): currentColor = self._bgColorButton.palette().color(QtGui.QPalette.Background) color = QtGui.QColorDialog.getColor(currentColor, self) if color.isValid(): style = QtCore.QString('QPushButton#bgColorButton {Background-color: %s}' % color.name()) self._bgColorButton.setStyleSheet(style) self._bgColorButton.setText(color.name()) self.setField(QtCore.QString('bgColor'), QtCore.QVariant(color.name())) config.get_settings().setValue(QtCore.QString(config.KEY_GL_BACKGROUND_COLOR), QtCore.QVariant(color.name()))
def check_for_updates(self): if config.get_settings()['update']['enabled']: self.update_download_url = self.request_update_download_url() if self.update_download_url: self.logger.info('Updates available!') self.update_available = True if config.get_settings()['update']['auto_update_enabled']: if not (self.updating_thread and self.updating_thread.is_alive()): self.updating_thread = threading.Thread(target = self.auto_update) self.updating_thread.start()
def global_settings(): try: g.settings = app.config['SETTINGS'] except KeyError: try: g.settings = config.get_settings(request.environ['DEPLOYMENT_TARGET']) except: g.settings = config.get_settings() g.renderer = render_gallery.GalleryRenderer(g.settings)
def add_numbers(a, b): realpath = os.path.dirname( os.path.realpath(__file__) ) file_path = os.path.abspath( os.path.join(realpath, "..", get_settings().APP, get_settings().UPLOAD_FOLDER) ) # relative to app print(file_path) # print(realpath) # print(get_settings().UPLOAD_FOLDER) print("model started") sleep(10) # Time in seconds print("model completed") return a + b
def check_for_updates(self): if config.get_settings()['update']['enabled']: self.update_download_url = self.request_update_download_url() if self.update_download_url: self.logger.info('Updates available!') self.update_available = True if config.get_settings()['update']['auto_update_enabled']: if not (self.updating_thread and self.updating_thread.is_alive()): self.updating_thread = threading.Thread( target=self.auto_update) self.updating_thread.start()
def start_listening() -> None: """Get settings and open socket""" settings_to_socket = get_settings("settings_to_socket") settings_to_publish = get_settings("settings_to_publish") event_log.info("Start working on %s:%s", settings_to_socket.get("host"), settings_to_socket.get("port")) open_socket(settings_to_socket, settings_to_publish) event_log.info("End working")
def connect_huey(): global huey try: queue_name = get_settings().HUEY_TASK_QUEUES url = get_settings().HUEY_REDIS_CONNECTION if url != "" and queue_name != "": huey = RedisHuey(queue_name, url=url, blocking=False) print("Huey Connect") else: print("Huey No Connection ") except Exception as e: print("Huey Connect Fail: " + str(e)) return huey
def connect_mongodb(): try: global mongodb url = get_settings().MONGODB_URL name = get_settings().MONGODB_DB if url != "" and name != "": client = MongoClient(url) mongodb = client[name] print("MongoDB Connected") else: print("No MongoDB Config") except Exception as e: print("MongoDB Connect Fail: " + str(e))
def __init__(self, exe=None, port=None, mode='c', colormap=None): if exe is None: exe = config.get_settings().value(config.KEY_GL_CLIENT_EXECUTABLE).toString() if port is None: port = config.get_settings().value(config.KEY_GL_PORT).toString() if colormap is None: colormap = config.get_settings().value(config.KEY_GL_COLORMAP).toString() self.opt_dict = {} self.opt_dict['-p'] = str(port) self.opt_dict['-m'] = str(mode) self.opt_dict['-c'] = str(colormap) self.executable = str(exe) self.running = False self.run()
def test_get_settings(self): settings = config.get_settings(SETTINGS_LOCATION) self.assertIsNotNone(config._CACHED_SETTINGS) self.assertIs(config._CACHED_SETTINGS, settings) settings_again = config.get_settings(SETTINGS_LOCATION) self.assertIs(settings, settings_again) settings_reloaded = config.get_settings(SETTINGS_LOCATION, refresh=True) self.assertIs(config._CACHED_SETTINGS, settings_reloaded) self.assertIsNot(settings_reloaded, settings) self.assertEqual(settings['Cities']['city9'], settings_reloaded['Cities']['city9'])
def prepare_seed_db() -> Dict: settings = get_settings() if not settings.is_test_env: raise Exception("Seed endpoint can be used only from test environment") client = get_client() client.drop_database(settings.mongo_initdb_database) user = create_user(TEST_USERNAME, "*****@*****.**", TEST_PASSWORD) access_token = _create_access_token(user) accounts = _create_accounts() employers = _create_employers(accounts) finance_categories = _create_finance_categories() currency_exchange_rates = _create_currency_exchange_rates() return { "data": { "access_token": access_token, "accounts": accounts, "employers": employers, "finance_categories": finance_categories, "currency_exchange_rates": currency_exchange_rates, "user": { "username": TEST_USERNAME, "password": TEST_PASSWORD, }, } }
async def connect_to_mongo(): logger.info("Connecting to mongo...") settings = get_settings() db.client = AsyncIOMotorClient(settings.mongo_url, maxPoolSize=settings.max_pool_size, minPoolSize=settings.min_pool_size) logger.info("Connected to mongo successfully")
def __init__(self): config.Config.instance().set_app_pointer(self) self.logger = log.create_logger('', log.LOG_FILE) self.logger.info("Starting 3DPrinterOS client. Version %s_%s" % (version.version, version.build)) self.logger.info('Operating system: ' + platform.system() + ' ' + platform.release()) signal.signal(signal.SIGINT, self.intercept_signal) signal.signal(signal.SIGTERM, self.intercept_signal) self.detected_printers = [] self.network_printers = [] self.printer_interfaces = [] self.virtual_printer_enabled = False self.network_detect_flag = False self.stop_flag = False self.closing_status = [] self.rights_checker_waiter = rights.RightsCheckerWaiter(self) self.conveyor_kill_waiter = makerware_utils.ConveyorKillWaiter(self) self.network_connection_checker = http_client.NetworkConnectionChecker(self) self.init_interface() self.rights_checker_waiter.wait() self.conveyor_kill_waiter.wait() self.network_connection_checker.wait() self.updater = updater.Updater() self.user_login = user_login.UserLogin(self) self.user_login.wait() if self.user_login.user_token and hasattr(self.user_login, "profiles"): config.Config.instance().set_profiles(self.user_login.profiles) self.virtual_printer_enabled = config.get_settings()['virtual_printer']['enabled'] self.tray_controller = tray_controller.TrayController() self.camera_controller = camera_controller.CameraController(self.user_login.user_token,\ self.user_login.http_client.mac) self.cloud_sync_controller = cloud_sync_controller.CloudSyncController() else: self.logger.error("Can't retrieve user login or printer profiles. Exiting...") self.quit()
def init_interface(self): if config.get_settings()['web_interface']['enabled']: import webbrowser from web_interface import WebInterface self.web_interface = WebInterface(self) self.web_interface.start() self.logger.debug("Waiting for webserver to start...") while not self.web_interface.server: time.sleep(0.01) if self.stop_flag: return self.logger.debug("...server is up and running. Connecting browser...") time.sleep(3) if config.get_settings()['web_interface']['browser_opening_on_start']: webbrowser.open("http://127.0.0.1:8008", 2, True) self.logger.debug("...done")
def display_readings(): "Display meter readings" settings = config.get_settings() port = open_serial(settings["device"]) readings = commands.display_readings(port, settings["address"]) print("{} kWh;{} kWh;{} kWh".format(*readings)) return 0
def submit_form(): data = request.form d = {} d['dob'] = data['dob'] d['name'] = data['name'] # account for missing data. Remove when form validation works if d['name'] is '': d['name'] = 'John Doe' if d['dob'] is '': d['dob'] = date.today().strftime('%m-%d-%Y') # process input and retrieve nubers person = PersonData(name=d['name'], dob=d['dob']) firebase.database().child('/data_from_users').\ child(firebase.database().generate_key()).\ set(person.get_json(pyrebase=True)) person = person.get_data() # retrieve relevant interpretations from config, then pass it to the template kindred = get_kindred(person) num_interps = {} settings = config.get_settings() for i in settings['core_numbers']: num_interps[i] = config.INTERPRETATIONS[i][str(person['numbers'][i])] return render_template("report.html", data=person, ni=num_interps, k=kindred, s=settings)
def update(self): if self.update_flag: self.logger.info('Updating client...') update_file_name = config.get_settings()['update']['update_file_name'] try: urllib.urlretrieve(config.get_settings()['update']['update_file_url'] + update_file_name, update_file_name) except Exception as e: error = 'Update failed!\nReason: error while downloading.\nDetails: ' + str(e) self.logger.error(error, exc_info=True) return error else: error = self.extract_update(update_file_name) if error: return error self.logger.info('...client successfully updated!') self.update_flag = False
def post(self): """Authorizes the caller to access AuthDB. In particular grants the caller "pubsub.subscriber" role on the AuthDB change notifications topic and adds the caller as Reader to the Google Storage object that contains AuthDB. Response body: { 'topic': <full name of PubSub topic with AuthDB change notifications>, 'authorized': true, 'gs': { 'auth_db_gs_path': <same as auth_db_gs_path in SettingsCfg proto>, 'authorized': true } } """ try: pubsub.authorize_subscriber(self.caller_email()) gcs.authorize_reader(self.caller_email()) return self.send_response({ 'topic': pubsub.topic_name(), 'authorized': True, 'gs': { 'auth_db_gs_path': config.get_settings().auth_db_gs_path, 'authorized': True, }, }) except (gcs.Error, pubsub.Error) as e: self.abort_with_error(409, text=str(e))
def get(self): """Queries whether the caller is authorized to access AuthDB already. Response body: { 'topic': <full name of PubSub topic with AuthDB change notifications>, 'authorized': <true if the caller is allowed to subscribe to it>, 'gs': { 'auth_db_gs_path': <same as auth_db_gs_path in SettingsCfg proto>, 'authorized': <true if the caller should be able to read GS files> } } """ try: return self.send_response({ 'topic': pubsub.topic_name(), 'authorized': pubsub.is_authorized_subscriber(self.caller_email()), 'gs': { 'auth_db_gs_path': config.get_settings().auth_db_gs_path, 'authorized': gcs.is_authorized_reader(self.caller_email()), }, }) except (gcs.Error, pubsub.Error) as e: self.abort_with_error(409, text=str(e))
def instant_vcp(): "Display instant voltage, current and power consumption" settings = config.get_settings() port = open_serial(settings["device"]) voltage, current, power = commands.instant_vcp(port, settings["address"]) print("{0} V;{1} A;{2} kW".format(voltage, current, power)) return 0
def form_main_page(self): if not self.server.app: pass page = '' if hasattr(self.server.app, 'rights_checker_waiter') and self.server.app.rights_checker_waiter.waiting: page = self.server.web_content_files['pages']['groups_warning.html'] elif hasattr(self.server.app, 'conveyor_kill_waiter') and self.server.app.conveyor_kill_waiter.waiting: page = self.server.web_content_files['pages']['conveyor_warning.html'] if hasattr(self.server.app, 'user_login'): if self.server.app.user_login.user_token: name = 'main_loop_form.html' else: name = 'login.html' page = self.server.web_content_files['pages'][name] if self.YOUR_ACCOUNT_BUTTON: your_account_button = self.server.web_content_files['buttons']['your_account_button.html'] else: your_account_button = '' page = page.replace('!!!YOUR_ACCOUNT_BUTTON!!!', your_account_button) login = self.server.app.user_login.login if login: page = page.replace('!!!LOGIN!!!', login) if config.get_settings()['cloud_sync']['enabled']: # next command performs replace to display CloudSync folder opening button when enabled page = page.replace('open_cloudsync_folder" style="display:none"', 'open_cloudsync_folder"') page = self.place_scripts_on_main_page(page) page = self.place_virtual_printer_button(page) return page
def connect_s3(): try: url = get_settings().S3_ENDPOINT_URL global s3 if url != "": s3 = boto3.client( "s3", endpoint_url=get_settings().S3_ENDPOINT_URL, aws_access_key_id=get_settings().S3_ACCESS_ID, aws_secret_access_key=get_settings().S3_SECRET_KEY) print("S3 Connected") else: s3 = None print("No S3 Config") except Exception as e: print("S3 Connect Fail: " + str(e))
def form_main_page(self): page = '' if self.server.app: if self.server.app.user_login.user_token and self.YOUR_ACCOUNT_BUTTON: name = 'web_interface/main_loop_form.html' elif self.server.app.user_login.user_token and not self.YOUR_ACCOUNT_BUTTON: name = 'web_interface/main_loop_form_button_off.html' else: name = 'web_interface/login.html' page = self.read_file(name) printers = self.get_printers_payload() page = page.replace('!!!PRINTERS!!!', printers) login = self.server.app.user_login.login if login: page = page.replace('!!!LOGIN!!!', login) if makerware_utils.get_conveyor_pid(): page = self.read_file('web_interface/conveyor_warning.html') if self.server.app.rights_checker_and_waiter.waiting: page = self.read_file('web_interface/groups_warning.html') if self.server.app.updater.update_flag: # next command performs replace to display update button when updates available page = page.replace('get_updates" style="display:none"', 'get_updates"') if config.get_settings()['cloud_sync']['enabled']: # next command performs replace to display CloudSync folder opening button when enabled page = page.replace( 'open_cloudsync_folder" style="display:none"', 'open_cloudsync_folder"') return page
def delete(self): """Revokes the authorization if it exists. Response body: { 'topic': <full name of PubSub topic with AuthDB change notifications>, 'authorized': false, 'gs': { 'auth_db_gs_path': <same as auth_db_gs_path in SettingsCfg proto>, 'authorized': false } } """ try: pubsub.deauthorize_subscriber(self.caller_email()) gcs.deauthorize_reader(self.caller_email()) return self.send_response({ 'topic': pubsub.topic_name(), 'authorized': False, 'gs': { 'auth_db_gs_path': config.get_settings().auth_db_gs_path, 'authorized': False, }, }) except (gcs.Error, pubsub.Error) as e: self.abort_with_error(409, text=str(e))
def send_email(partner, certificate, cert_url: HttpUrl, settings: Settings = get_settings()): body_text = EMAIL_BODY_TEXT.format(partner=partner, certificate=certificate, cert_url=cert_url, settings=settings) body_html = EMAIL_BODY_HTML.format(partner=partner, certificate=certificate, cert_url=cert_url, settings=settings) try: msg = MIMEMultipart("alternative") msg["Subject"] = settings.EMAIL_SUBJECT msg["From"] = settings.EMAIL_FROM msg["To"] = partner.email msg["Cc"] = settings.EMAIL_CC or "" part1 = MIMEText(body_text, "plain", "utf-8") part2 = MIMEText(body_html, "html", "utf-8") msg.attach(part1) msg.attach(part2) server = smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT) server.ehlo() server.login(settings.SMTP_USER, settings.SMTP_PASSWORD.get_secret_value()) server.sendmail(settings.EMAIL_FROM, partner.email, msg.as_string()) logger.info(f"email sent to: {partner.email}") except Exception as err: logger.error(f"email not sent: {err}")
def form_main_page(self): page = '' if self.server.app: if hasattr(self.server.app, 'rights_checker_waiter') and self.server.app.rights_checker_waiter.waiting: page = self.server.web_content_files['groups_warning.html'] elif hasattr(self.server.app, 'conveyor_kill_waiter') and self.server.app.conveyor_kill_waiter.waiting: page = self.server.web_content_files['conveyor_warning.html'] if hasattr(self.server.app, 'user_login'): if self.server.app.user_login.user_token and self.YOUR_ACCOUNT_BUTTON: name = 'main_loop_form.html' elif self.server.app.user_login.user_token and not self.YOUR_ACCOUNT_BUTTON: name = 'main_loop_form_button_off.html' else: name = 'login.html' page = self.server.web_content_files[name] printers = self.get_printers_payload() page = page.replace('!!!PRINTERS!!!', printers) login = self.server.app.user_login.login if login: page = page.replace('!!!LOGIN!!!', login) if self.server.app.updater.update_flag: # next command performs replace to display update button when updates available page = page.replace('get_updates" style="display:none"', 'get_updates"') if config.get_settings()['cloud_sync']['enabled']: # next command performs replace to display CloudSync folder opening button when enabled page = page.replace('open_cloudsync_folder" style="display:none"', 'open_cloudsync_folder"') return page
def __init__(self, parent=None): QtGui.QWizard.__init__(self, parent) self._pymooseDemosDir = str(config.get_settings().value(config.KEY_DEMOS_DIR).toString()) if not self._pymooseDemosDir: self._pymooseDemosDir = '/usr/share/doc/moose1.3/DEMOS/pymoose' # self._glclientPath = str(config.get_settings().value(config.KEY_GL_CLIENT_EXECUTABLE).toString()) # if not self._glclientPath: # self._glclientPath = '/usr/bin/glclient' self._colormapPath = str(config.get_settings().value(config.KEY_GL_COLORMAP).toString()) if not self._colormapPath: self._colormapPath = '/usr/share/moose1.3/colormaps/rainbow2' self.addPage(self._createIntroPage()) self.addPage(self._createDemosPage()) #self.addPage(self._createGLClientPage()) self.addPage(self._createColormapPage()) self.connect(self, QtCore.SIGNAL('accepted()'), self._finished)
def form_main_page(self): page = '' if self.server.app: if self.server.app.user_login.user_token and self.YOUR_ACCOUNT_BUTTON: name = 'web_interface/main_loop_form.html' elif self.server.app.user_login.user_token and not self.YOUR_ACCOUNT_BUTTON: name = 'web_interface/main_loop_form_button_off.html' else: name = 'web_interface/login.html' page = self.read_file(name) printers = self.get_printers_payload() page = page.replace('!!!PRINTERS!!!', printers) login = self.server.app.user_login.login if login: page = page.replace('!!!LOGIN!!!', login) if makerware_utils.get_conveyor_pid(): page = self.read_file('web_interface/conveyor_warning.html') if self.server.app.rights_checker_and_waiter.waiting: page = self.read_file('web_interface/groups_warning.html') if self.server.app.updater.update_flag: # next command performs replace to display update button when updates available page = page.replace('get_updates" style="display:none"', 'get_updates"') if config.get_settings()['cloud_sync']['enabled']: # next command performs replace to display CloudSync folder opening button when enabled page = page.replace('open_cloudsync_folder" style="display:none"', 'open_cloudsync_folder"') return page
def upload_auth_db(signed_auth_db, revision_json): """Updates Google Storage files to contain the latest AuthDB. Will write two Google Storage objects (in that order): * <auth_db_gs_path>/latest.db: binary-serialized SignedAuthDB. * <auth_db_gs_path>/latest.json: JSON-serialized AuthDBRevision. Where <auth_db_gs_path> is taken from 'auth_db_gs_path' in SettingsCfg in config.proto. Each individual file write is atomic, but it is possible latest.db is updated but latest.json is not (i.e. if the call crashes in between two writes). If this happens, 'upload_auth_db' should be retried. Eventually both files should agree. Args: signed_auth_db: binary-serialized SignedAuthDB proto message. revision_json: JSON-serialized AuthDBRevision proto message. Raises: net.Error if Google Storage writes fail. """ gs_path = config.get_settings().auth_db_gs_path if not gs_path: return assert not gs_path.endswith('/'), gs_path readers = _list_authorized_readers() _upload_file(path=gs_path + '/latest.db', data=signed_auth_db, content_type='application/protobuf', readers=readers) _upload_file(path=gs_path + '/latest.json', data=revision_json, content_type='application/json', readers=readers)
def check(self): if sys.platform.startswith('linux') and config.get_settings()['linux_rights_warning'] and not is_admin(): self.logger.info('Checking Linux rights') result = self.execute_command('groups') if not ('tty' in result and 'dialout' in result and 'usbusers' in result): self.logger.info('Current Linux user is not in tty and dialout groups') self.waiting = True
def start_cloud_sync_process(self): if config.get_settings()['cloud_sync']['enabled'] and self.CLOUD_SYNC_MODULE: self.logger.info('Launching CloudSync subprocess') cs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.CLOUD_SYNC_MODULE) try: self.cloud_sync_process = subprocess.Popen([sys.executable, cs_path]) except Exception as e: self.logger.warning('Could not launch CloudSync due to error:\n' + str(e))
def check_if_user_in_groups(self): if sys.platform.startswith('linux') and config.get_settings()['linux_rights_warning'] and not is_admin(): self.logger.debug('Checking Linux rights') result = self.execute_command('groups') if not ('tty' in result and 'dialout' in result and 'usbusers' in result): self.logger.debug('Current Linux user is not in tty and dialout groups') return False return True
def new_version_available(self): if config.get_settings()['update']['enabled']: self.http_client.connect() last_version = self.http_client.request('GET', self.http_client.connection, self.http_client.get_last_version_path, None, headers = {}) self.http_client.close() if last_version: reload(version) return self.compare_versions(version.version, last_version)
def get_app(config=get_settings()): app = Flask(__name__) app.config.from_object(config) register_extensions(app) register_blueprints(app) return app
def __init__(self, balloon_func): self.show_balloon = balloon_func self.notifications = config.get_settings()['tray_icon']['notifications_enabled'] self.identical_printers_status = False self.updates_available_status = False self.last_printer_statuses = [] self.stop_flag = False self.main_loop = threading.Thread(target=self.start_main_loop) self.main_loop.start()
def create_logger(logger_name, log_file_name=None): logger = logging.getLogger(logger_name) logger.setLevel(logging.DEBUG) std_handler = logging.StreamHandler(stream=sys.stdout) std_handler.setLevel(logging.DEBUG) logger.addHandler(std_handler) if log_file_name and config.get_settings().get('logging') and config.get_settings()['logging']['enabled']: if config.get_settings()['logging']['erase_on_start']: clear_logs() try: file_handler = logging.handlers.RotatingFileHandler(log_file_name, 'a', LOG_FILE_SIZE, LOG_BACKUPS) file_handler.setFormatter(logging.Formatter('%(levelname)s\t%(asctime)s\t%(threadName)s/%(funcName)s\t%(message)s')) file_handler.setLevel(logging.DEBUG) logger.addHandler(file_handler) print "File logger created: " + log_file_name except Exception as e: print 'Could not create log file because' + e.message + '\n.No log mode.' return logger
def update(self): if self.update_flag: self.logger.info('Updating client...') update_file_name = config.get_settings()['update']['update_file_name'] try: urllib.urlretrieve(config.get_settings()['update']['update_file_url'] + update_file_name, update_file_name) except Exception as e: error_message = 'Update failed!\nReason: error while downloading.\nDetails: ' + str(e) config.create_error_report(0, error_message, None, self.logger, is_blocking=True) return error_message else: error = self.extract_update(update_file_name) if error: return error self.logger.info('...client successfully updated!') self.update_flag = False log.send_logs() log.clear_logs()
def init_interface(self): if config.get_settings()['web_interface']['enabled']: import webbrowser from web_interface import WebInterface self.web_interface = WebInterface(self) self.web_interface.start() self.logger.debug("Waiting for webserver to start...") while not self.web_interface.server: time.sleep(0.01) if self.stop_flag: return self.logger.debug( "...server is up and running. Connecting browser...") time.sleep(3) if config.get_settings( )['web_interface']['browser_opening_on_start']: webbrowser.open("http://127.0.0.1:8008", 2, True) self.logger.debug("...done")
def execute(media_type, item_id): path, command = get_settings('path', 'command') if path != 'None': t = threading.Thread(target=execute_thread, args=(media_type, item_id, path, command)) t.start() return 'started' else: return 'no setup'
def run_around_tests(): settings = get_settings() # setup # to be sure that each test is independent client = get_client() client.drop_database(settings.mongo_initdb_database) yield
def start(self): self.logger.info('CloudSync started!') self.stop_flag = False self.login() self.create_folders() if self.mswin: self.create_shortcuts_win() if config.get_settings()['cloud_sync']['virtual_drive_enabled']: self.enable_virtual_drive() self.main_loop()
def toggle_virtual_printer(self): self.virtual_printer_enabled = not self.virtual_printer_enabled if not self.virtual_printer_enabled: for printer_interface in self.printer_interfaces: usb_info = getattr(printer_interface, 'usb_info', None) if usb_info and usb_info == self.VIRTUAL_PRINTER_USB_INFO: printer_interface.close() settings = config.get_settings() settings['virtual_printer']['enabled'] = self.virtual_printer_enabled config.Config.instance().save_settings(settings)
def toggle_cloud_sync(self): settings = config.get_settings() if self.server.app.cloud_sync_controller.cloud_sync_process: self.server.app.cloud_sync_controller.stop_cloud_sync_process() settings['cloud_sync']['enabled'] = False else: self.server.app.cloud_sync_controller.start_cloud_sync_process() settings['cloud_sync']['enabled'] = True config.Config.instance().save_settings(settings) self.do_GET()
def __init__(self): self.logger = log.create_logger("app.camera") self.stop_flag = False paths.init_path_to_libs() import numpy as np import cv2 as cv2 self.np = np self.cv2 = cv2 signal.signal(signal.SIGINT, self.intercept_signal) signal.signal(signal.SIGTERM, self.intercept_signal) ul = user_login.UserLogin(self) ul.wait() self.user_token = ul.user_token self.image_extension = config.get_settings()["camera"]["img_ext"] self.image_quality = config.get_settings()["camera"]["img_qual"] self.hardware_resize = config.get_settings()["camera"]["hardware_resize"] self.min_loop_time = config.get_settings()["camera"]["min_loop_time"] self.search_cameras() self.http_client = http_client.HTTPClient(keep_connection_flag=True) self.main_loop()
def __init__(self, port_name, baudrate, timeout=DEFAULT_TIMEOUT, start_dtr=None): self.logger = logging.getLogger(__name__) self.port_name = port_name self.baudrate = baudrate self.timeout = timeout self.start_dtr = start_dtr self.port_recv_lock = threading.Lock() self.port_send_lock = threading.Lock() self.verbose = config.get_settings()['verbose'] self.port = None self.connect()
def start_camera_process(self, camera_name=None): self.logger.info('Launching camera subprocess') if not camera_name: camera_name = config.get_settings()['camera']['default'] module_name = self.CAMERA_MODULES[camera_name] if module_name: cam_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), module_name) try: self.camera_process = subprocess.Popen([sys.executable, cam_path]) self.current_camera_name = camera_name except Exception as e: self.logger.warning('Could not launch camera due to error:\n' + str(e))
def start(self): tray_settings = config.get_settings().get('tray_icon') if tray_settings.get('enabled'): if platforms.PLATFORM == 'mac': module_name = 'mac_tray.py' elif platforms.PLATFORM == 'win': module_name = 'wx_tray.py' elif platforms.PLATFORM == 'linux': module_name = 'gtk_tray.py' else: module_name = None if module_name: module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), module_name) return subprocess.Popen([sys.executable, module_path], close_fds=True)
def get_settings(): """ Request handler for the /settings/ path. GET: returns the current jobber settings as a json doc. Args: None Returns: Jobber settings (str): jobber settings as json doc. """ try: return _make_response(response=config.get_settings()) except Exception as e: return _make_error(500, e.message)
def select_printer_groups(self): usb_info = self.get_posted_data('usb_info') page = self.page_former.form_printer_groups_page(usb_info) if page: self.write_with_autoreplace(page) else: if config.get_settings()['HTTPS']: prefix = 'https://' else: prefix = 'http://' back_button = self.page_former.form_back_button('/') self.write_message("<p>To create a new Workgroup Access code, please check Admin tab \ at <a href='" + prefix + \ "!!!URL!!!/workgroup' target='_blank'>!!!URL!!!/workgroup</a></p>\ Workgroup access codes is a premium \ feature, to use that please contact our sales: \ <a href='mailto:[email protected]'>[email protected]</a>" \ + back_button , show_time=0)