Example #1
0
def run(send_spec, recv_spec, handlers):
  logger = helpers.init_logger('handler', config.LOG_PATH)
  sender_id = uuid4().hex

  conn = handler.Connection(
    sender_id, send_spec, recv_spec)

  while True:
    logger.debug('wait for request')
    req = conn.recv()

    if req.is_disconnect():
      logger.debug('request disconnected')
      continue
    else:
      method = req.headers.get('METHOD')
      logger.debug('incoming %s request' % method)

      code = 500
      status = 'Internal Server Error'
      response = 'Server Error'
      headers = None
      try:
        if method not in handlers:
          code = 405
          status = 'Method Not Allowed'
          response = 'The given method of %s is not supported' % method
        else:
          method_handler = handlers[method]
          code, status, response, headers = method_handler(
            req.path, req.headers, req.body)
          if 0 == code:
            logger.debug('Continue %s', response)
            continue
      except:
        logger.warn('An error occurs - %s', helpers.format_exception())
        logger.debug('Sending response - %s', response)
        conn.reply_http(req, response, code, status, headers)
        logger.debug('Request handled')
        
      logger.debug('Sending response - %s', response)
      conn.reply_http(req, response, code, status, headers)
      logger.debug('Request handled')
Example #2
0
    def __init__(self):
        self.heap = Heap()

        # for self.globals, self.locals:
        # key: name of variable
        # val: heap offset
        self.globals = {}
        # list of args/local variables of a function
        # this will be cleared when done parsing a function
        self.locals = {}

        # list of arrays
        # key: name of array
        # val: {
        #   offset: heap offset
        #   size
        # }
        self.arrays = {}

        self.opcodes = ""

        # function table containing offsets at which
        # functions can be found at, starting at 0
        # key: name of function
        # val: {
        #   opcodes,
        #   offset
        # }
        self.functions = collections.OrderedDict()
        # tracks total length of functions
        # to calculate future offsets
        self.funcs_len = FUNCTION_OFFSET_START

        self.is_in_func = False

        self.logger = helpers.init_logger("TRANSLATOR")
Example #3
0
DEBUG = GLOBALS.get("DEBUG", False)

APP_NAME = "PTZAutomation"

import time
import random
from itertools import cycle
from __builtin__ import object

import host

import helpers

helpers.set_script_name()
logger = helpers.init_logger(APP_NAME, debug=DEBUG)

from schedule import ScheduleObject

assert CHANNEL, "Channel not selected"
channel = host.object(CHANNEL.split("_")[0])
try:
    channel.state("signal")
except EnvironmentError:
    raise EnvironmentError("Channel %s not found or disabled" % CHANNEL)


def __get_random_timout():
    return random.randint(PATROL_PRESET_TIMEOUT,
                          PATROL_PRESET_TIMEOUT_RAND_MAX)
Example #4
0
FTP_PASSWORD = GLOBALS.get("FTP_PASSWORD", "12345")
FTP_WORK_DIR = GLOBALS.get("FTP_WORK_DIR", "/trassir/shots/")
FTP_ADD_RELATIVE_PATH = GLOBALS.get("FTP_ADD_RELATIVE_PATH", False)
FTP_PASSIVE_MODE = GLOBALS.get("FTP_PASSIVE_MODE", True)

import re
import os
import datetime
import threading
from functools import wraps
from __builtin__ import object
import host
import helpers

helpers.set_script_name()
logger = helpers.init_logger("ShotSaver", debug=DEBUG)

from ftp import FTPClient, status as ftp_status
from schedule import ScheduleObject
from email_sender import EmailSender
from shot_saver import ShotSaver, status as shot_status

tr = host.tr

if not SELECTED_SERVER:
    SELECTED_SERVER = host.settings("").guid

if EVENT_OBJECTS:
    EVENT_OBJECTS = EVENT_OBJECTS.split(",")

