def getAdminData(self):
    """
    Deliver admin content of module monitors (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get("action") == "thumb":  # create dynamic thumbnail of layout
        layout = MonitorLayout.getLayouts(id=request.args.get("id"))
        return layout.getLayoutThumb()

    if request.args.get("action") == "widgetparams":  # params: width, height, w_id,
        return render_template(
            "admin.monitors.actions.html",
            width=request.args.get("width"),
            height=request.args.get("height"),
            widget=request.args.get("w_id"),
        )  # macro='widgetparams'

    if request.args.get("action") == "ping":  # ping clients
        from emonitor.extensions import monitorserver

        clients = monitorserver.getClients()  # start discovery
        return dict(clients=[k for k in clients.keys() if clients[k][0]])

    if request.args.get("action") == "schedules":  # get active schedules
        return render_template(
            "admin.monitors.actions_actions.html", schedjobs=scheduler.get_jobs()
        )  # macro='schedjobs'

    return ""
Example #2
0
    def updateSchedules(self, reference=0):
        """
        set scheduler events for current alarm:

        * autoclose
        * autoarchive

        :param reference: 0 (default)= time.time()
                          1 = alarm.timestamp
        """
        for job in scheduler.get_jobs():  # remove schedules of current alarm
            if job.name.startswith('alarms_') and job.name.endswith('_{}'.format(self.id)):
                scheduler.remove_job(job.id)

        if reference == 0:
            reference = time.time()
        else:
            reference = time.mktime(self.timestamp.timetuple())

        # test autoclose
        if self.state == 1 and self.type == 1 and Settings.get('alarms.autoclose', '0') != '0':  # only for open alarms
            closingtime = reference + float(Settings.get('alarms.autoclose', 30)) * 60.0  # minutes -> seconds
            if closingtime > time.time():  # close alarm in future
                logger.debug("add close schedule in future for alarmid {}".format(self.id))
                scheduler.add_job(self.changeState, run_date=datetime.datetime.fromtimestamp(closingtime), args=[self.id, 2], name="alarms_close_{}".format(self.id))
            else:  # close alarm now
                logger.debug("add close schedule now for alarmid {}".format(self.id))
                scheduler.add_job(self.changeState, args=[self.id, 2], name="alarms_close_{}".format(self.id))
                self.state = 2

        # test autoarchive
        if self.state == 2 and Settings.get('alarms.autoarchive', '0') != '0':  # only closed alarms
            archivetime = reference + float(Settings.get('alarms.autoarchive', 12)) * 3600.0  # hours -> seconds
            if archivetime > time.time():  # archive alarm in future
                logger.debug("add archive schedule in future for alarmid {}".format(self.id))
                scheduler.add_job(self.changeState, run_date=datetime.datetime.fromtimestamp(archivetime), args=[self.id, 3], name="alarms_archive_{}".format(self.id))
            else:  # archive alarm now
                logger.debug("add archive schedule now for alarmid {}".format(self.id))
                scheduler.add_job(self.changeState, args=[self.id, 3], name="alarms_archive_{}".format(self.id))
Example #3
0
def getAdminData(self):
    """
    Deliver admin content of module monitors (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'thumb':  # create dynamic thumbnail of layout
        layout = MonitorLayout.getLayouts(id=request.args.get('id'))
        return layout.getLayoutThumb()
    
    if request.args.get('action') == 'widgetparams':  # params: width, height, w_id,
        return render_template('admin.monitors.actions.html', width=request.args.get('width'), height=request.args.get('height'), widget=request.args.get('w_id'))  # macro='widgetparams'
        
    if request.args.get('action') == 'ping':  # ping clients
        from emonitor.extensions import monitorserver
        clients = monitorserver.getClients()  # start discovery
        return dict(clients=[k for k in clients.keys() if clients[k][0]])

    if request.args.get('action') == 'schedules':  # get active schedules
        return render_template('admin.monitors.actions_actions.html', schedjobs=scheduler.get_jobs())  # macro='schedjobs'
        
    return ""
Example #4
0
    def updateSchedules(self, reference=0):
        """
        set scheduler events for current alarm:

        * autoclose
        * autoarchive

        :param reference: 0 (default)= time.time()
                          1 = alarm.timestamp
        """
        for job in scheduler.get_jobs():  # remove schedules of current alarm
            if job.name.startswith('alarms_') and job.name.endswith('_{}'.format(self.id)):
                scheduler.remove_job(job.id)

        if reference == 0:
            reference = time.time()
        else:
            reference = time.mktime(self.timestamp.timetuple())

        # autoclose
        if self.state == 1 and self.type == 1 and Settings.get('alarms.autoclose', '0') != '0':  # only for open alarms
            closingtime = reference + float(Settings.get('alarms.autoclose', 30)) * 60.0  # minutes -> seconds
            if closingtime > time.time():  # close alarm in future
                logger.debug("add close schedule in future for alarmid {}".format(self.id))
                scheduler.add_job(Alarm.changeState, run_date=datetime.datetime.fromtimestamp(closingtime), args=[self.id, 2], name="alarms_close_{}".format(self.id))
            else:  # close alarm now
                logger.debug("add close schedule now for alarmid {}".format(self.id))
                scheduler.add_job(Alarm.changeState, args=[self.id, 2], name="alarms_close_{}".format(self.id))
                self.state = 2

        # autoarchive
        if self.state == 2 and Settings.get('alarms.autoarchive', '0') != '0':  # only closed alarms
            archivetime = reference + float(Settings.get('alarms.autoarchive', 12)) * 3600.0  # hours -> seconds
            if archivetime > time.time():  # archive alarm in future
                logger.debug("add archive schedule in future for alarmid {}".format(self.id))
                scheduler.add_job(Alarm.changeState, run_date=datetime.datetime.fromtimestamp(archivetime), args=[self.id, 3], name="alarms_archive_{}".format(self.id))
            else:  # archive alarm now
                logger.debug("add archive schedule now for alarmid {}".format(self.id))
                scheduler.add_job(Alarm.changeState, args=[self.id, 3], name="alarms_archive_{}".format(self.id))
Example #5
0
    def changeState(id, state):
        """
        Change state of alarm with given id. Adds entry in alarmhistory and sends signal

        :param id: id of alarm
        :param state: new state as :py:attr:`emonitor.modules.alarms.alarm.Alarm.ALARMSTATES`
        """
        from emonitor.extensions import monitorserver
        global LASTALARM
        alarm = Alarm.getAlarms(id=id)
        if not alarm:
            return []

        if alarm.state != state:  # only change
            _op = 'changestate'
        else:
            _op = 'added'

        if alarm.get('alarmtype', '') != '':
            _type = '.{}'.format(alarm.get('alarmtype'))
        else:
            _type = ''

        alarm.state = state
        try:
            alarm.addHistory('autochangeState', Alarm.ALARMSTATES[str(state)])
        except KeyError:
            alarm.addHistory('autochangeState', 'archived')
        db.session.commit()

        if state == 1:  # activate alarm
            c = []
            for a in Alarm.getActiveAlarms():  # check cars
                if a.id == id:
                    continue
                c.extend(set(a.cars1).intersection(set(alarm.cars1)))
                c.extend(set(a.cars2).intersection(set(alarm.cars2)))
                c.extend(set(a.material).intersection(set(alarm.material)))

            if time.time() - LASTALARM < 60.0:
                try:
                    ids = [a.id for a in Alarm.getActiveAlarms()]
                    for j in [job for job in scheduler.get_jobs() if job.name == 'changeLayout']:
                        for i in ids:
                            if "'alarmid', %s" % i in str(j.args):  # layout changes for given alarm
                                scheduler.unschedule_job(j)
                except:
                    logger.error('%s' % [a.id for a in Alarm.getActiveAlarms()])
            LASTALARM = time.time()
            alarm.updateSchedules(reference=0)  # use current time + delta
            j = scheduler.add_job(events.raiseEvent, next_run_time=datetime.datetime.fromtimestamp(LASTALARM), args=['alarm_{}{}'.format(_op, _type)], kwargs={'alarmid': id}, name="alarms_activate_{}".format(id))
            signal.send('alarm', 'added', alarmid=id)
            try:
                flash(babel.gettext(u'alarms.statechangeactivated'), 'alarms.activate')
            except:
                pass
            finally:
                monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
                #signal.send('alarm', 'changestate', newstate=1)
                return list(set(c))

        elif state == 2:  # close alarm
            LASTALARM = 0.0
            alarm.updateSchedules(reference=1)  # use alarm.timestamp + delta
            monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
            signal.send('alarm', 'changestate', newstate=2)
            return []

        elif state == 3:  # archive alarm
            alarm.updateSchedules()
            signal.send('alarm', 'changestate', newstate=3)
            return []

        signal.send('alarm', 'changestate', newstate=state)
Example #6
0
def monitorContent(clientid=0):
    """
    Create monitor area under url */monitor*

    :return: rendered template */emonitor/monitor/templates/monitor.html*
    """
    alarmid = None
    footer = 0
    count = []
    pos = 0

    if 'alarmid' in request.args:  # eval active alarms or defined id
        alarmid = int(request.args.get('alarmid'))
        if len(Alarm.getActiveAlarms()) > 0:
            count = Alarm.getActiveAlarms()
    elif len(Alarm.getActiveAlarms()) > 0:
        alarmid = Alarm.getActiveAlarms()[0].id
        count = Alarm.getActiveAlarms()
    alarm = Alarm.getAlarms(id=alarmid)

    defmonitor = Monitor.getMonitors(clientid=int(clientid))
    try:
        layout = defmonitor.currentlayout
    except AttributeError:
        return render_template('monitor-test.html')

    if 'layoutid' in request.args:  # eval current layout
        layout = defmonitor.layout(int(request.args.get('layoutid')))
    else:
        try: layout = defmonitor.getLayouts(triggername='default')[0]
        except: pass

    if len(count) > 0:  # eval layout for current and next alarm
        footer = 1
        nextalarm = currentalarm = count[0]
        for c in count:
            if c.id == alarmid:
                pos = count.index(c) + 1
                currentalarm = count[(pos - 1) % len(count)]
                nextalarm = count[pos % len(count)]

            for j in [job for job in scheduler.get_jobs(name='changeLayout') if "'alarmid', %s" % c.id in str(job.args)]:
                scheduler.remove_job(j.id)  # layout changes for given alarm

        for l in defmonitor.getLayouts(triggername='alarm_added'):
            for tr in l.trigger.split(';'):  # support more than one trigger for layout
                if ('.' in tr and len(count) >= 1 and tr.split('.')[-1] == currentalarm.get('alarmtype')) or ('.' not in tr and currentalarm.get('alarmtype', '') == ""):
                    layout = l
                    break

        if len(count) > 1:
            for l in defmonitor.getLayouts(triggername='alarm_added'):
                for tr in l.trigger.split(';'):  # support more than one trigger for layout
                    if ('.' in tr and tr.split('.')[-1] == nextalarm.get('alarmtype')) or ('.' not in tr and nextalarm.get('alarmtype', '') == ""):
                        if int(l.mintime) != 0:
                            #scheduler.add_job(monitorserver.changeLayout, next_run_time=datetime.datetime.fromtimestamp(time.time() + float(l.mintime)), args=[defmonitor.clientid, l.id, [('alarmid', nextalarm.id), ('monitorid', defmonitor.id)]])
                            scheduler.add_job(monitorserver.changeLayout, next_run_time=datetime.datetime.fromtimestamp(time.time() + float(l.mintime)), args=[defmonitor.clientid, l.id], kwargs=dict(alarmid=nextalarm.id))  # TODO

    # render content for monitor
    content = '<div id="content">%s</div>' % layout.htmllayout
    for w in re.findall('\[\[\s?(.+?)\s?\]\]', content):
        for widgets in current_app.blueprints['widget'].modules:
            for widget in widgets.getMonitorWidgets():
                if widget.getName() == w:
                    params = widget.addParameters(alarmid=alarmid, alarm=alarm, clientid=clientid, layout=layout)
                    if params and 'footer' in params and params['footer'] == 1:
                        footer = 1
                    content = content.replace(u'[[%s]]' % w, widget.getHTML(request))

    return render_template('monitor.html', content=content, clientid=clientid, theme=layout.theme, activecount=len(count), footer=footer, position=pos, app_name=current_app.config.get('PROJECT'), app_version=current_app.config.get('APP_VERSION'))
Example #7
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module settings

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    def chunks(l, n):
        return [l[i:i + n] for i in range(0, len(l), n)]

    if len(module) == 2:
        if module[1] == 'department':  # department submodule
            if request.method == 'POST':
                if request.form.get('action') == 'savedept':  # save department
                    if request.form.get('dep_id') != 'None':  # update
                        department = Department.getDepartments(request.form.get('dep_id'))
                        l = request.form.get('dep_pos')
                    else:  # add
                        l = len(Department.getDepartments()) + 1
                        department = Department('', '', '', 0)
                        db.session.add(department)
                    department.name = request.form.get('dep_name')
                    department.shortname = request.form.get('dep_shortname')
                    department.color = request.form.get('dep_color')
                    department.set(u'address_name', unicode(request.form.get('dep_address_name')))
                    department.set(u'address_street', unicode(request.form.get('dep_address_street')))
                    department.set(u'address_city', unicode(request.form.get('dep_address_city')))
                    department.set(u'address_phone', unicode(request.form.get('dep_address_phone')))
                    department.set(u'address_fax', unicode(request.form.get('dep_address_fax')))
                    department.set(u'address_email', unicode(request.form.get('dep_address_email')))
                    if len(request.files) > 0:
                        uploadfile = request.files.get('dep_logo')
                        if uploadfile.filename != '':
                            _fname, _fext = os.path.splitext(uploadfile.filename)
                            db.session.flush()  # flush to get department id of new department
                            fname = os.path.join(current_app.config.get('PATH_DATA'), 'departmentlogo_{}{}'.format(department.id, _fext))
                            uploadfile.save(fname)
                            department.set(u'logo', u'departmentlogo_{}{}'.format(department.id, _fext))  # store relative path from data directory
                        elif request.form.get('logoaction') == 'deletelogo':
                            if os.path.exists('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo'])):
                                os.remove('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo']))
                                department.set(u'logo', u'')
                    department.orderpos = l
                    department.defaultcity = request.form.get('dep_city')
                    db.session.commit()
                    
                elif request.form.get('action') == 'createdepartment':  # add department
                    params.update({'department': Department('', '', '', 0), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('detaildept_'):  # edit department
                    params.update({'department': Department.getDepartments(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('deletedept_'):  # delete department
                    _c = []
                    for city in City.getCities():
                        if city.department.id == int(request.form.get('action').split('_')[-1]):
                            _c.append(city.name)
                    if len(_c) == 0:
                        db.session.delete(Department.getDepartments(id=request.form.get('action').split('_')[-1]))
                        db.session.commit()
                    else:
                        params.update({'error': babel.gettext('admin.settings.department_deleteerror1', cities=', '.join(_c))})
                    
                elif request.form.get('action') == 'ordersetting':  # change department order
                    for _id in request.form.getlist('departmentids'):
                        Department.getDepartments(id=_id).orderpos = request.form.getlist('departmentids').index(_id) + 1
                    db.session.commit()
            
            params.update({'departments': Department.getDepartments(), 'cities': City.getCities()})
            return render_template('admin.settings.department.html', **params)

        elif module[1] == 'cars':
            if request.method == 'POST':
                if request.form.get('action') == 'updatetypes':
                    Settings.set('cartypes', [i for i in chunks(request.form.getlist('cartype'), 2) if i[0] != ''])
                    db.session.commit()
            params.update({'cartypes': Settings.getCarTypes()})
            return render_template('admin.settings.cars.html', **params)

        elif module[1] == 'communication':
            from emonitor.extensions import communication
            if request.method == 'POST':
                if request.form.get('action') == 'telegramsettings':
                    vals = Settings.get('telegramsettings')
                    vals['telegramkey'] = request.form.get('telegrambot').strip()
                    vals['welcomemsg'] = request.form.get('welcometext')
                    vals['helpmsg'] = request.form.get('helptext')
                    Settings.set('telegramsettings', vals)
                    db.session.commit()
                    tb = communication.telegram
                    if not tb:
                        communication.init_app(app=communication.app)
                        tb = communication.telegram
                    else:
                        tb.stop()
                    try:
                        tb.updateToken(vals['telegramkey'])
                    except AttributeError:
                        pass

                elif request.form.get('action') == 'telegramgroups':
                    vals = Settings.get('telegramsettings')
                    g = {}
                    for f in filter(lambda x: x.startswith('groupname_'), request.form):
                        _id = f.split('_')[-1]  # fieldname in form
                        if request.form.get('groupname_' + _id) in ['newgroup', '']:
                            continue
                        g[request.form.get('groupname_' + _id)] = request.form.get('members_selectable_' + _id).split(';')
                    vals['groups'] = g
                    Settings.set('telegramsettings', vals)
                    db.session.commit()

            params.update({'bot': communication.telegram, 'settings': Settings.getYaml('telegramsettings'), 'configtelegramkey': current_app.config.get('TELEGRAMKEY', '')})
            return render_template('admin.settings.communication.html', **params)

        elif module[1] == 'start':

            if request.method == 'POST':
                if request.form.get('action') == 'updatestart':  # update start page definition
                    areas = dict()
                    areas['center'] = {'module': request.form.get('center.module'), 'width': '0', 'visible': 1}
                    areas['west'] = {'module': request.form.get('west.module'), 'moduleadd': request.form.getlist('west.module.add'), 'width': '.%s' % request.form.get('west.width'), 'visible': request.form.get('west.visible')}
                    areas['east'] = {'module': request.form.get('east.module'), 'moduleadd': request.form.getlist('east.module.add'), 'width': '.%s' % request.form.get('east.width'), 'visible': request.form.get('east.visible')}

                    Settings.set('frontend.default', areas)
                    db.session.commit()

            def modname(obj):  # get translation for sorting of module
                _t = "module.%s" % obj.info['name']
                return babel.gettext(_t)

            params.update({'mods': sorted([m for m in current_app.blueprints['frontend'].modules.values() if m.frontendContent() == 1], key=modname), 'center': Settings.getFrontendSettings('center'), 'west': Settings.getFrontendSettings('west'), 'east': Settings.getFrontendSettings('east')})
            return render_template('admin.settings.start.html', **params)

    else:

        if request.method == 'POST':  # save settings
            if request.form.get('action') == 'observerstate':
                Settings.set('observer.interval', request.form.get('observerinterval'))
                _jobserver = scheduler.get_jobs('observerinterval')[0]
                if Settings.get('observer.interval', '0') == '0':
                    _jobserver.pause()
                else:
                    scheduler.reschedule_job(_jobserver.id, trigger=eMonitorIntervalTrigger(seconds=int(Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL', 2)))))
            elif request.form.get('action') == 'monitorping':
                Settings.set('monitorping', request.form.get('monitorping'))
                _jping = scheduler.get_jobs('monitorping')[0]
                if Settings.get('monitorping', '0') == '0':
                    _jping.pause()
                else:
                    scheduler.reschedule_job(_jping.id, trigger=eMonitorIntervalTrigger(minutes=int(Settings.get('monitorping', current_app.config.get('MONITORPING', 2)))))

        paths = dict(pathdata=current_app.config.get('PATH_DATA'), pathtmp=current_app.config.get('PATH_TMP'), pathincome=current_app.config.get('PATH_INCOME'), pathdone=current_app.config.get('PATH_DONE'))
        params.update({'paths': paths, 'observerinterval': Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL')), 'monitorping': Settings.get('monitorping', current_app.config.get('MONITORPING')), 'alarmsevalfields': Settings.get('alarms.evalfields'), 'alembic': alembic})
        return render_template('admin.settings.html', **params)
    return redirect("/admin/settings", code=302)
Example #8
0
    def changeState(id, state):
        """
        Change state of alarm with given id. Adds entry in alarmhistory and sends signal

        :param id: id of alarm
        :param state: new state as :py:attr:`emonitor.modules.alarms.alarm.Alarm.ALARMSTATES`
        """
        from emonitor.extensions import monitorserver
        global LASTALARM
        alarm = Alarm.getAlarms(id=id)
        if not alarm:
            return []

        if alarm.state != state and alarm.state != 0:  # only change
            _op = 'changestate'
        else:
            _op = 'added'

        if alarm.get('alarmtype', '') != '':
            _type = '.{}'.format(alarm.get('alarmtype'))
        else:
            _type = ''

        alarm.state = state
        try:
            alarm.addHistory('autochangeState', Alarm.ALARMSTATES[str(state)])
        except KeyError:
            alarm.addHistory('autochangeState', 'archived')
        db.session.commit()

        if state == 1:  # activate alarm
            c = []
            for a in Alarm.getActiveAlarms():  # check cars
                if a.id == id:
                    continue
                c.extend(set(a.cars1).intersection(set(alarm.cars1)))
                c.extend(set(a.cars2).intersection(set(alarm.cars2)))
                c.extend(set(a.material).intersection(set(alarm.material)))

            if time.time() - LASTALARM < 60.0:
                try:
                    ids = [a.id for a in Alarm.getActiveAlarms()]
                    for j in [job for job in scheduler.get_jobs() if job.name == 'changeLayout']:
                        for i in ids:
                            if "'alarmid', %s" % i in str(j.args):  # layout changes for given alarm
                                scheduler.unschedule_job(j)
                except:
                    logger.error('%s' % [a.id for a in Alarm.getActiveAlarms()])
            LASTALARM = time.time()
            alarm.updateSchedules(reference=0)  # use current time + delta
            j = scheduler.add_job(events.raiseEvent, next_run_time=datetime.datetime.fromtimestamp(LASTALARM), args=['alarm_{}{}'.format(_op, _type)], kwargs={'alarmid': id}, name="alarms_activate_{}".format(id))
            signal.send('alarm', _op, alarmid=id, newstate=state)
            try:
                flash(babel.gettext(u'alarms.statechangeactivated'), 'alarms.activate')
            except:
                pass
            finally:
                monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
                return list(set(c))

        elif state == 2:  # close alarm
            LASTALARM = 0.0
            alarm.updateSchedules(reference=1)  # use alarm.timestamp + delta
            monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
            signal.send('alarm', 'changestate', newstate=2)
            return []

        elif state == 3:  # archive alarm
            alarm.updateSchedules()
            signal.send('alarm', 'changestate', newstate=3)
            return []

        signal.send('alarm', 'changestate', newstate=state)
Example #9
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module settings

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    def chunks(l, n):
        return [l[i:i + n] for i in range(0, len(l), n)]

    if len(module) == 2:
        if module[1] == 'department':  # department submodule
            if request.method == 'POST':
                if request.form.get('action') == 'savedept':  # save department
                    if request.form.get('dep_id') != 'None':  # update
                        department = Department.getDepartments(request.form.get('dep_id'))
                        l = request.form.get('dep_pos')
                    else:  # add
                        l = len(Department.getDepartments()) + 1
                        department = Department('', '', '', 0)
                        db.session.add(department)
                    department.name = request.form.get('dep_name')
                    department.shortname = request.form.get('dep_shortname')
                    department.color = request.form.get('dep_color')
                    department.set(u'address_name', unicode(request.form.get('dep_address_name')))
                    department.set(u'address_street', unicode(request.form.get('dep_address_street')))
                    department.set(u'address_city', unicode(request.form.get('dep_address_city')))
                    department.set(u'address_phone', unicode(request.form.get('dep_address_phone')))
                    department.set(u'address_fax', unicode(request.form.get('dep_address_fax')))
                    department.set(u'address_email', unicode(request.form.get('dep_address_email')))
                    if len(request.files) > 0:
                        uploadfile = request.files.get('dep_logo')
                        if uploadfile.filename != '':
                            _fname, _fext = os.path.splitext(uploadfile.filename)
                            db.session.flush()  # flush to get department id of new department
                            fname = os.path.join(current_app.config.get('PATH_DATA'), 'departmentlogo_{}{}'.format(department.id, _fext))
                            uploadfile.save(fname)
                            department.set(u'logo', u'departmentlogo_{}{}'.format(department.id, _fext))  # store relative path from data directory
                        elif request.form.get('logoaction') == 'deletelogo':
                            if os.path.exists('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo'])):
                                os.remove('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo']))
                                department.set(u'logo', u'')
                    department.orderpos = l
                    department.defaultcity = request.form.get('dep_city')
                    db.session.commit()
                    
                elif request.form.get('action') == 'createdepartment':  # add department
                    params.update({'department': Department('', '', '', 0), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('detaildept_'):  # edit department
                    params.update({'department': Department.getDepartments(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('deletedept_'):  # delete department
                    _c = []
                    for city in City.getCities():
                        if city.department.id == int(request.form.get('action').split('_')[-1]):
                            _c.append(city.name)
                    if len(_c) == 0:
                        db.session.delete(Department.getDepartments(id=request.form.get('action').split('_')[-1]))
                        db.session.commit()
                    else:
                        params.update({'error': babel.gettext('admin.settings.department_deleteerror1', cities=', '.join(_c))})
                    
                elif request.form.get('action') == 'ordersetting':  # change department order
                    for _id in request.form.getlist('departmentids'):
                        Department.getDepartments(id=_id).orderpos = request.form.getlist('departmentids').index(_id) + 1
                    db.session.commit()
            
            params.update({'departments': Department.getDepartments(), 'cities': City.getCities()})
            return render_template('admin.settings.department.html', **params)

        elif module[1] == 'cars':
            if request.method == 'POST':
                if request.form.get('action') == 'updatetypes':
                    Settings.set('cartypes', [i for i in chunks(request.form.getlist('cartype'), 2) if i[0] != ''])
                    db.session.commit()
            params.update({'cartypes': Settings.getCarTypes()})
            return render_template('admin.settings.cars.html', **params)

        elif module[1] == 'communication':
            from emonitor.extensions import communication
            if request.method == 'POST':
                if request.form.get('action') == 'telegramsettings':
                    vals = Settings.get('telegramsettings')
                    vals['telegramkey'] = request.form.get('telegrambot').strip()
                    vals['welcomemsg'] = request.form.get('welcometext')
                    vals['helpmsg'] = request.form.get('helptext')
                    Settings.set('telegramsettings', vals)
                    db.session.commit()
                    tb = communication.telegram
                    if not tb:
                        communication.init_app(app=communication.app)
                        tb = communication.telegram
                    #else:
                     #   tb.stop()
                    try:
                        tb.updateToken(vals['telegramkey'])
                    except AttributeError:
                        pass

                elif request.form.get('action') == 'telegramgroups':
                    vals = Settings.get('telegramsettings')
                    g = {}
                    for f in filter(lambda x: x.startswith('groupname_'), request.form):
                        _id = f.split('_')[-1]  # fieldname in form
                        if request.form.get('groupname_' + _id) in ['newgroup', '']:
                            continue
                        g[request.form.get('groupname_' + _id)] = request.form.get('members_selectable_' + _id).split(';')
                    vals['groups'] = g
                    Settings.set('telegramsettings', vals)
                    db.session.commit()

            params.update({'bot': communication.telegram, 'settings': Settings.getYaml('telegramsettings'), 'configtelegramkey': current_app.config.get('TELEGRAMKEY', '')})
            return render_template('admin.settings.communication.html', **params)

        elif module[1] == 'start':

            if request.method == 'POST':
                if request.form.get('action') == 'updatestart':  # update start page definition
                    areas = dict()
                    areas['center'] = {'module': request.form.get('center.module'), 'width': '0', 'visible': 1}
                    areas['west'] = {'module': request.form.get('west.module'), 'moduleadd': request.form.getlist('west.module.add'), 'width': '.%s' % request.form.get('west.width'), 'visible': request.form.get('west.visible')}
                    areas['east'] = {'module': request.form.get('east.module'), 'moduleadd': request.form.getlist('east.module.add'), 'width': '.%s' % request.form.get('east.width'), 'visible': request.form.get('east.visible')}

                    Settings.set('frontend.default', areas)
                    db.session.commit()

            def modname(obj):  # get translation for sorting of module
                _t = "module.%s" % obj.info['name']
                return babel.gettext(_t)

            params.update({'mods': sorted([m for m in current_app.blueprints['frontend'].modules.values() if m.frontendContent() == 1], key=modname), 'center': Settings.getFrontendSettings('center'), 'west': Settings.getFrontendSettings('west'), 'east': Settings.getFrontendSettings('east')})
            return render_template('admin.settings.start.html', **params)

    else:

        if request.method == 'POST':  # save settings
            if request.form.get('action') == 'observerstate':
                Settings.set('observer.interval', request.form.get('observerinterval'))
                if 'observerinterval' in [j.name for j in scheduler.get_jobs()]:  # use file
                    _jobserver = scheduler.get_jobs('observerinterval')[0]
                    if Settings.get('observer.interval', '0') == '0':
                        _jobserver.pause()
                    else:
                        scheduler.reschedule_job(_jobserver.id, trigger=eMonitorIntervalTrigger(seconds=int(Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL', 2)))))

            elif request.form.get('action') == 'monitorping':
                Settings.set('monitorping', request.form.get('monitorping'))
                _jping = scheduler.get_jobs('monitorping')[0]
                if Settings.get('monitorping', '0') == '0':
                    _jping.pause()
                else:
                    scheduler.reschedule_job(_jping.id, trigger=eMonitorIntervalTrigger(minutes=int(Settings.get('monitorping', current_app.config.get('MONITORPING', 2)))))

        paths = dict(pathdata=current_app.config.get('PATH_DATA'), pathtmp=current_app.config.get('PATH_TMP'), pathincome=current_app.config.get('PATH_INCOME'), pathdone=current_app.config.get('PATH_DONE'))
        params.update({'paths': paths, 'observerinterval': Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL')), 'watchdog': 'observerinterval' not in [j.name for j in scheduler.get_jobs()], 'monitorping': Settings.get('monitorping', current_app.config.get('MONITORPING')), 'alarmsevalfields': Settings.get('alarms.evalfields'), 'alembic': alembic})
        return render_template('admin.settings.html', **params)
    return redirect("/admin/settings", code=302)