Example #1
0
def country_coordinates(country_id_numbers):
    '''
    Get and put country coordinates in a dictionary.
    '''
    countries_long_lat = {}

    for id in country_id_numbers.unique():
        id_region_code = region_code_for_country_code(id)
        id_str = str(id)
        if str(id) in iso3166.countries_by_numeric:
            # print("key in dict")
            id_region_code = iso3166.countries_by_numeric[str(id)][1]
        else:
            id_region_code = region_code_for_country_code(id)

        # 'ZZ' denotes 'unknown or unspecified country'
        if id_region_code == 'ZZ':
            countries_long_lat[id] = -1
            # countries_long_lat['ZZ'] = ''
            pass
        else:
            country_info = pycountry.countries.get(alpha_2=id_region_code)

            # get longitudal and latitudal coordinates of country
            ll = get_boundingbox_country(country=country_info.name,
                                         output_as='center')

            # key is the country id number
            countries_long_lat[id] = ll

    return countries_long_lat
Example #2
0
    def verify(self):
        if self.otp == self.otp_entry.get():
            messagebox.showinfo("Success","Verified", parent=self.root2)
            self.count = str(region_code_for_country_code(self.code.get()))
            self.UID=self.name_txt.get()+str(random.randint(1000,40000))

            self.conn=sqlite3.connect("bakery.db")
            self.c=self.conn.cursor()
            self.c.execute("CREATE TABLE IF NOT EXISTS user(UID TEXT UNIQUE PRIMARY KEY NOT NULL ,Uname TEXT NOT NULL, Email TEXT UNIQUE NOT NULL ,Country_Code TEXT NOT NULL, Country TEXT NOT NULL,Phone_No TEXT UNIQUE NOT NULL,Password TEXT NOT NULL)")
            self.find_user = ("SELECT * FROM user WHERE Email= ?  or Phone_No = ?")
            self.c.execute(str(self.find_user),(self.email_txt.get(),self.contact_txt.get()))
            results = (self.c).fetchall()
            if results:
                messagebox.showerror("Error","Email or Contact  is already Used")
            else:
                try:
                    self.c.execute("INSERT INTO user (UID ,Uname, Email ,Country_Code, Country,Phone_No,Password ) VALUES (?,?,?,?,?,?,?)",
                    (self.UID,self.name_txt.get(),self.email_txt.get(),self.code.get(),self.count, self.contact_txt.get(),self.pass_txt.get()))
                    self.conn.commit()
                    self.c.close()
                    self.conn.close()
                    self.otp_entry.delete(0,END)
                    self.otp=None
                    return messagebox.showinfo("Successfull","Successfully Added Data, Now You Can Login")
                    
                except Exception:
                    return messagebox.showerror("Error!!","Somthing went wrong not able to add data try again. "+"You  User ID :"+self.UID)        
        else:
            messagebox.showerror("Error","OTP Enterd Is Wrong! Try Again To Resend again click on Resgister")            
Example #3
0
def step_phone_verification(selenium_client, sms_receiver):
    # Wizard - step 6 - phone verification (optional)
    logger.info("Submitted wizard for step 4")
    phone = phonenumbers.parse(sms_receiver.get_phone_number())
    country = region_code_for_country_code(phone.country_code)
    select_value(
        selenium_client,
        By.XPATH,
        "//div[@id='wlspispHipChallengeContainer']//select",
        country,
    )
    log_write(
        selenium_client,
        By.XPATH,
        "//div[@id='wlspispHipChallengeContainer']//input",
        phone.national_number,
    )
    log_click(
        selenium_client,
        By.XPATH,
        "//div[@id='wlspispHipControlButtonsContainer']//a[@title='Send SMS code']",
    )
    validate_error(selenium_client, "Code error")
    text = sms_receiver.get_latest_sms(phone)
    code = text.split(":")[1].strip()
    log_write(
        selenium_client,
        By.XPATH,
        "//label[@id='wlspispHipSolutionContainer']//input",
        code,
    )
    log_click(selenium_client, By.ID, "iSignupAction")
Example #4
0
    def detectCountryFromPhone(self, srcPhoneNumber):
        """Lookup name of country from phone number region code.

        Args:
            srcPhoneNumber (str): phone number

        Returns:
            str: country name
        """

        if not isinstance(srcPhoneNumber, str):
            return None

        try:
            phoneNumber = phonenumbers.parse(srcPhoneNumber)
        except BaseException:
            self.sf.debug(f"Skipped invalid phone number: {srcPhoneNumber}")
            return None

        try:
            countryCode = region_code_for_country_code(
                phoneNumber.country_code)
        except BaseException:
            self.sf.debug(
                f"Lookup of region code failed for phone number: {srcPhoneNumber}"
            )
            return None

        if not countryCode:
            return None

        return self.sf.countryNameFromCountryCode(countryCode.upper())
