当前位置: 首页>>代码示例>>Python>>正文


Python mixin.VerifiedNumber类代码示例

本文整理汇总了Python中corehq.apps.sms.mixin.VerifiedNumber的典型用法代码示例。如果您正苦于以下问题:Python VerifiedNumber类的具体用法?Python VerifiedNumber怎么用?Python VerifiedNumber使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了VerifiedNumber类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: incoming

def incoming(phone_number, backend_api):
    cleaned_number = phone_number
    if len(cleaned_number) > 0 and cleaned_number[0] == "+":
        cleaned_number = cleaned_number[1:]
    
    # Try to look up the verified number entry
    v = VerifiedNumber.view("sms/verified_number_by_number",
        key=cleaned_number,
        include_docs=True
    ).one()
    
    # If none was found, try to match only the last digits of numbers in the database
    if v is None:
        v = VerifiedNumber.view("sms/verified_number_by_suffix",
            key=cleaned_number,
            include_docs=True
        ).one()
    
    # Save the call entry
    msg = CallLog(
        phone_number    = cleaned_number,
        direction       = INCOMING,
        date            = datetime.utcnow(),
        backend_api     = backend_api
    )
    if v is not None:
        msg.domain = v.domain
        msg.couch_recipient_doc_type = v.owner_doc_type
        msg.couch_recipient = v.owner_id
    msg.save()
开发者ID:mchampanis,项目名称:core-hq,代码行数:30,代码来源:api.py

示例2: handle

    def handle(self, *args, **options):
        # This is ok, there's only like 50k of these and we're only querying ids
        vns = VerifiedNumber.view(
            'phone_numbers/verified_number_by_owner_id',
            include_docs=False
        ).all()

        # Convert to a dict of {owner id: count of total numbers}
        owners = {}
        for vn in vns:
            owner_id = vn['key']
            if owner_id in owners:
                owners[owner_id] += 1
            else:
                owners[owner_id] = 1

        # Convert to a list of owner ids that have more than one VerifiedNumber
        # (excluding pending numbers)
        mult_list = []
        for owner_id, count in owners.iteritems():
            if count > 1:
                owner_vns = VerifiedNumber.view(
                    'phone_numbers/verified_number_by_owner_id',
                    key=owner_id,
                    include_docs=True
                ).all()
                owner_vns = [vn for vn in owner_vns if vn.verified]
                if len(owner_vns) > 1:
                    mult_list.append(owner_id)

        # If the old methodology's preferred number doesn't match the
        # new one, report it here. Only fix it if options['fix'] is True
        for owner_id in mult_list:
            user = CouchUser.get_by_user_id(owner_id)
            if not user:
                print 'ERROR: User not found: %s' % owner_id
                continue
            if not self.phones_are_strings(user):
                print 'ERROR: Phone numbers should be strings: %s' % owner_id
                continue
            preferred_old_vn = get_verified_number_for_recipient_old(user)
            preferred_new_vn = get_verified_number_for_recipient(user)

            if preferred_old_vn._id != preferred_new_vn._id:
                print "Need to change %s %s from %s to %s" % (
                    user.domain,
                    owner_id,
                    preferred_new_vn.phone_number,
                    preferred_old_vn.phone_number,
                )
                if preferred_old_vn.phone_number not in user.phone_numbers:
                    print 'ERROR: Phone numbers are out of sync: %s' % owner_id
                    continue
                if options.get('fix', False):
                    print "  fixing..."
                    user.set_default_phone_number(preferred_old_vn.phone_number)
开发者ID:ansarbek,项目名称:commcare-hq,代码行数:56,代码来源:fix_preferred_number.py

示例3: assertMatch

    def assertMatch(self, match, phone_search, suffix_search, owner_id_search):
        lookedup = VerifiedNumber.by_phone(phone_search)
        self.assertEqual(match._id, lookedup._id)
        self.assertEqual(match._rev, lookedup._rev)

        lookedup = VerifiedNumber.by_suffix(suffix_search)
        self.assertEqual(match._id, lookedup._id)
        self.assertEqual(match._rev, lookedup._rev)

        [lookedup] = VerifiedNumber.by_owner_id(owner_id_search)
        self.assertEqual(match._id, lookedup._id)
        self.assertEqual(match._rev, lookedup._rev)
开发者ID:ansarbek,项目名称:commcare-hq,代码行数:12,代码来源:test_phone_numbers.py

示例4: edit_contact

