def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append("%s/emonitor/modules/locations/templates" % app.config.get('PROJECT_ROOT'))

        # translations
        babel.gettext(u'module.locations')
Example #2
0
def getAdminData(self, **params):
    """
    Deliver admin content of module settings (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'checkpath':
        if os.path.exists(request.args.get('path')):
            return '1'
        return '0'

    elif request.args.get('action') == 'upgradedb':
        try:
            alembic.upgrade()
            return str(alembic.current())
        except:
            return babel.gettext(u'admin.settings.updatedberror')

    elif request.args.get('action') == 'downgradedb':
        return alembic.downgrade() or "done"

    elif request.args.get('action') == 'sendtelegramtest':
        from emonitor.extensions import communication
        communication.telegram.sendMessage(addressee=int(request.args.get('user')), message=request.args.get('msg'))
        return babel.gettext(u'admin.settings.telegramtest.done')

    return ""
Example #3
0
def getAdminData(self, **params):
    """
    Deliver admin content of module settings (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'checkpath':
        if os.path.exists(request.args.get('path')):
            return '1'
        return '0'

    elif request.args.get('action') == 'upgradedb':
        try:
            alembic.upgrade()
            return str(alembic.current())
        except:
            return babel.gettext(u'admin.settings.updatedberror')

    elif request.args.get('action') == 'downgradedb':
        return alembic.downgrade() or "done"

    elif request.args.get('action') == 'sendtelegramtest':
        from emonitor.extensions import communication
        communication.telegram.sendMessage(addressee=int(request.args.get('user')), message=request.args.get('msg'))
        return babel.gettext(u'admin.settings.telegramtest.done')

    return ""
Example #4
0
    def action(**kwargs):
        """
        implementation of image-message specific actions
        :param kwargs: list of parameters: action, mid and all arguments of ajax requests
        :return: results of action
        """
        if kwargs.get('action') == 'imageupload':
            imagepath = "{}messages/{}".format(
                current_app.config.get('PATH_DATA'), kwargs.get('key', '0'))
            if not os.path.exists(imagepath):
                os.makedirs(imagepath)
            images = filter(
                lambda x: x.lower().endswith('.jpg') or x.lower().endswith(
                    '.png'), os.listdir(imagepath))
            ext = kwargs.get('name').lower().split('.')[-1]
            filename = "{}.{}".format(len(images) + 1, ext)
            while os.path.exists("{}/{}".format(imagepath, filename)):
                filename = "{}.{}".format(int(filename.split('.')[0]) + 1, ext)

            f = open('{}/{}'.format(imagepath, filename), 'wb')
            f.write(kwargs.get('data').split('base64,')[-1].decode('base64'))
            text = '<p id="{imgshort}"><input type="checkbox" name="images" value="{img}" checked="checked"> <a href="/messages/inc/message/{key}/{img}" target=_blank">{img}</a> <i class="fa fa-trash-o fa-lg" onclick="deleteFile(\'{img}\')"></i></p>'.format(
                imgshort=filename.replace('.', ''),
                img=filename,
                key=kwargs.get('key'))
            return {
                'message': babel.gettext('messages.fileupload.done'),
                'text': text
            }

        elif kwargs.get('action') == 'imagedelete':
            """
            delete image of message with given filename
            """
            imagepath = "{}messages/{}/".format(
                current_app.config.get('PATH_DATA'), kwargs.get('key', '0'))
            if os.path.exists(imagepath + kwargs.get('filename')):
                os.remove(imagepath + kwargs.get('filename'))
            return {
                'message': babel.gettext('messages.filedelete.done'),
                'filename': kwargs.get('filename')
            }

        elif kwargs.get('action') == 'delete':
            """
            operation before message object deleted:
            remove all uploaded images
            """
            message = Messages.getMessages(kwargs.get('mid'))
            if os.path.exists("{}messages/{}".format(
                    current_app.config.get('PATH_DATA'),
                    message.get('key', '0'))):
                shutil.rmtree("{}messages/{}".format(
                    current_app.config.get('PATH_DATA'),
                    message.get('key', '0')))

        return "ok"
Example #5
0
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(
            "%s/emonitor/modules/locations/templates" %
            app.config.get('PROJECT_ROOT'))

        # translations
        babel.gettext(u'module.locations')
    def __init__(self, app):
        """
        Add event handler for *script-event*

        :param app: *Flask* app object
        """
        Module.__init__(self, app)

        # eventhandlers
        events.addHandlerClass('*', 'emonitor.modules.scripts.script.Script', Script.handleEvent, ['in.scriptname'])

        # translations
        babel.gettext(u'emonitor.modules.scripts.script.Script')
Example #7
0
    def __init__(self, app):
        """
        Add event handler for *script-event*

        :param app: *Flask* app object
        """
        Module.__init__(self, app)

        # eventhandlers
        events.addHandlerClass('*', 'emonitor.modules.scripts.script.Script',
                               Script.handleEvent, ['in.scriptname'])

        # translations
        babel.gettext(u'emonitor.modules.scripts.script.Script')
Example #8
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append("%s/emonitor/modules/maps/templates" % app.config.get('PROJECT_ROOT'))

        # subnavigation
        self.adminsubnavigation = [('/admin/maps', 'maps.base'), ('/admin/maps/position', 'module.maps.position')]

        self.widgets = [MapWidget('maps_map')]

        # signals and handlers
        signal.connect('map', 'tiledownloadstart', adminMapHandler.handleMapDownloadStart)
        signal.connect('map', 'tiledownloadstop', adminMapHandler.handleMapDownloadStop)
        signal.connect('map', 'tiledownloaddone', adminMapHandler.handleMapDownloadDone)
        signal.connect('map', 'tiledownloadprogress', adminMapHandler.handleMapDownloadProgress)

        # static folders
        @app.route('/maps/inc/<path:filename>')
        def maps_static(filename):
            return send_from_directory("%s/emonitor/modules/maps/inc/" % app.config.get('PROJECT_ROOT'), filename)

        # translations
        babel.gettext(u'module.maps')
        babel.gettext(u'maps_map')
        babel.gettext(u'maps.base')
        babel.gettext(u'module.maps.position')
Example #9
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)

        # add template path
        app.jinja_loader.searchpath.append(
            u"{}/emonitor/modules/alarmkeys/templates".format(
                app.config.get('PROJECT_ROOT')))

        # create database tables
        from alarmkey import Alarmkey
        from alarmkeycar import AlarmkeyCars

        # static folders
        @app.route('/alarmkeys/inc/<path:filename>')
        def alarmkeys_static(filename):
            return send_from_directory(
                u"{}/emonitor/modules/alarmkeys/inc/".format(
                    app.config.get('PROJECT_ROOT')), filename)

        babel.gettext(u'module.alarmkeys')
        babel.gettext(u'alarmkeys.upload.states0')
        babel.gettext(u'alarmkeys.upload.states1')
        babel.gettext(u'alarmkeys.upload.states-1')
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)

        # add template path
        app.jinja_loader.searchpath.append(
            u"{}/emonitor/modules/events/templates".format(app.config.get("PROJECT_ROOT"))
        )

        # translations
        babel.gettext(u"module.events")
