Exemple #1
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
def getFrontendData(self):
    """
    Deliver frontend content of module messages (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'messagetypefields':
        impl = filter(lambda x: x[0] == request.args.get('messagetypename'), MessageType.getMessageTypes())
        if len(impl) > 0:
            return impl[0][1].getEditorContent(**dict(message=Messages('', '', '', '', 0, impl[0][0])))

    elif request.args.get('action', None):
        """
        send all action request of messages to message class
        """
        impl = filter(lambda x: x[0].split('.')[0] == request.form.get('type'), MessageType.getMessageTypes())
        if len(impl) == 1:
            message = impl[0][1]
        else:
            message = Messages.getMessages(request.form.get('messageid')).type
        if message:
            data = {k: request.args.get(k) for k in request.args}
            data.update({k: request.form.get(k) for k in request.form})
            return message.action(**data)
        else:
            return None

    return ""
Exemple #3
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module messages

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

    if 'saveparameters' in request.form.keys():  # save parameters for modules
        for k in [k for k in request.form if k != 'saveparameters']:
            Settings.set("messages.%s" % k, request.form.get(k))
        monitorserver.sendMessage('0', 'reset')  # refresh monitor layout

    if len(module) == 2:
        if module[1] == 'types':  # type submodule
            params.update({'implementations': MessageType.getMessageTypes()})
            return render_template('admin.messages.types.html', **params)
    else:
        messages = {
            '1': Messages.getMessages(state=1),
            '0': Messages.getMessages(state=0)
        }
        params.update({'messages': messages})
        return render_template('admin.messages.html', **params)
Exemple #4
0
    def addParameters(self, **kwargs):
        """
        Add special parameters for widget and create content of widget from MessageType
        :param kwargs: list of parameters for update
        """
        content = ""
        if 'clientid' in kwargs:
            messages = filter(lambda x: x.currentState and kwargs['clientid'] in x.monitors, Messages.getActiveMessages())
        else:
            messages = filter(lambda x: x.currentState, Messages.getActiveMessages())

        kwargs.update({'settings': Settings})
        if len(messages) > 0:
            for message in messages:
                kwargs.update({'message': message, 'count': len(messages)})
                pos = render_template('monitor.messages.position.html', number=len(messages), position=messages.index(message))
                content += '<div class="slide">%s%s</div>\n' % (message.type.getMonitorContent(**kwargs), pos)

        else:  # load default message widget
            for mt in MessageType.getMessageTypes():
                if mt[0] == Settings.get('messages.base.default'):
                    kwargs.update({'footer': 1})  # set footer
                    content = mt[1].getMonitorContent(**kwargs)

        kwargs.update({'content': content, 'count': len(messages)})
        if len(messages) > 0:
            kwargs.update({'footer': 1})
        self.params = kwargs
        return kwargs
Exemple #5
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"
def getAdminData(self, **params):
    """
    Deliver admin content of module messages (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'messagesforstate':
        messages = Messages.getMessages(state=int(request.args.get('state')))
        return render_template('admin.messages_message.html', messages=messages)
    return ""
Exemple #7
0
def getAdminData(self, **params):
    """
    Deliver admin content of module messages (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'messagesforstate':
        messages = Messages.getMessages(state=int(request.args.get('state')))
        return render_template('admin.messages_message.html',
                               messages=messages)
    return ""
def getAdminContent(self, **params):
    """
    Deliver admin content of module messages

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

    if 'saveparameters' in request.form.keys():  # save parameters for modules
        for k in [k for k in request.form if k != 'saveparameters']:
            Settings.set("messages.%s" % k, request.form.get(k))
        monitorserver.sendMessage('0', 'reset')  # refresh monitor layout

    if len(module) == 2:
        if module[1] == 'types':  # type submodule
            params.update({'implementations': MessageType.getMessageTypes()})
            return render_template('admin.messages.types.html', **params)
    else:
        messages = {'1': Messages.getMessages(state=1), '0': Messages.getMessages(state=0)}
        params.update({'messages': messages})
        return render_template('admin.messages.html', **params)
Exemple #9
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"
Exemple #10
0
def getFrontendContent(**params):
    """
    Deliver frontend content of module messages

    :return: data of messages
    """
    if 'area' in request.args:
        params['area'] = request.args.get('area')

    if 'area' not in params:
        params['area'] = 'center'
    if 'activeacc' not in params:
        params['activeacc'] = 0

    if request.form.get('action') == 'updatemessage':
        sd = datetime.datetime.strptime('%s %s' % (request.form.get('messages.startdate'), '00:00:00'), "%d.%m.%Y %H:%M:%S")
        ed = datetime.datetime.strptime('%s %s' % (request.form.get('messages.enddate'), '23:59:59'), "%d.%m.%Y %H:%M:%S")
        if request.form.get('messages.id') != 'None':  # update message
            msg = Messages.getMessages(id=request.form.get('messages.id'))
            msg.startdate = sd
            msg.enddate = ed
        else:  # create new message
            msg = Messages('', '', sd, ed, 0, request.form.get('messages.type'))
            db.session.add(msg)
        msg.name = request.form.get('messages.name')
        msg.remark = request.form.get('messages.remark')
        msg.state = int(request.form.get('messages.state'))
        msg.monitors = request.form.getlist('messages.monitors')
        cron = dict(day_of_week='*', hour='*')
        if len(request.form.getlist('messages.cron.day_of_week')) > 0:
            cron['day_of_week'] = ",".join(request.form.getlist('messages.cron.day_of_week'))
        if len(request.form.getlist('messages.cron.hour')) > 0:
            cron['hour'] = ",".join(request.form.getlist('messages.cron.hour'))
        attributes = dict(cron=cron)

        # add type specific fields
        for fn in msg.type.getFieldNames():
            attributes[fn] = request.form.get('messages.' + fn)

        msg.attributes = attributes
        db.session.commit()
        Messages.updateMessageTrigger()

    elif request.args.get('action') == 'deletemessage':
        message = Messages.getMessages(id=int(request.args.get('messageid')))
        message.type.action(mid=message.id, action='delete')  # run delete action if implemented in module
        db.session.delete(message)
        db.session.commit()

    elif request.args.get('action') == 'editmessage':
        monitors = Monitor.getMonitors()
        if request.args.get('messageid', '0') == '0':  # add new message
            message = Messages('', '', datetime.datetime.now(), datetime.datetime.now(), 0, '')
            message.monitors = [str(m.id) for m in monitors]
        else:  # edit message
            message = Messages.getMessages(id=int(request.args.get('messageid')))
        return render_template('frontend.messages_edit.html', message=message, implementations=filter(lambda x: str(x[1]) != 'base', MessageType.getMessageTypes()), frontendarea=params['area'], frontendmodules=frontend.frontend.modules, frontendmoduledef=Settings.get('frontend.default'), monitors=monitors)

    messages = {'1': Messages.getMessages(state=1), '0': Messages.getMessages(state=0)}
    return render_template('frontend.messages_smallarea.html', messages=messages, frontendarea=params['area'], frontendmodules=frontend.frontend.modules, frontendmoduledef=Settings.get('frontend.default'), monitors=Monitor.getMonitors())