Пример #1
0
 def plain_ascii(self):
     if not hasattr(self, '_cached_plain_ascii'):
         if self.ascii:
             ascii = unidecode_name(self.ascii)
         else:
             ascii = unidecode_name(self.name)
         prefix, first, middle, last, suffix = name_parts(ascii)
         self._cached_plain_ascii = u" ".join([first, last])
     return self._cached_plain_ascii
Пример #2
0
 def ascii_name(self):
     if not hasattr(self, '_cached_ascii_name'):
         if self.ascii:
             # It's possibly overkill with unidecode() here, but needed until
             # we're validating the content of the ascii field, and have
             # verified that the field is ascii clean in the database:
             if not all(ord(c) < 128 for c in self.ascii):
                 self._cached_ascii_name = unidecode_name(self.ascii)
             else:
                 self._cached_ascii_name = self.ascii
         else:
             self._cached_ascii_name = unidecode_name(self.plain_name())
     return self._cached_ascii_name
Пример #3
0
def make_nomineeposition_for_newperson(nomcom, candidate_name, candidate_email,
                                       position, author):

    # This is expected to fail if called with an existing email address
    email = Email.objects.create(address=candidate_email)
    person = Person.objects.create(name=candidate_name,
                                   ascii=unidecode_name(candidate_name),
                                   address=candidate_email)
    email.person = person
    email.save()

    # send email to secretariat and nomcomchair to warn about the new person
    subject = 'New person is created'
    from_email = settings.NOMCOM_FROM_EMAIL.format(year=nomcom.year())
    (to_email, cc) = gather_address_lists('nomination_created_person',
                                          nomcom=nomcom)
    context = {
        'email': email.address,
        'fullname': email.person.name,
        'person_id': email.person.id,
        'year': nomcom.year(),
    }
    nomcom_template_path = '/nomcom/%s/' % nomcom.group.acronym
    path = nomcom_template_path + INEXISTENT_PERSON_TEMPLATE
    send_mail(None, to_email, from_email, subject, path, context, cc=cc)

    return make_nomineeposition(nomcom, email.person, position, author)
Пример #4
0
def create_person(group,
                  role_name,
                  name=None,
                  username=None,
                  email_address=None,
                  password=None,
                  is_staff=False,
                  is_superuser=False):
    """Add person/user/email and role."""
    if not name:
        name = group.acronym.capitalize() + " " + role_name.capitalize()
    if not username:
        username = group.acronym + "-" + role_name
    if not email_address:
        email_address = username + "@ietf.org"
    if not password:
        password = username + "+password"

    user = User.objects.create(username=username,
                               is_staff=is_staff,
                               is_superuser=is_superuser)
    user.set_password(password)
    user.save()
    person = Person.objects.create(name=name,
                                   ascii=unidecode_name(smart_text(name)),
                                   user=user)
    email = Email.objects.create(address=email_address, person=person)
    Role.objects.create(group=group,
                        name_id=role_name,
                        person=person,
                        email=email)
    return person
Пример #5
0
class PersonFactory(factory.DjangoModelFactory):
    class Meta:
        model = Person

    user = factory.SubFactory(UserFactory)
    name = factory.LazyAttribute(lambda p: u'%s %s' %
                                 (p.user.first_name, p.user.last_name))
    ascii = factory.LazyAttribute(lambda p: unicode(unidecode_name(p.name)))

    class Params:
        with_bio = factory.Trait(biography=u"\n\n".join(fake.paragraphs()))

    @factory.post_generation
    def default_aliases(obj, create, extracted, **kwargs):  # pylint: disable=no-self-argument
        make_alias = getattr(AliasFactory, 'create' if create else 'build')
        make_alias(person=obj, name=obj.name)
        make_alias(person=obj, name=obj.ascii)
        if obj.name != obj.plain_name():
            make_alias(person=obj, name=obj.plain_name())
        if obj.ascii != obj.plain_ascii():
            make_alias(person=obj, name=obj.plain_ascii())

    @factory.post_generation
    def default_emails(obj, create, extracted, **kwargs):  # pylint: disable=no-self-argument
        if extracted is None:
            extracted = True
        if create and extracted:
            make_email = getattr(EmailFactory, 'create' if create else 'build')
            make_email(person=obj, address=obj.user.email)

    @factory.post_generation
    def default_photo(obj, create, extracted, **kwargs):  # pylint: disable=no-self-argument
        import atexit
        if obj.biography:
            photo_name = obj.photo_name()
            media_name = u"%s/%s.jpg" % (settings.PHOTOS_DIRNAME, photo_name)
            obj.photo = media_name
            obj.photo_thumb = media_name
            photosrc = os.path.join(settings.TEST_DATA_DIR,
                                    "profile-default.jpg")
            photodst = os.path.join(settings.PHOTOS_DIR, photo_name + '.jpg')
            if not os.path.exists(photodst):
                shutil.copy(photosrc, photodst)

            def delete_file(file):
                os.unlink(file)

            atexit.register(delete_file, photodst)