Example #11
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)

        # add template path
        app.jinja_loader.searchpath.append(
            u"{}/emonitor/modules/events/templates".format(
                app.config.get('PROJECT_ROOT')))

        # translations
        babel.gettext(u'module.events')
Example #12
0
    def msg_start(bot, update, **kwargs):
        """
        send start message and add user id to emonitor user if found
        :param bot:
        :param update:
        :param kwargs:
        """
        for person in TelegramBot.users.getPersons():
            if person.firstname == update.message.from_user[
                    'first_name'] and person.lastname == update.message.from_user[
                        'last_name']:
                TelegramBot.logger.info(
                    'add telegramid {} to user {} {}'.format(
                        update.message.from_user['id'], person.firstname,
                        person.lastname))
                _additional = person.options
                _additional['telegramid'] = update.message.from_user['id']
                person._options = yaml.safe_dump(_additional, encoding='utf-8')
                db.session.commit()

        msgtext = Settings.get('telegramsettings')[
            'welcomemsg'] or babel.gettext('telegram.default.welcomemsg')
        bot.sendMessage(update.message.chat_id,
                        text=msgtext.format(
                            vorname=update.message.from_user.first_name,
                            nachname=update.message.from_user.last_name))
        TelegramBot.logger.info(
            'send message from "msg_start" to {} {}'.format(
                update.message.from_user.first_name,
                update.message.from_user.last_name))
Example #13
0
def getData(module=u''):
    """
    Frontend area is reachable unter `http://[servername]:[port]/data/[module]`

    This path is used to run background operations (e.g. ajax calls) and delivers the result of the `getFrontendData`
    method of the module. If **format=json** in the url the result will be formated as json

    :param module: module name as string
    :return: return value of `getFrontendData` method of `module`
    """
    current_mod = frontend.modules['startpages']

    if module == u"frontpage" and 'action' in request.args:
        if request.args.get('action') == 'info':
            return render_template('frontend.emonitorinfo.html', app_name=current_app.config.get('PROJECT'), app_version=current_app.config.get('APP_VERSION'))
        elif request.args.get('action') == 'systeminfo':
            return render_template('frontend.systeminfo.html')
        elif request.args.get('action') == 'restart':
            from emonitor.extensions import scheduler
            scheduler.add_job(restartService)
            return ""
        elif request.args.get('action') == 'translatebaseinfo':
            return jsonify({'connection_info': babel.gettext(u'frontend.connection_info')})

    try:
        current_mod = [frontend.modules[m] for m in frontend.modules if frontend.modules[m].info['path'] == module.split('/')[0]][0]
    except IndexError:
        current_app.logger.info("module '%s' not found" % module)

    result = current_mod.getFrontendData()
    if request.args.get('format') == 'json':
        result = jsonify(result)
    return result
Example #14
0
 def __init__(self, app):
     Module.__init__(self, app)
     # add template path
     app.jinja_loader.searchpath.append("%s/emonitor/modules/user/templates" % app.config.get('PROJECT_ROOT'))
     
     babel.gettext(u'module.users')
     babel.gettext(u'userlevel.notset')
     babel.gettext(u'userlevel.admin')
     babel.gettext(u'userlevel.user')
 def __init__(self, name, dept, parameters, position):
     self.fieldtype = self.__class__.__name__
     if self.fieldtype == name:  # translate if classname an name are same
         name = babel.gettext(name)
     self.name = name
     self.dept = dept
     self._parameters = yaml.safe_dump(parameters, encoding='utf-8')
     self.position = position
Example #16
0
 def __init__(self, name, dept, parameters, position):
     self.fieldtype = self.__class__.__name__
     if self.fieldtype == name:  # translate if classname an name are same
         name = babel.gettext(name)
     self.name = name
     self.dept = dept
     self._parameters = yaml.safe_dump(parameters, encoding='utf-8')
     self.position = position
Example #17
0
 def updateAdminSubNavigation(self):
     """
     Add subnavigation for admin area with sections for alarmkey module
     """
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(('/admin/alarmkeys/%s' % dep.id, dep.name))
     self.adminsubnavigation.append(('/admin/alarmkeys/0', babel.gettext('admin.alarmkeys.sets.edit...')))
 def updateAdminSubNavigation(self):
     """
     Add subnavigation for admin area
     """
     from .city import City
     self.adminsubnavigation = []
     for c in City.getCities():
         self.adminsubnavigation.append((u"/admin/streets/{}".format(c.id), c.name))
     self.adminsubnavigation.append(('/admin/streets/0', babel.gettext('admin.streets.cities.edit...')))
 def updateAdminSubNavigation(self):
     """
     Add submenu entries for admin area
     """
     from emonitor.modules.settings.department import Department
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(('/admin/persons/%s' % dep.id, dep.name))
     self.adminsubnavigation.append(('/admin/persons/0', babel.gettext('admin.persons.edit...')))
