def get_cameras(server_guid): """ Args: server_guid (str): Returns: Dict() """ is_local = host.settings("").guid == server_guid for sett in host.settings("/%s/ip_cameras" % server_guid).ls(): if sett.type != "Grabber": continue if is_local: yield sett else: if not sett["grabber_enabled"]: logger.debug( "for server %s device %s (%s) is disabled, skipping it", server_guid, sett.name, sett.guid, ) continue yield sett
def check_fr_master_guid(server_guid): """ Проверяем какой тип БД на указанном сервере с распознавателем лиц: локальная или другой сервер Для статистики. Args: server_guid (str): server guid with """ this_server_guid = host.settings("").guid if this_server_guid == "client": msg = "This is Trassir Client." else: msg = "This is Trassir Server guid: {s_guid}.".format( s_guid=this_server_guid) try: master_guid = host.settings("/{server_guid}/face_recognizer".format( server_guid=server_guid))["master_guid"] if master_guid != this_server_guid: msg = "{} Fr master guid: {} is another server.".format( msg, master_guid) logger.debug(msg) except KeyError as err: if "face_recognizer" in err[0]: err_msg = "Face recognizer not found on: {}.".format(server_guid) else: err_msg = err[0] logger.error(err_msg)
def _create_path(self, rel_path): """ Args: rel_path (str): Returns: """ logger.debug("start create path: %s", rel_path) split_path = self._split_path(rel_path) logger.debug("split file: %s", split_path) relative_full_path = "persons" for path in split_path: parent_folder = host.settings( "{path}".format(path=relative_full_path)) relative_full_path = "/".join([relative_full_path, path]) logger.debug("relative full path: %s", relative_full_path) try: host.settings("{path}".format(path=relative_full_path)) except KeyError: ts_start = time.time() res = host.service_create_person_folder( { "parent_guid": parent_folder.guid, "name": path }, 3) logger.info( 'folder "%s" created. Time for creation: %s. result: %s', path, time.time() - ts_start, res, )
def __init__( self, file_name_tmpl="{name} ({dt_start} - {dt_end}){sub}.avi", export_folder=None, callback=None, queue_maxlen=1000 ): """ Args: file_name_tmpl (str, optional): Default filename template, default: "{name} ({dt_start} - {dt_end}){sub}.avi" export_folder (str, optional): Default export path, default: screenshots_folder callback (callable, optional): Default callback function, default: None queue_maxlen (int, optional): Max queue length, default: 1000 """ self._export_folder = "" self.export_folder = ( export_folder or host.settings("system_wide_options")["screenshots_folder"] ) self._now_exporting = False self._queue = deque(maxlen=queue_maxlen) self.file_name_tmpl = file_name_tmpl self._default_prebuffer = host.settings("archive")["prebuffer"] + 2 self.callback = callback or _do_nothing self.__exporting_task = None
def find_channel(self, str_channel): channels_list = str_channel.split(",") channels_guid_list = [] for srv in host.settings("/").ls(): if srv.type in ["LocalServer", "RemoteServer"]: for sett_chan in host.settings("/%s/channels" % srv.guid).ls(): if self.check_access(sett_chan): if sett_chan.name in channels_list: channels_guid_list.append( "%s_%s" % (sett_chan.guid, srv.guid)) return channels_guid_list
def get_channels(server_guid, channel_names=None): channels_ = [] server = Server(host.settings("/%s" % server_guid)) for sett in host.settings("/%s/channels" % server_guid).ls(): if sett.type == "Channel": try: if channel_names is None or sett.name in channel_names: if _is_channel_enabled(sett): channels_.append(Channel(sett, server)) except ValueError: logger.warning("Can't check channel, maybe user has no access", exc_info=True) return channels_
def __init__( self, file_name="%s.log" % host.settings("scripts/%s" % __name__).name.split("\\")[-1], write_log=True, ): self.dir_path = host.settings( "system_wide_options")["screenshots_folder"] self.file_name = file_name self.file_path = os.path.join(self.dir_path, self.file_name) self.write_log = write_log self.max_rows = 500
def collect_users(): logger.debug("collect users") all_users = [] for user in host.settings("users").ls(): if user.type == "User" and user.name not in ("Admin", "Script"): user.group_acl = None if user["group"]: user.group_acl = host.settings("users/%s" % user["group"])["acl"] user.rights = UserRightsChecker(user) all_users.append(user) return all_users
def restore_lost(): for device in host.settings("/{srv}/ip_cameras".format(srv=SERVER)).ls(): if device.type == "Grabber": for x in xrange(31): if device["channel%02d_guid" % x] == change_channel: host.message("Replace!") device["channel%02d_guid" % x] = changer_channel host.settings("/{}/channels/{}".format( changer_srv, changer_channel))["archive_zombie_flag"] = 0 host.settings("/{}/channels/{}".format( change_srv, change_channel))["archive_zombie_flag"] = 1 return host.error("Can't find channel to replace")
def __init__(self, attention_monitor, alarm_template_after, time_to_del): self.attention_monitor = attention_monitor self.operate_gui = host.object("operatorgui_" + host.settings("").guid) self.chan_on_template = [] for tmpl in host.settings("templates").ls(): if tmpl.type == "Template" and tmpl.name == alarm_template_after: alarm_template_after_content = tmpl["content"] break else: raise RuntimeError("Шаблон не найден") self.alarm_template_after = alarm_template_after self.alarm_template_after_content = alarm_template_after_content self.time_to_del = time_to_del self.time_dict = {}
def get_channels(select_channels): for sett in host.settings("channels").ls(): if sett.type == "Channel" and not sett["archive_zombie_flag"]: if select_channels is None or sett.name in select_channels: grabber = get_channel_grabber(sett) if grabber and grabber["grabber_enabled"]: yield sett.guid
def servers_generator(names=None): """ Args: names (set): Returns: Server """ for server_name, server_guid, _, _ in host.objects_list("Server"): if names and server_name not in names: logger.debug("object name: %s not in %s, continue", server_name, names) continue try: _srv_obj = host.settings("/{}".format(server_guid)) except EnvironmentError as err: logger.error( "Can't get settings object for server: %s (%s), err: %s", server_name, server_guid, err, ) raise EnvironmentError( "Can't get settings object for server: %s (%s)" % (server_name, server_guid)) else: yield ServerObj(_srv_obj)
def get_channels(server_guid, channel_names=None): """ Args: server_guid (str): channel_names (Set('name_1', 'name_2')): Returns: List[ Channel_1, Channel_2] """ channels_ = [] server = Server(host.settings("/%s" % server_guid)) for sett in host.settings("/%s/channels" % server_guid).ls(): if sett.type == "Channel" and not sett["archive_zombie_flag"]: if channel_names is None or sett.name in channel_names: if _is_channel_enabled(sett): channels_.append(Channel(sett, server)) return channels_
def __init__(self, name=None, guid=None, parent=None): super(ScriptObject, self).__init__("Script") scr_parent = host.stats().parent() self._name = name or SCRIPT_NAME self.set_name(self._name) self._guid = guid or "{}-object".format(scr_parent.guid) self.set_guid(self._guid) self._parent = parent or host.settings("").guid self.set_parent(self._parent) self._folder = "" self._health = "OK" self._check_me = True self.set_initial_state([self._health, self._check_me]) host.object_add(self) self._obj = host.object(self._guid) self.context_menu = []
def set_generate_motion_events(self, st, channels=[]): channels = channels if channels else self.objs['Channel'].keys() for channel in channels: parent = self.objs['Channel'][channel]['parent'] guid = self.objs['Channel'][channel]['guid'] host.settings('/%s/channels/%s' % (parent, guid))['generate_motion_events'] = st
def __init__( self, alarm_template, base_template, display_number, max_channels, show_channel_duration, no_motion_check, ): self.alarm_template = alarm_template self.base_template = base_template self.display_number = display_number self.max_channels = max_channels self.show_channel_duration = show_channel_duration self.no_motion_check = no_motion_check self._gui = host.object("operatorgui_" + host.settings("").guid) self._CLEAN = "gui7(-1, '')" self._displaying_channels = OrderedDict() self.template_dropped = False self.show_timer_running = False logger.debug( "Display number is: %s, max channels is: %s", self.display_number, self.max_channels, )
def utc_offset(server_guid): utc_offset = 0 try: utc_offset = host.settings("/{server_guid}/system_wide_options".format( server_guid=server_guid))["utc_offset_minutes"] except KeyError as err: logger.error("Can't get utc_offset for server: %s, error occurred: %s", utc_offset, err) try: utc_offset = host.settings("system_wide_options".format( server_guid=server_guid))["utc_offset_minutes"] except KeyError as err: logger.error("Can't get local utc_offset, error occurred: %s", err) return utc_offset
def create_module(guid, name=None, lang=None, icon_path=None, check_rights=None): name = name or guid.title() lang = lang or host.stats().parent()["language"] or host.settings( "system_wide_options")["i18n_language"] tmod = host.TrassirModule(guid) tmod.set_name(name) tmod.set_lang(lang) tmod.set_icon_data(_get_icon(icon_path)) def _mod_check_rights(userid, username): return User(userid, cog_guid=guid).has_view_rights tmod.set_check_rights(check_rights or _mod_check_rights) tmod.set_url(guid) host.trassir_module_add(tmod) host.cog_create_or_update(guid, name, None) tmod.name = name tmod.guid = guid tmod.name = name tmod.lang = lang return tmod
def write(self): try: with open( host.settings("system_wide_options")["screenshots_folder"] + "/" + "License_Free.txt", "a", ) as f: if self.start: f.write("В файле лицензии: \n") logger.debug("В файле лицензии:") else: f.write("Свободных лицензий: \n") logger.debug("Свободных лицензий:") for name, count in self.license_dict.iteritems(): f.write("%s - %s \n" % (name, count)) logger.debug("%s - %s" % (name, count)) if self.error_dict: f.write("Не возможно лицензировать: \n") logger.debug("Не возможно лицензировать:") for name, family in self.error_dict.iteritems(): f.write("%s - %s \n" % (name, family)) logger.debug("%s - %s" % (name, family)) f.close() except Exception as err: host.error("Error: %s" % err) logger.debug("Error: %s" % err)
def get_channel(channel_guid): for _, guid, _, parent in host.objects_list("Channel"): if guid == channel_guid: server_settings = host.settings("/%s" % parent[:-1]) channel_settings = server_settings.cd("channels").cd(guid) server = Server(server_settings) return Channel(channel_settings, server)
def check_grabbers_on_server(self): grabber_dict = {} for sett in host.settings("/{}/ip_cameras/".format( self.server.guid)).ls(): if sett.type == "Grabber": grabber_dict["{s[connection_ip]}:{s[connection_port]}".format( s=sett)] = sett.guid return grabber_dict
def __init__(self, carousel_dict, hand_using, func): self.chan_on_template = [] self.gui = host.object("operatorgui_" + host.settings("").guid) self.carousel_dict = carousel_dict self.hand_using = hand_using self.func = func self.idx = 0 self.carousel_go()
def __init__(self, filename): super(MyFileHandler, self).__init__() self.__file_path = win_encode_path( os.path.join( host.settings("system_wide_options")["screenshots_folder"], filename)) self.__writer_working = False self.__msg_queue = deque(maxlen=1000)
def get_settings_path(): if os.name == "nt": settings_directory = os.getcwd() if host.settings("").guid == "client": settings_path, license_path = _client(settings_directory) else: settings_path, license_path = _server(settings_directory) else: if host.settings("health")["architecture"] == "x86_64": settings_directory = "/home/trassir" settings_path, license_path = _server(settings_directory) else: # ARM settings_path = os.path.join("/data/userdata/", "_t1server.settings") license_path = os.path.join("/data/", " Trassir 3 License.txt") return settings_path, license_path
def get_channel_grabber(sett): info = sett.cd("info") if info: try: grabber = host.settings(info["grabber_path"]) except KeyError: return return grabber
def get_email_account(account): if not account: raise ValueError("Empty account") for sett in host.settings("scripts").ls(): if sett.type == "EmailAccount" and (sett.name == account or sett.guid == account): return sett raise EmailAccountNotFound(account)
def utc_offset(server_guid): _utc_offset = 0 try: _utc_offset = host.settings( "/{server_guid}/system_wide_options".format(server_guid=server_guid) )["utc_offset_minutes"] except (IndexError, KeyError) as err: logger.error("can't get utc offset. Error: %s", err) return _utc_offset
def get_name(self, obj): split_obj = obj.split('/') len_obj = len(split_obj) try: if len_obj == 2: return host.settings(obj)['name'] elif len_obj == 3: return '%s/%s' % (host.settings('/%s' % split_obj[1])['name'], self.translate.get(split_obj[2], split_obj[2])) elif len_obj == 4: return '%s/%s/%s' % ( host.settings('/%s' % split_obj[1])['name'], self.translate.get(split_obj[2], split_obj[2]), host.settings(obj)['name']) else: return obj except KeyError: return obj
def find_sensor(self, name_orion): sensor_guid = "" for sett_orion in host.settings("/%s/orion" % self.server_orion).ls(): if sett_orion.type == "OrionNode": for sett_sensor in sett_orion.ls(): if (sett_sensor.type == "OrionNode" and name_orion == sett_sensor.name): sensor_guid = sett_sensor.guid break return sensor_guid
def __init__(self, shots_folder_obj): if not issubclass(shots_folder_obj.__class__, ShotsFolder): raise TypeError( "{} is not subclass of ShotsFolder".format( shots_folder_obj.__class__.__name__ ) ) logger.info("FolderSetter(%s)", shots_folder_obj.__class__.__name__) self.folder = shots_folder_obj self._prev_folder = host.settings("system_wide_options")["screenshots_folder"]