def edit_contact(request, domain, sample_id, case_id):
    case = CommCareCase.get(case_id)
    if case.domain != domain:
        raise Http404
    if request.method == "POST":
        form = EditContactForm(request.POST)
        if form.is_valid():
            phone_number = form.cleaned_data.get("phone_number")
            vn = VerifiedNumber.view('sms/verified_number_by_number',
                                        key=phone_number,
                                        include_docs=True,
                                    ).one()
            if vn is not None and vn.owner_id != case_id:
                form._errors["phone_number"] = form.error_class(["Phone number is already in use."])
            else:
                update_contact(domain, case_id, request.couch_user.get_id, contact_phone_number=phone_number)
                return HttpResponseRedirect(reverse("edit_sample", args=[domain, sample_id]))
    else:
        initial = {
            "phone_number" : case.get_case_property("contact_phone_number"),
        }
        form = EditContactForm(initial=initial)
    
    context = {
        "domain" : domain,
        "case" : case,
        "form" : form,
    }
    return render(request, "reminders/partial/edit_contact.html", context)
开发者ID:tsinkala,项目名称:core-hq,代码行数:29,代码来源:views.py

示例5: tearDownClass

 def tearDownClass(cls):
     cls.user1.delete()
     cls.national_user.delete()
     cls.regional_user.delete()
     for vn in VerifiedNumber.by_domain(TEST_DOMAIN):
         vn.delete()
     super(TestAlerts, cls).tearDownClass()
开发者ID:ansarbek,项目名称:commcare-hq,代码行数:7,代码来源:test_alerts.py

示例6: validate_sms_users

    def validate_sms_users(self):
        for sms_user in iterate_over_api_objects(self.endpoint.get_smsusers):
            description = ""
            user = CommCareUser.get_by_username(self.get_username(sms_user)[0])
            if not user:
                description = "Not exists"
                EWSMigrationProblem.objects.create(
                    domain=self.domain,
                    external_id=sms_user.id,
                    object_type='smsuser',
                    description=description
                )
                continue

            phone_numbers = {
                apply_leniency(connection.phone_number) for connection in sms_user.phone_numbers
            }

            if phone_numbers - set(user.phone_numbers):
                description += "Invalid phone numbers, "

            phone_to_backend = {
                connection.phone_number: connection.backend
                for connection in sms_user.phone_numbers
            }

            default_phone_number = [
                connection.phone_number for connection in sms_user.phone_numbers if connection.default
            ]

            default_phone_number = default_phone_number[0] if default_phone_number else None

            if default_phone_number and (apply_leniency(default_phone_number) != user.default_phone_number):
                description += "Invalid default phone number, "

            for phone_number in user.phone_numbers:
                vn = VerifiedNumber.by_phone(phone_number)
                if not vn or vn.owner_id != user.get_id:
                    description += "Phone number not verified, "
                else:
                    backend = phone_to_backend.get(phone_number)
                    if backend == 'message_tester' and vn.backend_id != 'MOBILE_BACKEND_TEST' \
                            or (backend != 'message_tester' and vn.backend_id):
                        description += "Invalid backend, "

            if description:
                migration_problem, _ = EWSMigrationProblem.objects.get_or_create(
                    domain=self.domain,
                    object_id=user.get_id,
                    object_type='smsuser'
                )
                migration_problem.external_id = sms_user.id
                migration_problem.description = description.rstrip(' ,')
                migration_problem.save()
            else:
                EWSMigrationProblem.objects.filter(
                    domain=self.domain,
                    external_id=sms_user.id,
                    object_type='smsuser'
                ).delete()
开发者ID:ansarbek,项目名称:commcare-hq,代码行数:60,代码来源:balance.py

示例7: ivr_in

def ivr_in(request):
    """
    Handles tropo call requests
    """
    if request.method == "POST":
        data = json.loads(request.body)
        phone_number = data["session"]["from"]["id"]
        # TODO: Implement tropo as an ivr backend. In the meantime, just log the call.

        if phone_number:
            cleaned_number = strip_plus(phone_number)
            v = VerifiedNumber.by_extensive_search(cleaned_number)
        else:
            v = None

        # Save the call entry
        msg = CallLog(
            phone_number=cleaned_number,
            direction=INCOMING,
            date=datetime.utcnow(),
            backend_api=SQLTropoBackend.get_api_id(),
        )
        if v is not None:
            msg.domain = v.domain
            msg.couch_recipient_doc_type = v.owner_doc_type
            msg.couch_recipient = v.owner_id
        msg.save()

        t = Tropo()
        t.reject()
        return HttpResponse(t.RenderJson())
    else:
        return HttpResponseBadRequest("Bad Request")
开发者ID:philipkaare,项目名称:commcare-hq,代码行数:33,代码来源:views.py