Example #5
0
def twilioSMS(k,msg, count):
	
	# To check for country code
	pn = phonenumbers.parse(k)
	print pn.country_code
	country = pycountry.countries.get(alpha_2=region_code_for_number(pn))
	yo = region_code_for_country_code(pn.country_code)
	
	# To get timezone for the specified country
	url = "http://api.timezonedb.com/v2/list-time-zone?key=" + API_Key + "&format=json&country=" + yo
	json_obj_places = urllib2.urlopen(url)
	places = json.load(json_obj_places)
	print places["zones"][0]["zoneName"]

	local_date = datetime.now(pytz.timezone(places["zones"][0]["zoneName"]))
	print local_date.time()

	hour = local_date.time().hour

	try:
		# To check whether the time is the night time or not
		if hour in range(7, 23):
			client = Client(account_sid, auth_token)
			message = client.messages.create(to=k, from_=my_twilio, body=msg)

			time.sleep( 60 )
			print message.sid
			bappa = client.messages(message.sid).fetch()

			print(bappa.body)
			print(bappa.status)

			# Checking the status of the Message after 1 minute if not delivered or sent, sending again
			if bappa.status not in ["delivered", "sent"] and count<5:
				print bappa.status
				count = count +1
				print count
				logging.basicConfig()
				time.sleep(2)
				obj = MessageLog(number=k, dateField=local_date.date(), timeField=local_date.time(), status="Failed or Undelivered")
				obj.save()
				print "yoyo"
				time.sleep(5)
				twilioSMS(k,msg, count)	
		else:
			#Saving to database in Night Time
			print "Night time"
			time.sleep(2)
			logging.basicConfig()
			obj = MessageLog(number=k, dateField=local_date.date(), timeField=local_date.time(), status="Night Time")
			print obj
			obj.save()
			print "bappa"
	except:
		# Checking if the number is invalid
		print "yo bappa"
		obj = MessageLog(number=k, dateField=local_date.date(), timeField=local_date.time(), status="Not Sent")
		obj.save()
		print "error"
Example #6
0
def verify_country_code(country_code: str):
    """Verifies country code of the phone number"""
    country_code = country_code.replace("+", "")
    if not country_code.isdigit():
        raise AssertionError(f"Invalid country_code {country_code}")

    region_code = region_code_for_country_code(int(country_code))
    if region_code == "ZZ":
        raise AssertionError(f"Invalid country_code {country_code}")
Example #7
0
    def __get_country_by_phone(self, phone):
        if phone == None:
            return {}

        pn = phonenumbers.parse(phone)
        country = pycountry.countries.get(alpha_2=region_code_for_number(pn))
        return {
            'region_code': region_code_for_country_code(pn.country_code),
            'country': country.name
        }
Example #8
0
    def gen_callnumber(self):
        r = random.randint(1, 10)
        if r < 8:
            place = "1"
        else:
            place = random.randint(1, 300)
            while (region_code_for_country_code(place) == "ZZ"):
                place = random.randint(1, 300)
        first = str(random.randint(100, 999))
        second = str(random.randint(1, 888)).zfill(3)
        last = str(random.randint(1, 9998)).zfill(4)

        return '+{}-{}-{}-{}'.format(str(place), first, second, last)
Example #9
0
 def phone_info(self):
     """ Get phone number information.
     """
     try:
         number = parse(self.phone)
         region = pnu.region_code_for_country_code(number.country_code)
         return {
             'number': number,
             'valid': pnu.is_valid_number(number),
             'country': countries.get(alpha2=region),
         }
     except pnu.NumberParseException:
         return {}
Example #10
0
    def gen_callednumber(self, rate_place_distribution):
        r1 = random.randint(1, 100)
        if r1 < 100 * rate_place_distribution:
            place = "1"
        else:
            place = random.randint(1, 300)
            while (region_code_for_country_code(place) == "ZZ"):
                place = random.randint(1, 300)

        first = str(random.randint(100, 999))
        second = str(random.randint(1, 888)).zfill(3)
        last = str(random.randint(1, 9998)).zfill(4)
        return '+{}-{}-{}-{}'.format(str(place), first, second, last)
Example #11
0
def get_country_cca2(phone_number: str) -> str:
    """
    Retrieves the alpha-2 country code from the phone number

    Parameters:
    phone_number (int): The phone number tfrom which the country code is to be extracted

    Returns:
    str: the alpha-2 country code corresponding to the supplied phone number

    Throws:
    NumberParseException: the supplied phone number is invalid
    """
    number_obj = phonenumbers.parse(phone_number, None)

    return region_code_for_country_code(number_obj.country_code)
