Пример #1
0
def events(request):

    data = {}

    if 'event' in request.GET and request.GET['event'] != '':
        logger.debug('event details view triggered by %s for event: %s' %
                     (request.user.username, request.GET['event']))
        try:
            data = cache.get('event_' + request.GET['event'])
        except:
            raise
        return render(request, 'isubscribe/generic.html',
                      {'DATA': data['check']})

    logger.debug('events view triggered by %s' % request.user.username)

    for word in cache.keys("event_*"):
        entity = re.sub(r'^event_', '', word)
        try:
            data[entity] = {}
            event_data = cache.get('event_' + entity)
            data[entity]['entity_element_id'] = re.sub(r':|\.', '_', entity)
            data[entity]['entity'] = entity
            data[entity]['status'] = event_data['check']['status']
            data[entity]['output'] = json.dumps(event_data['check']['output'],
                                                ensure_ascii=False)
            data[entity]['timestamp'] = event_data['timestamp']

            if 'ack_' + entity in cache.keys("ack_*"):
                data[entity]['ack'] = True
                ack = cache.get('ack_' + entity)
                data[entity]['ack_by'] = ack['user_name']
                data[entity]['ack_comment'] = ack['ack_comment']
            else:
                data[entity]['ack'] = False

            if 'silent_' + entity in cache.keys("silent_*"):
                data[entity]['silent'] = True
                silent = cache.get('silent_' + entity)
                data[entity]['silent_by'] = silent['user_name']
                data[entity]['silent_comment'] = silent['silent_comment']
            else:
                data[entity]['silent'] = False

        except:
            raise

    profile_form = ContactForm(instance=Contact.objects.get(
        user=request.user.id))

    return render(
        request, 'isubscribe/events.html', {
            'DATA':
            OrderedDict(
                sorted(data.items(),
                       key=lambda x: x[1]['timestamp'],
                       reverse=True)),
            'profile_form':
            profile_form
        })
Пример #2
0
def user_settings(request):        
    
    logger.debug('settings view triggered by %s' % (request.user.username))
    
    form = ContactForm(request.POST, instance=Contact.objects.get(user=request.user.id), user=request.user, update=True)
    #form = ContactForm(request.POST, user=request.user, update=True)
    if form.is_valid:
        try:
            form.save()
            return HttpResponse('Done', status=200)
        except:        
            return HttpResponse(json.dumps(form.errors), status=409)
    else:
        return HttpResponse(json.dumps(form.errors), status=409)

    
    
    return render(request, 'isubscribe/user_settings.html', {'DATA':data, 'form': form})
Пример #3
0
def subscriptions(request):        

    data = {}
    
    for word in r.keys("subscription_*"):
        subscription = re.sub(r'^subscription_', '', str(word.decode('utf-8')))
        try:
            
            subscription_data = r.lrange(word, 0, -1)
            data[subscription] = subscription_data 
            
        except:
            raise
    
    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id), user=request.user)   
    
    return render(request, 'isubscribe/subscriptions.html', {'DATA':data, 'profile_form': profile_form})
Пример #4
0
def clients(request):        

    data = {}
    
    for word in cache.keys("client_*"):
        client = re.sub(r'^client_', '', word)
        try:
            
            client_data = cache.get(word)
            data[client] = client_data 
            
        except:
            raise
    
    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id), user=request.user)
    
    return render(request, 'isubscribe/clients.html', {'DATA':data, 'profile_form': profile_form})