Example #20
0
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(
            "%s/emonitor/modules/user/templates" %
            app.config.get('PROJECT_ROOT'))

        babel.gettext(u'module.users')
        babel.gettext(u'userlevel.notset')
        babel.gettext(u'userlevel.admin')
        babel.gettext(u'userlevel.user')
 def getFields(self, **params):
     return [FieldName('basic.address', babel.gettext('admin.alarms.address')),
             FieldName('basic.department', babel.gettext('admin.alarms.department')),
             FieldName('basic.department.address', babel.gettext('admin.alarms.department.address')),
             FieldName('basic.currentdate', babel.gettext('admin.currentdate')),
             FieldName('alarm.key', babel.gettext('alarms.key')),
             FieldName('alarm.date', babel.gettext('alarms.date')),
             FieldName('alarm.time', babel.gettext('alarms.time'))]
Example #22
0
 def msg_help(bot, update, **kwargs):
     """
     send information about the bot
     :param bot:
     :param update:
     :param kwargs:
     """
     msgtext = Settings.get('telegramsettings')['helpmsg'] or babel.gettext('telegram.default.helpmsg')
     bot.sendMessage(update.message.chat_id, msgtext, parse_mode='Markdown')
     TelegramBot.logger.debug("help_msg sent.")
Example #23
0
 def getRouting(self):
     if self.get('routing', '') == "":  # load from webservice if not stored
         routingdata = alarmutils.getAlarmRoute(self)
         if len(routingdata['coordinates']) > 0:
             self.set('routing', yaml.safe_dump(routingdata, encoding="UTF-8"))
             db.session.commit()
     data = yaml.load(self.get('routing'))
     if 'error' in data:
         data['errormessage'] = babel.gettext(u'alarms.routingerror')
     return data
Example #24
0
 def getRouting(self):
     if self.get('routing', '') == "":  # load from webservice if not stored
         routingdata = alarmutils.getAlarmRoute(self)
         if len(routingdata['coordinates']) > 0:
             self.set('routing', yaml.safe_dump(routingdata, encoding="UTF-8"))
             db.session.commit()
     data = yaml.load(self.get('routing'))
     if 'error' in data:
         data['errormessage'] = babel.gettext(u'alarms.routingerror')
     return data
Example #25
0
 def updateAdminSubNavigation(self):
     """
     Add subnavigation for admin area with sections for alarmkey module
     """
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(
             ('/admin/alarmkeys/%s' % dep.id, dep.name))
     self.adminsubnavigation.append(
         ('/admin/alarmkeys/0',
          babel.gettext('admin.alarmkeys.sets.edit...')))
Example #26
0
 def updateAdminSubNavigation(self):
     """
     Add submenu entries for admin area
     """
     from emonitor.modules.settings.department import Department
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(
             ('/admin/persons/%s' % dep.id, dep.name))
     self.adminsubnavigation.append(
         ('/admin/persons/0', babel.gettext('admin.persons.edit...')))
Example #27
0
 def msg_help(bot, update, **kwargs):
     """
     send information about the bot
     :param bot:
     :param update:
     :param kwargs:
     """
     msgtext = Settings.get('telegramsettings')['helpmsg'] or babel.gettext(
         'telegram.default.helpmsg')
     bot.sendMessage(update.message.chat_id, msgtext, parse_mode='Markdown')
     TelegramBot.logger.debug("help_msg sent.")
Example #28
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append("%s/emonitor/modules/cars/templates" % app.config.get('PROJECT_ROOT'))

        self.widgets = [CarWidget('cars')]

        # create database tables
        from emonitor.modules.cars.car import Car
        #classes.add('car', Car)
        #db.create_all()

        # translations
        babel.gettext(u'module.cars')
        babel.gettext(u'cars')
Example #29
0
 def updateAdminSubNavigation(self):
     """
     Add subnavigation for admin area
     """
     from .city import City
     self.adminsubnavigation = []
     for c in City.getCities():
         self.adminsubnavigation.append(
             (u"/admin/streets/{}".format(c.id), c.name))
     self.adminsubnavigation.append(
         ('/admin/streets/0',
          babel.gettext('admin.streets.cities.edit...')))
 def getExportFields(self):
     ret = []
     l = 0
     for f in self.getFields():
         if f.getArg('child'):
             l += 1
             if l == 1:
                 ret[-1] = ("{} ({})".format(ret[-1][0], babel.gettext('list')), ret[-1][1])
         else:
             l = 0
             ret.append((f.getLabel(), f.id))
     return ret
Example #31
0
    def action(**kwargs):
        """
        implementation of image-message specific actions
        :param kwargs: list of parameters: action, mid and all arguments of ajax requests
        :return: results of action
        """
        if kwargs.get('action') == 'imageupload':
            imagepath = "{}messages/{}".format(current_app.config.get('PATH_DATA'), kwargs.get('key', '0'))
            if not os.path.exists(imagepath):
                os.makedirs(imagepath)
            images = filter(lambda x: x.lower().endswith('.jpg') or x.lower().endswith('.png'), os.listdir(imagepath))
            ext = kwargs.get('name').lower().split('.')[-1]
            filename = "{}.{}".format(len(images) + 1, ext)
            while os.path.exists("{}/{}".format(imagepath, filename)):
                filename = "{}.{}".format(int(filename.split('.')[0]) + 1, ext)

            f = open('{}/{}'.format(imagepath, filename), 'wb')
            f.write(kwargs.get('data').split('base64,')[-1].decode('base64'))
            text = '<p id="{imgshort}"><input type="checkbox" name="images" value="{img}" checked="checked"> <a href="/messages/inc/message/{key}/{img}" target=_blank">{img}</a> <i class="fa fa-trash-o fa-lg" onclick="deleteFile(\'{img}\')"></i></p>'.format(imgshort=filename.replace('.', ''), img=filename, key=kwargs.get('key'))
            return {'message': babel.gettext('messages.fileupload.done'), 'text': text}

        elif kwargs.get('action') == 'imagedelete':
            """
            delete image of message with given filename
            """
            imagepath = "{}messages/{}/".format(current_app.config.get('PATH_DATA'), kwargs.get('key', '0'))
            if os.path.exists(imagepath + kwargs.get('filename')):
                os.remove(imagepath + kwargs.get('filename'))
            return {'message': babel.gettext('messages.filedelete.done'), 'filename': kwargs.get('filename')}

        elif kwargs.get('action') == 'delete':
            """
            operation before message object deleted:
            remove all uploaded images
            """
            message = Messages.getMessages(kwargs.get('mid'))
            if os.path.exists("{}messages/{}".format(current_app.config.get('PATH_DATA'), message.get('key', '0'))):
                shutil.rmtree("{}messages/{}".format(current_app.config.get('PATH_DATA'), message.get('key', '0')))

        return "ok"