Example #5
0
    """,
}
t1utils.resources_check(script_path, resources)

GLOBALS = globals()
FILE = GLOBALS.get("FILE", "")
SERVER = GLOBALS.get("SERVER", "")
COMMAND = GLOBALS.get("COMMAND", "create")
TIMEOUT = GLOBALS.get("TIMEOUT", 1)
AUTODETECT_TIMEOUT = GLOBALS.get("AUTODETECT_TIMEOUT", 20)
DEBUG = GLOBALS.get("DEBUG", False)

import helpers

helpers.set_script_name()
logger = helpers.init_logger("create_grabber_from_csv", debug=DEBUG)

import re
import time
import os
import host
from collections import defaultdict
import threading
from functools import wraps

if not SERVER:
    raise ValueError("Need select a server")
if not FILE:
    raise ValueError("Need to specify the absolute path to the .csv file")

Example #6
0
        <resource>schedule_object.py</resource>
    </resources>
</parameters>
"""

GLOBALS = globals()
RESTART_TYPE = GLOBALS.get("RESTART_TYPE", "HW Reboot")
STARTUP_DELAY_SEC = GLOBALS.get("STARTUP_DELAY_SEC", 180)
SCHEDULE = GLOBALS.get("SCHEDULE", "")
SCHEDULE_LOAD_TIME = GLOBALS.get("SCHEDULE_LOAD_TIME", 10)
DEBUG = GLOBALS.get("DEBUG", False)

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,
Example #7
0
  q = xapian.Query(xapian.Query.OP_OR, l)

  enquire.set_query(q)
  matches = enquire.get_mset(0, 100)

  print '%i results found.' % matches.get_matches_estimated()
  print 'Result - %i:' % matches.size()

  r = []
  for m in matches:
    # print '%i: %i%% docid=%i [%s]' % (m.rank + 1, m.percent, m.docid,\
    # m.document.get_data())
    r.append(m.document.get_data())

  print json.dumps(r)

  return 200, 'OK', json.dumps(r), None 

handlers = { 'GET': get }
logger = helpers.init_logger('search', config.LOG_PATH)

if __name__ == '__main__':
  
  try:
    handler_config = config.HANDLER_CONFIG['search']
    handler.run(handler_config.send_spec, handler_config.recv_spec, handlers)
  except:
    logger.error(helpers.format_exception())
else:
  handler.handlers_registry[__name__] = handlers