Пример #5
0
def onduty(request):

    if 'action' in request.GET and request.GET['action'] == 'onduty_agenda':

        data = []

        FROM = datetime.datetime.strptime(request.GET['start'], "%Y-%m-%d")
        TO = datetime.datetime.strptime(request.GET['end'], "%Y-%m-%d")

        for event_start, event_end, instance in ScheduledOccurrence.objects.filter(
                event__in=ScheduledEvent.objects.filter(
                    event=0)).all_occurrences(from_date=FROM, to_date=TO):

            description = []
            for member in instance.event.members_list():
                if not hasattr(member,
                               'contact') or member.contact.phone_number in [
                                   None, ''
                               ]:
                    description.append(member.username)
                else:
                    description.append(member.username + ': ' +
                                       member.contact.phone_number)

            if request.user in instance.event.members_list():
                event_privileges = True
            else:
                event_privileges = False

            data.append({
                'id': instance.id,
                'title': instance.event.description,
                'description': description,
                'start': event_start,
                'end': event_end,
                'repeat': instance.repeat,
                'repeat_until': instance.repeat_until,
                'instance_start': instance.start,
                'instance_end': instance.end,
                'source': reverse_lazy('onduty'),
                'event_id': instance.event.id,
                'privileges': event_privileges
            })

        for event_start, event_end, instance in ScheduledOccurrence.objects.filter(
                event__in=ScheduledEvent.objects.filter(
                    event=1, members__in=[request.user.id])).all_occurrences(
                        from_date=FROM, to_date=TO):

            description = []
            for member in instance.event.members_list():
                if not hasattr(member,
                               'contact') or member.contact.phone_number in [
                                   None, ''
                               ]:
                    description.append(member.username)
                else:
                    description.append(member.username + ': ' +
                                       member.contact.phone_number)

            data.append({
                'id': instance.id,
                'title': instance.event.description,
                'description': description,
                'start': event_start,
                'end': event_end,
                'repeat': instance.repeat,
                'repeat_until': instance.repeat_until,
                'instance_start': instance.start,
                'instance_end': instance.end,
                'source': reverse_lazy('onduty'),
                'event_id': instance.event.id,
                'privileges': True
            })

        return JsonResponse(data, safe=False)

    elif 'action' in request.POST and request.POST[
            'action'] == 'onduty_toggle_alerts':
        if cache.get('onduty_disable_alerts'):
            logger.debug('onduty view disable onduty alerts triggered by %s' %
                         (request.user.username))
            cache.set('onduty_disable_alerts', False, timeout=None)
            action_value = False
        else:
            logger.debug('onduty view enable onduty alerts triggered by %s' %
                         (request.user.username))
            cache.set('onduty_disable_alerts', True, timeout=None)
            action_value = True

        Group("on-duty").send({
            "text":
            json.dumps({
                "action_type": "onduty_toggle_alerts",
                "action_value": action_value,
                "action_by": request.user.username
            })
        })

        return HttpResponse(request.POST['action'])

    # no good! DnD objects should be created when creating user
    if len(
            ScheduledEvent.objects.filter(event=1,
                                          members__in=[request.user.id])) < 1:
        logger.info('onduty view creating DnD object for user: %s' %
                    (request.user.username))
        e = ScheduledEvent(event=1,
                           description='DnD - ' + request.user.username)
        e.save()
        m = EventMembers(order=0, event_id=e.id, member_id=request.user.id)
        m.save()

    if 'onduty_disable_alerts' in cache.keys("onduty_disable_*"):
        onduty_disable_alerts = cache.get('onduty_disable_alerts')
    else:
        onduty_disable_alerts = False

    # check form
    if 'id' in request.POST:

        if request.POST['id'] == 'new':
            form = ScheduledEventForm(request.POST,
                                      user=request.user,
                                      editable=True)
        else:
            event_instance = ScheduledOccurrence.objects.get(
                id=request.POST['id'])
            form = ScheduledEventForm(request.POST,
                                      user=request.user,
                                      editable=True,
                                      instance=event_instance)

        if form.is_valid():
            logger.debug('update ScheduledOccurrence')
            form.save()
        else:
            logger.debug('********************* ' + json.dumps(form.errors))

    profile_form = ContactForm(instance=Contact.objects.get(
        user=request.user.id))

    return render(
        request, 'isubscribe/cal.html', {
            'onduty_disable_alerts': onduty_disable_alerts,
            'form_view': ScheduledEventForm(user=request.user, editable=False),
            'form_edit': ScheduledEventForm(user=request.user, editable=True),
            'profile_form': profile_form
        })