Example #12
0
def incoming():
    """
Captures the body of the message

Example request.form:
{
  "account_sid": "ACf4c269b45de4664b2fdcc5386cc5d54b",
  "api_version": "2010-04-01",
  "body": "Hello! 👍",
  "date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
  "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
  "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
  "direction": "outbound-api",
  "error_code": null,
  "error_message": null,
  "from": "+14155552345",
  "messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "num_media": "0",
  "num_segments": "1",
  "price": -0.00750,
  "price_unit": "USD",
  "sid": "MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "status": "sent",
  "subresource_uris": {
    "media": "/2010-04-01/Accounts/ACf4c269b45de4664b2fdcc5386cc5d54b/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
  },
  "to": "+14155552345",
  "uri": "/2010-04-01/Accounts/ACf4c269b45de4664b2fdcc5386cc5d54b/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
}
"""
    form = request.form
    cuerpo = parse_body(form, 'Body')
    phone_number = phonenumbers.parse(parse_body(form, 'From'))
    region_code = phone_number.country_code
    country_code = region_code_for_country_code(region_code)
    # print('Telefono: {0}'.format(phone_number))
    # print('Pais: {0}  Region: {1}'.format(country_code, region_code ))
    resp = MessagingResponse()
    if 'ayuda' in cuerpo.lower():
        resp.message(welcome_user('es'))
    elif 'help' in cuerpo.lower():
        resp.message(welcome_user('en'))
    else:
        resp.message(wikipedia_lookup(cuerpo, lang='es'))
    return str(resp)
Example #13
0
    def detectCountryFromPhone(self, srcPhoneNumber):

        # Get dictionary of country codes and country names
        abbvCountryCodes = self.getCountryCodeDict()

        # Check if country code is present in the phone number
        try:
            # Parse source phone nummber
            phoneNumber = phonenumbers.parse(srcPhoneNumber)
            # Get country code of phone number
            countryCode = region_code_for_country_code(
                phoneNumber.country_code)
            # try block handles key not found exception
            return abbvCountryCodes[countryCode.upper()]
        except:
            # Region code not present in source phone number
            self.sf.debug("Skipped invalid phone number: " + srcPhoneNumber)
            return None
Example #14
0
from phonenumbers.phonenumberutil import PhoneMetadata
from phonenumbers import geocoder
from phonenumbers.phonenumberutil import (
    region_code_for_country_code,
    region_code_for_number,
    national_significant_number
)
from phonenumbers import carrier
from phonenumbers import timezone

text = '+16473612505'
text1 = '+73812332308'

x=phonenumbers.parse(text1, None)
print(x)

y=str(geocoder.country_name_for_number(x, "en"))
print(y)

z=str(geocoder.description_for_number(x, "en"))
print(z)

code=region_code_for_country_code(x.country_code)
print(code)

country = pycountry.countries.get(alpha_2=str(code))
print(country)

