def mount(self): """Check, create and return custom folder Returns: str: Full path to your custom shots folder Raises: OSError: if cant' crate folder EnvironmentError: if folder not exist and CUSTOM_CREATE is False """ if not os.path.isdir(self.folder): if self.create_if_not_exists: try: os.makedirs(self.folder) except OSError as err: logger.exception("Can't create folder %r", self.folder) raise OSError( host.tr( "Can't create folder '{}'<br>" "Error code {}: {}" ).format(self.folder, err.errno, err.strerror) ) else: raise EnvironmentError( host.tr("Folder {} not exist.<br>Set 'Create if not exist' = True") ) return self.folder
def list_type(self, list_type_to_react): all_types_of_lists = { host.tr("не распознан"): [-100], } _list_type = all_types_of_lists.get(list_type_to_react) if _list_type is None: raise ValueError(host.tr("Тип списка не установлен")) else: self._list_type = _list_type
def show_popup(self, channel, ts, alrm_msg): logger.debug("Start show popup window") host.question( alrm_msg, host.tr("Отмена"), self.cancel_function, host.tr("Посмотреть событие в архиве"), lambda: self.open_archive(channel, ts), 60 * 60, )
def mount(self): """This script use host.path_arbitrary_data method And returns /media/TrassirArchive*/TrassirArbitraryData/shots Note: If there are several HDDs in the system, the path /media/TrassirArchive* is mounted dynamically and change at each boot. Returns: str: ...path_arbitrary_data/shots path Raises: EnvironmentError: if HDD not found """ data_path = host.path_arbitrary_data() logger.debug("data_path = %r", data_path) if not data_path: logger.error("HDD Not Found") raise EnvironmentError( host.tr( "HDD Not Found!<br>" "Make sure at least 1 HDD is active.<br>" "Restart script. If you see this message again - contact with [email protected]" ) ) shots_path = os.path.join(data_path, "shots") if not os.path.isdir(shots_path): os.makedirs(shots_path) return shots_path
def __init__(self, source_path, delete_persons=False, update_same_person=False): if not os.path.exists(source_path): raise ValueError(host.tr("path not found: %s" % source_path)) self.source_path = source_path self.gender_codes = {"male": 1, "female": 2, "other": 3} self.delete_persons = delete_persons self.update_same_person = update_same_person
def initialization(): if CHAN_BAD: bad_list = [host.object(x).guid for x in CHAN_BAD.split(",")] else: bad_list = [] logger.debug(bad_list) logger.debug(choice_dict[CHOICE]) if CHAN: carousel_list = [ host.object(x).guid for x in CHAN.split(",") if not host.object(x).guid in bad_list ] else: carousel_list = [ x[1] for x in host.objects_list(choice_dict[CHOICE]) if not x[1] in bad_list ] logger.debug(carousel_list) for x in [z[1] for z in host.objects_list("IP Device")]: if x in carousel_list: raise ValueError( host.tr("Имеется IP устройство с именем канала %s") % host.object(x).name ) logger.debug("list %s done!" % carousel_list) return {x: z for x, z in enumerate(carousel_list)}
class SettingsHandler(BaseHandler): __template__ = "settings.mako" title = host.tr("Настройки") rights = "has_setup_rights" def get(self, request, *args, **kwargs): if not request.user.has_setup_rights: return HttpResponseForbidden( "Sorry %s, you have no setup rights" % request.user.name ) return self.render(config=config, saved=kwargs.get("saved"), errors=kwargs.get("errors", {})) get.need_auth = True def post(self, request, *args, **kwargs): if not request.user.has_setup_rights: return HttpResponseForbidden( "Sorry %s, you have no setup rights" % request.user.name ) with lock: success, errors = config.save_form_data(request.POST) kwargs["saved"] = success kwargs["errors"] = errors return self.get(request, *args, **kwargs) post.need_auth = True
def __init__(self, key, name, *args, **kwargs): self.key = key self.name = host.tr(name) self.multiple = kwargs.get("multiple", False) self.description = kwargs.get("description", "") self.onchange = kwargs.get("onchange") self.kwargs = kwargs self.__value = self.default if callable(self.onchange): self.onchange(self, None)
def get_alarm_message(chan_name, tmstmp): event_time = BaseUtils.ts_to_dt(tmstmp) alarm_messages = { "alert_message": ("<br><b><font color='red'>{event_time} {event_type}</font></b>" "<br>{on_channel}: {chan_name}").format( event_time=event_time.strftime("%H:%M:%S"), event_type=host.tr("Номер не распознан"), on_channel=host.tr("Канал"), chan_name=chan_name, ), "sms_message": ("{event_time}.{event_type}. {on_channel}:{chan_name}").format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Номер не распознан"), on_channel=host.tr("Канал"), chan_name=chan_name, ), "mail_message": ("{event_time}. {event_type}. {on_channel}: {chan_name}").format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Номер не распознан"), on_channel=host.tr("Канал"), chan_name=chan_name, ) } return alarm_messages
def acs_operation(self): try: self.ts_to_come_back = time.time() + self.delay_operations if self.come_back_timer_is_working: return else: self.come_back_timer_is_working = True if self.operation_type == host.tr("открыть дверь"): self._open_door() else: self._close_door() self._timer() except Exception as err: logger.exception("Error occur in access control module: %s", err)
def list_type(self, list_type_to_react): all_types_of_lists = { host.tr("чёрном"): [0], host.tr("белом"): [2], host.tr("информационном"): [1], host.tr("любом"): [0, 1, 2], host.tr("нет в списках"): [-1], host.tr("любой номер"): [-1, 0, 1, 2], } _list_type = all_types_of_lists.get(list_type_to_react) if _list_type is None: raise ValueError(host.tr("Тип списка не установлен")) else: self._list_type = _list_type
class IndexHandler(BaseHandler): __template__ = "index.mako" title = host.tr("Главная") def get(self, request, *args, **kwargs): return self.render() def post(self, request, *args, **kwargs): return JsonResponse( { "current": config.peoples_current.value, "total": config.peoples_total.value, "available": config.peoples_total.value - config.peoples_current.value, } )
def __init__(self, folder, create_if_not_exists=False): """Create if need and return your path Args: folder (str): Full path to your custom shots folder create_if_not_exists (bool, optional): If True - script trying to create folder if it not exists. Default: False Raises: ValueError: if custom folder not set """ if not folder: logger.warning("Custom folder not set") raise ValueError(host.tr("Custom folder not set")) self.folder = folder self.create_if_not_exists = create_if_not_exists
def direction(self, direction_to_work): if direction_to_work not in [ host.tr("вниз"), host.tr("вверх"), host.tr("любое"), ]: raise ValueError("{text}: {direction}".format( text=host.tr("Не правильный тип направления движения авто"), direction=direction_to_work, )) direction_types = { host.tr("вниз"): [2], host.tr("вверх"): [1], host.tr("любое"): [1, 2], } self._direction = direction_types[direction_to_work] logger.debug("direction to work: %s", self._direction)
def _check_path(path): """Check write access to folder Args: path (str): Full folder path Raises: IOError: if can't write test file to folder """ test_file = os.path.join(path, "write_test") try: with open(test_file, "w") as opened_file: opened_file.write("Test write access") os.remove(test_file) except IOError as err: logger.exception("No write access to folder %r", path) raise IOError( host.tr( "Check write access to folder '{}' failed<br>" "Error code {}: {}<br>" "Change folder or disable 'Check write access'" ).format(path, err.errno, err.strerror) )
USER = GLOBALS.get("USER", "") DEBUG = GLOBALS.get("DEBUG", False) import helpers helpers.set_script_name() logger = helpers.init_logger("Carousel Universal", debug=DEBUG) import host import time import threading from functools import wraps choice_dict = { host.tr("Каналы"): "Channel", host.tr("Шаблоны"): "Template", } def _run_as_thread(fn): @wraps(fn) def run(*args, **kwargs): t = threading.Thread(target=fn, args=args, kwargs=kwargs) t.daemon = True t.start() return t return run
SOUND_NAME = GLOBALS.get("SOUND_NAME", "bell.wav") OUTPUT_ON = GLOBALS.get("OUTPUT_ON", False) ACS_ENBL = GLOBALS.get("ACS_ENBL", False) SHOW_MESSAGE = GLOBALS.get("SHOW_MESSAGE", False) SHOW_POPUP = GLOBALS.get("SHOW_POPUP", False) SHOW_MESSAGE_DELAY = GLOBALS.get("SHOW_MESSAGE_DELAY", 5) CHANNELS_NAMES = GLOBALS.get("CHANNELS_NAMES") # """Тревожный монитор""" AM_ALARM_TEMPLATE = GLOBALS.get("AM_ALARM_TEMPLATE") AM_MAX_CHANS = GLOBALS.get("AM_MAX_CHANS", 6) AM_BASE_TEMPLATE = GLOBALS.get("AM_BASE_TEMPLATE") AM_DISPLAY_DURATION = GLOBALS.get("AM_DISPLAY_DURATION", 30) AM_TYPE = GLOBALS.get("AM_TYPE", host.tr("Отобразить канал")) AM_NO_MOTION_CHECK = GLOBALS.get("AM_NO_MOTION_CHECK", False) AM_CHANGE_TEMPLATE_CHECK = GLOBALS.get("AM_CHANGE_TEMPLATE_CHECK", False) AM_MON = GLOBALS.get("AM_MON", 1) # """ Операции со СКУД """ ACS_MAN_ACTIV = GLOBALS.get("ACS_MAN_ACTIV", host.tr("нет")) ACS_TYPE = GLOBALS.get("ACS_TYPE", "Sigur") ACS_DOOR = GLOBALS.get("ACS_DOOR") ACS_DELAY = GLOBALS.get("ACS_DELAY", 5) ACS_LOGIC = GLOBALS.get("ACS_LOGIC", "open the door") # """ Настройка e-mail """ EMAIL_ACCOUNT = GLOBALS.get("EMAIL_ACCOUNT", "") EMAIL_ADDRESSES = GLOBALS.get("EMAIL_ADDRESSES", "")
def get_alarm_message(chan_name, tmstmp, plate, plate_comment, list_name): """ Args: chan_name (str): channel name tmstmp (long): Trassir timestamp plate (str): plate from event or recognized plate plate_comment (str): plate comment list_name (str): list_name Returns: 'dict' """ alarm_messages = {} event_time = BaseUtils.ts_to_dt(tmstmp) plate = plate.upper() if plate_comment: plate_comment_alarm_message = "<br>Комментарий: {}.".format(plate_comment) plate_comment_mail_message = " Комментарий: {}.".format(plate_comment) else: plate_comment_alarm_message = "" plate_comment_mail_message = "" if list_name: list_name_alarm_message = "<br>Имя списка: {list_name}.".format( list_name=list_name ) list_name_mail_message = " Имя списка: {list_name}.".format(list_name=list_name) else: list_name_alarm_message = "" list_name_mail_message = "" alarm_messages["alert_message"] = ( "<br><b><font color='red'>{event_time} {event_type}</font></b>" "<br>{plate}{plate_comment}{list_name}" "<br>{on_channel}: {chan_name}" ).format( event_time=event_time.strftime("%H:%M:%S"), event_type=host.tr("Распознан номер"), plate=plate, plate_comment=plate_comment_alarm_message, on_channel=host.tr("Канал"), chan_name=chan_name, list_name=list_name_alarm_message, ) alarm_messages["sms_message"] = ( "{event_time}.{event_type}:{plate}{plate_comment}.{on_channel}:{chan_name}" ).format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Распознан номер"), plate=plate, plate_comment=plate_comment, on_channel=host.tr("Канал"), chan_name=chan_name, ) alarm_messages["mail_message"] = ( "{event_time}. {event_type}: {plate}.{plate_comment}{list_name} {on_channel}: {chan_name}" ).format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Распознан номер"), plate=plate, plate_comment=plate_comment_mail_message, on_channel=host.tr("Канал"), chan_name=chan_name, list_name=list_name_mail_message, ) return alarm_messages
logger.debug("Person created with guid: %s", person_guid) host.service_fr_person_enroll(person_guid, 10) time.sleep(0.1) if folder_obj.persons and self.delete_persons: self._delete_person(folder_obj) # ---------------------------------------- # Initializing # ---------------------------------------- if __name__ != host.stats().parent().guid: raise EnvironmentError("Script run on Trassir server only") if TYPE_OF_WORK == "import": IMPORT_FOLDER = os.path.normpath(IMPORT_FOLDER) assert os.path.isdir(IMPORT_FOLDER), host.tr("Source not found: %s" % IMPORT_FOLDER) logger.debug("source folder to upload data: %s", IMPORT_FOLDER) importer = Importer(IMPORT_FOLDER, DELETE_PERSONS, UPDATE_SAME_PERSON) importer.upload_data() else: folder_name = "face_from_folder_{}".format( datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S")) destination_path = os.path.join( host.settings("system_wide_options")["screenshots_folder"], folder_name) exporter = Exporter(destination_path) exporter.collect_data()
def save( self, channel_full_guid, dt=None, figures=False, file_name=None, file_path=None, callback=None, task_guid=None, fmt=None, ): """Saving screenshot Args: channel_full_guid (str): Screenshot full guid, `channelGuid_serverGuid` dt (datetime.datetime, optional): Shot datetime, default current time figures (bool, optional): Trying to save shots with figures if True file_name (str, optional): Screenshot filename, default None file_path (str, optional): Path to save shot, default None callback (callable, optional): Callback after shot saved, default None task_guid (str, optional): Custom task guid, default None fmt (Dict[str: Any]): Used as kwargs for filename/filepath formatting Returns: Tuple[str, str]: task guid and file path """ task_guid = task_guid or host.random_guid() callback = callback or self.callback logger.debug( "ShotSaver.save(%r, dt=%r, figures=%r, file_name=%r, file_path=%r, callback=%r, task_guid=%r)", channel_full_guid, dt, figures, file_name, file_path, callback, task_guid, ) if "_" not in channel_full_guid: raise ValueError( "Expected full channel guid, got {}".format(channel_full_guid)) channel_guid, server_guid = channel_full_guid.split("_") try: server = host.settings( "/{server_guid}".format(server_guid=server_guid)) except KeyError: raise EnvironmentError( host.tr("Server %s not found") % server_guid) try: channel = host.settings( "/{server_guid}/channels/{channel_guid}".format( server_guid=server_guid, channel_guid=channel_guid)) except KeyError: raise EnvironmentError( host.tr("Channel %s not found on server %s") % (channel_guid, server.name)) if dt is None: ts = 0 dt = datetime.datetime.now() else: if not isinstance(dt, datetime.datetime): ts = dt try: dt = ts_to_dt(dt) except ValueError: raise ValueError( "Can't parse datetime from %s, try to use datetime.datetime instance" % dt) else: ts = dt_to_ts(dt) ts = str(ts) if fmt is None: fmt = {} file_name = (file_name or self.file_name_tmpl).format(channel=channel, server=server, **fmt) file_name = dt.strftime(file_name) file_path = (file_path or self.screenshots_folder).format(channel=channel, server=server, **fmt) file_path = dt.strftime(file_path) created_ts = time.time() + self.buffer_ts self.__check_path(file_path) self.__thread_pool.add_task( self.__async_shot, channel_full_guid, file_name, file_path, ts, created_ts, figures, callback, task_guid, ) host.timeout(10, lambda: callback(task_guid, status.in_queue)) return task_guid, _win_encode_path(os.path.join(file_path, file_name))
def path_to_sound_file(self, file_name): self._path_to_sound_file = os.path.join(os.getcwd(), "sounds", file_name) if not os.path.exists(self._path_to_sound_file): raise ValueError(host.tr("Не найден файл для звуковых оповещений")) logger.debug("Sound file path: %s", self._path_to_sound_file)
return self._set_screenshots_folder(new_folder) if self.folder.rollback is True: host.register_finalizer(self.rollback) if __name__ == host.stats().parent().guid: t1utils.resources_check(script_path, resources) name_changed = set_script_name("Screenshot Folder Changer") if not name_changed: if os.name == "nt": raise OSError(host.tr("This script only for TrassirOS")) if SHOTS_PATH in (host.tr("Default"), "Default"): folder_obj = DefaultFolder() elif SHOTS_PATH == host.tr("HDD"): folder_obj = HDDFolder() elif SHOTS_PATH == host.tr("Network (CIFS)"): logger.info( "NET_SOURCE, NET_USERNAME, NET_PASSWORD = %r, %r, %r", NET_SOURCE, NET_USERNAME, NET_PASSWORD, ) folder_obj = NetworkFolder(NET_SOURCE)
import helpers helpers.set_script_name() logger = helpers.init_logger("shutdown_by_schedule", debug=DEBUG) import os import sys import time import host from __builtin__ import object from schedule_object import ScheduleObject if os.name == "nt" and RESTART_TYPE == "Reset monitor settings": raise EnvironmentError( host.tr("Reset monitor settings is not available for WinOS")) EXIT_CODES = { "Shutdown Trassir only": 0, "SW reboot": 102, "HW Reboot": 103, "Power off": 104, "Reset monitor settings": 103, } MONITOR_SETTINGS_FILE = "/home/trassir/nvr-system-settings.ini" def get_uptime_sec(): return int(time.time() - (int(host.settings("health")["startup_ts"]) / 1e6))
def save( self, channel_full_guid, dt=None, figures=False, file_name=None, file_path=None, callback=None, task_guid=None, ): task_guid = task_guid or host.random_guid() callback = callback or self.callback logger.debug( "ShotSaver.save(%r, dt=%r, figures=%r, file_name=%r, file_path=%r, callback=%r, task_guid=%r)", channel_full_guid, dt, figures, file_name, file_path, callback, task_guid, ) if "_" not in channel_full_guid: raise ValueError( "Expected full channel guid, got {}".format(channel_full_guid)) channel_guid, server_guid = channel_full_guid.split("_") try: server = host.settings( "/{server_guid}".format(server_guid=server_guid)) except KeyError: raise EnvironmentError( host.tr("Server %s not found") % server_guid) try: channel = host.settings( "/{server_guid}/channels/{channel_guid}".format( server_guid=server_guid, channel_guid=channel_guid)) except KeyError: raise EnvironmentError( host.tr("Channel %s not found on server %s") % (channel_guid, server.name)) if dt is None: ts = 0 dt = datetime.datetime.now() else: if not isinstance(dt, datetime.datetime): ts = dt try: dt = ts_to_dt(dt) except ValueError: raise ValueError( "Can't parse datetime from %s, try to use datetime.datetime instance" % dt) else: ts = dt_to_ts(dt) ts = str(ts) file_name = (file_name or self.file_name_tmpl).format(channel=channel, server=server) file_name = dt.strftime(file_name) file_path = file_path or self.screenshots_folder self.__check_path(file_path) self.__thread_pool.add_task( self.__async_shot, channel_full_guid, file_name, file_path, ts, figures, callback, task_guid, ) host.timeout(10, lambda: callback(task_guid, status.in_queue)) return task_guid, _win_encode_path(os.path.join(file_path, file_name))