Example #32
0
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(
            u"{}/emonitor/modules/streets/templates".format(
                app.config.get('PROJECT_ROOT')))

        # subnavigation
        self.widgets = [StreetWidget('streets_street')]

        signal.addSignal('housenumber', 'osm')
        signal.connect('housenumber', 'osm',
                       adminHousenumberHandler.handleOSMChanged)
        signal.connect('housenumber', 'osmdone',
                       adminHousenumberHandler.handleOSMDone)

        # static folders
        @app.route('/streets/inc/<path:filename>')
        def streets_static(filename):
            return send_from_directory(
                u"{}/emonitor/modules/streets/inc/".format(
                    app.config.get('PROJECT_ROOT')), filename)

        # translations
        babel.gettext(u'module.streets')
        babel.gettext(u'module.streets.0')
        babel.gettext(u'streets_street')  # widget name
Example #33
0
def processFile(incomepath, filename):
    """
    run processing in test mode
    """
    params = dict(incomepath=incomepath, filename=filename, mode='test')
    handlers = events.getEvents('file_added').getHandlerList()
    dbhandlers = Eventhandler.getEventhandlers(event='file_added')
    from emonitor.extensions import db
    db.session.rollback()
    for handler in dbhandlers:  # db
        for hdl in handlers:
            if handler.handler == hdl[0]:
                res = []
                try:
                    params.update(hdl[1]('file_added', **params))
                except:
                    params.update({'error': u'<b>error in handler {}:</b><br/> <em>{}</em><br>'.format(hdl[0], traceback.format_exc().splitlines())})

                for p in handler.getParameterList():
                    try:
                        res.append(u'{}:\n{}'.format(p, params[p.split('.')[1]].strip()))
                    except:
                        try:
                            if p.split(u'.')[1] in params.keys():
                                res = [u'{}:\n{}\n'.format(p, params[p.split('.')[1]].strip())]
                            else:
                                with babel.app.test_request_context('/') as ctx:
                                    ctx.push()
                                    res = [u'<b style="color:red">{}</b><br>'.format(babel.gettext('alarm.testcontext.parametererror').format(p))]
                                    params['error'] = babel.gettext('alarm.handler.missing.parameter').format(p, babel.gettext(handler.handler))
                                    ctx.pop()
                        except:
                            signal.send('alarm', 'testupload_start', result='done')
                res = "\n".join(res)
                if u'error' in params.keys():
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1], error=params['error'])
                else:
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1])
    signal.send('alarm', 'testupload_start', result='done')
    return params
Example #34
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(
            "%s/emonitor/modules/cars/templates" %
            app.config.get('PROJECT_ROOT'))

        self.widgets = [CarWidget('cars')]

        # create database tables
        from emonitor.modules.cars.car import Car
        #classes.add('car', Car)
        #db.create_all()

        # translations
        babel.gettext(u'module.cars')
        babel.gettext(u'cars')
Example #35
0
 def getFields(self, **params):
     return [
         FieldName('basic.address', babel.gettext('admin.alarms.address')),
         FieldName('basic.department',
                   babel.gettext('admin.alarms.department')),
         FieldName('basic.department.address',
                   babel.gettext('admin.alarms.department.address')),
         FieldName('basic.currentdate', babel.gettext('admin.currentdate')),
         FieldName('alarm.key', babel.gettext('alarms.key')),
         FieldName('alarm.date', babel.gettext('alarms.date')),
         FieldName('alarm.time', babel.gettext('alarms.time'))
     ]
Example #36
0
 def getExportFields(self):
     ret = []
     l = 0
     for f in self.getFields():
         if f.getArg('child'):
             l += 1
             if l == 1:
                 ret[-1] = ("{} ({})".format(ret[-1][0],
                                             babel.gettext('list')),
                            ret[-1][1])
         else:
             l = 0
             ret.append((f.getLabel(), f.id))
     return ret
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(u"{}/emonitor/modules/alarmobjects/templates".format(app.config.get('PROJECT_ROOT')))

        # subnavigation
        self.adminsubnavigation = [(u'/admin/alarmobjects', u'module.alarmobjects.base'), (u'/admin/alarmobjects/types', u'module.alarmobjects.types'), (u'/admin/alarmobjects/fields', u'module.alarmobjects.fields')]

        # translations
        babel.gettext(u'module.alarmobjects')
        babel.gettext(u'module.alarmobjects.base')
        babel.gettext(u'module.alarmobjects.types')
        babel.gettext(u'module.alarmobjects.fields')

        @app.route('/alarmobjects/file/<path:filename>')  # filename = [id]-[filensme].ext
        def objectfile_static(filename):
            id, name = filename.split('-')
            alarmobjectfile = AlarmObjectFile.getFile(id=id, filename=name)
            return send_from_directory(u'{}alarmobjects/{}/'.format(current_app.config.get('PATH_DATA'), id), alarmobjectfile.filename)