#short = national_significant_number(text1)
short1= PhoneMetadata.short_metadata_for_region(code)
print(short1)
Example #15
0
def sync_cover(country, city):
    if fk.request.method == 'GET':
        _country = get_country(country)
        if _country is None:
            return service_response(204, 'Unknown country', 'We could not find this country.')
        else:
            lat = _country["lat"]
            lng = _country["lng"]
            if lat == "":
                lat = 0.00
                lng = 0.00
            tz = tzwhere.tzwhere()
            timeZoneStr = tz.tzNameAt(lat, lng)
            timeZoneObj = timezone(timeZoneStr)
            now_time = datetime.datetime.now(timeZoneObj)
            day = str(now_time).split(" ")[0]
            date = datetime.datetime.strptime(day, "%Y-%m-%d")
            next_date = date + datetime.timedelta(days=1)
            next_day = datetime.datetime.strftime(next_date, "%Y-%m-%d")
            if "-" in str(now_time).split(" ")[1]:
                country_time = str(now_time).split(" ")[1].split("-")[0]
            if "+" in str(now_time).split(" ")[1]:
                country_time = str(now_time).split(" ")[1].split("+")[0]
            country_hour = int(country_time.split(":")[0])
            pn = phonenumbers.parse(get_one_number(country), None)
            country_code = str(pn.country_code)
            _country_name_short = region_code_for_country_code(pn.country_code)

            if city == 'all':
                cities, language = get_cities(country)
            else:
                ignore, language = get_cities(country)
                cities = [city]

            if country_hour == 21: # We push the sync
                cities_to_sync = []
                for city in cities:
                    check_weather = Weather.objects(country=country, city=city.lower().replace(" ", "-"), day=next_day).first()
                    if check_weather is None:
                        cities_to_sync.append(city.lower().replace(" ", "-"))
                if len(cities_to_sync) == 0:
                    return service_response(204, 'Weather synched already', 'The weather for country: {0} and city: {1} is already synched.'.format(country, city))
                unknown_cities = []
                for city in cities_to_sync:
                    pred_weather = get_weather(city.lower(), _country_name_short)
                    try:
                        if pred_weather['title'] == "":
                            unknown_cities.append(city.lower())
                        else:
                            _weather = Weather(created_at=str(datetime.datetime.utcnow()), country=country, city=city.lower(), day=next_day)
                            if language not in ['en', 'unknown']:
                                translator = Translator(to_lang=language)
                                _data = {'title':translator.translate(pred_weather['title'])}
                                _data['day'] = translator.translate("During the day: {0}".format(pred_weather['day']))
                                _data['night'] = translator.translate("During the night: {0}".format(pred_weather['night']))
                                _weather.predictions = _data
                            else:
                                _weather.predictions = pred_weather
                                _data = {'title':pred_weather['title']}
                                _data['day'] = "During the day: {0}".format(pred_weather['day'])
                                _data['night'] = "During the night: {0}".format(pred_weather['night'])
                                _weather.predictions = _data
                            _weather.save()

                        # if pred_weather['city']['name'].lower() == city.lower():
                        #     _weather = Weather(created_at=str(datetime.datetime.utcnow()), country=country, city=city.lower(), day=next_day)
                        #     predictions = {'03:00:00':{}, '06:00:00':{}, '09:00:00':{}, '12:00:00':{}, '15:00:00':{}, '18:00:00':{}, '21:00:00':{}, '00:00:00':{}}
                        #
                        #     for pred in pred_weather['list']:
                        #         for hour, val in predictions.items():
                        #             filterer = "{0} {1}".format(next_day, hour)
                        #             if pred["dt_txt"] == filterer:
                        #                 clim_content = ', '.join([w["description"] for w in pred["weather"]])
                        #                 if language not in ['en', 'unknown']:
                        #                     translator = Translator(to_lang=language)
                        #                     clim_content = translator.translate(clim_content)
                        #                 # Use the language here later to translate directly the news.
                        #                 predictions[hour]['climate'] = clim_content
                        #                 predictions[hour]['humidity'] = "{0} %".format(pred["main"]["humidity"])
                        #                 predictions[hour]['temp-min'] = "{0} C".format(str(pytemperature.k2c(pred["main"]["temp_min"])).split('.')[0])
                        #                 predictions[hour]['temp-max'] = "{0} C".format(str(pytemperature.k2c(pred["main"]["temp_max"])).split('.')[0])
                        #                 break
                        #     _weather.predictions = predictions
                        #     _weather.save()
                        # else:
                        #     unknown_cities.append(city.lower())
                    except:
                        unknown_cities.append(city.lower())
                data = {'unknown-cities':unknown_cities, 'country-cities':cities, 'cities-to-sync':cities_to_sync}
                data['country'] = country_code
                translator = Translator(to_lang=language)
                data['message'] = translator.translate('Weather in () tomorrow:')
                data['country_code'] = _country_name_short
                return service_response(200, 'Weather sync done.', data)
            else:
                return service_response(204, 'Weather not synched', 'It is not yet time to sync weather. country-time:{0}'.format(country_time))
    else:
        return service_response(405, 'Method not allowed', 'This endpoint supports only a GET method.')