示例8: initiate_sms_verification_workflow

def initiate_sms_verification_workflow(contact, phone_number):
    # For now this is only applicable to mobile workers
    assert isinstance(contact, CommCareUser)

    logged_event = MessagingEvent.get_current_verification_event(
        contact.domain, contact.get_id, phone_number)

    with CriticalSection(['verifying-phone-number-%s' % phone_number]):
        vn = VerifiedNumber.by_phone(phone_number, include_pending=True)
        if vn:
            if vn.owner_id != contact._id:
                return VERIFICATION__ALREADY_IN_USE
            if vn.verified:
                return VERIFICATION__ALREADY_VERIFIED
            else:
                result = VERIFICATION__RESENT_PENDING
        else:
            contact.save_verified_number(contact.domain, phone_number, False)
            result = VERIFICATION__WORKFLOW_STARTED
            # Always create a new event when the workflow starts
            if logged_event:
                logged_event.status = MessagingEvent.STATUS_NOT_COMPLETED
                logged_event.save()
            logged_event = MessagingEvent.create_verification_event(contact.domain, contact)

        if not logged_event:
            logged_event = MessagingEvent.create_verification_event(contact.domain, contact)

        send_verification(contact.domain, contact, phone_number, logged_event)
        return result
开发者ID:ansarbek,项目名称:commcare-hq,代码行数:30,代码来源:verify.py

示例9: get_couch_ids

 def get_couch_ids(self):
     result = VerifiedNumber.view(
         'phone_numbers/verified_number_by_domain',
         include_docs=False,
         reduce=False,
     ).all()
     return [row['id'] for row in result]
开发者ID:dimagi,项目名称:commcare-hq,代码行数:7,代码来源:delete_messaging_couch_phone_numbers.py

示例10: handle

    def handle(self, *args, **options):
        if len(args) == 0:
            raise CommandError('Usage: python manage.py set_backend_ids domain [backend_id] [--test]')

        domain = args[0]
        if len(args) > 1:
            backend_id = args[1]
        else:
            backend_id = None

        test_only = options['test']

        for vn in VerifiedNumber.by_domain(domain):
            if (not vn.backend_id) and (not backend_id):
                pass
            elif vn.backend_id == backend_id:
                pass
            elif test_only:
                print '%s %s, number %s has backend %s instead of %s' % \
                    (vn.owner_doc_type, vn.owner_id, vn.phone_number,
                     'None' if vn.backend_id is None else "'%s'" % vn.backend_id, backend_id)
            else:
                if vn.owner_doc_type == "CommCareCase":
                    print 'Cannot update backend_id for %s because it is a case' % vn.owner_id
                else:
                    print 'Updating backend_id from %s to %s for %s %s, number %s' % \
                        (vn.backend_id, backend_id, vn.owner_doc_type, vn.owner_id, vn.phone_number)
                    vn.backend_id = backend_id
                    vn.save()
开发者ID:LifeCoaching,项目名称:commcare-hq,代码行数:29,代码来源:set_backend_ids.py

示例11: chat_contacts

def chat_contacts(request, domain):
    domain_obj = Domain.get_by_name(domain, strict=True)
    verified_numbers = VerifiedNumber.by_domain(domain)
    contacts = []
    for vn in verified_numbers:
        owner = vn.owner
        if owner is not None and owner.doc_type in ('CommCareCase','CommCareUser'):
            if owner.doc_type == "CommCareUser":
                url = reverse(EditCommCareUserView.urlname, args=[domain, owner._id])
                name = owner.raw_username
            else:
                url = reverse("case_details", args=[domain, owner._id])
                if domain_obj.custom_case_username:
                    name = owner.get_case_property(domain_obj.custom_case_username) or _("(unknown)")
                else:
                    name = owner.name
            contacts.append({
                "id" : owner._id,
                "doc_type" : owner.doc_type,
                "url" : url,
                "name" : name,
            })
    context = {
        "domain" : domain,
        "contacts" : contacts,
    }
    return render(request, "sms/chat_contacts.html", context)
开发者ID:dszafranek,项目名称:commcare-hq,代码行数:27,代码来源:views.py