def getAdminData(self):
    """
    Deliver admin content of module mapitems (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'loadfromosm':  # load all objects from osm
        itemdefinition = [t for t in Settings.get('mapitemdefinition') if t['name'] == request.args.get('type')][0]
        dbodmids = [int(i.osmid) for i in MapItem.getMapitems(itemtype=itemdefinition['name'])]

        for cid in itemdefinition['cities']:
            city = City.getCities(id=cid)
            for item in MapItem.loadFromOSM(itemdefinition, city.name):
                if int(item['id']) > 0 and int(item['id']) not in dbodmids:  # add item
                    attrs = item.copy()
                    del attrs['id']
                    db.session.add(MapItem(itemdefinition['name'], int(item['id']), attrs))
                else:  # update
                    pass  # TODO write update method

        db.session.commit()

    elif request.args.get('action') == 'uploadlayouter':
        if request.files:
            ufile = request.files['uploadfile']
            if not os.path.exists('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)):
                ufile.save('%s/emonitor/modules/mapitems/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename))
                try:
                    cls = imp.load_source('emonitor.modules.mapitems.inc', 'emonitor/modules/mapitems/inc/%s' % ufile.filename)
                    if isinstance(getattr(cls, cls.__all__[0])(), ItemLayout):
                        return "ok"
                except:
                    pass
                os.remove('%s/emonitor/modules/mapitems/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename))
                return babel.gettext(u'admin.mapitems.layouternotvalid')
        return ""

    elif request.args.get('action') == 'buildtiles':
        itemdefinition = [t for t in Settings.get('mapitemdefinition') if t['name'] == request.args.get('type')][0]
        for layouter in MapItem.getLayouters():
            if layouter.getName() == itemdefinition['parameters']['layout']:
                scheduler.add_job(layouter.buildTiles, args=[MapItem.getMapitems(itemdefinition['name']), itemdefinition['attributes']])
                break

    return ""
Example #39
0
    def msg_start(bot, update, **kwargs):
        """
        send start message and add user id to emonitor user if found
        :param bot:
        :param update:
        :param kwargs:
        """
        for person in TelegramBot.users.getPersons():
            if person.firstname == update.message.from_user['first_name'] and person.lastname == update.message.from_user['last_name']:
                TelegramBot.logger.info('add telegramid {} to user {} {}'.format(update.message.from_user['id'], person.firstname, person.lastname))
                _additional = person.options
                _additional['telegramid'] = update.message.from_user['id']
                person._options = yaml.safe_dump(_additional, encoding='utf-8')
                db.session.commit()

        msgtext = Settings.get('telegramsettings')['welcomemsg'] or babel.gettext('telegram.default.welcomemsg')
        bot.sendMessage(update.message.chat_id, text=msgtext.format(vorname=update.message.from_user.first_name, nachname=update.message.from_user.last_name))
        TelegramBot.logger.info('send message from "msg_start" to {} {}'.format(update.message.from_user.first_name, update.message.from_user.last_name))
Example #40
0
def getData(module=u''):
    """
    Frontend area is reachable unter `http://[servername]:[port]/data/[module]`

    This path is used to run background operations (e.g. ajax calls) and delivers the result of the `getFrontendData`
    method of the module. If **format=json** in the url the result will be formated as json

    :param module: module name as string
    :return: return value of `getFrontendData` method of `module`
    """
    current_mod = frontend.modules['startpages']

    if module == u"frontpage" and 'action' in request.args:
        if request.args.get('action') == 'info':
            return render_template(
                'frontend.emonitorinfo.html',
                app_name=current_app.config.get('PROJECT'),
                app_version=current_app.config.get('APP_VERSION'))
        elif request.args.get('action') == 'systeminfo':
            return render_template('frontend.systeminfo.html')
        elif request.args.get('action') == 'restart':
            from emonitor.extensions import scheduler
            scheduler.add_job(restartService)
            return ""
        elif request.args.get('action') == 'translatebaseinfo':
            return jsonify({
                'connection_info':
                babel.gettext(u'frontend.connection_info')
            })

    try:
        current_mod = [
            frontend.modules[m] for m in frontend.modules
            if frontend.modules[m].info['path'] == module.split('/')[0]
        ][0]
    except IndexError:
        current_app.logger.info("module '%s' not found" % module)

    result = current_mod.getFrontendData()
    if request.args.get('format') == 'json':
        result = jsonify(result)
    return result
def getAdminData(self, **params):
    """
    Deliver admin content of module settings (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'checkpath':
        if os.path.exists(request.args.get('path')):
            return '1'
        return '0'

    elif request.args.get('action') == 'upgradedb':
        try:
            alembic.upgrade()
            return str(alembic.current())
        except:
            return babel.gettext(u'admin.settings.updatedberror')

    elif request.args.get('action') == 'downgradedb':
        return alembic.downgrade() or "done"

    return ""
Example #42
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)
        
        # add template path
        app.jinja_loader.searchpath.append(u"{}/emonitor/modules/alarmkeys/templates".format(app.config.get('PROJECT_ROOT')))

        # create database tables
        from alarmkey import Alarmkey
        from alarmkeycar import AlarmkeyCars

        # static folders
        @app.route('/alarmkeys/inc/<path:filename>')
        def alarmkeys_static(filename):
            return send_from_directory(u"{}/emonitor/modules/alarmkeys/inc/".format(app.config.get('PROJECT_ROOT')), filename)
            
        babel.gettext(u'module.alarmkeys')
        babel.gettext(u'alarmkeys.upload.states0')
        babel.gettext(u'alarmkeys.upload.states1')
        babel.gettext(u'alarmkeys.upload.states-1')
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)

        # add template path
        app.jinja_loader.searchpath.append("%s/emonitor/modules/mapitems/templates" % app.config.get('PROJECT_ROOT'))

        # static folders
        @app.route('/mapitem/inc/<path:filename>')
        def mapitm_static(filename):
            return send_from_directory("%s/emonitor/modules/mapitem/inc/" % app.config.get('PROJECT_ROOT'), filename)

        # translations
        babel.gettext(u'module.mapitems')
        babel.gettext(u'module.mapitems.definition')
        babel.gettext(u'mapitems.definition')
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(u"{}/emonitor/modules/streets/templates".format(app.config.get('PROJECT_ROOT')))

        # subnavigation
        self.widgets = [StreetWidget('streets_street')]

        signal.addSignal('housenumber', 'osm')
        signal.connect('housenumber', 'osm', adminHousenumberHandler.handleOSMChanged)
        signal.connect('housenumber', 'osmdone', adminHousenumberHandler.handleOSMDone)

        # static folders
        @app.route('/streets/inc/<path:filename>')
        def streets_static(filename):
            return send_from_directory(u"{}/emonitor/modules/streets/inc/".format(app.config.get('PROJECT_ROOT')), filename)
            
        # translations
        babel.gettext(u'module.streets')
        babel.gettext(u'module.streets.0')
        babel.gettext(u'streets_street')  # widget name