Example #8
0
</parameters>
"""

GLOBALS = globals()
DEBUG = GLOBALS.get("DEBUG", False)
SERVER_ORION = GLOBALS.get("SERVER_ORION", "")
MON = GLOBALS.get("MON", 1)
ALARM_TEMPLATE_AFTER = GLOBALS.get("ALARM_TEMPLATE_AFTER", "")
TIMEOUT = GLOBALS.get("TIMEOUT", 1)
STOP_SENSOR_TIME = GLOBALS.get("STOP_SENSOR_TIME", 1)
EVENT_ORION = GLOBALS.get("EVENT_ORION", "Взять под охрану")

import helpers

helpers.set_script_name()
logger = helpers.init_logger("association_orion", debug=DEBUG)

import host
import json
from script_object import ScriptObject
from datetime import datetime, timedelta

orion_event = None
if EVENT_ORION:
    orion_event = set(ev_type.strip() for ev_type in EVENT_ORION.split(","))
else:
    raise ValueError("Необходимо указать события!")

obj = ScriptObject()

Example #9
0
 def __init__(self, size=0x1000):
     self.heap = array.array('l', (0 for _ in range(size)))
     self.logger = helpers.init_logger("HEAP")
Example #10
0
      auth_token = token_cipher
    except:
      return 401, 'Unauthorized', 'Invalid token', {}

    field = 'identity'
    if not field in headers:
      return 400, 'Bad Request', 'Identity missing', {}
    identity_str = headers[field]
    _logger.debug("identity = %s", identity_str)

    global db
    if None == db: 
      return 500, "Internal Server Error", "Failed to connect to DB", {}

    try:
      identity = Identity.load(db, identity_str)
    except IdentityError:
      return 401, 'Unauthorized', 'Invliad identity', {}

    token_str, secret = db.load_token(identity.user_id)

    token = Token(token_str, secret)
    if not token.verify(auth_token):
      return 401, 'Unauthorized', 'Invalid token', {}
    return func(path, headers, body)

  return impl

_logger = helpers.init_logger(__name__, config.LOG_PATH)
db = Database()
Example #11
0
CUSTOM_STRING = GLOBALS.get("CUSTOM_STRING", "")
DEBUG = GLOBALS.get("DEBUG", False)
# Display parameters
X1 = GLOBALS.get("X1", 20)
Y1 = GLOBALS.get("Y1", 30)
X2 = GLOBALS.get("X2", 30)
Y2 = GLOBALS.get("Y2", 30)
FONT_COLOR = GLOBALS.get("FONT_COLOR", "")
BACKGROUND_COLOR = GLOBALS.get("BACKGROUND_COLOR", "")
FONT_SIZE = GLOBALS.get("FONT_SIZE", "")

import host
import helpers

helpers.set_script_name()
logger = helpers.init_logger("display_text", debug=DEBUG)
from figures import draw, text_ext

if CHANNELS:
    CHANNELS = CHANNELS.split(",")
else:
    CHANNELS = None


def get_channel_grabber(sett):
    info = sett.cd("info")
    if info:
        try:
            grabber = host.settings(info["grabber_path"])
        except KeyError:
            return
Example #12
0
configPath = os.path.abspath("./MailConfig.ini")
config = configparser.SafeConfigParser(allow_no_value=True)
try:
    fp = open(configPath, "r")
    config.readfp(fp)
except:
    print("Can not read the configuration from %s:" % configPath,
          sys.exc_info()[0])
    exit("Error")

########################## initialise logger ##########################
from helpers import init_logger
if (config.has_option("General", "logFile")):
    loggerPath = config.get("General", "logfile")
    loggerPath = os.path.abspath(loggerPath)
    logger = init_logger(loggerPath)
else:
    loggerPath = os.path.abspath("./MailParser.log")
    logger = init_logger(loggerPath)
    logger.warn(
        "No logfile path found in configuration. Created logfile on %s" %
        loggerPath)
logger.info("#################### MailParser.py started ####################")

####################### connect to imap server #######################
if (config.get("General", "protocol").lower() == "imap"):
    server = config.get("General", "imapserver")
    userName = config.get("General", "username")
    password = config.get("General", "password")
    server = server.split(":")
    try:
Example #13
0
HOURS_MAIN = GLOBALS.get("HOURS_MAIN", True)
HOURS_SUB = GLOBALS.get("HOURS_SUB", False)
HOURS_VALUE = GLOBALS.get("HOURS_VALUE", 1)
TIME_REPORT_HOURS = ":15"

DEBUG = GLOBALS.get("DEBUG", False)

import json
import datetime
from functools import wraps
import host

import helpers

default_script_name = helpers.set_script_name()
logger = helpers.init_logger("Archive_stat", debug=DEBUG)

from script_object import ScriptObject
from date_utils import ts_to_dt
import schedule
from schedule_object import ScheduleObject
from email_sender import EmailSender

MAIL = None
if MAIL_ACCOUNT:
    MAIL = EmailSender(MAIL_ACCOUNT)

if MAIL_SUBJECT:
    MAIL_SUBJECT = MAIL_SUBJECT.format(server_name=host.settings("").name)
else:
    MAIL_SUBJECT = None
FTP_HOST = GLOBALS.get("FTP_HOST", "172.20.0.10")
FTP_PORT = GLOBALS.get("FTP_PORT", 21)
FTP_USER = GLOBALS.get("FTP_USER", "trassir")
FTP_PASSWORD = GLOBALS.get("FTP_PASSWORD", "12345")
FTP_WORK_DIR = GLOBALS.get("FTP_WORK_DIR", "/trassir/exported/")
FTP_PASSIVE_MODE = GLOBALS.get("FTP_PASSIVE_MODE", True)

import os
from datetime import datetime, timedelta

import host

import helpers

helpers.set_script_name()
logger = helpers.init_logger("video_exporter_universal", debug=DEBUG)

from video_exporter import VideoExporter, status
from ftp import FTPClient, status as ftp_status

if not SELECTED_SERVER:
    raise ValueError("Server not selected")
if not SELECTED_CHANNELS:
    raise ValueError("No channels selected")

DELETE_EMPTY_FOLDERS = "{server_name}" in SAVE_FOLDER
if REMOVE and not DELETE_EMPTY_FOLDERS:
    logger.warning(
        "Folder path does not start with the server name, empty folders will not be deleted."
    )
Example #15
0
MOUSE_TIME = GLOBALS.get("MOUSE_TIME", 10)
HAND_USING = GLOBALS.get("HAND_USING", False)
ALARM_TEMPLATE = GLOBALS.get("ALARM_TEMPLATE", "")
ATTENTION_MONITOR = GLOBALS.get("ATTENTION_MONITOR", 2)
ATTENTION_TIMEOUT = GLOBALS.get("ATTENTION_TIMEOUT", 2)
MOTION_REACTION = GLOBALS.get("MOTION_REACTION", False)
LEFT_OBJECT_REACTION = GLOBALS.get("LEFT_OBJECT_REACTION", False)
SABOTAGE_REACTION = GLOBALS.get("SABOTAGE_REACTION", False)
FIRE_REACTION = GLOBALS.get("FIRE_REACTION", False)
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)
Example #16
0
      password = hashlib.new('md5', password).hexdigest()
      create_with_phone_number(identity, password)
    else:
      pass

    return 200, 'OK', message, {
      'Content-Type': 'text/plain'}
  except rsa.DecryptionError:
    logger.error(helpers.format_exception())
    return 500, 'Internal Server Error', 'Decryption failed', {}

def post(path, headers, body):
  pass

def delete(path, headers, body):
  pass

handlers = {
  'PUT': put, 'GET': get, 'post': post, 'delete': delete }
logger = helpers.init_logger('signup', config.LOG_PATH)

if __name__ == '__main__':
  
  try:
    handler_config = config.HANDLER_CONFIG['signup']
    handler.run(handler_config.send_spec, handler_config.recv_spec, handlers)
  except:
    logger.error(helpers.format_exception())
else:
  handler.handlers_registry[__name__] = handlers
Example #17
0
  else:
    book_id = path.split('/')[-1]
    
    if (not book_id.isdigit()):
      return 400, 'Bad Request', 'book id expected', None
    
    arguments = { 'book_id': book_id }  
        
  return 200, 'OK', da.query_book(arguments), {
    'Content-Type': 'application/json;charset=UTF-8'}

def post(path, query, body):
  pass

def delete(path, query, body):
  pass

handlers = {
  'PUT': put, 'GET': get, 'post': post, 'delete': delete }
logger = helpers.init_logger('book', config.LOG_PATH)

if __name__ == '__main__':
  
  try:
    handler_config = config.HANDLER_CONFIG['book']
    handler.run(handler_config.send_spec, handler_config.recv_spec, handlers)
  except:
    logger.error(helpers.format_exception())
else:
  handler.handlers_registry[__name__] = handlers
Example #18
0
        <resource>exthttp/core/module.py</resource>
        <resource>exthttp/core/__init__.py</resource>
        <resource>exthttp/http/request.py</resource>
        <resource>exthttp/http/response.py</resource>
        <resource>exthttp/http/__init__.py</resource>
    </resources>
</parameters>
"""