Example #16
0
def _get_country_code(number):
    number = f"+{number}" if number[0] != "+" else number
    return region_code_for_country_code(
        parse_phone_number(number=number).country_code).lower()
    def save(self):
        if self.fname.get() == "" and self.pasw.get() == "" and self.email.get(
        ) == "" and self.gender.get() == "" and self.contact.get(
        ) == "" and self.code.get() == "Code":
            messagebox.showerror("Error!", "All Feilds Required")
        if self.fname.get() == '':
            return messagebox.showinfo('Error', 'Enter a firstname')

        if self.pasw.get() == '':
            return messagebox.showinfo('Error', 'Enter a password')

        if len(str(self.pasw.get())) < 8:
            return messagebox.showwarning(
                "Warning", "Password should be Minimum 8 charactrs")

        if self.contact.get() == '':
            return messagebox.showinfo('Error', 'Enter a contact')

        try:
            tmp = self.contact.get()
            int(tmp)
        except ValueError:
            return messagebox.showinfo('Error',
                                       'Contact No. Should Be Integer')

        if len(self.contact.get() + str(self.code.get())) < 10 and len(
                self.contact.get() + str(self.code.get())) > 15:
            return messagebox.showinfo('Error', 'Enter a valid contact')

        if self.email.get() == '':
            return messagebox.showinfo('Error', 'Enter an email')

        if self.gender.get() == '':
            return messagebox.showinfo('Error', 'Choose Gender')

        if self.code.get() == '':
            return messagebox.showinfo('Error', 'Choose Country Code')

        if "@" not in self.email.get():
            return messagebox.showwarning("Warrning",
                                          "Email should have '@' Character")
        # sdms>CREATE OR REPLACE TRIGGER update_last_login AFTER UPDATE OR INSERT ON admin FOR EACH ROW  BEGIN ; END;
        if self.today < self.DOB.get():
            return messagebox.showwarning("Error", "D.O.B not Possible")
        else:
            self.con2 = str(region_code_for_country_code(self.code.get()))
            #self.DOB=str(self.calendar)
            self.UID = random.randint(200000, 1000000)
            self.uname = self.fname.get() + str(random.randint(1000, 40000))

            self.conn = sqlite3.connect("sdms.db")
            self.c = self.conn.cursor()
            self.c.execute(
                "CREATE TABLE IF NOT EXISTS admin(UID TEXT UNIQUE NOT NULL ,first_name TEXT NOT NULL, last_name TEXT , uname TEXT PRIMARY KEY UNIQUE NOT NULL, pasw TEXT NOT NULL,Role TEXT,email TEXT NOT NULL, gender TEXT NOT NULL, code TEXT NOT NULL, contact TEXT NOT NULL, country TEXT, Joining TEXT, DOB TEXT, Time1 TIME )"
            )
            self.find_user = (
                "SELECT * FROM admin WHERE email= ?  or contact = ?")
            self.c.execute(str(self.find_user),
                           (self.email.get(), self.contact.get()))
            results = (self.c).fetchall()
            if results:
                messagebox.showerror("Error",
                                     "Email or Contact  is already Used")
            else:
                try:
                    self.c.execute(
                        "INSERT INTO admin (UID ,first_name,last_name,uname, pasw , Role,email, gender , code , contact , country , Joining , DOB , Time1 ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                        (self.UID, self.fname.get(), self.lname.get(),
                         self.uname, self.pasw.get(), self.Role,
                         self.email.get(), self.gender.get(), self.code.get(),
                         self.contact.get(), self.con2, self.today,
                         self.DOB.get(), self.Time1))
                    self.conn.commit()
                    self.c.close()
                    self.conn.close()
                    messagebox.showinfo(
                        "Successfull",
                        "Successfully Added Data, For Login Click on Back")
                    self.clear()
                except Exception:
                    messagebox.showerror(
                        "Error!!",
                        "Somthing went wrong not able to add data try again or for Login Click on Back"
                    )
                    self.clear()
def phone_country_alphanumeric(phone: str) -> bool:
    from phonenumbers.phonenumberutil import region_code_for_country_code

    # this list represents all countries without alphanumeric support or you need to apply for it.
    nonalphanumeric_countries = {
        "AS": "American Samoa",
        "AR": "Argentina",
        "AM": "Armenia",
        "BS": "Bahamas",
        "BE": "Belgium",
        "BY": "Belarus",
        "BZ": "Belize",
        "CA": "Canada",
        "KY": "Cayman Islands (UK)",
        "TD": "Chad",
        "CL": "Chile",
        "CN": "China",
        "CO": "Colombia",
        "CG": "Congo (Republic of the Congo)",
        "CR": "Costa Rica",
        "CU": "Cuba",
        "CZ": "Czech Republic",
        "DO": "Dominican Republic",
        "EC": "Ecuador",
        "EG": "Egypt",
        "SV": "El Salvador",
        "GF": "French Guiana",
        "GU": "Guam",
        "GT": "Guatemala",
        "HN": "Honduras",
        "HU": "Hungary",
        "IN": "India",
        "ID": "Indonesia",
        "IR": "Iran",
        "IL": "Israel",
        "JP": "Japan",
        "JO": "Jordan",
        "KZ": "Kazakhstan",
        "KE": "Kenya",
        "KW": "Kuwait",
        "KG": "Kyrgyzstan",
        "LB": "Lebanon",
        "MW": "Malawi",
        "MY": "Malaysia",
        "ML": "Mali",
        "MX": "Mexico",
        "MC": "Monaco",
        "MA": "Morocco",
        "MM": "Myanmar",
        "NA": "Namibia",
        "NR": "Nauru",
        "NP": "Nepal",
        "NZ": "New Zealand",
        "NI": "Nicaragua",
        "OM": "Oman",
        "PK": "Pakistan",
        "PS": "Palestine",
        "PA": "Panama",
        "PE": "Peru",
        "PH": "Philippines",
        "PR": "Puerto Rico",
        "QA": "Qatar",
        "RU": "Russia",
        "SA": "Saudi Arabia",
        "ZA": "South Africa",
        "KR": "South Korea",
        "LK": "Sri Lanka",
        "SD": "Sudan",
        "SY": "Syria",
        "TW": "Taiwan",
        "TZ": "Tanzania",
        "TH": "Thailand",
        "TN": "Tunisia",
        "TR": "Turkey",
        "UA": "Ukraine",
        "AE": "United Arab Emirates",
        "US": "United States",
        "UY": "Uruguay",
        "VE": "Venezuela",
        "YE": "Yemen",
        "ZM": "Zambia",
        "ZW": "Zimbabwe",
    }
    pn = phonenumbers.parse(phone)
    if region_code_for_country_code(
            pn.country_code) in nonalphanumeric_countries:
        return False
    else:
        return True
