Ejemplo n.º 1
0
def getFrontendData(self):
    """
    Deliver frontend content of module alarms (ajax)

    :return: rendered template as string or json dict
    """
    from emonitor.extensions import monitorserver

    if "download" in request.path:  # deliver file
        with open('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1]), 'rb') as data:
            si = StringIO.StringIO(data.read()).getvalue()
            output = make_response(si)
        if request.path.split('/')[-1].startswith('temp'):  # remove if filename starts with temp == temporary file
            os.remove('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1]))
        output.headers["Content-Disposition"] = "attachment; filename=report.{}".format(request.path.split('.')[-1])
        output.headers["Content-type"] = "application/x.download"
        return output

    if request.args.get('action') == 'editalarm':
        
        if request.args.get('alarmid', '0') == '0':  # add new alarm
            alarm = Alarm(datetime.datetime.now(), '', 2, 0)

        else:  # edit alarm
            alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        return render_template('frontend.alarms_edit.html', alarm=alarm, cities=City.getCities(), objects=AlarmObject.getAlarmObjects(), cars=Car.getCars(), frontendarea=request.args.get('frontendarea'))

    elif request.args.get('action') == 'alarmmonitor':  # send alarm to monitor
        for monitor in Monitor.getMonitors():
            scheduler.deleteJobForEvent('changeLayout')  # send update to monitors
            for l in MonitorLayout.getLayouts(mid=int(monitor.id)):
                if l.trigger == 'alarm_added':
                    #monitorserver.sendMessage(str(monitor.id), 'load', ['layoutid=%s' % l.id, 'alarmid=%s' % request.args.get('alarmid')])  TODO changed from list
                    monitorserver.sendMessage(str(monitor.id), 'load', layoutid=l.id, alarmid=request.args.get('alarmid'))

    elif request.args.get('action') == 'printalarm':
        Printers.getPrinters(pid=int(request.args.get('printerdef'))).doPrint(object=Alarm.getAlarms(id=int(request.args.get('alarmid'))), id=request.args.get('alarmid'), copies=1)
        return ""

    elif request.args.get('action') == 'routeinfo':
        return render_template('frontend.alarms_routing.html', routing=Alarm.getAlarms(id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'routecoords':
        return jsonify(Alarm.getAlarms(id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'message':
        return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(id=request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'), reload=request.args.get('reload', 'true'))

    elif request.args.get('action') == 'addmessage':  # add message
        if request.form.get('messagetext') != "":
            alarm = Alarm.getAlarms(request.form.get('alarmid'))
            alarm.addHistory(request.form.get('messagestate'), request.form.get('messagetext'))
            db.session.commit()
        return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(request.form.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'))

    elif request.args.get('action') == 'deletemessage':  # delete selected message
        alarm = Alarm.getAlarms(request.args.get('alarmid'))
        for msg in alarm.history:
            if str(msg.timestamp) == request.args.get('datetime'):
                db.session.delete(msg)
        db.session.commit()
        return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'))

    elif request.args.get('action') == 'housecoordinates':  # return a dict with coordinats of housenumber
        if request.args.get('alarmid') != "None":
            alarm = Alarm.getAlarms(id=int(request.args.get('alarmid')))
            if alarm and alarm.housenumber:
                return {'lat': map(lambda x: x[0], alarm.housenumber.points), 'lng': map(lambda x: x[1], alarm.housenumber.points)}
        return []

    elif request.args.get('action') == 'evalhouse':  # try to eval housenumer
        street = Street.getStreets(id=request.args.get('streetid'))
        if street:
            points = dict(lat=[], lng=[])
            for hn in street.housenumbers:
                if str(hn.number) == request.args.get('housenumber').strip():
                    points['lat'].extend(map(lambda x: x[0], hn.points))
                    points['lng'].extend(map(lambda x: x[1], hn.points))
            return points
        return {}

    elif request.args.get('action') == 'alarmsforstate':  # render alarms for given state
        if 'alarmfilter' not in session:
            session['alarmfilter'] = 7
        return render_template('frontend.alarms_alarm.html', alarms=Alarm.getAlarms(days=int(session['alarmfilter']), state=int(request.args.get('state', '-1'))), printdefs=Printers.getActivePrintersOfModule('alarms'))

    elif request.args.get('action') == 'collective':  # render collective form
        reports = [r for r in AlarmReport.getReports() if r.reporttype.multi]
        if len(reports) == 0:
            return ""
        return render_template('frontend.alarms_collective.html', alarms=Alarm.getAlarms(state=2), reports=reports)

    elif request.args.get('action') == 'docollective':  # build collective form
        if request.args.get('ids') == "":
            ids = []
        else:
            ids = request.args.get('ids').split(',')
        f = AlarmReport.getReports(request.args.get('form')).createReport(ids=ids)
        _path, _filename = os.path.split(f)
        shutil.move(f, "{}{}".format(current_app.config.get('PATH_TMP'), _filename))
        return _filename

    elif request.args.get('action') == 'alarmpriocars':  # show prio cars
        cars = []
        c = Settings.getIntList('alarms.spc_cars.{}'.format(request.args.get('state')))
        if len(c) == 0:
            return ""
        for alarm in Alarm.getAlarms(state=request.args.get('state')):
            cars.extend([car for car in alarm.cars1 if car.id in c])
        cars = Counter(cars)
        return render_template('frontend.alarms_cars.html', cars=cars)

    elif request.args.get('action') == 'showdetailsform':  # build alarmdetails edtit form
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm.street.city:
            fields = AlarmField.getAlarmFields(dept=alarm.street.city.dept)
        else:
            fields = AlarmField.getAlarmFields(dept=Department.getDefaultDepartment().id)
        return render_template('frontend.alarms_fields.html', alarm=alarm, fields=fields, reports=AlarmReport.getReports())

    elif request.args.get('action') == 'saveextform':  # store ext-form values
        alarm = Alarm.getAlarms(id=request.form.get('alarmid'))
        for field in AlarmField.getAlarmFields(dept=alarm.street.city.dept):
            field.saveForm(request, alarm)
        db.session.commit()

    return ""
Ejemplo n.º 2
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module printers

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

    if len(module) == 2:
        if module[1] == 'settings':  # printer settings
            if request.method == 'POST':
                if request.form.get('action') == 'savereprintersparams':
                    Settings.set('printer.callstring',
                                 request.form.get('printers_callstring'))

            _p = dict()
            _p['callstring'] = Settings.get('printer.callstring')
            params.update({'params': _p})
            return render_template('admin.printers.settings.html', **params)
    else:

        def _printernames(callstring):
            printernames = ['<default>']
            if len(callstring.split()) > 0:
                callstring = '{} -printer "xxx"'.format(callstring.split()[0])
            try:
                subprocess.check_output(callstring,
                                        stderr=subprocess.STDOUT,
                                        shell=True)
            except subprocess.CalledProcessError as e:
                for l in e.output.split('\r\n'):
                    if l.startswith('  "'):
                        printernames.append(l[3:-1].strip())
            return printernames

        #def _callstring():  # get callstring and replace variables
        #    callstring = classes.get('settings').get('printer.callstring')
        #    callstring = callstring.replace('[basepath]', current_app.config.get('PROJECT_ROOT'))
        #    return callstring

        def _templates():  # get all printer templates
            templates = {}
            for root, dirs, files in os.walk("{}/emonitor/modules/".format(
                    current_app.config.get('PROJECT_ROOT'))):
                mod = root.replace(
                    "{}/emonitor/modules/".format(
                        current_app.config.get('PROJECT_ROOT')),
                    '').replace('\\templates', '')
                for f in files:
                    if f.endswith('.html') and f.startswith('print.'):
                        if mod not in templates:
                            templates[mod] = []
                        templates[mod].append(
                            PrintLayout('{}.{}'.format(mod, f)))
            return templates

        if request.method == 'POST':
            if request.form.get(
                    'action') == 'createprinter':  # add printer definition
                printer = Printers('', '', '', '', "['1']")
                params.update({
                    'printer':
                    printer,
                    'templates':
                    _templates(),
                    'printernames':
                    sorted(_printernames(printer.getCallString()))
                })
                return render_template('admin.printers_actions.html', **params)

            elif request.form.get('action').startswith('editprinters_'):
                printer = Printers.getPrinters(
                    int(request.form.get('action').split('_')[-1]))
                params.update({
                    'printer':
                    printer,
                    'templates':
                    _templates(),
                    'printernames':
                    sorted(_printernames(printer.getCallString()))
                })
                return render_template('admin.printers_actions.html', **params)

            elif request.form.get('action') == 'updateprinter':
                if request.form.get(
                        'printer_id') == 'None':  # add new printerdefintion
                    p = Printers('', '', '', '', settings="", state=0)
                    db.session.add(p)
                else:
                    p = Printers.getPrinters(
                        int(request.form.get('printer_id')))
                p.name = request.form.get('printername')
                p.printer = request.form.get('printerprinter')
                p.module = request.form.get('template').split('.')[0]
                p.layout = '.'.join(
                    request.form.get('template').split('.')[1:])
                _s = [request.form.get('printersettings'),
                      []]  # add settings from template
                for tparam in [
                        _p
                        for _p in request.form.get('templateparams').split(';')
                        if _p != ""
                ]:
                    _s[1].append('{}={}'.format(tparam[7:],
                                                request.form.get(tparam)))
                _s[1] = ';'.join(_s[1])
                p.settings = _s
                p.state = request.form.get('printerstate')
                db.session.commit()

            elif request.form.get('action').startswith(
                    'deleteprinters_'):  # delete printer definition
                db.session.delete(
                    Printers.getPrinters(
                        pid=request.form.get('action').split('_')[-1]))
                db.session.commit()

    params.update({'printers': Printers.getPrinters()})
    return render_template('admin.printers.html', **params)
def getAdminContent(self, **params):
    """
    Deliver admin content of module printers

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

    if len(module) == 2:
        if module[1] == 'settings':  # printer settings
            if request.method == 'POST':
                if request.form.get('action') == 'savereprintersparams':
                    Settings.set('printer.callstring', request.form.get('printers_callstring'))

            _p = dict()
            _p['callstring'] = Settings.get('printer.callstring')
            params.update({'params': _p})
            return render_template('admin.printers.settings.html', **params)
    else:

        def _printernames(callstring):
            printernames = ['<default>']
            if len(callstring.split()) > 0:
                callstring = '{} -printer "xxx"'.format(callstring.split()[0])
            try:
                subprocess.check_output(callstring, stderr=subprocess.STDOUT, shell=True)
            except subprocess.CalledProcessError as e:
                for l in e.output.split('\r\n'):
                    if l.startswith('  "'):
                        printernames.append(l[3:-1].strip())
            return printernames

        #def _callstring():  # get callstring and replace variables
        #    callstring = classes.get('settings').get('printer.callstring')
        #    callstring = callstring.replace('[basepath]', current_app.config.get('PROJECT_ROOT'))
        #    return callstring

        def _templates():  # get all printer templates
            templates = {}
            for root, dirs, files in os.walk("{}/emonitor/modules/".format(current_app.config.get('PROJECT_ROOT'))):
                mod = root.replace("{}/emonitor/modules/".format(current_app.config.get('PROJECT_ROOT')), '').replace('\\templates', '')
                for f in files:
                    if f.endswith('.html') and f.startswith('print.'):
                        if mod not in templates:
                            templates[mod] = []
                        templates[mod].append(PrintLayout('{}.{}'.format(mod, f)))
            return templates

        if request.method == 'POST':
            if request.form.get('action') == 'createprinter':  # add printer definition
                printer = Printers('', '', '', '', "['1']")
                params.update({'printer': printer, 'templates': _templates(), 'printernames': sorted(_printernames(printer.getCallString()))})
                return render_template('admin.printers_actions.html', **params)

            elif request.form.get('action').startswith('editprinters_'):
                printer = Printers.getPrinters(int(request.form.get('action').split('_')[-1]))
                params.update({'printer': printer, 'templates': _templates(), 'printernames': sorted(_printernames(printer.getCallString()))})
                return render_template('admin.printers_actions.html', **params)

            elif request.form.get('action') == 'updateprinter':
                if request.form.get('printer_id') == 'None':  # add new printerdefintion
                    p = Printers('', '', '', '', settings="", state=0)
                    db.session.add(p)
                else:
                    p = Printers.getPrinters(int(request.form.get('printer_id')))
                p.name = request.form.get('printername')
                p.printer = request.form.get('printerprinter')
                p.module = request.form.get('template').split('.')[0]
                p.layout = '.'.join(request.form.get('template').split('.')[1:])
                _s = [request.form.get('printersettings'), []]  # add settings from template
                for tparam in [_p for _p in request.form.get('templateparams').split(';') if _p != ""]:
                    _s[1].append('{}={}'.format(tparam[7:], request.form.get(tparam)))
                _s[1] = ';'.join(_s[1])
                p.settings = _s
                p.state = request.form.get('printerstate')
                db.session.commit()

            elif request.form.get('action').startswith('deleteprinters_'):  # delete printer definition
                db.session.delete(Printers.getPrinters(pid=request.form.get('action').split('_')[-1]))
                db.session.commit()

    params.update({'printers': Printers.getPrinters()})
    return render_template('admin.printers.html', **params)
Ejemplo n.º 4
0
def getFrontendData(self):
    """
    Deliver frontend content of module alarms (ajax)

    :return: rendered template as string or json dict
    """
    from emonitor.extensions import monitorserver

    if "download" in request.path:  # deliver file
        with open(
                '{}{}'.format(current_app.config.get('PATH_TMP'),
                              request.path.split('download/')[-1]),
                'rb') as data:
            si = StringIO.StringIO(data.read()).getvalue()
            output = make_response(si)
        if request.path.split('/')[-1].startswith(
                'temp'
        ):  # remove if filename starts with temp == temporary file
            os.remove('{}{}'.format(current_app.config.get('PATH_TMP'),
                                    request.path.split('download/')[-1]))
        output.headers[
            "Content-Disposition"] = "attachment; filename=report.{}".format(
                request.path.split('.')[-1])
        output.headers["Content-type"] = "application/x.download"
        return output

    if request.args.get('action') == 'editalarm':

        if request.args.get('alarmid', '0') == '0':  # add new alarm
            alarm = Alarm(datetime.datetime.now(), '', 2, 0)

        else:  # edit alarm
            alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        return render_template('frontend.alarms_edit.html',
                               alarm=alarm,
                               cities=City.getCities(),
                               objects=AlarmObject.getAlarmObjects(),
                               cars=Car.getCars(),
                               frontendarea=request.args.get('frontendarea'))

    elif request.args.get('action') == 'alarmmonitor':  # send alarm to monitor
        for monitor in Monitor.getMonitors():
            scheduler.deleteJobForEvent(
                'changeLayout')  # send update to monitors
            for l in MonitorLayout.getLayouts(mid=int(monitor.id)):
                if l.trigger == 'alarm_added':
                    #monitorserver.sendMessage(str(monitor.id), 'load', ['layoutid=%s' % l.id, 'alarmid=%s' % request.args.get('alarmid')])  TODO changed from list
                    monitorserver.sendMessage(
                        str(monitor.id),
                        'load',
                        layoutid=l.id,
                        alarmid=request.args.get('alarmid'))

    elif request.args.get('action') == 'printalarm':
        Printers.getPrinters(pid=int(request.args.get('printerdef'))).doPrint(
            object=Alarm.getAlarms(id=int(request.args.get('alarmid'))),
            id=request.args.get('alarmid'),
            copies=1)
        return ""

    elif request.args.get('action') == 'routeinfo':
        return render_template(
            'frontend.alarms_routing.html',
            routing=Alarm.getAlarms(
                id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'routecoords':
        return jsonify(
            Alarm.getAlarms(id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'message':
        return render_template(
            'frontend.alarms_message.html',
            alarm=Alarm.getAlarms(id=request.args.get('alarmid')),
            messagestates=AlarmHistory.historytypes,
            area=request.args.get('area'),
            reload=request.args.get('reload', 'true'))

    elif request.args.get('action') == 'addmessage':  # add message
        if request.form.get('messagetext') != "":
            alarm = Alarm.getAlarms(request.form.get('alarmid'))
            alarm.addHistory(request.form.get('messagestate'),
                             request.form.get('messagetext'))
            db.session.commit()
        return render_template('frontend.alarms_message.html',
                               alarm=Alarm.getAlarms(
                                   request.form.get('alarmid')),
                               messagestates=AlarmHistory.historytypes,
                               area=request.args.get('area'))

    elif request.args.get(
            'action') == 'deletemessage':  # delete selected message
        alarm = Alarm.getAlarms(request.args.get('alarmid'))
        for msg in alarm.history:
            if str(msg.timestamp) == request.args.get('datetime'):
                db.session.delete(msg)
        db.session.commit()
        return render_template('frontend.alarms_message.html',
                               alarm=Alarm.getAlarms(
                                   request.args.get('alarmid')),
                               messagestates=AlarmHistory.historytypes,
                               area=request.args.get('area'))

    elif request.args.get(
            'action'
    ) == 'housecoordinates':  # return a dict with coordinats of housenumber
        if request.args.get('alarmid') != "None":
            alarm = Alarm.getAlarms(id=int(request.args.get('alarmid')))
            if alarm and alarm.housenumber:
                return {
                    'lat': map(lambda x: x[0], alarm.housenumber.points),
                    'lng': map(lambda x: x[1], alarm.housenumber.points)
                }
        return []

    elif request.args.get('action') == 'evalhouse':  # try to eval housenumer
        street = Street.getStreets(id=request.args.get('streetid'))
        if street:
            points = dict(lat=[], lng=[])
            for hn in street.housenumbers:
                if str(hn.number) == request.args.get('housenumber').strip():
                    points['lat'].extend(map(lambda x: x[0], hn.points))
                    points['lng'].extend(map(lambda x: x[1], hn.points))
            return points
        return {}

    elif request.args.get(
            'action') == 'alarmsforstate':  # render alarms for given state
        if 'alarmfilter' not in session:
            session['alarmfilter'] = 7
        return render_template(
            'frontend.alarms_alarm.html',
            alarms=Alarm.getAlarms(days=int(session['alarmfilter']),
                                   state=int(request.args.get('state', '-1'))),
            printdefs=Printers.getActivePrintersOfModule('alarms'))

    elif request.args.get('action') == 'collective':  # render collective form
        reports = [r for r in AlarmReport.getReports() if r.reporttype.multi]
        if len(reports) == 0:
            return ""
        return render_template('frontend.alarms_collective.html',
                               alarms=Alarm.getAlarms(state=2),
                               reports=reports)

    elif request.args.get('action') == 'docollective':  # build collective form
        if request.args.get('ids') == "":
            ids = []
        else:
            ids = request.args.get('ids').split(',')
        f = AlarmReport.getReports(
            request.args.get('form')).createReport(ids=ids)
        _path, _filename = os.path.split(f)
        shutil.move(
            f, "{}{}".format(current_app.config.get('PATH_TMP'), _filename))
        return _filename

    elif request.args.get('action') == 'alarmpriocars':  # show prio cars
        cars = []
        c = Settings.getIntList('alarms.spc_cars.{}'.format(
            request.args.get('state')))
        if len(c) == 0:
            return ""
        for alarm in Alarm.getAlarms(state=request.args.get('state')):
            cars.extend([car for car in alarm.cars1 if car.id in c])
        cars = Counter(cars)
        return render_template('frontend.alarms_cars.html', cars=cars)

    elif request.args.get(
            'action') == 'showdetailsform':  # build alarmdetails edtit form
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm.street.city:
            fields = AlarmField.getAlarmFields(dept=alarm.street.city.dept)
        else:
            fields = AlarmField.getAlarmFields(
                dept=Department.getDefaultDepartment().id)
        return render_template('frontend.alarms_fields.html',
                               alarm=alarm,
                               fields=fields,
                               reports=AlarmReport.getReports())

    elif request.args.get('action') == 'saveextform':  # store ext-form values
        alarm = Alarm.getAlarms(id=request.form.get('alarmid'))
        for field in AlarmField.getAlarmFields(dept=alarm.street.city.dept):
            field.saveForm(request, alarm)
        db.session.commit()

    return ""