示例12: post

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        reminder = request.POST.get('reminder')
        phone_number = context.get('phone_number')

        if reminder and phone_number:
            phone_number = clean_phone_number(phone_number)
            v = VerifiedNumber.by_phone(phone_number, include_pending=True)
            if v and v.verified:
                user = v.owner
                if reminder == 'first_soh':
                    first_soh_process_user(user, test=True)
                elif reminder == 'second_soh':
                    now = datetime.datetime.utcnow()
                    date = now - datetime.timedelta(days=5)
                    second_soh_process_user(user, date, test=True)
                elif reminder == 'third_soh':
                    third_soh_process_users_and_facilities([user], [user.location.sql_location], test=True)
                elif reminder == 'stockout':
                    stockout_process_user(user, test=True)
                elif reminder == 'rrirv':
                    rrirv_process_user(user, test=True)
                elif reminder == 'visit_website':
                    visit_website_process_user(user, test=True)
        messages.success(request, "Reminder was sent successfully")
        return self.get(request, *args, **kwargs)
开发者ID:jmaina,项目名称:commcare-hq,代码行数:27,代码来源:views.py

示例13: process_verification

def process_verification(phone_number, msg, backend_id=None):
    v = VerifiedNumber.by_phone(phone_number, True)
    if not v:
        return

    if not verification_response_ok(msg.text):
        return

    msg.domain = v.domain
    msg.couch_recipient_doc_type = v.owner_doc_type
    msg.couch_recipient = v.owner_id
    msg.save()

    if not domain_has_privilege(msg.domain, privileges.INBOUND_SMS):
        return

    if backend_id:
        backend = MobileBackend.load(backend_id)
    else:
        backend = MobileBackend.auto_load(phone_number, v.domain)

    # i don't know how to dynamically instantiate this object, which may be any number of doc types...
    #owner = CommCareMobileContactMixin.get(v.owner_id)
    assert v.owner_doc_type == 'CommCareUser'
    owner = CommCareUser.get(v.owner_id)

    v = owner.save_verified_number(v.domain, phone_number, True, backend.name)
    with localize(owner.language):
        send_sms_to_verified_number(v, _(CONFIRM))
开发者ID:jmaina,项目名称:commcare-hq,代码行数:29,代码来源:verify.py

示例14: process_incoming

def process_incoming(msg, delay=True):
    v = VerifiedNumber.by_phone(msg.phone_number, include_pending=True)

    if v is not None and v.verified:
        msg.couch_recipient_doc_type = v.owner_doc_type
        msg.couch_recipient = v.owner_id
        msg.domain = v.domain
        msg.save()

    if msg.domain_scope:
        # only process messages for phones known to be associated with this domain
        if v is None or v.domain != msg.domain_scope:
            raise DomainScopeValidationError(
                'Attempted to simulate incoming sms from phone number not ' \
                'verified with this domain'
            )
    create_billable_for_sms(msg, msg.backend_api, delay=delay)

    if v is not None and v.verified:
        for h in settings.SMS_HANDLERS:
            try:
                handler = to_function(h)
            except:
                logging.exception('error loading sms handler: %s' % h)
                continue

            try:
                was_handled = handler(v, msg.text, msg=msg)
            except Exception, e:
                logging.exception('unhandled error in sms handler %s for message [%s]: %s' % (h, msg._id, e))
                was_handled = False

            if was_handled:
                break
开发者ID:piyushmadan,项目名称:commcare-hq,代码行数:34,代码来源:api.py

示例15: ivr_in

def ivr_in(request):
    """
    Handles tropo call requests
    """
    if request.method == "POST":
        data = json.loads(request.raw_post_data)
        phone_number = data["session"]["from"]["id"]
        ####
        
        # TODO: Implement tropo as an ivr backend. In the meantime, just log the call.
        
        cleaned_number = phone_number
        if cleaned_number is not None and len(cleaned_number) > 0 and cleaned_number[0] == "+":
            cleaned_number = cleaned_number[1:]
        
        # Try to look up the verified number entry
        v = VerifiedNumber.view("sms/verified_number_by_number",
            key=cleaned_number,
            include_docs=True
        ).one()
        
        # If none was found, try to match only the last digits of numbers in the database
        if v is None:
            v = VerifiedNumber.view("sms/verified_number_by_suffix",
                key=cleaned_number,
                include_docs=True
            ).one()
        
        # Save the call entry
        msg = CallLog(
            phone_number = cleaned_number,
            direction = INCOMING,
            date = datetime.utcnow(),
            backend_api = TropoBackend.get_api_id(),
        )
        if v is not None:
            msg.domain = v.domain
            msg.couch_recipient_doc_type = v.owner_doc_type
            msg.couch_recipient = v.owner_id
        msg.save()
        
        ####
        t = Tropo()
        t.reject()
        return HttpResponse(t.RenderJson())
    else:
        return HttpResponseBadRequest("Bad Request")
开发者ID:kennknowles,项目名称:commcare-hq,代码行数:47,代码来源:views.py


注:本文中的corehq.apps.sms.mixin.VerifiedNumber类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。