Example #19
0
    def validate(self, data):
        reservation = self.instance
        request_user = self.context['request'].user
        # this check is probably only needed for PATCH
        try:
            resource = data['resource']
        except KeyError:
            resource = reservation.resource
            data.update({'resource': resource})

        if not data.get('begin', None):
            data.update({'begin': reservation.begin})

        if not data.get('end', None):
            data.update({'end': reservation.end})

        if not resource.can_make_reservations(request_user):
            raise PermissionDenied(
                _('You are not allowed to make reservations in this resource.')
            )

        if data['end'] < timezone.now():
            raise ValidationError(
                _('You cannot make a reservation in the past'))

        if resource.min_age and is_underage(request_user, resource.min_age):
            raise PermissionDenied(
                _('You have to be over %s years old to reserve this resource' %
                  (resource.min_age)))

        if resource.max_age and is_overage(request_user, resource.max_age):
            raise PermissionDenied(
                _('You have to be under %s years old to reserve this resource'
                  % (resource.max_age)))

        is_resource_admin = resource.is_admin(request_user)
        is_resource_manager = resource.is_manager(request_user)

        if not isinstance(request_user, AnonymousUser):
            if request_user.preferred_language is None:
                request_user.preferred_language = settings.LANGUAGES[0][0]
                request_user.save()

        if not resource.can_ignore_opening_hours(request_user):
            reservable_before = resource.get_reservable_before()
            if reservable_before and data['begin'] >= reservable_before:
                raise ValidationError(
                    _('The resource is reservable only before %(datetime)s' %
                      {'datetime': reservable_before}))
            reservable_after = resource.get_reservable_after()
            if reservable_after and data['begin'] < reservable_after:
                raise ValidationError(
                    _('The resource is reservable only after %(datetime)s' %
                      {'datetime': reservable_after}))

        # Check given home municipality is included in resource's home municipality set
        if 'home_municipality' in data:
            included = resource.get_included_home_municipality_names()
            found = False

            for municipality in included:
                if data['home_municipality'].id == municipality['id']:
                    found = True
                    break

            if not found:
                raise ValidationError(
                    _('Home municipality has to be one of the included home municipality options'
                      ))

        # normal users cannot make reservations for other people
        if not resource.can_create_reservations_for_other_users(request_user):
            data.pop('user', None)

        # Check user specific reservation restrictions relating to given period.
        resource.validate_reservation_period(reservation,
                                             request_user,
                                             data=data)
        reserver_phone_number = data.get('reserver_phone_number', '')
        if reserver_phone_number.startswith('+'):
            if not region_code_for_country_code(
                    phonenumbers.parse(reserver_phone_number).country_code):
                raise ValidationError(
                    dict(reserver_phone_number=_('Invalid country code')))

        if data.get('staff_event', False):
            if not resource.can_create_staff_event(request_user):
                raise ValidationError(
                    dict(staff_event=_(
                        'Only allowed to be set by resource managers')))

        if 'type' in data:
            if (data['type'] != Reservation.TYPE_NORMAL
                    and not resource.can_create_special_type_reservation(
                        request_user)):
                raise ValidationError({
                    'type':
                    _('You are not allowed to make a reservation of this type')
                })

        if 'comments' in data:
            if not resource.can_comment_reservations(request_user):
                raise ValidationError(
                    dict(
                        comments=_('Only allowed to be set by staff members')))

        if 'access_code' in data:
            if data['access_code'] is None:
                data['access_code'] = ''

            access_code_enabled = resource.is_access_code_enabled()

            if not access_code_enabled and data['access_code']:
                raise ValidationError(
                    dict(access_code=_(
                        'This field cannot have a value with this resource')))

            if access_code_enabled and reservation and data[
                    'access_code'] != reservation.access_code:
                raise ValidationError(
                    dict(access_code=_('This field cannot be changed')))

        # Mark begin of a critical section. Subsequent calls with this same resource will block here until the first
        # request is finished. This is needed so that the validations and possible reservation saving are
        # executed in one block and concurrent requests cannot be validated incorrectly.
        Resource.objects.select_for_update().get(pk=resource.pk)

        # Check maximum number of active reservations per user per resource.
        # Only new reservations are taken into account ie. a normal user can modify an existing reservation
        # even if it exceeds the limit. (one that was created via admin ui for example).
        if reservation is None and not isinstance(request_user, AnonymousUser):
            resource.validate_max_reservations_per_user(request_user)

        # Run model clean
        instance = Reservation(**data)
        try:
            instance.clean(original_reservation=reservation, user=request_user)
        except DjangoValidationError as exc:
            # Convert Django ValidationError to DRF ValidationError so that in the response
            # field specific error messages are added in the field instead of in non_field_messages.
            if not hasattr(exc, 'error_dict'):
                raise ValidationError(exc)
            error_dict = {}
            for key, value in exc.error_dict.items():
                error_dict[key] = [error.message for error in value]
            raise ValidationError(error_dict)
        return data