Пример #6
0
def ensure_person_email_info_exists(name, email):
    addr = email
    email = None
    person = get_person_from_name_email(name, addr)

    # make sure we have a person
    if not person:
        person = Person()
        person.name = name
        log.assertion('isinstance(person.name, six.text_type)')
        person.ascii = unidecode_name(person.name).decode('ascii')
        person.save()

    # make sure we have an email address
    if addr and (addr.startswith('unknown-email-') or is_valid_email(addr)):
        active = True
        addr = addr.lower()
    else:
        # we're in trouble, use a fake one
        active = False
        addr = u"unknown-email-%s" % person.plain_ascii().replace(" ", "-")

    try:
        email = person.email_set.get(address=addr)
    except Email.DoesNotExist:
        try:
            # An Email object pointing to some other person will not exist
            # at this point, because get_person_from_name_email would have
            # returned that person, but it's possible that an Email record
            # not associated with any Person exists
            email = Email.objects.get(address=addr, person__isnull=True)
        except Email.DoesNotExist:
            # most likely we just need to create it
            email = Email(address=addr)
            email.active = active

        email.person = person
        if email.time is None:
            email.time = datetime.datetime.now()
        email.save()

    return person, email
Пример #7
0
    for row in namedtuplefetchall(c):
        if row.login not in needed_personnel:
            continue

        if (team.acronym, row.login) in reviewer_blacklist:
            continue  # ignore

        name_to_login[row.name] = row.login

        email = Email.objects.filter(
            address=row.email).select_related("person").first()
        if not email:
            person = Person.objects.filter(alias__name=row.name).first()
            if not person:
                person, created = Person.objects.get_or_create(
                    name=row.name, ascii=unidecode_name(row.name))
                if created:
                    print "created person", unicode(person).encode("utf-8")
                existing_aliases = set(
                    Alias.objects.filter(person=person).values_list("name",
                                                                    flat=True))
                curr_names = set(x for x in [
                    person.name,
                    person.ascii,
                    person.ascii_short,
                    person.plain_name(),
                ] if x)
                new_aliases = curr_names - existing_aliases
                for name in new_aliases:
                    Alias.objects.create(person=person, name=name)
Пример #8
0
def get_meeting_registration_data(meeting):
    """"Retrieve registration attendee data and summary statistics.  Returns number
    of Registration records created."""
    num_created = 0
    num_processed = 0
    response = requests.get(settings.REGISTRATION_ATTENDEES_BASE_URL +
                            meeting.number)
    if response.status_code == 200:
        decoded = []
        try:
            decoded = response.json()
        except ValueError:
            if response.content.strip() == 'Invalid meeting':
                pass
            else:
                raise RuntimeError(
                    "Could not decode response from registrations API: '%s...'"
                    % (response.content[:64], ))

        # for each user identified in the Registration system
        # Create a DataTracker MeetingRegistration object
        for registration in decoded:
            person = None
            # capture the stripped registration values for later use
            first_name = registration['FirstName'].strip()
            last_name = registration['LastName'].strip()
            affiliation = registration['Company'].strip()
            country_code = registration['Country'].strip()
            address = registration['Email'].strip()
            object, created = MeetingRegistration.objects.get_or_create(
                meeting_id=meeting.pk,
                first_name=first_name,
                last_name=last_name,
                affiliation=affiliation,
                country_code=country_code,
                email=address,
            )

            # Add a Person object to MeetingRegistration object
            # if valid email is available
            if object and not object.person and address:
                # If the person already exists do not try to create a new one
                emails = Email.objects.filter(address=address)
                # there can only be on Email object with a unique email address (primary key)
                if emails.exists():
                    person = emails.first().person
                # Create a new Person object
                else:
                    # Normalize all-caps or all-lower entries.  Don't touch
                    # others, there might be names properly spelled with
                    # internal uppercase letters.
                    if ((first_name == first_name.upper()
                         or first_name == first_name.lower())
                            and (last_name == last_name.upper()
                                 or last_name == last_name.lower())):
                        first_name = first_name.capitalize()
                        last_name = last_name.capitalize()
                    regname = "%s %s" % (first_name, last_name)
                    # if there are any unicode characters decode the string to ascii
                    ascii_name = unidecode_name(regname)

                    # Create a new user object if it does not exist already
                    # if the user already exists do not try to create a new one
                    users = User.objects.filter(username=address)
                    if users.exists():
                        user = users.first()
                    else:
                        # Create a new user.
                        user = User.objects.create(
                            first_name=first_name,
                            last_name=last_name,
                            username=address,
                            email=address,
                        )
                        user.save()

                    aliases = Alias.objects.filter(name=regname)
                    if aliases.exists():
                        person = aliases.first().person
                    else:
                        # Create the new Person object.
                        person = Person.objects.create(
                            name=regname,
                            ascii=ascii_name,
                            affiliation=affiliation,
                            user=user,
                        )
                        person.save()

                    # Create an associated Email address for this Person
                    email = Email.objects.create(
                        person=person,
                        address=address,
                    )

                    # If this is the only email address, set primary to true.
                    # If the person already existed (found through Alias) and
                    # had email addresses, we don't do this.
                    if Email.objects.filter(person=person).count() == 1:
                        email.primary = True
                        email.save()

                # update the person object to an actual value
                object.person = person
                object.save()

            if created:
                num_created += 1
            num_processed += 1
    else:
        raise RuntimeError("Bad response from registrations API: %s, '%s'" %
                           (response.status_code, response.content))
    num_total = MeetingRegistration.objects.filter(
        meeting_id=meeting.pk).count()
    return num_created, num_processed, num_total