Example #45
0
    def __init__(self, app):
        """
        Add specific parameters and configuration to app object

        :param app: flask wsgi application
        """
        Module.__init__(self, app)

        # add template path
        app.jinja_loader.searchpath.append(
            "%s/emonitor/modules/mapitems/templates" %
            app.config.get('PROJECT_ROOT'))

        # static folders
        @app.route('/mapitem/inc/<path:filename>')
        def mapitm_static(filename):
            return send_from_directory(
                "%s/emonitor/modules/mapitem/inc/" %
                app.config.get('PROJECT_ROOT'), filename)

        # translations
        babel.gettext(u'module.mapitems')
        babel.gettext(u'module.mapitems.definition')
        babel.gettext(u'mapitems.definition')
Example #46
0
import json
from flask import render_template
from emonitor.extensions import babel
from emonitor.widget.monitorwidget import MonitorWidget
from emonitor.modules.settings.settings import Settings
from emonitor.modules.maps.map import Map
from emonitor.utils import getreStructuredText

__all__ = ['MapWidget']

babel.gettext(u'map')
babel.gettext(u'message.map')


class MapWidget(MonitorWidget):
    """Widget for map messages"""
    __info__ = {'icon': 'fa-map-signs'}
    __fields__ = ['text', 'mapconfig', 'textposition']
    template = 'widget.message.map.html'
    size = (5, 4)

    def __repr__(self):
        return "map"

    def getAdminContent(self, **params):
        """
        Get content for admin area to config all parameters of message type object

        :param params: list of all currently used parameters
        :return: rendered template of text message type
        """
Example #47
0
 def __init__(self, app):
     Module.__init__(self, app)
     babel.gettext(u'module.startpages')
     babel.gettext(u'emonitor.communication.Communication')