Example #20
0
 def update(self):
     if str(self.role.get()) == "Service_Provider":
         try:
             self.con2 = str(region_code_for_country_code(self.code.get()))
             self.conn=sqlite3.connect("bakery.db")
             self.c=self.conn.cursor()
             self.c.execute("SELECT * from Emp WHERE EmpID="+str(self.EID.get()))
             self.data=self.c.fetchall()
             if self.data:
                     for i in self.data:
                         print(i)
                     a=(str(i[4])) 
                     y=\
                     """UPDATE Emp SET EmpID  =\"""" + self.EID.get()+\
                     """\" , EmpName   =\""""+ self.Name.get()+\
                     """\" , Email    =\""""+ self.Email.get()+\
                     """\" , Country_Code =\""""+ str(self.code.get())+\
                     """\" , Country   =\""""+ str(self.con2)+\
                     """\" , Phone_No  =\""""+ str(self.contact.get()) +\
                     """\" , Password  =\""""+ self.pass_.get() +\
                     """\" , ZoneID   =\""""+ self.zoneID.get()+\
                     """\" , BranchID  =\""""+ self.branchID.get() +\
                     """ \""""
                     y=y+" WHERE EmpID= "+self.EID.get()
                     #print(str(y))              
                     self.c.execute(y)
                     self.conn.commit()
                     return messagebox.showinfo("Info"," Data Updated")
                     self.conn.close()
             else:
                 return messagebox.showerror("Error","Employee ID No not Matched")
         except Exception:
             return messagebox.showerror("Error!!","Somthing went wrong not able to add data try again ")
     
     else:
         try:
             self.con2 = str(region_code_for_country_code(self.code.get()))
             self.conn=sqlite3.connect("bakery.db")
             self.c=self.conn.cursor()
             self.c.execute("SELECT * from Bakers WHERE Baker_ID="+str(self.EID.get()))
             self.data=self.c.fetchall()
             if self.data:
                     for i in self.data:
                         print(i)
                     a=(str(i[4])) 
                     y=\
                     """UPDATE Emp SET Baker_ID  =\"""" + self.EID.get()+\
                     """\" , Name   =\""""+ self.Name.get()+\
                     """\" , Email    =\""""+ self.Email.get()+\
                     """\" , Country_Code =\""""+ str(self.code.get())+\
                     """\" , Country   =\""""+ str(self.con2)+\
                     """\" , Phone_No  =\""""+ str(self.contact.get()) +\
                     """\" , Zone_ID   =\""""+ self.zoneID.get()+\
                     """\" , BranchID  =\""""+ self.branchID.get() +\
                     """ \""""
                     y=y+" WHERE Baker_ID= "+self.EID.get()
                     #print(str(y))              
                     self.c.execute(y)
                     self.conn.commit()
                     return messagebox.showinfo("Info"," Data Updated")
                     self.conn.close()
                     
             else:
                 return messagebox.showerror("Error","Baker ID No not Matched")
         except Exception:
                     return messagebox.showerror("Error!!","Somthing went wrong not able to add data try again ")
