Ejemplo n.º 1
0
 def get_phone_and_phone_cc(client_phone, country_code):
     """
     Parse the contact phone number
     :param client_phone: the phone number added by the client
     :param country_code: eg.: 'RO', 'IT',..
     :return: returns the client national phone number and it's phone country code
     """
     phone_cc = None
     try:
         parsed_phone = phonenumbers.parse(client_phone)
         phone_cc = parsed_phone.country_code
         phone = parsed_phone.national_number
     except Exception as e:
         LOG.debug(e)
         if client_phone[
                 0] != '+':  # number misses country code, determine it then add the national number
             for ph_cc, country_c in COUNTRY_CODE_TO_REGION_CODE.items():
                 if country_code in country_c:
                     phone_cc = ph_cc
                     break
             parsed_phone = phonenumbers.parse('+{}{}'.format(
                 phone_cc, client_phone))
             phone = parsed_phone.national_number
         else:
             raise e
     return phone, phone_cc
Ejemplo n.º 2
0
    def country_code_response(self):
        gateway = self.data.get('gateway')
        try:
            backend = SMSBackend.get(gateway)
            backend_api_id = get_backend_by_class_name(
                backend.doc_type).get_api_id()
        except Exception:
            return []
        direction = self.data.get('direction')
        criteria_query = SmsGatewayFeeCriteria.objects.filter(
            direction=direction, backend_api_id=backend_api_id)
        country_codes = criteria_query.exclude(
            country_code__exact=None).values_list('country_code',
                                                  flat=True).distinct()
        final_codes = []
        countries = dict(COUNTRIES)
        for code in country_codes:
            cc = COUNTRY_CODE_TO_REGION_CODE.get(code)
            country_name = force_unicode(countries.get(cc[0])) if cc else ''
            final_codes.append((code, country_name))

        search_term = self.data.get('searchString')
        if search_term:
            search_term = search_term.lower().replace('+', '')
            final_codes = filter(
                lambda x: (str(x[0]).startswith(search_term) or x[1].lower().
                           startswith(search_term)), final_codes)
        final_codes = [(c[0], "+%s%s" % (c[0], " (%s)" % c[1] if c[1] else ''))
                       for c in final_codes]
        if criteria_query.filter(country_code__exact=None).exists():
            final_codes.append(
                (NONMATCHING_COUNTRY,
                 _('Any Country (Delivery not guaranteed via connection)')))
        return final_codes
Ejemplo n.º 3
0
def upgrade():
    data = []
    for country_code, iso_codes in COUNTRY_CODE_TO_REGION_CODE.items():
        if country_code not in COUNTRY_CODES_FOR_NON_GEO_REGIONS:
            for iso_code in iso_codes:
                data.append({
                    "iso_code": iso_code,
                    "country_code": country_code
                })
    op.bulk_insert(country, data)
Ejemplo n.º 4
0
def resolve_shop(root, info):
    permissions = get_permissions()
    permissions = format_permissions_for_display(permissions)
    languages = settings.LANGUAGES
    languages = [LanguageDisplay(
        code=language[0], language=language[1]) for language in languages]
    phone_prefixes = list(COUNTRY_CODE_TO_REGION_CODE.keys())
    countries_map = [
        CountryDisplay(
            code=country[0], country=country[1]) for country in countries]
    return Shop(
        permissions=permissions,
        languages=languages,
        phone_prefixes=phone_prefixes,
        countries=countries_map)
Ejemplo n.º 5
0
def resolve_shop(root, info):
    permissions = get_permissions()
    permissions = format_permissions_for_display(permissions)
    languages = settings.LANGUAGES
    languages = [
        LanguageDisplay(code=language[0], language=language[1])
        for language in languages
    ]
    phone_prefixes = list(COUNTRY_CODE_TO_REGION_CODE.keys())
    countries_map = [
        CountryDisplay(code=country[0], country=country[1])
        for country in countries
    ]
    return Shop(permissions=permissions,
                languages=languages,
                phone_prefixes=phone_prefixes,
                countries=countries_map)
Ejemplo n.º 6
0
def phonenumber_validation_view(request):
    phone_number = request.GET.get("phone", "").replace(" ", "")
    country_code = "DE"  # DEFAULT
    for region_code, country_code_list in COUNTRY_CODE_TO_REGION_CODE.items():
        prefix = f"+{region_code}"
        if phone_number.startswith(prefix):
            country_code = country_code_list[0]
            break
    formater = phonenumbers.AsYouTypeFormatter(country_code)
    result = ""
    for digit in phone_number:
        result = formater.input_digit(digit)
    return JsonResponse(data={
        "phone": result,
        "country_code": country_code
    },
                        status=201,
                        safe=False)