GLOBALS = globals()
DEBUG = GLOBALS.get("DEBUG", False)

import helpers

helpers.set_script_name()
logger = helpers.init_logger("Screenshots_API", debug=DEBUG)

import host
import time
import os
from datetime import datetime
from exthttp.core import create_app, BaseHandler
from exthttp.http import HttpResponse, HttpResponseNotFound
from shot_saver import ShotSaver, status

app = create_app("screenshots")

check_work_state = {}


def callback(task_guid, state):
Example #19
0
    </resources>
</parameters>
"""

import os
import time
import host
from functools import wraps
import threading
import helpers

GLOBALS = globals()
DEBUG = GLOBALS.get("DEBUG", False)

helpers.set_script_name()
logger = helpers.init_logger("LicenseFree", debug=DEBUG)


def run_as_thread(func):
    """Run function as thread"""
    @wraps(func)
    def run(*args, **kwargs):
        thread = threading.Thread(target=func, args=args, kwargs=kwargs)
        thread.daemon = True
        thread.start()
        return thread

    return run


class RunUp:
        <resource>localization/report.py</resource>
        <resource>localization/__init__.py</resource>
    </resources>
</parameters>
"""
GLOBALS = globals()
# Main settings
FOLDER_PATH = GLOBALS.get("FOLDER_PATH", "default") or None