Example #48
0
def getAdminData(self):
    """
    Deliver admin content of module alarmkeys (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'loaddetails':  # details for given key
        return render_template('admin.alarmkeys.detail.html',
                               keys=Alarmkey.getAlarmkeysByCategoryId(
                                   request.args.get('category'),
                                   keysetid=int(request.args.get(
                                       'keysetid', 0))),
                               department=request.args.get('department'))

    elif request.args.get(
            'action', '') == "changekeyset":  # deliver alarmkeys for given set
        ak = Alarmkey
        if request.args.get('keysetid', '0') == '0':
            counted_keys = db.get(ak.category.label('category'),
                                  func.count(ak.key).label('key'),
                                  ak.id.label('id'),
                                  func.count(
                                      ak.id).label('keysetcount')).group_by(
                                          ak.category).filter_by(_keyset=None)
        else:
            counted_keys = db.get(
                ak.category.label('category'),
                func.count(ak.key).label('key'), ak.id.label('id'),
                func.count(ak.id).label('keysetcount')).group_by(
                    ak.category).filter_by(
                        _keyset=request.args.get('keysetid'))
        _sum = 0
        alarmkeys_count = []
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)
        return render_template('admin.alarmkeys.macro.html',
                               alarmkeys_count=alarmkeys_count,
                               depid=request.args.get('department'),
                               sum=_sum)

    elif request.args.get('action') == 'upload':
        if request.files:
            uploadfile = request.files['uploadfile']
            fname = os.path.join(current_app.config.get('PATH_TMP'),
                                 werkzeug.secure_filename(uploadfile.filename))
            uploadfile.save(fname)
            uploadfiles[uploadfile.filename] = XLSFile(fname)

            return render_template(
                'admin.alarmkeys.upload2.html',
                sheets=uploadfiles[uploadfile.filename].getSheets())

    elif request.args.get('action') == 'upload_sheet':  # sheet selector
        definitionfile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.upload3.html',
                               cols=definitionfile.getCols(
                                   request.args.get('sheetname')))

    elif request.args.get('action') == 'testimport':  # build data for preview
        col_definition = {
            'dept': request.args.get('department'),
            'sheet': request.args.get('sheetname'),
            'category': request.form.get('category'),
            'key': request.form.get('key'),
            'keyinternal': request.form.get('keyinternal'),
            'remark': request.form.get('remark'),
            'cars1': request.form.getlist('cars1'),
            'cars2': request.form.getlist('cars2'),
            'material': request.form.getlist('material')
        }

        deffile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.uploadpreview.html',
                               vals=deffile.getValues(col_definition),
                               keysets=AlarmkeySet.getAlarmkeySets())

    elif request.args.get(
            'action') == 'doimport':  # do import and store values
        coldefinition = {
            'dept': request.args.get('department'),
            'sheet': request.args.get('sheetname'),
            'category': request.form.get('category'),
            'key': request.form.get('key'),
            'keyinternal': request.form.get('keyinternal'),
            'remark': request.form.get('remark'),
            'cars1': request.form.getlist('cars1'),
            'cars2': request.form.getlist('cars2'),
            'material': request.form.getlist('material')
        }
        deffile = uploadfiles[request.args.get('filename')]

        vals = deffile.getValues(coldefinition)
        states = []

        if request.form.get('add_material'):  # add new material
            p = re.compile(r'<.*?>')
            for k in vals['carsnotfound']:
                n_car = vals['carsnotfound'][k]
                n_car.name = p.sub('', n_car.name)
                if n_car.name == '':
                    continue
                db.session.add(n_car)
            db.session.flush()

        if request.form.get('add_new'):  # add new keys ( item state=-1)
            states.append('-1')

        if request.form.get(
                'add_update'):  # update existing keys (item state=1)
            states.append('1')

        if request.form.get('add_assign') and request.form.get(
                'keyset', '') != '':  # assign keys to keyset (item state=2)
            keyset = AlarmkeySet.getAlarmkeySets(request.form.get('keyset'))
            states.append('2')

        for key in vals['keys']:  # item list
            if key['state'] in states:  # import only with correct state

                if key['state'] == '-1':  # add key
                    k = Alarmkey(key['category'], key['key'],
                                 key['keyinternal'], key['remark'])
                    db.session.add(k)
                    db.session.flush()
                    k.setCars(coldefinition['dept'],
                              cars1=";".join([str(c.id)
                                              for c in key['cars1']]),
                              cars2=";".join([str(c.id)
                                              for c in key['cars2']]),
                              materials=";".join(
                                  [str(c.id) for c in key['material']]))
                    db.session.commit()
                    key['state'] = '0'

                elif key['state'] == '1':  # update key
                    k = Alarmkey.getAlarmkeys(id=int(key['dbid']))
                    k.category = key['category']
                    k.key = key['key']
                    k.key_internal = key['keyinternal']
                    k.remark = key['remark']
                    k.setCars(coldefinition['dept'],
                              cars1=';'.join(filter(None, key['cars1_ids'])),
                              cars2=';'.join(filter(None, key['cars2_ids'])),
                              materials=';'.join(
                                  filter(None, key['material_ids'])))
                    db.session.commit()

                if '2' in states:  # assign keys to keyset
                    item = filter(
                        lambda x: x.get('stichwort') == k.category and x.get(
                            'schlagwort') == k.key, keyset.alarmkeys)
                    k._keyset = keyset.id
                    if len(item) > 0:
                        k.keysetitem = item[0].get('nr')

        db.session.commit()
        return ""

    elif request.args.get('action') == 'download':
        # build exportfile
        filename = buildDownloadFile(request.args.get('department'),
                                     request.args.get('options'))
        if filename != "":
            return filename

    elif request.args.get('action') == 'keyslookup':
        keys = {}

        for k in Alarmkey.getAlarmkeys(keysetid=request.args.get('keysetid')):
            keys[str(k.id)] = '%s: %s' % (k.category, k.key)
        return keys

    elif request.args.get('action') == 'categorylookup':
        key = Alarmkey.getAlarmkeys(id=int(request.args.get('keyid')))
        return {'id': key.id, 'category': key.category}

    elif request.args.get('action', '') == 'keysetlookup':
        try:
            return AlarmkeySet.getAlarmkeySets(
                request.args.get('setid')).alarmkeys
        except ValueError:  # no base given
            return []

    elif request.args.get('action', '') == 'uploaddefinition':
        if request.files:
            ufile = request.files['uploadfile']
            if not os.path.exists("{}alarmkeysetbase/".format(
                    current_app.config.get('PATH_DATA'))):
                os.makedirs("{}alarmkeysetbase/".format(
                    current_app.config.get('PATH_DATA')))
            fname = os.path.join(
                "{}alarmkeysetbase/".format(
                    current_app.config.get('PATH_DATA')), ufile.filename)
            ufile.save(fname)
            with codecs.open(fname, 'r', encoding='utf-8') as fin:
                aksetbase = AlarmkeySetBase(ufile.filename, json.load(fin),
                                            'external')
                return jsonify(state="ok",
                               name=aksetbase.name,
                               startdate=datetime.datetime.strftime(
                                   aksetbase.start, "%d.%m.%Y"),
                               items=len(aksetbase.items),
                               filename=aksetbase.id,
                               type=aksetbase.settype)

        return jsonify(state="error")

    elif request.args.get('action', '') == 'createbaseset':
        """
        create base keys for given set and return number of updated
        """
        stats = AlarmkeySet.getAlarmkeySets(
            id=request.args.get('setid')).createBaseKeys()
        return babel.gettext('alarmkeys.createbaseset.result',
                             num_success=stats[0],
                             num_error=stats[1])

    if "/download/" in request.url:  # deliver file
        filename = os.path.basename(request.url)
        mime = "application/x.download"
        if filename.endswith('.xlsx'):
            mime = "application/vnd.ms-excel"
        return send_from_directory("%s/" % current_app.config.get('PATH_TMP'),
                                   filename,
                                   as_attachment=True,
                                   mimetype=mime)
    return ""
Example #49
0
 def __str__(self):
     return u'{} ({})'.format(self.name, babel.gettext(self.type))
Example #50
0
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append(
            u"{}/emonitor/modules/printers/templates".format(
                app.config.get('PROJECT_ROOT')))

        # add events and handler
        events.addHandlerClass('*',
                               'emonitor.modules.printers.printers.Printers',
                               Printers.handleEvent, ['in.printerid'])

        # subnavigation
        self.adminsubnavigation = [('/admin/printers', 'printers.main'),
                                   ('/admin/printers/settings',
                                    'module.printers.settings')]

        # static folders
        @app.route('/printer/inc/<path:filename>')
        def printer_static(filename):
            return send_from_directory(
                u"{}/emonitor/modules/printers/inc/".format(
                    app.config.get('PROJECT_ROOT')), filename)

        # translations
        babel.gettext(u'module.printers')
        babel.gettext(u'printers.main')
        babel.gettext(u'module.printers.settings')
        babel.gettext(u'emonitor.modules.printers.printers.Printers')
        babel.gettext(u'template.alarm_sum')
        babel.gettext(u'template.alarm_original')
 def __init__(self, app):
     Module.__init__(self, app)
     babel.gettext(u'module.startpages')
Example #52
0
import datetime
import time
import urllib2, urllib, json
import codecs
from itertools import ifilter
from flask import render_template, current_app
from emonitor.widget.monitorwidget import MonitorWidget
from emonitor.extensions import babel
from emonitor.modules.settings.settings import Settings

__all__ = ['WeatherWidget']

babel.gettext('Mon')
babel.gettext('Tue')
babel.gettext('Wed')
babel.gettext('Thu')
babel.gettext('Fri')
babel.gettext('Sat')
babel.gettext('Sun')
babel.gettext('message.weather')

wIcons = ['{}.png'.format(i) for i in range(0, 19)]


def getIcon4Code(code, iconlist):
    try:
        return wIcons[[_i for _i, x in enumerate(iconlist) if code in x][0]]
    except IndexError:
        return wIcons[0]

    info = dict(area=['frontend'], name='modulename', path='modulepath', ...)

This example will add the module 'modulename' in frontend area with url `server/modulepath`
"""
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, send_from_directory, request, jsonify
from flask.ext import login
from emonitor.user import User
from emonitor.extensions import babel
from emonitor.utils import restartService