Ejemplo n.º 7
0
class UpdatePhoneForm(FlaskForm):
    choices = []
    for code, countries in COUNTRY_CODE_TO_REGION_CODE.items():
        for country in countries:
            try:
                choices.append('+' + str(code) + ' ' +
                               pycountry.countries.get(alpha_2=country).name)
            except AttributeError:
                pass
    choices = [choice.split(',')[0] for choice in choices]

    country = SelectField('Country code',
                          validators=[DataRequired()],
                          choices=choices)
    phone = StringField('Your phone number',
                        validators=[DataRequired(),
                                    Length(max=20)])
    public = BooleanField('Allow', default='checked')
    submit = SubmitField('Submit')
Ejemplo n.º 8
0
    def country_code_response(self):
        gateway = self.data.get('gateway')
        try:
            backend = SMSBackend.get(gateway)
            backend_api_id = get_backend_by_class_name(backend.doc_type).get_api_id()
        except Exception:
            return []
        direction = self.data.get('direction')
        criteria_query = SmsGatewayFeeCriteria.objects.filter(
            direction=direction, backend_api_id=backend_api_id
        )
        country_codes = criteria_query.exclude(
            country_code__exact=None
        ).values_list('country_code', flat=True).distinct()
        final_codes = []
        countries = dict(COUNTRIES)
        for code in country_codes:
            cc = COUNTRY_CODE_TO_REGION_CODE.get(code)
            country_name = force_unicode(countries.get(cc[0])) if cc else ''
            final_codes.append((code, country_name))

        search_term = self.data.get('searchString')
        if search_term:
            search_term = search_term.lower().replace('+', '')
            final_codes = filter(
                lambda x: (str(x[0]).startswith(search_term)
                           or x[1].lower().startswith(search_term)),
                final_codes
            )
        final_codes = [(c[0], "+%s%s" % (c[0], " (%s)" % c[1] if c[1] else '')) for c in final_codes]
        if criteria_query.filter(country_code__exact=None).exists():
            final_codes.append((
                NONMATCHING_COUNTRY,
                _('Any Country (Delivery not guaranteed via connection)')
            ))
        return final_codes
Ejemplo n.º 9
0
 def resolve_phone_prefixes(_, _info):
     return list(COUNTRY_CODE_TO_REGION_CODE.keys())
Ejemplo n.º 10
0
 def resolve_phone_prefixes(_, _info):
     return list(COUNTRY_CODE_TO_REGION_CODE.keys())
Ejemplo n.º 11
0
def get_calling_code(iso):
    for code, isos in COUNTRY_CODE_TO_REGION_CODE.items():
        if iso.upper() in isos:
            return code
    return None
Ejemplo n.º 12
0
from django.forms import Select, TextInput
from phonenumber_field.widgets import PhoneNumberPrefixWidget
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE

phone_prefixes = [('+{}'.format(k), '+{}'.format(k))
                  for (k, v) in sorted(COUNTRY_CODE_TO_REGION_CODE.items())]


class PhonePrefixWidget(PhoneNumberPrefixWidget):
    """Uses choices with tuple in a simple form of "+XYZ: +XYZ".

    Workaround for an issue:
    https://github.com/stefanfoulis/django-phonenumber-field/issues/82
    """

    template_name = 'account/snippets/phone_prefix_widget.html'

    def __init__(self, attrs=None):
        widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput())
        # pylint: disable=bad-super-call
        super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)


class DatalistTextWidget(Select):
    template_name = "account/snippets/datalist.html"
    input_type = "text"

    def get_context(self, *args):
        context = super(DatalistTextWidget, self).get_context(*args)
        context['widget']['type'] = self.input_type
        return context
Ejemplo n.º 13
0
class AddressForm(ModelForm):
    class Meta:
        model = Address
        fields = [
            'addressee', 'street', 'apt', 'city', 'state', 'zip_code',
            'country', 'phone', 'phone_prefix', 'email'
        ]
        widgets = {
            'addressee':
            TextInput(attrs={
                'required': "true",
                "id": "recip",
                "class": "address-field"
            }),
            'street':
            TextInput(
                attrs={
                    'id': 'autocomplete',
                    'class': 'input-field col mods field address-field',
                    'required': "true"
                }),
            'city':
            TextInput(
                attrs={
                    'class': 'input-field col mods field address-field',
                    'id': 'locality',
                    'required': "true"
                }),
            'state':
            TextInput(
                attrs={
                    'class': 'input-field col mods field address-field',
                    'id': 'administrative_area_level_1',
                    'required': "true"
                }),
            'zip_code':
            TextInput(
                attrs={
                    'class': 'input-field col mods address-field',
                    'id': 'postal_code',
                    'required': "true"
                }),
            'phone':
            TextInput(attrs={
                'class': 'input-field col mods',
                'id': 'phone'
            }),
            'phone_prefix':
            Select(attrs={
                'class': 'input-field col mods',
                'id': 'phone-prefix'
            }),
            'email':
            TextInput(
                attrs={
                    'class': 'input-field col mods address-field',
                    'id': 'email',
                    'required': "true"
                }),
            'apt':
            TextInput(attrs={
                'class': 'input-field col mods',
                'id': 'apt'
            })
        }

    phone_prefix = ChoiceField(
        choices=[('+{}'.format(key), '+{} ({})'.format(key, value[0]))
                 for key, value in COUNTRY_CODE_TO_REGION_CODE.items()])