# Other settings
DEBUG = GLOBALS.get("DEBUG", False)

import helpers

helpers.set_script_name()
logger = helpers.init_logger("user_rights_for_channels", debug=DEBUG)

import host
import os
import re
from datetime import datetime
import xlsxwriter
from __builtin__ import object
import localization as loc

shot_path = host.settings("system_wide_options")["screenshots_folder"]
host.stats()["run_count"] = 0


def _win_encode_path(path):
    if os.name == "nt":
Example #21
0
# -*- coding:utf8 -*-

from multiprocessing import Process
import config
import handler
import helpers

if __name__ == '__main__':
  logger = helpers.init_logger('loader', config.LOG_PATH)
  for name in config.HANDLER_CONFIG:
    handler_config = config.HANDLER_CONFIG[name]
    try:
      exec 'import ' + handler_config.module_name
      process = Process(
        target = handler.run,
        name = handler_config.module_name,
        args = (
          handler_config.send_spec, 
          handler_config.recv_spec, 
          handler.handlers_registry[
            handler_config.module_name]))
      logger.info('starting %s', process.name)
      process.start()
      logger.info('process %d started', process.pid)
    except:
      logger.error(helpers.format_exception())
Example #22
0
        <name>Debug</name>
        <value>False</value>
   </parameter>
    <resources>
        <resource>helpers.py</resource>
    </resources>
