示例#1
0
def send_message(fxf, status=None, comment=None, comment_url=None):
    roles = UserRole.objects.filter(site=fxf.site,
                                    ended_at=None,
                                    group__name="Site Supervisor")
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    is_delete = True if status is None and fxf.fsform is not None else False
    is_deployed = True
    if fxf.is_deployed:
        status_message = "New Form Deployed"
    else:
        is_deployed = False
        status_message = "Form Undeployed"
    message = {
        'notify_type': 'Form',
        'is_delete': is_delete,
        'form_id': fxf.id,
        'comment': comment,
        'form_name': fxf.xf.title,
        'xfid': fxf.xf.id_string,
        'form_type': fxf.form_type(),
        'form_type_id': fxf.form_type_id(),
        'status': status_message,
        'is_deployed': is_deployed,
        'comment_url': comment_url,
        'site': {
            'name': fxf.site.name,
            'id': fxf.site.id
        }
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#2
0
def create_messages(sender, instance, created,  **kwargs):
    if created and instance.site is not None and instance.group.name in ["Site Supervisor"]:
        Device = get_device_model()
        if Device.objects.filter(name=instance.user.email).exists():
            message = {'notify_type':'Assign Site', 'site':{'name': instance.site.name, 'id': instance.site.id}, 'project':{'name': instance.project.name, 'id': instance.project.id}}
            try:
                email = instance.user.email
                save_notification(message, [str(email)])
                Device.objects.filter(name=email).send_message(message)
            except:
                pass

    if created and instance.group.name == "Project Manager":
        from onadata.apps.fsforms.tasks import created_manager_form_share
        task_obj = CeleryTaskProgress.objects.create(
            user=instance.user,
            description='Share all forms',
            task_type=18,
            content_object=instance
            )
        if task_obj:
            try:
                with transaction.atomic():
                    created_manager_form_share.apply_async(kwargs={'userrole': instance.id, 'task_id': task_obj.id}, countdown=5)
            except IntegrityError:
                pass

    roles = UserRole.get_active_roles(instance.user)
    # roles = Role.objects.filter(user=request.user).select_related('group', 'organization')
    if roles:
        cache.set('roles_{}'.format(instance.user.id), roles, 2 * 60)
        if roles.filter(group__name="Super Admin").exists():
            cache.set('admin_{}'.format(instance.user.id), True, 2 * 60)
        else:
            cache.set('admin_{}'.format(instance.user.id), False, 2 * 60)
示例#3
0
def notify_koboform_updated(xform):
    from onadata.apps.fsforms.models import FieldSightXF
    project_ids = FieldSightXF.objects.filter(xf=xform).values_list(
        'project_id', flat=True).distinct().order_by()
    site_ids = FieldSightXF.objects.filter(xf=xform).values_list(
        'site_id', flat=True).distinct().order_by()
    project_ids = [v for v in project_ids if v]
    site_ids = [v for v in site_ids if v]
    emails = UserRole.objects.filter(
        ended_at=None,
        group__name__in=["Site Supervisor", "Region Supervisor"]).filter(
            Q(site__id__in=site_ids)
            | Q(site__project__id__in=project_ids)).values_list(
                'user__email', flat=True).distinct().order_by()
    Device = get_device_model()
    is_delete = False
    message = {
        'notify_type': 'Form',
        'is_delete': is_delete,
        'form_name': xform.title,
        'xfid': xform.id_string,
        'form_type': "",
        'form_type_id': "",
        'status': "Form Updated",
        'site': {}
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#4
0
def remove_role(request):
    try:
        role = UserRole.objects.get(pk=request.data.get("id"))
        role.ended_at = timezone.now()
        role.save()
        if role.group.name == "Site Supervisor":
            Device = get_device_model()
            if Device.objects.filter(name=role.user.email).exists():
                message = {
                    'notify_type': 'UnAssign Site',
                    'site': {
                        'name': role.site.name,
                        'id': role.site.id
                    }
                }
                Device.objects.filter(
                    name=role.user.email).send_message(message)
        # serializer = UserRoleSerializer(role)
        return Response(
            {
                'role': role.id,
                'role_name': role.group.name,
                'msg': "Sucessfully Unassigned {}".format(role.user.username)
            },
            status=status.HTTP_200_OK)
    except Exception as e:
        return Response({'error': e.message},
                        status=status.HTTP_400_BAD_REQUEST)
示例#5
0
def send_message_project_form(fxf,
                              status=None,
                              comment=None,
                              comment_url=None):
    roles = UserRole.objects.filter(
        site__project=fxf.project,
        ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    is_delete = False
    status_message = "New Form"
    if fxf.is_deployed:
        status_message = "New Form Deployed"
    else:
        status_message = "Form Undeployed"
    message = {
        'notify_type': 'ProjectForm',
        'is_delete': is_delete,
        'form_id': fxf.id,
        'comment': comment,
        'form_name': fxf.xf.title,
        'xfid': fxf.xf.id_string,
        'form_type': fxf.form_type(),
        'form_type_id': fxf.form_type_id(),
        'status': status_message,
        'comment_url': comment_url,
        'site': {},
        'project': {
            'name': fxf.project.name,
            'id': fxf.project.id
        }
    }
    print(message)
    Device.objects.filter(name__in=emails).send_message(message)
示例#6
0
def send_message_flagged(fi=None, comment=None, comment_url=None):
    if fi.submitted_by:
        emails = [fi.submitted_by.email]
        Device = get_device_model()
        is_delete = False
        message = {
            'notify_type': 'Form_Flagged',
            'is_delete': is_delete,
            'form_id': fi.fsxf.id,
            'project_form_id': fi.fsxf.id,
            'comment': comment,
            'form_name': fi.fsxf.xf.title,
            'xfid': fi.fsxf.xf.id_string,
            'form_type': fi.fsxf.form_type(),
            'form_type_id': fi.fsxf.form_type_id(),
            'status': FORM_STATUS.get(fi.form_status, "New Form"),
            'comment_url': comment_url,
            'submission_date_time': str(fi.date),
            'submission_id': fi.id,
            'version': fi.version
        }
        if fi.site:
            message['site'] = {
                'name': fi.site.name,
                'id': fi.site.id,
                'identifier': fi.site.identifier
            }
        if fi.project:
            message['project'] = {'name': fi.project.name, 'id': fi.project.id}
        if fi.fsxf.site:
            message['site_level_form'] = True
        else:
            message['site_level_form'] = False
        Device.objects.filter(name__in=emails).send_message(message)
    def custom_create(self, * args, **kwargs):
        data = self.request.data
        level = self.kwargs.get('level')
        try:
            with transaction.atomic():
                group = Group.objects.get(name=data.get('group'))
                for user in data.get('users'):
                    if level == "0":
                        site = Site.objects.get(pk=self.kwargs.get('pk'))
                        role, created = UserRole.objects.get_or_create(user_id=user, site_id=site.id,
                                                                       project__id=site.project.id, group=group)
                        Device = get_device_model()
                        if Device.objects.filter(name=role.user.email).exists():
                            message = {'notify_type':'Assign Site', 'site':{'name': site.name, 'id': site.id}}
                            Device.objects.filter(name=role.user.email).send_message(message)

                    elif level == "1":
                        project = Project.objects.get(pk=self.kwargs.get('pk'))
                        role, created = UserRole.objects.get_or_create(user_id=user, project_id=self.kwargs.get('pk'),
                                                                       organization__id=project.organization.id, group=group)
                    elif level =="2":
                        role, created = UserRole.objects.get_or_create(user_id=user,
                                                                       organization_id=self.kwargs.get('pk'), group=group)
                    if not created:
                        role.ended_at = None
                        role.save()
        except Exception as e:
            raise ValidationError({
                "User Creation Failed ",
            })
        return Response({'msg': 'ok'}, status=status.HTTP_200_OK)
示例#8
0
def send_message_un_deploy_project(fxf):
    roles = UserRole.objects.filter(
        site__project=fxf.project,
        ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Form Altered Project',
        'is_delete': False,
        'form_id': fxf.id,
        'is_deployed': fxf.is_deployed,
        'form_name': fxf.xf.title,
        'xfid': fxf.xf.id_string,
        'form_type': fxf.form_type(),
        'form_type_id': fxf.form_type_id(),
        'site': {},
        'project': {
            'name': fxf.project.name,
            'id': fxf.project.id
        }
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#9
0
def sendmsg(sender, instance, **kwargs):
    Device = get_device_model()

    Device.objects.all().send_message({
        'message':
        instance.title,
        'title':
        'SAVEGREEN AWCS',
        'icon':
        'http://127.0.0.1:8000/static/img/slider/slide4.jpg',
        'click':
        'http://127.0.0.1:8000/home/event/' + str(instance.id)
    })
示例#10
0
def send_message_stages(site):
    roles = UserRole.objects.filter(site=site)
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Stages Ready',
        'is_delete': True,
        'site': {
            'name': site.name,
            'id': site.id
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#11
0
def create_messages(sender, instance, created, **kwargs):
    if created and instance.site is not None and instance.group.name in [
            "Site Supervisor"
    ]:
        Device = get_device_model()
        if Device.objects.filter(name=instance.user.email).exists():
            message = {
                'notify_type': 'Assign Site',
                'site': {
                    'name': instance.site.name,
                    'id': instance.site.id
                }
            }
            Device.objects.filter(
                name=instance.user.email).send_message(message)
示例#12
0
def send_bulk_message_stages(site_ids):
    return
    roles = UserRole.objects.filter(
        site_id__in=site_ids, ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Stages Ready',
        'is_delete': True,
        'site': {
            'name': site.name,
            'id': site.id
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#13
0
def FCM(request, format=None):
    "Sending Notification"
    if request.method == 'PUT' or request.method == 'POST':
        verify = request.GET['verify']
        time_start = request.GET['time_start']
        labelSound = request.GET['labelsound']
        print(labelSound)
        if verify == '0':
            message = "fail to verify\n" + str(
                time_start) + "/n Labels: " + str(labelSound)
            Device = get_device_model()
            my_phone = Device.objects.get(name="An device")
            my_phone.send_message({'mess': message}, collapse_key='something')
            return JsonResponse("success", safe=False, status=200)
        return JsonResponse("success", safe=False, status=200)
    return JsonResponse(errors, safe=False, status=400)
示例#14
0
def send_bulk_message_stages_deployed_site(site):
    roles = UserRole.objects.filter(site=site,
                                    ended_at=None,
                                    group__name="Site Supervisor")
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'deploy_all',
        'is_delete': True,
        'is_project': 0,
        'description': "Stages Ready in Site {}".format(site.name),
        'site': {
            'name': site.name,
            'id': site.id
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#15
0
def send_bulk_message_stages_deployed_project(project):
    roles = UserRole.objects.filter(
        site__project=project, ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'deploy_all',
        'is_delete': True,
        'is_project': 1,
        'description': "Stages Ready in Project {}".format(project.name),
        'project': {
            'name': project.name,
            'id': project.id
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#16
0
def send_message_stages(site):
    roles = UserRole.objects.filter(site=site,
                                    ended_at=None,
                                    group__name="Site Supervisor")
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Stages Ready',
        'is_delete': True,
        'site': {
            'name': site.name,
            'id': site.id
        }
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#17
0
def send_message_un_deploy(fxf):
    roles = UserRole.objects.filter(site=fxf.site)
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Form Altered',
        'is_delete': False,
        'form_id': fxf.id,
        'is_deployed': fxf.is_deployed,
        'form_name': fxf.xf.title,
        'xfid': fxf.xf.id_string,
        'form_type': fxf.form_type(),
        'form_type_id': fxf.form_type_id(),
        'site': {
            'name': fxf.site.name,
            'id': fxf.site.id
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#18
0
def send_bulk_message_stage_deployed_project(project, main_stage, deploy_id):
    roles = UserRole.objects.filter(
        site__project=project, ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'deploy_ms',
        'is_delete': True,
        'is_project': 1,
        'deploy_id': deploy_id,
        'description': u"Main Stage Ready in Project {}".format(project.name),
        'project': {
            'name': project.name,
            'id': project.id
        }
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#19
0
def send_message_xf_changed(fxf=None, form_type=None, id=None):
    roles = UserRole.objects.filter(site=fxf.site)
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Kobo Form Changed',
        'is_delete': True,
        'site': {
            'name': fxf.site.name,
            'id': fxf.site.id
        },
        'form': {
            'xfid': fxf.xf.id_string,
            'form_id': fxf.id,
            'form_type': form_type,
            'form_source_id': id,
            'form_name': fxf.xf.title
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#20
0
def send_sub_stage_deployed_site(site, sub_stage, deploy_id):
    roles = UserRole.objects.filter(
        site=site, ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'deploy_ss',
        'is_delete': True,
        'is_project': 0,
        'deploy_id': deploy_id,
        'description': "Sub Stage Ready in Site {}".format(site.name),
        'site': {
            'name': site.name,
            'id': site.id
        }
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#21
0
def send_message(fxf, status=None, comment=None):
    roles = UserRole.objects.filter(site=fxf.site)
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    is_delete = True if status is None and fxf.fsform is not None else False
    message = {
        'notify_type': 'Form',
        'is_delete': is_delete,
        'form_id': fxf.id,
        'comment': comment,
        'form_name': fxf.xf.title,
        'xfid': fxf.xf.id_string,
        'form_type': fxf.form_type(),
        'form_type_id': fxf.form_type_id(),
        'status': FORM_STATUS.get(status, "New Form"),
        'site': {
            'name': fxf.site.name,
            'id': fxf.site.id
        }
    }
    Device.objects.filter(name__in=emails).send_message(message)
示例#22
0
def send_message_xf_changed(fxf=None, form_type=None, id=None):
    roles = UserRole.objects.filter(
        site=fxf.site, ended_at=None,
        group__name="Site Supervisor").distinct('user')
    emails = [r.user.email for r in roles]
    Device = get_device_model()
    message = {
        'notify_type': 'Kobo Form Changed',
        'is_delete': True,
        'site': {
            'name': fxf.site.name,
            'id': fxf.site.id
        },
        'form': {
            'xfid': fxf.xf.id_string,
            'form_id': fxf.id,
            'form_type': form_type,
            'form_source_id': id,
            'form_name': fxf.xf.title
        }
    }
    save_notification(message, emails)
    Device.objects.filter(name__in=emails,
                          is_active=True).send_message(message)
示例#23
0
from rest_framework import viewsets, status, response
from fcm.utils import get_device_model
from fcm.serializers import DeviceSerializer
Device = get_device_model()


class DeviceViewSet(viewsets.ModelViewSet):
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=False)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        try:
            device = Device.objects.get(dev_id=serializer.data["dev_id"])
        except Device.DoesNotExist:
            device = Device(dev_id=serializer.data["dev_id"])
        device.is_active = True
        device.reg_id = serializer.data["reg_id"]
        device.name = serializer.data["name"]
        device.save()

    def destroy(self, request, *args, **kwargs):
        try:
            instance = Device.objects.get(dev_id=kwargs["pk"])
            self.perform_destroy(instance)
示例#24
0
    def custom_create(self, *args, **kwargs):
        data = self.request.data
        # print "======================================================="
        # print data
        # print data.get('users')

        level = self.kwargs.get('level')
        # try:
        with transaction.atomic():
            group = Group.objects.get(name=data.get('group'))
            for user in data.get('users'):
                if level == "0":
                    site = Site.objects.get(pk=self.kwargs.get('pk'))
                    role, created = UserRole.objects.get_or_create(
                        user_id=user,
                        site_id=site.id,
                        project__id=site.project.id,
                        organization__id=site.project.organization_id,
                        group=group,
                        ended_at=None)

                    if created:
                        description = "{0} was assigned  as {1} in {2}".format(
                            role.user.get_full_name(), role.group.name,
                            role.project)
                        noti_type = 8

                        if data.get('group') == "Reviewer":
                            noti_type = 7

                        noti = role.logs.create(
                            source=role.user,
                            type=noti_type,
                            title=description,
                            description=description,
                            content_object=site,
                            site=site,
                            project=site.project,
                            organization=site.project.organization,
                            extra_object=self.request.user)
                        result = {}
                        result['description'] = description
                        result['url'] = noti.get_absolute_url()
                        ChannelGroup("notify-{}".format(
                            role.organization.id)).send(
                                {"text": json.dumps(result)})
                        ChannelGroup("project-{}".format(
                            role.project.id)).send(
                                {"text": json.dumps(result)})
                        ChannelGroup("site-{}".format(role.site.id)).send(
                            {"text": json.dumps(result)})
                        ChannelGroup("notify-0").send(
                            {"text": json.dumps(result)})

                    Device = get_device_model()
                    if Device.objects.filter(name=role.user.email).exists():
                        message = {
                            'notify_type': 'Assign Site',
                            'site': {
                                'name': site.name,
                                'id': site.id
                            }
                        }
                        Device.objects.filter(
                            name=role.user.email).send_message(message)

                elif level == "1":
                    project = Project.objects.get(pk=self.kwargs.get('pk'))
                    role, created = UserRole.objects.get_or_create(
                        user_id=user,
                        organization_id=project.organization_id,
                        project_id=self.kwargs.get('pk'),
                        site_id=None,
                        group=group,
                        ended_at=None)
                    print role.__dict__

                    if created:
                        print role.__dict__
                        description = "{0} was assigned  as {2} in {1}".format(
                            role.user.get_full_name(), role.project,
                            role.group.name)
                        noti = role.logs.create(
                            source=role.user,
                            type=25,
                            title=description,
                            organization=project.organization,
                            project=project,
                            description=description,
                            content_object=project,
                            extra_object=self.request.user)
                        result = {}
                        result['description'] = description
                        result['url'] = noti.get_absolute_url()
                        ChannelGroup("notify-{}".format(
                            role.organization.id)).send(
                                {"text": json.dumps(result)})
                        ChannelGroup("project-{}".format(
                            role.project.id)).send(
                                {"text": json.dumps(result)})
                        ChannelGroup("notify-0").send(
                            {"text": json.dumps(result)})
                elif level == "2":
                    organization = Organization.objects.get(
                        pk=self.kwargs.get('pk'))
                    role, created = UserRole.objects.get_or_create(
                        user_id=user,
                        organization_id=self.kwargs.get('pk'),
                        project_id=None,
                        site_id=None,
                        group=group)
                    if created:
                        description = "{0} was assigned  as Organization Admin in {1}".format(
                            role.user.get_full_name(), role.organization)
                        noti = role.logs.create(source=role.user,
                                                type=4,
                                                title=description,
                                                organization=organization,
                                                description=description,
                                                content_object=organization,
                                                extra_object=self.request.user)
                        result = {}
                        result['description'] = description
                        result['url'] = noti.get_absolute_url()
                        ChannelGroup("notify-{}".format(
                            role.organization.id)).send(
                                {"text": json.dumps(result)})
                        ChannelGroup("notify-0").send(
                            {"text": json.dumps(result)})
                    else:
                        role.ended_at = None
                        role.save()

        # except Exception as e:
        #     raise ValidationError({
        #         "User Creation Failed ".format(str(e)),
        #     })
        return Response({'msg': data}, status=status.HTTP_200_OK)
示例#25
0
    def post(self, *args, **kwargs):
        queryset = UserRole.objects.filter(organization__isnull=False,
                                           ended_at__isnull=True)
        data = self.request.data
        level = self.kwargs.get('level')
        try:
            with transaction.atomic():
                group = Group.objects.get(name=data.get('group'))
                if level == "0":
                    for site_id in data.get('sites'):
                        site = Site.objects.get(pk=site_id)
                        for user in data.get('users'):
                            role, created = UserRole.objects.get_or_create(
                                user_id=user,
                                site_id=site.id,
                                project__id=site.project.id,
                                organization_id=site.project.organization.id,
                                group=group)
                            if created:
                                description = "{0} was assigned  as {1} in {2}".format(
                                    role.user.get_full_name(),
                                    role.lgroup.name, role.project)
                                noti_type = 8

                                if data.get('group') == "Reviewer":
                                    noti_type = 7

                                noti = role.logs.create(
                                    source=role.user,
                                    type=noti_type,
                                    title=description,
                                    description=description,
                                    content_type=site,
                                    extra_object=self.request.user,
                                    site=role.site)
                                result = {}
                                result['description'] = description
                                result['url'] = noti.get_absolute_url()
                                ChannelGroup("notify-{}".format(
                                    role.organization.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("project-{}".format(
                                    role.project.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("site-{}".format(
                                    role.site.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("notify-0").send(
                                    {"text": json.dumps(result)})

                            Device = get_device_model()
                            if Device.objects.filter(
                                    name=role.user.email).exists():
                                message = {
                                    'notify_type': 'Assign Site',
                                    'site': {
                                        'name': site.name,
                                        'id': site.id
                                    }
                                }
                                Device.objects.filter(
                                    name=role.user.email).send_message(message)

                elif level == "1":
                    for project_id in data.get('projects'):
                        project = Project.objects.get(pk=project_id)
                        for user in data.get('users'):
                            role, created = UserRole.objects.get_or_create(
                                user_id=user,
                                project_id=project_id,
                                organization__id=project.organization.id,
                                group=group)
                            if created:
                                description = "{0} was assigned  as Project Manager in {1}".format(
                                    role.user.get_full_name(), role.project)
                                noti = role.logs.create(
                                    source=role.user,
                                    type=6,
                                    title=description,
                                    description=description,
                                    content_type=project,
                                    extra_object=self.request.user)
                                result = {}
                                result['description'] = description
                                result['url'] = noti.get_absolute_url()
                                ChannelGroup("notify-{}".format(
                                    role.organization.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("project-{}".format(
                                    role.project.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("notify-0").send(
                                    {"text": json.dumps(result)})

                elif level == "2":
                    for organization_id in data.get('organizations'):
                        organization = Organization.objects.get(
                            pk=organization_id)
                        for user in data.get('users'):
                            role, created = UserRole.objects.get_or_create(
                                user_id=user,
                                organization_id=project_id,
                                group=group)
                            if created:
                                description = "{0} was assigned  as Organization Admin in {1}".format(
                                    role.user.get_full_name(), role.project)
                                noti = role.logs.create(
                                    source=role.user,
                                    type=7,
                                    title=description,
                                    description=description,
                                    content_type=organization,
                                    extra_object=self.request.user)
                                result = {}
                                result['description'] = description
                                result['url'] = noti.get_absolute_url()
                                ChannelGroup("notify-{}".format(
                                    role.organization.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("project-{}".format(
                                    role.project.id)).send(
                                        {"text": json.dumps(result)})
                                ChannelGroup("notify-0").send(
                                    {"text": json.dumps(result)})

        except Exception as e:
            raise ValidationError({
                "User Creation Failed ".format(str(e)),
            })
        return Response({'msg': 'ok'}, status=status.HTTP_200_OK)
示例#26
0
文件: utils.py 项目: jwjimmy/counsel
def send_to_android(estate_str):
    Device = get_device_model()
    test_phone = Device.objects.get(name="TestDevice104")
    test_phone.send_message({'message': 'hit for ' + estate_str},
                            collapse_key='something')
示例#27
0
from django.core.management.base import BaseCommand, CommandError

from fcm.utils import get_device_model

Device = get_device_model()


class Command(BaseCommand):
    args = ['<device_id>', '<message>']
    help = 'Send message through fcm api'

    def add_arguments(self, parser):
        # this store list
        parser.add_argument('--device_id', nargs='*', type=str)
        parser.add_argument('--msg', nargs='*', type=str)

        parser.add_argument(
            '--devices',
            action='store_true',
            dest='devices',
            default=False,
            help='List of available devices',
        )
        parser.add_argument(
            '--collapse-key',
            dest='collapse_key',
            default='message',
            help='Set value of collapse_key flag, default is "message"',
        )

    def handle(self, *args, **options):
示例#28
0
def inactivityMonitor():
    '''
    Track for basic inactivity within the house
    Assume threshold to be 30 minutes 
    Sound the alarm if inactive
    
    https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by
    *incase required to order the list of positiveLogs*
    '''

    currentTime = datetime.now()
    #http://stackoverflow.com/questions/6685834/django-want-to-sort-comments-by-datetime
    lastLog = PositiveLog.objects.latest('date')

    #http://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python
    #http://stackoverflow.com/questions/20631855/get-the-difference-between-two-datetime-objects-in-minutes-in-python
    timeDifference = (currentTime - lastLog.date).total_seconds()
    if (timeDifference > 1 * 60):

        #Set the datetime object where the threshold time of after 15 minutes where the alert is first flagged to the elder
        #http://stackoverflow.com/questions/18406165/creating-a-timer-in-python
        timeoutThreshold = datetime.now() + timedelta(
            minutes=1)  #timeout = 15 minutes

        #send alert and set elderAlert flag to True
        print("Alert to be sent to elder's phone")
        tempAccount = Account.objects.get(userType="Elder")
        phoneNumber = tempAccount.phoneNumber

        #tempDevice = MyDevice.objects.get(dev_id = phoneNumber, name = tempAccount.name)
        #regID = tempDevice.reg_id

        Device = get_device_model()
        my_phone = Device.objects.get(dev_id=phoneNumber)
        my_phone.send_message({'message': 'my test message'})
        '''
        print(regID)
        test = {"to":regID}
        message = {
            'to':regID,
            'notification':{
                'title':'Inactivity Detected!',
                'body':'Please move around house or deactivate alert through phone!'
            },
            'priority': 'high'
        }
        
        r = requests.post('https://fcm.googleapis.com/fcm/send', 
                      data=json.dumps(test),
                      headers = {
                          'Authorization': 'key=AAAA4Rk__ek:APA91bEqZTWrNIRHXNTT8nse4yD6XSKNXalbsM46phizb-I3ZGxyzbAmVREVSyuBOBY_b_uOZtgiFZnb89_BRgXIeARrRv4vxNL5JJlgHPE0khJqOV0TWWI8C6oasZGtOLHvh_nrgB8Y',
                          'Content-Type': 'application/json',
                      }
                     )
        
        print(r.status_code)
        print(r.text)
        '''

        tempState = stateFlag.objects.get(name="elderPhoneAlertState")
        tempState.state = True
        tempState.save()

        boolAlertCheck = True
        changeState(boolAlertCheck, "alertState")

        while (boolAlertCheck == True):
            print("Inside the alert loop now...")
            tempState = stateFlag.objects.get(name="familyPhoneAlertState")

            if (timeoutThreshold < datetime.now() and not tempState.state):
                print("\n\nALERT SENT TO FAMILY NOW\n\n"
                      )  #keep alerting family? or set some limit? ****
                tempState.state = True
                tempState.save()

            time.sleep(5)
            boolAlertCheck = stateFlag.objects.get(name="alertState").state
示例#29
0
def remove_role(request):
    try:
        role = UserRole.objects.get(pk=request.data.get("id"))
        role.ended_at = timezone.now()
        role.save()
        if role.group.name == "Site Supervisor":
            Device = get_device_model()
            if Device.objects.filter(name=role.user.email).exists():
                message = {
                    'notify_type': 'UnAssign Site',
                    'site': {
                        'name': role.site.name,
                        'id': role.site.id
                    }
                }
                Device.objects.filter(
                    name=role.user.email).send_message(message)
        # serializer = UserRoleSerializer(role)
        return Response(
            {
                'role': role.id,
                'role_name': role.group.name,
                'msg': "Sucessfully Unassigned {}".format(role.user.username)
            },
            status=status.HTTP_200_OK)
    except Exception as e:
        return Response({'error': e.message},
                        status=status.HTTP_400_BAD_REQUEST)


# class MultiUserAssignRoleViewSet(ListView):

#     def get(self, request, *args, **kwargs):
#         queryset = UserRole.objects.filter(organization__isnull=False, ended_at__isnull=True)
#         try:
#             level = self.kwargs.get('level', None)
#             pk = self.kwargs.get('pk', None)
#             if level == "0":
#                 user_queryset = queryset.filter(site__id=pk, group__name__in=['Site Supervisor', 'Reviewer'])
#             elif level == "1":
#                 user_queryset = queryset.filter(project__id=pk, group__name='Project Manager')
#             elif level == "2":
#                 user_queryset = queryset.filter(organization__id=pk, group__name='Organization Admin')
#         except:
#             user_queryset = []

#         # try:
#         #     pk = self.kwargs.get('pk', None)
#         #     if level == "1":
#         #         content_queryset = Sites.objects.filter(project__id=pk)
#         #         content = OrganizationSerializer(content_queryset, many=True, context=context)

#         #     elif level == "2":
#         #         content_queryset = Project.objects.filter(organization__id=pk)
#         #         content = ProjectSerializer(content_queryset, many=True, context=context)
#         # except:
#         #     content_queryset = []

#         # queryset=[]
#         # queryset[users] = user_queryset
#         # queryset[content] = content_queryset

#         users = UserRoleSerializer(user_queryset)

#         return queryset

#     def post(self, * args, **kwargs):
#         data = self.request.data
#         level = self.kwargs.get('level')
#         try:
#             with transaction.atomic():
#                 group = Group.objects.get(name=data.get('group'))
#                 if level == "0":
#                     for site_id in data.get('sites'):
#                         site = Site.objects.get(pk=site_id)
#                         for user in data.get('users'):
#                             role, created = UserRole.objects.get_or_create(user_id=user, site_id=site.id,
#                                                                            project__id=site.project.id, group=group)

#                             if created:
#                                 description = "{0} was assigned  as {1} in {2}".format(
#                                     role.user.get_full_name(), role.lgroup.name, role.project)
#                                 noti_type = 8

#                                 if data.get('group') == "Reviewer":
#                                     noti_type =7

#                                 noti = role.logs.create(source=role.user, type=noti_type, title=description,
#                                                         description=description, content_type=site, extra_object=self.request.user,
#                                                         site=role.site)
#                                 result = {}
#                                 result['description'] = description
#                                 result['url'] = noti.get_absolute_url()
#                                 ChannelGroup("notify-{}".format(role.organization.id)).send({"text": json.dumps(result)})
#                                 ChannelGroup("project-{}".format(role.project.id)).send({"text": json.dumps(result)})
#                                 ChannelGroup("site-{}".format(role.site.id)).send({"text": json.dumps(result)})
#                                 ChannelGroup("notify-0").send({"text": json.dumps(result)})

#                             Device = get_device_model()
#                             if Device.objects.filter(name=role.user.email).exists():
#                                 message = {'notify_type':'Assign Site', 'site':{'name': site.name, 'id': site.id}}
#                                 Device.objects.filter(name=role.user.email).send_message(message)

#                 elif level == "1":
#                     for project_id in data.get('projects'):
#                         project = Project.objects.get(pk=project_id)
#                         for user in data.get('users'):
#                             role, created = UserRole.objects.get_or_create(user_id=user, project_id=project_id,
#                                                                            organization__id=project.organization.id,
#                                                                            project__id=project_id,
#                                                                            group=group)
#                             if created:
#                                 description = "{0} was assigned  as Project Manager in {1}".format(
#                                     role.user.get_full_name(), role.project)
#                                 noti = role.logs.create(source=role.user, type=6, title=description, description=description,
#                                  content_type=project, extra_object=self.request.user)
#                                 result = {}
#                                 result['description'] = description
#                                 result['url'] = noti.get_absolute_url()
#                                 ChannelGroup("notify-{}".format(role.organization.id)).send({"text": json.dumps(result)})
#                                 ChannelGroup("project-{}".format(role.project.id)).send({"text": json.dumps(result)})
#                                 ChannelGroup("notify-0").send({"text": json.dumps(result)})

#                 elif level =="2":
#                     for organization_id in data.get('organizations'):
#                         organization = Organization.objects.get(pk=organization_id)
#                         for user in data.get('users'):
#                             role, created = UserRole.objects.get_or_create(user_id=user,
#                                                                            organization_id=organization_id, group=group)
#                             if created:
#                                 description = "{0} was assigned  as Organization Admin in {1}".format(
#                                     role.user.get_full_name(), role.organization)
#                                 noti = role.logs.create(source=role.user, type=4, title=description, description=description,
#                                  content_type=organization, extra_object=self.request.user)
#                                 result = {}
#                                 result['description'] = description
#                                 result['url'] = noti.get_absolute_url()
#                                 ChannelGroup("notify-{}".format(role.organization.id)).send({"text": json.dumps(result)})
#                                 ChannelGroup("notify-0").send({"text": json.dumps(result)})
#                             else:
#                                 role.ended_at = None
#                                 role.save()

#         except Exception as e:
#             raise ValidationError({
#                 "User Creation Failed ".format(str(e)),
#             })
#         return Response({'msg': 'ok'}, status=status.HTTP_200_OK)
示例#30
0
def label_predict(request, format=None):
    """Label predict api."""
    if request.method == 'PUT' or request.method == 'POST':
        """wave = request.GET['wave']
        print (type(wave))
        sr = request.GET['sr']
        time_start = request.GET['time_start']

        """
        content = json.loads(request.body)
        wave = content['wave']
        if (wave == []):
            return JsonResponse("wave must be not empty",
                                safe=False,
                                status=400)
        if (type(wave) is not list):
            return JsonResponse("wave must be list", safe=False, status=400)
        sr = content['sr']
        time_start = content['time_start']
        user_id_id = content['user_id_id']
        predicted_labels = predict_sound(time_start, wave, sr, user_id_id)
        serializer = SoundSerializer(
            data={
                'time_start': time_start,
                'wave': wave,
                'label': predicted_labels,
                'user_id_id': user_id_id
            })
        trigger_label = ["flushing", "cryingBaby"]
        trigger = False
        for key in predicted_labels:
            for labels in trigger_label:
                if (key == labels):
                    trigger = true
                    break
        if serializer.is_valid():
            serializer.save()
            noti = False
            noti_label = "cryingBaby"
            for key in predicted_labels:
                if key == noti_label:
                    noti = True
                    break
            if (noti):
                message = str(noti_label) + "\n" + str(
                    serializer.data["time_start"])
                Device = get_device_model()
                my_phone = Device.objects.get(name="An device")
                my_phone.send_message({'mess': message},
                                      collapse_key='something')

            return JsonResponse(
                {
                    "Labels": predicted_labels,
                    "Trigger": trigger
                },
                safe=False,
                status=201)
        Device = get_device_model()
        my_phone = Device.objects.get(name="An device")
        my_phone.send_message({'mess': message}, collapse_key='something')
        return JsonResponse({
            "Labels": predicted_labels,
            "Trigger": trigger
        },
                            safe=False,
                            status=200)
    return JsonResponse({
        "Labels": predicted_labels,
        "Trigger": trigger
    },
                        safe=False,
                        status=400)