Ejemplo n.º 14
0
from django.forms import Select, TextInput
from phonenumber_field.widgets import PhoneNumberPrefixWidget
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE

phone_prefixes = [
    ("+{}".format(k), "+{}".format(k))
    for (k, v) in sorted(COUNTRY_CODE_TO_REGION_CODE.items())
]


class PhonePrefixWidget(PhoneNumberPrefixWidget):
    """Uses choices with tuple in a simple form of "+XYZ: +XYZ".

    Workaround for an issue:
    https://github.com/stefanfoulis/django-phonenumber-field/issues/82
    """

    template_name = "account/snippets/phone_prefix_widget.html"

    def __init__(self, attrs=None):
        widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput())
        # pylint: disable=bad-super-call
        super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)

    def value_from_datadict(self, data, files, name):
        value = super().value_from_datadict(data, files, name)
        # FIXME: this is a hack, we should not be using a multiwidget
        # in forms used by the API but here we are
        if not value and name in data:
            value = data[name]
        return value
Ejemplo n.º 15
0
 def phone_prefix(self):
     for code, isos in COUNTRY_CODE_TO_REGION_CODE.items():
         if self.code in isos:
             return '+' + str(code)
     return None
Ejemplo n.º 16
0
class Profile(models.Model):
    choices = []
    for code, countries in COUNTRY_CODE_TO_REGION_CODE.items():
        for country in countries: 
            try:
                choices.append([
                    '+' + str(code),
                    '+' + str(code) + ' ' + pycountry.countries.get(alpha_2 = country).name
                ])
            except AttributeError:
                pass
    choices = [[None, '']] + [[i, j.split(',')[0]] for i, j in choices]
                

    user = models.OneToOneField(User, on_delete = models.CASCADE)

    id = models.BigAutoField(primary_key = True, default = gen_key)
    created_at_ip = models.GenericIPAddressField(null = True, blank = True)
    handle = models.TextField(
        default = gen_hex,
        unique = True, 
        error_messages={
            'unique': 'That username has been taken. Please choose another.'
        }
    )
    country_code = models.CharField(max_length = 200, null = True, choices = choices)
    phone = models.CharField(max_length = 20, null = True, blank = True, unique = True)
    phone_public = models.BooleanField(default = True)
    birthdate = models.DateField(null = True, blank = True)

    profile_image = models.ImageField(default = 'default_profile.png', upload_to = 'profile_pics')
    background_image = models.ImageField(default = 'default_background.png', upload_to = 'background_pics')
    bio = models.TextField(max_length = 160, null = True, blank = True)
    location = models.TextField(max_length = 30, null = True, blank = True)
    website = models.URLField(max_length = 100, null = True, blank = True)

    following = models.ManyToManyField(
        'self', 
        symmetrical = False,
        through = 'Following',
        # through_fields = ('profile', 'profile')     # not needed to itself w/ 2 ForeignKey
    )

    last_checked_message_at = DateTimeField(default = timezone.now)

    @property
    def new_message(self):
        if len(self.received.all()) == 0:
            return False
        elif self.received.order_by('-created_at').first().created_at > self.last_checked_message_at:
            return True

    @property
    def follow_recommendation(self):
        recommendation = Profile.objects.exclude(
            Q(handle__in = self.following.values('handle')) |
            Q(handle = self.handle)
        ).order_by('?')[:3]
        return recommendation


    # disable to avoid PIL conflict with s3
    # will do it through s3 lambda
    # override save() in the Model class
    # def save(self, *args, **kwargs):
    #     super().save(*args, **kwargs)                                                      # first run the parent's save method
    #     output_size = {'profile': (400, 400), 'background': (600, 200)}
    #     p_img = Image.open(self.profile_image.path)
    #     b_img = Image.open(self.background_image.path)

    #     if p_img.width > 400 or p_img.height > 400:
    #         p_img.thumbnail(output_size.get('profile'))
    #         p_img.save(self.profile_image.path)

    #     if b_img.width > 600 or p_img.height > 200:
    #         b_img.thumbnail(output_size.get('background'))
    #         b_img.save(self.background_image.path)

    def __repr__(self):
        return f'{self.user.username.title()}'

    def __str__(self):
        return f'{self.user.username.title()}'
Ejemplo n.º 17
0
def country_name_from_isd_code_or_empty(isd_code):
    cc = COUNTRY_CODE_TO_REGION_CODE.get(isd_code)
    return force_str(COUNTRIES.get(cc[0])) if cc else ''
Ejemplo n.º 18
0
def country_name_from_isd_code_or_empty(isd_code):
    cc = COUNTRY_CODE_TO_REGION_CODE.get(isd_code)
    return force_unicode(COUNTRIES.get(cc[0])) if cc else ''