Example #21
0
    def add(self):
        if self.Name.get()=="" and self.pass_.get()=="" and self.Email.get()=="" and self.contact.get()=="" and self.code.get()==0 and self.role.get()=="" and self.zoneID.get()=="" and self.branchID.get()=="" :
            return messagebox.showerror("Error!","All Feilds Required")
        
        if self.Name.get()=='':
            return messagebox.showinfo('Error','Enter a Name')
        
        if self.Email.get()=='':
            return messagebox.showinfo('Error','Enter a Email address')

        if "@" not in self.Email.get():
            return messagebox.showwarning("Warrning","Email should have '@' Character")

            
        if self.pass_.get()=='':
            return messagebox.showinfo('Error','Enter a password')

        if len(str(self.pass_.get()))<8:
            return messagebox.showwarning("Warning","Password should be Minimum 8 charactrs")
        
        if self.contact.get()=='':
            return messagebox.showinfo('Error','Enter a contact')
        
        try:
            tmp=self.contact.get()
            int(tmp)
        except ValueError:
            return messagebox.showinfo('Error','Contact No. Should Be Integer')
        
        if len(self.contact.get()+str(self.code.get()))<10 and len(self.contact.get()+str(self.code.get()))>15:
            return messagebox.showinfo('Error','Enter a valid contact')      
        
        if self.code.get()==0:
            return messagebox.showinfo('Error','Choose Country Code')

        if self.role.get()=="Choose Role":
            return messagebox.showwarning("Warrning","Choose Role Please!!!")

        else:
            if str(self.role.get()) == "Service_Provider":
                self.con2 = str(region_code_for_country_code(self.code.get()))
                self.conn=sqlite3.connect("bakery.db")
                self.c=self.conn.cursor()
                self.c.execute("CREATE TABLE IF NOT EXISTS Emp(EmpID TEXT PRIMARY KEY ,EmpName TEXT, Email TEXT UNIQUE , Country_Code TEXT , Country TEXT, Phone_No TEXT UNIQUE, Password TEXT, FOREIGN KEY (ZoneID) REFERENCES Zone (Zone_ID),FOREIGN KEY (BranchID) REFERENCES Branch (Branch_ID) )")
                self.find_user = ("SELECT * FROM Emp WHERE Email= ?  or Phone_No = ?")
                self.c.execute(str(self.find_user),(self.Email.get(),self.contact.get()))
                results = (self.c).fetchall()
                if results:
                    messagebox.showerror("Error","Email or Contact  is already Used")
                else:
                    try:
                        self.c.execute("INSERT INTO Emp (EmpID, EmpName, Email, Country_Code, Country, Phone_No, Password, ZoneID, BranchID  ) VALUES (?,?,?,?,?,?,?,?,?)",
                        (self.EID.get(),self.Name.get(),str(self.Email.get()),str(self.code.get()),self.con2,self.contact.get(),self.pass_.get(),self.zoneID.get(),self.branchID.get()))
                        self.conn.commit()
                        self.c.close()
                        self.conn.close()
                        messagebox.showinfo("Successfull","Successfully Added Data")
                        self.clear()
                    except Exception:
                        return messagebox.showerror("Error!!","Somthing went wrong not able to add data try again ")
                        self.clear()        
            else:
                self.con2 = str(region_code_for_country_code(self.code.get()))
                self.conn=sqlite3.connect("bakery.db")
                self.c=self.conn.cursor()
                self.c.execute("CREATE TABLE IF NOT EXISTS Bakers(Baker_ID TEXT PRIMARY KEY ,Name TEXT, Email TEXT UNIQUE , Country_Code TEXT , Country TEXT, Phone_No TEXT UNIQUE, FOREIGN KEY (Zone_ID) REFERENCES Zone (Zone_ID),FOREIGN KEY (BranchID) REFERENCES Branch (Branch_ID) )")
                self.find_user = ("SELECT * FROM Bakers WHERE Email= ?  or Phone_No = ?")
                self.c.execute(str(self.find_user),(self.Email.get(),self.contact.get()))
                results = (self.c).fetchall()
                if results:
                    messagebox.showerror("Error","Email or Contact  is already Used")
                else:
                    try:
                        self.c.execute("INSERT INTO Bakers (Baker_ID, Name, Email, Country_Code, Country, Phone_No, Zone_ID, BranchID  ) VALUES (?,?,?,?,?,?,?,?)",
                        (self.EID.get(),self.Name.get(),str(self.Email.get()),str(self.code.get()),self.con2,self.contact.get(),self.zoneID.get(),self.branchID.get()))
                        self.conn.commit()
                        self.c.close()
                        self.conn.close()
                        messagebox.showinfo("Successfull","Successfully Added Data")
                        self.clear()
                    except Exception:
                        return messagebox.showerror("Error!!","Somthing went wrong not able to add data try again ")
                        self.clear()