frontend = Blueprint("frontend", __name__, template_folder="web/templates")
frontend.modules = OrderedDict()

babel.gettext(u"emonitor.monitorserver.MonitorServer")
babel.gettext(u"trigger.default")

from emonitor.modules.settings.settings import Settings


def _addModule(module):
    if module.info["name"] not in frontend.modules.keys():
        frontend.modules[module.info["name"]] = module


frontend.addModule = _addModule


@frontend.route("/favicon.ico", methods=["GET"])
def favicon():
Example #54
0

def addProcess(process):
    """
    The admin area uses processes. External modules can add own *processes* needed for background operations

    :param process: process object
    """
    if process not in admin.processes:
        admin.processes.append(process)
        #signal.send('admin.processes')


admin.addModule = addModule

babel.gettext(u'trigger.default')
babel.gettext(u'trigger.file_added')
babel.gettext(u'trigger.file_removed')


@admin.route('/admin')
@admin.route('/admin/')
@admin.route('/admin/<path:module>', methods=['GET', 'POST'])
@admin_required
def adminContent(module=''):
    """
    Admin area is reachable under *http://[servername]:[port]/admin/[module]*

    *module* will execute the *getAdminContent* method of registered module. If no nodule is given, the startpage of
    the admin area will be used
Example #55
0
import datetime
import math
from collections import OrderedDict
from flask import render_template
from emonitor.extensions import babel
from emonitor.modules.persons.persons import Person
from emonitor.widget.monitorwidget import MonitorWidget
from emonitor.modules.settings.settings import Settings

__all__ = ['BirthdayWidget']

babel.gettext(u'message.birthday')


class BirthdayWidget(MonitorWidget):
    """Widget for text messages"""
    __info__ = {'icon': 'fa-birthday-cake'}
    __fields__ = ['orientation', 'number']
    template = 'widget.message.birthday.html'
    size = (5, 4)

    def __repr__(self):
        return "birthday"

    def getAdminContent(self, **params):
        """
        Get content for admin area to config all parameters of message type object

        :param params: list of all currently used parameters
        :return: rendered template of text message type
        """
    def __init__(self, app):
        Module.__init__(self, app)

        # add template path
        app.jinja_loader.searchpath.append("%s/emonitor/modules/monitors/templates" % app.config.get('PROJECT_ROOT'))

        # subnavigation
        self.adminsubnavigation = [('/admin/monitors', 'monitors.definition'), ('/admin/monitors/style', 'module.monitors.style'), ('/admin/monitors/current', 'module.monitors.current'), ('/admin/monitors/actions', 'module.monitors.actions')]
        self.widgets = [PlaceholderWidget('placeholder')]

        signal.connect('monitorserver', 'clientsearchdone', frontendMonitorHandler.handleClientSearch)
        signal.connect('monitorserver', 'clientanswer', frontendMonitorHandler.handleClientAnswer)

        # static folders
        @app.route('/monitors/inc/<path:filename>')
        def monitors_static(filename):
            return send_from_directory("%s/emonitor/modules/monitors/inc/" % app.config.get('PROJECT_ROOT'), filename)
            
        # translations
        babel.gettext(u'module.monitors')
        babel.gettext(u'monitors.definition')
        babel.gettext(u'module.monitors.style')
        babel.gettext(u'module.monitors.current')
        babel.gettext(u'module.monitors.actions')
        babel.gettext(u'monitors.landscape')
        babel.gettext(u'monitors.portrait')
        babel.gettext(u'monitors.orientation.0')
        babel.gettext(u'monitors.orientation.1')
        babel.gettext(u'placeholder')
import os
from emonitor import app
from emonitor.modules.mapitems.mapitem import ItemLayout
from emonitor.modules.mapitems.mapitem_utils import deg2num
from emonitor.extensions import babel
from PIL import Image, ImageDraw

__all__ = ['LayoutFFEntry']
babel.gettext('mapitems.params.ffentry')


class LayoutFFEntry(ItemLayout):
    """LayoutFFEntry"""

    __name__ = 'ffentry'
    __version__ = '0.2'

    itemtype = 'way'
    filter = '[highway][service="emergency_access"]'
    attributes = ['id', 'lat', 'lon']

    ZOOMLEVELS = 16, 17, 18
    DESTPATH = '{}{}'.format(app.config.get('PATH_TILES'), __name__)

    LINECOLOR = (255, 0, 0)  # yellow

    def buildTiles(self, items, attributes):
        """
        Build tiles of given items

        :param items: list of items to build
Example #58
0
    def __init__(self, app):
        Module.__init__(self, app)
        # add template path
        app.jinja_loader.searchpath.append("%s/emonitor/modules/messages/templates" % app.config.get('PROJECT_ROOT'))

        # subnavigation
        self.adminsubnavigation = [('/admin/messages', 'messages.main'), ('/admin/messages/types', 'messages.types')]
        self.widgets = [MessageWidget('messages', size=(4, 2), template='widget.message.messages.html'), WeatherWidget('weather', size=(5, 4), template='widget.message.weather.html')]

        # static folders
        @app.route('/messages/inc/<path:filename>')
        def messages_static(filename):
            if filename.startswith('message/'):
                filename = filename.split('/')
                return send_from_directory("{}messages/{}/".format(app.config.get('PATH_DATA'), filename[-2]), filename[-1])
            else:
                return send_from_directory("%s/emonitor/modules/messages/inc/" % app.config.get('PROJECT_ROOT'), filename)

        # translations
        babel.gettext(u'module.messages')
        babel.gettext(u'messages.main')
        babel.gettext(u'messages.types')
        babel.gettext(u'weather')
        babel.gettext(u'messages')
        babel.gettext(u'messagestate.1')  # activated
        babel.gettext(u'messagestate.0')  # deactivated
        babel.gettext(u'message.state.1')  # active
        babel.gettext(u'message.state.0')  # in-active

        # init
        # Do init script for messages at start and add active messages
        try:
            Messages.initMessageTrigger()
        except ProgrammingError:
            pass