</parameters>
"""
GLOBALS = globals()
URL = GLOBALS.get("URL", "")
DEBUG = GLOBALS.get("DEBUG", False)

import helpers

helpers.set_script_name()
logger = helpers.init_logger("lpr_events_pusher", debug=DEBUG)

import host
import json
import requests
import threading
from functools import wraps
from __builtin__ import object

assert URL, "No address specified for POST request"


def _run_as_thread(fn):
    @wraps(fn)
    def run(*args, **kwargs):
        t = threading.Thread(target=fn, args=args, kwargs=kwargs)
except ImportError:
    raise RuntimeError("You need to update Trassir")

GLOBALS = globals()

DEBUG = GLOBALS.get("DEBUG", False)
TYPE_OF_WORK = GLOBALS.get("TYPE_OF_WORK", "export")
DELETE_PERSONS = GLOBALS.get("DELETE_PERSONS", False)
UPDATE_SAME_PERSON = GLOBALS.get("UPDATE_SAME_PERSON", False)
FOLDER = GLOBALS.get("FOLDER", "{path}/face_from_folder")

IMPORT_FOLDER = FOLDER.format(
    path=host.settings("system_wide_options")["screenshots_folder"])

set_script_name("Face from folder")
logger = init_logger(name=host.stats().parent().name, debug=DEBUG)

engine = host.get_database_connection()
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()


class PersonImage(Base):
    __tablename__ = "persons_images_t"
    person_guid = Column(String(8))
    image_guid = Column(String(8),
                        primary_key=True,
                        nullable=False,
                        unique=True)
    image = Column(BINARY)
Example #24
0
    db = mysql.connect(**config.DB_PARAMETERS)
    writer = CatalogMySQLWriter(db)
    try:
      import_catalog(
        parts[0].get_content_stream(),
        parts[1].get_content_stream(),
        writer)
    finally:
      db.close()

    response = "UPLOAD GOOD: %s" % hashlib.md5(body).hexdigest()

    return 200, 'OK', response, {
      'Content-Type': 'application/json;charset=UTF-8'}

  else:
    return 200, 'OK', 'unknown request', None

handlers = { 'POST': post }
logger = helpers.init_logger('catalog_handler', config.LOG_PATH)

if '__main__' == __name__:
  try:
    handler_config = config.HANDLER_CONFIG['catalog_handler']
    handler.run(handler_config.send_spec, handler_config.recv_spec, handlers)
  except:
    logger.error(helpers.format_exception())
else:
  handler.handler_registry[__name__] = handlers
Example #25
0
    """,
}
t1utils.resources_check(script_path, resources)

GLOBALS = globals()
MIN_FREE_SPACE = GLOBALS.get("MIN_FREE_SPACE", 500)
FOLDER = GLOBALS.get("FOLDER", "")
CHECK_INTERVAL = GLOBALS.get("CHECK_INTERVAL", 1)
FILE_AGE = GLOBALS.get("FILE_AGE", 10)
FILTER_EXT = GLOBALS.get("FILTER_EXT", "")
DEBUG = GLOBALS.get("DEBUG", False)

import helpers

helpers.set_script_name()
logger = helpers.init_logger("folder_cleaner", debug=DEBUG)

logger.debug(
    "script started with params folder:%s, free space(Mb):%s, check interval(min):%s, file age(days):%s, "
    "filter ext: %s",
    FOLDER,
    MIN_FREE_SPACE,
    CHECK_INTERVAL,
    FILE_AGE,
    FILTER_EXT,
)

import psutil
import time
import os
import host
Example #26
0
        avnyW30ZNi4BU7Fdcq9e75RUUpXkmSQn/JS7aBVQi7NOkTUAyQkUMEV05ZMG9PqUV2uKd04D
        QcmuV3WlE0EIFhVfZiyeNrkNN3IA4dkmLAuolqXayN49mcfEhxWCARybOEc60Tpis6eb14zO
        9fQZREGFxOgYegdMXqXXZMgbwakkS8FWUi63pfpsVTIAcdqJX4pT9E9h4Rwdn0mp87yFKl9r
        OE9X/G+OSJTE+rLRzHzpyr85hfud+SnqofaeCf/KtQh41C960Ehnfbarvp1VG/i+xuPQDsTI
        WIuvlCgz6f8DOZtdDw==
    """,
}
t1utils.resources_check(script_path, resources)

import host
import helpers

GLOBALS = globals()
DEBUG = GLOBALS.get("DEBUG", False)

logger = helpers.init_logger("IP_Device_info", debug=DEBUG)

from export import save_data

screen_folder = host.settings("system_wide_options")["screenshots_folder"]

grabber_feedback_state = {
    1: "On Work",
    0: "No Work",
    3: "Exceed specification",
    4: "Invalid argument specified",
    9: "Wrong login or password",
    8: "Wrong login or password",
    1025: "On Work - No HDD",
    2051: "Exceed specification - HDD ok",
    1027: "Exceed specification - No HDD",