Пример #6
0
def entities(request):
    '''            
    for Test in r.scan_iter(match=':1:entity_*'):
        print('************************************' + Test.decode('utf-8'))
    '''

    logger.debug('entities view triggered by %s' % request.user.username)

    if request.method == 'POST' and 'search' in request.POST and request.POST[
            'search'] != '':

        logger.debug('entities view search by user %s search: %s' %
                     (request.user.username, request.POST['search']))

        data = {}
        mimetype = 'application/json'

        Group("entities-private-%s" % request.user.id).send(
            {"text": json.dumps({'flush_signal': True})})

        match_counter = 0
        for word in r.scan_iter(match=':1:entity_*'):

            try:

                entity = re.sub(r'^:1:entity_', '', word.decode('utf-8'))
                patterns = re.compile(r'(?:%s)' % request.POST['search'],
                                      re.IGNORECASE)

                if patterns.search(entity):

                    match_counter += 1
                    if match_counter > settings.MAX_ENTITY_SEARCH_RESULTS:
                        break
                    status_1 = False
                    status_2 = False
                    subscribed_status = []

                    try:
                        rule = cache.get('rule_' + entity)
                        if '1' in rule and request.user.id in rule['1']:
                            subscribed_status.append(1)
                        if '2' in rule and request.user.id in rule['2']:
                            subscribed_status.append(2)
                    except:
                        pass

                    if 1 in subscribed_status:
                        status_1 = True
                    if 2 in subscribed_status:
                        status_2 = True

                    regex_match_1 = False
                    regex_match_2 = False
                    regex_match_status = []

                    for rule_status in [1, 2]:
                        try:
                            patterns = pickle.loads(
                                r.get('regexrule_%s_%s' %
                                      (request.user.id, rule_status)))
                            if patterns.search(entity):
                                regex_match_status.append(rule_status)
                        except:
                            pass

                    if 1 in regex_match_status:
                        regex_match_1 = True
                    if 2 in regex_match_status:
                        regex_match_2 = True

                    if 'silent_' + entity in cache.keys("silent_*"):
                        silent = True
                    else:
                        silent = False

                    result = {
                        'entity': entity,
                        'status_1': status_1,
                        'status_2': status_2,
                        'silent': silent,
                        'regex_1': regex_match_1,
                        'regex_2': regex_match_2
                    }

                    Group("entities-private-%s" % request.user.id).send(
                        {"text": json.dumps(result)})

                    #logger.debug("entities view search: %s result: %s" % (request.POST['search'], json.dumps(result)))
            except:
                raise

        data['search'] = request.POST['search']
        data['status'] = 0
        data['timestamp'] = datetime.datetime.now().timestamp()

        return HttpResponse(json.dumps(data), mimetype)

    if request.method == 'POST' and 'name' in request.POST:

        logger.debug('entities view new rule user %s' %
                     (request.user.username))
        mimetype = 'application/json'

        try:
            re.compile(request.POST['regex_string'])
        except:
            return HttpResponse(json.dumps(['invalid regex_string']),
                                status=409)

        form = RuleForm(request.POST, user=request.user)
        if form.is_valid:
            try:
                new_rule = form.save(commit=True)
                logger.debug('entities view new rule id: %s' % new_rule.id)
                Channel('background-build-user-rules').send(
                    {'user_id': request.user.id})
                return HttpResponse(
                    json.dumps({
                        'id': new_rule.id,
                        'name': new_rule.name,
                        'regex_string': new_rule.regex_string,
                        'status': new_rule.status
                    }), mimetype)
            except:
                return HttpResponse(json.dumps(form.errors), status=409)
        else:
            return HttpResponse(json.dumps(form.errors), status=409)

    if request.method == 'POST' and 'action' in request.POST and request.POST[
            'action'] == 'rule_delete':

        logger.debug('entities delete new rule id %s' % (request.POST['id']))

        rule_obj = Rule.objects.get(owner=request.user.id,
                                    id=request.POST['id'])
        form = RuleForm(instance=rule_obj, user=request.user)
        if form.is_valid:
            try:
                rule_obj.delete()
                Channel('background-build-user-rules').send(
                    {'user_id': request.user.id})
                return HttpResponse('Done', status=200)
            except:
                return HttpResponse(json.dumps(form.errors), status=409)
        else:
            return HttpResponse(json.dumps(form.errors), status=409)

    if request.method == 'POST' and 'action' in request.POST and request.POST[
            'action'] == 'rule_list':

        logger.debug('entities list new rule for user %s' %
                     (request.user.username))

        data = {}
        mimetype = 'application/json'

        return HttpResponse(
            json.dumps(Rule.objects.filter(owner=request.user.id).all()),
            mimetype)

    data = {}
    user_rules = Rule.objects.filter(owner=request.user.id)
    rule_form = RuleForm(initial={'owner': request.user}, user=request.user)
    profile_form = ContactForm(instance=Contact.objects.get(
        user=request.user.id))

    return render(
        request, 'isubscribe/entities.html', {
            'DATA': data,
            'profile_form': profile_form,
            'user_rules': user_rules,
            'rule_form': rule_form
        })
Пример #7
0
def entities(request):

    '''            
    for Test in r.scan_iter(match=':1:entity_*'):
        print('************************************' + Test.decode('utf-8'))
    '''    
     
    logger.debug('entities view triggered by %s' % request.user.username)
    
    if request.method == 'POST' and 'search' in request.POST and request.POST['search'] != '':
        
        logger.debug('entities view search by user %s search: %s' % (request.user.username, request.POST['search']))
        
        data = {}
        mimetype = 'application/json'
        
        Group("entities-private-%s" % request.user.id).send({
            "text": json.dumps({'flush_signal':True})
        })
    
                     
        #for word in cache.keys("entity_*%s*" % request.POST['search']):
        for word in r.scan_iter(match=':1:entity_*'):
            #if request.POST['search'].lower() in word.decode('utf-8').lower():
            if re.search(request.POST['search'].lower(), word.decode('utf-8'), re.IGNORECASE):
                #entity = re.sub(r'^entity_', '', word)            
                entity = re.sub(r'^:1:entity_', '', word.decode('utf-8'))
                status_1 = False       
                status_2 = False 
                try:
                    rule = cache.get('rule_' + entity)            
                    if '1' in rule and request.user.id in rule['1']:
                        status_1 = True            
                    if '2' in rule and request.user.id in rule['2']:
                        status_2 = True            
                except:
                    pass
                if 'silent_' + entity in cache.keys("silent_*"):                
                    silent = True
                else:
                    silent = False
                    
                result = { 'entity': entity, 'status_1': status_1, 'status_2': status_2, 'silent': silent }
                
                Group("entities-private-%s" % request.user.id).send({
                    "text": json.dumps(result)
                })
                
                #logger.debug("entities view search: %s result: %s" % (request.POST['search'], json.dumps(result)))
            
        data['search'] = request.POST['search']        
        data['status'] = 0
        data['timestamp'] = datetime.datetime.now().timestamp()
            
        return HttpResponse(json.dumps(data), mimetype)
        
    
    data = {}
    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id), user=request.user)
      
    return render(request, 'isubscribe/entities.html', {'DATA':data, 'profile_form': profile_form})