def getAmazon(self): # Amazon requires a special header amazon_headers = { 'authority': 'www.amazon.com', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'dnt': '1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'document', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } print('Checking Amazon...\t', end='', flush='True') URL = 'https://www.amazon.com/PlayStation-5-Digital/dp/B08FC6MR62/ref=sr_1_7?crid=GPI3HCDC7U4D&dchild=1&keywords=ps5+digital+edition&qid=1609975951&sprefix=ps5+d%2Caps%2C172&sr=8-7' stock_text = re.compile('currently unavailable|available from these') try: page = requests.get(URL, headers=amazon_headers) soup = BeautifulSoup(page.content, 'html.parser') inventory = 0 totalinventory = 2 # Digital unavailable_text = soup.select( "span.a-size-medium")[0].text.lower().strip() in_stock = not re.search(stock_text, unavailable_text) if in_stock: inventory += 1 link = URL if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('PS5', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} PS5 found: {}'.format(getTime(), link)) # writeToFile(URL) # return 1 # Disc URL = 'https://www.amazon.com/PlayStation-5-Console/dp/B08FC5L3RG/ref=sr_1_4?dchild=1&keywords=ps5&qid=1609975756&sr=8-4' page = requests.get(URL, headers=amazon_headers) soup = BeautifulSoup(page.content, 'html.parser') unavailable_text = soup.select( "span.a-size-medium")[0].text.lower().strip() in_stock = not re.search(stock_text, unavailable_text) if in_stock: inventory += 1 link = URL if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('PS5', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} PS5 found: {}'.format(getTime(), link)) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve amazon data. [{}]'.format(e))
def do_login(self, loginText, passwordText): app = App.get_running_app() app.username = loginText app.password = passwordText if app.password == "": Alert('Error', 'Invalid Username or password') else: con = cx_Oracle.connect('meetapp/meetapp@localhost') # Now execute the sqlquery cursor = con.cursor() cursor.execute( "select id from auth_user where username=:user_name", user_name=loginText) row = cursor.fetchone() cursor.close() if row != None: global uid uid = row[0] self.manager.transition = SlideTransition(direction="left") self.manager.current = 'connected' else: Alert('Error', 'Invalid Username or password') self.resetForm() app.config.read(app.get_application_config()) app.config.write()
def _earlyWarning(self, spoofer, target): if (spoofer in self.spoofer_list): pass else: self.spoofer_list.append(spoofer) # WINDOW: spoofing detected ! alert = Alert("'Etherwall - ARP Spoofing Detected !'","'ARP from %s [%s] \npretends to be %s.'" % (spoofer.split()[0],spoofer.split()[1],target),self.msgbox) alert.start()
def __init__(self): ''' Constructor ''' Alert.__init__(self) self._mailServer = config.param['mailServer'] # The SMTP server. self._mailRecipient = config.param['mailRecipient'] # The recipient for notification mails. self._mailSender = config.param['mailSender'] # The sender for notification mails.
def blockAccountCallback(self): try: result = changeAccountStatus(readToken(), self.accountNumberTextInput.text.strip(), BLOCKED) if result == None: raise Exception self.app.screenManager.current = MENU_SCREEN Alert(title="Success", text='Account Successfully Blocked') except Exception: Alert(title="Input Error", text='Invalid Account Number! Try Again')
def _earlyWarning(self, spoofer, target): if (spoofer in self.spoofer_list): pass else: self.spoofer_list.append(spoofer) # WINDOW: spoofing detected ! alert = Alert( "'Etherwall - ARP Spoofing Detected !'", "'ARP from %s [%s] \npretends to be %s.'" % (spoofer.split()[0], spoofer.split()[1], target), self.msgbox) alert.start()
def loginCallback(self): if len(self.usernameTextInput.text.strip()) == 0 or len(self.passwordTextInput.text.strip()) == 0: Alert(title="Input Error", text='Empty Fields are not Allowed Here! Try Again') return tokenStored = False try: tokenStored = storeToken(self.usernameTextInput.text.strip(), self.passwordTextInput.text.strip()) except: Alert(title="Connection Error", text='Connection Error, Try Again Later') return if tokenStored: self.app.screenManager.current = MENU_SCREEN return Alert(title="Auhthentication Error", text='Invalid Username or Password, Try Again')
def addAccountCallback(self): if len(self.nationalCodeTextInput.text.strip()) == 0: Alert(title="Input Error", text='Empty Field! Try Again') return try: result = addAccount(readToken(), self.nationalCodeTextInput.text.strip()) if result == None: raise Exception self.app.screenManager.current = MENU_SCREEN Alert(title="Success", text='Account<%s> Successfully Created' % result['accountNumber']) except Exception: Alert(title="Input Error", text='Invalid National Code! Try Again')
class Test_is_in_range_and_distance(object): @classmethod def setup_class(self): """ Setup code run before any tests are run """ self.alert = Alert({ 'id': None, 'onsetDate': None, 'expireDate': None, 'isUpdate': False, 'isCancel': False, 'locations':[] }) @classmethod def teardown_class(self): """ Teardown code run after all tests are run """ self.alert = None def setUp(self): """ Run before each test method is run """ del self.alert.locations[:] self.alert.add_all_locations([(00.00, 00.00), (77.77, 77.77)]) self.alert.isCancel = False def test_is_in_range_happy_path(self): assert_true(self.alert.is_in_range((00.00, 00.00), 1.0)) assert_false(self.alert.is_in_range((90.00, 00.00), 1.0)) def test_is_in_range_max(self): assert_true(self.alert.is_in_range((00.14, 00.00), 10.0)) assert_false(self.alert.is_in_range((00.15, 00.00), 10.0)) def test_is_in_range_negative_num(self): assert_false(self.alert.is_in_range((00.00, 00.00), -10.0)) def test_is_in_range_canceled_alert(self): assert_true(self.alert.is_in_range(00.00, 00.00), 1.0) self.alert.isCancel = True assert_false(self.alert.is_in_range(00.00, 00.00), 1.0) def test_distance_happy_path(self): assert_almost_equal(self.alert.distance((00.00, 00.00)), 0) assert_almost_equal(self.alert.distance((00.14, 00.00)), 9.675790717)
def getNewEgg(self): print('Checking Newegg...\t', end='', flush='True') URL = 'https://www.newegg.com/p/pl?nm_mc=AFC-RAN-COM&cm_mmc=AFC-RAN-COM&utm_medium=affiliates&utm_source=afc' \ '-GameSpot&AFFID=2424817&AFFNAME=GameSpot&ACRID=1&ASUBID=gs-gs11006475811-dtp-en%7Cxid%3Afr1605967179676ech' \ '&ASID=https%3A%2F%2Fwww.gamespot.com%2F&ranMID=44583&ranEAID=2424817&ranSiteID=VZfI20jEa0c' \ '-qpsf9RpsZIMhmwLtRMkO0w&N=101696840%204021 ' try: page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') ps5_elems = soup.find_all(class_='item-container') inventory = 0 totalinventory = len(ps5_elems) for ps5_elem in ps5_elems: in_stock = ps5_elem.find(class_='item-button-area').text.lower( ).strip().__contains__('add') if in_stock: inventory += 1 link = ps5_elem.find('a')['href'] if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.SMS_FLAG or self.EMAIL_FLAG: Alert('PS5', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} PS5 found: {}'.format(getTime(), link)) # writeToFile(link) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve Newegg data [{}]'.format(e))
def signup(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] dao = UserDAO() user = dao.signup_user(username, password) ldao = LogDAO() if not user: ldao.add_log(request, None, ldao.REQUEST_SIGNUP, 0) resp = make_response(redirect("/signup?alert=Username is Already Taken|Try another username and sign up again.|alert-fail")) return resp else: ldao.add_log(request, user.username, ldao.REQUEST_SIGNUP, 1) resp = make_response(redirect("/?alert=Sign Up Success|Start creating and browsing awesome recipes.|alert-suc")) resp.set_cookie("signedIn", "true") resp.set_cookie("user", user.username) resp.set_cookie("session_key", user.sessionKey) return resp else: alertParam = request.args.get("alert") alert = None if alertParam: alertData = urllib.parse.unquote(alertParam) alertData = alertData.split("|") alert = Alert(alertData[0], alertData[1], alertData[2]) resp = make_response(render_template("signup.html", signedIn = request.cookies.get("signedIn"), user = request.cookies.get("user"), alert = alert)) return resp
def getNewEgg(self): print('Checking Newegg...\t', end='', flush='True') URL = 'https://www.newegg.com/p/pl?d=3060+ti&LeftPriceRange=399+450' # Price Range: $399 - $450 try: page = requests.get(URL, headers=self.headers) soup = BeautifulSoup(page.content, 'html.parser') rtx_elems = soup.find_all(class_='item-container') inventory = 0 totalinventory = len(rtx_elems) for rtx_elem in rtx_elems: product_name = rtx_elem.find(class_='item-title').text.strip() in_stock = rtx_elem.find(class_='item-button-area').text.lower( ).strip().__contains__('add') if in_stock: inventory += 1 link = rtx_elem.find('a')['href'] webbrowser.open_new_tab(link) Alert('3060Ti', link) print( colored( '{} 3060 Ti found: {}'.format( self.getTime(), link), 'green')) # writeToFile(link) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve Newegg data [{}]'.format(e))
def getBestBuy(self): print('Checking BestBuy...\t', end='', flush='True') URL = 'https://www.bestbuy.com/site/searchpage.jsp?_dyncharset=UTF-8&id=pcat17071&iht=y&keys=keys&ks=960&list=n&qp=currentprice_facet%3DPrice~699.99%20to%20750&sc=Global&st=rtx%203080&type=page&usc=All%20Categories' stock_available = re.compile('add|see details') try: page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') rtx_elems = soup.find_all(class_='fulfillment-add-to-cart-button') inventory = 0 totalinventory = len(rtx_elems) for rtx_elem in rtx_elems: add_to_cart_text = rtx_elem.text.lower() in_stock = re.search(stock_available, add_to_cart_text) if in_stock: inventory += 1 link = 'https://www.bestbuy.com' + rtx_elem.find('a')['href'] if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('3080', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} 3080 found: {}'.format(getTime(), link)) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except(ConnectionError, Exception) as e: print('Exception trying to retrieve bestbuy data. [{}]'.format(e))
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] dao = UserDAO() user = dao.login_user(username, password) ldao = LogDAO() if user == None: ldao.add_log(request, None, ldao.REQUEST_SIGNIN, 0) return redirect("/login?alert=Sign In Failed!|Make sure the details you entered are correct and try again.|alert-fail") else: ldao.add_log(request, user.username, ldao.REQUEST_SIGNIN, 1) resp = make_response(redirect("/?alert=Sign In Success|Start creating and browsing awesome recipes.|alert-suc")) resp.set_cookie("signedIn", "true") resp.set_cookie("user", user.username) resp.set_cookie("session_key", user.sessionKey) return resp elif request.method == 'GET': alertParam = request.args.get("alert") alert = None if alertParam: alertData = urllib.parse.unquote(alertParam) alertData = alertData.split("|") alert = Alert(alertData[0], alertData[1], alertData[2]) return render_template("login.html", signedIn = request.cookies.get("signedIn"), user = request.cookies.get("user"), alert = alert)
def getNewEgg(self): print('Checking Newegg...\t', end='', flush='True') URL = 'https://www.newegg.com/p/pl?d=rtx+3080&LeftPriceRange=699+900' # Price Range: $699 - $900 try: page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') rtx_elems = soup.find_all(class_='item-button-area') inventory = 0 totalinventory = len(rtx_elems) for rtx_elem in rtx_elems: if rtx_elem.__eq__(None): totalinventory -= 1 continue in_stock = rtx_elem.text.lower().strip().__contains__('add') if in_stock: inventory += 1 link = rtx_elem.find('a')['href'] if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('3080', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} 3080 found: {}'.format(getTime(), link)) # writeToFile(link) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except(ConnectionError, Exception) as e: print('Exception trying to retrieve Newegg data [{}]'.format(e))
def getBestBuy(self): print('Checking BestBuy...\t', end='', flush='True') URL = 'https://www.bestbuy.com/site/searchpage.jsp?st=%223060+Ti%22&_dyncharset=UTF-8&_dynSessConf=&id=pcat17071&type=page&sc=Global&cp=1&nrp=&sp=&qp=&list=n&af=true&iht=y&usc=All+Categories&ks=960&keys=keys' try: page = requests.get(URL, headers=self.headers) soup = BeautifulSoup(page.content, 'html.parser') rtx_elems = soup.find_all(class_='fulfillment-add-to-cart-button') inventory = 0 totalinventory = len(rtx_elems) for rtx_elem in rtx_elems: in_stock = rtx_elem.text.lower().__contains__('add') if in_stock: inventory += 1 link = 'https://www.bestbuy.com' + rtx_elem.find( 'a')['href'] webbrowser.open_new_tab(link) Alert('3060Ti', link) print( colored( '{} 3060 Ti found: {}'.format( self.getTime(), link), 'green')) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve bestbuy data. [{}]'.format(e))
def getBestBuy(self): print('Checking BestBuy...\t', end='', flush='True') URL = 'https://www.bestbuy.com/site/playstation-5/ps5-consoles/pcmcat1587395025973.c?id=pcmcat1587395025973' try: page = requests.get(URL, headers=self.headers) soup = BeautifulSoup(page.content, 'html.parser') ps5_elems = soup.find_all(class_='fulfillment-add-to-cart-button') inventory = 0 totalinventory = len(ps5_elems) for ps5_elem in ps5_elems: in_stock = ps5_elem.text.lower().__contains__('add') if in_stock: inventory += 1 link = 'https://www.bestbuy.com' + ps5_elem.find( 'a')['href'] webbrowser.open_new_tab(link) Alert('PS5', link) print( colored( '{} PS5 found: {}'.format(self.getTime(), link), 'green')) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve bestbuy data. [{}]'.format(e))
def getBestBuy(self): print('Checking BestBuy...\t', end='', flush='True') URL = 'https://www.bestbuy.com/site/playstation-5/ps5-consoles/pcmcat1587395025973.c?id=pcmcat1587395025973' stock_available = re.compile('add|see details') try: page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') ps5_elems = soup.find_all(class_='fulfillment-add-to-cart-button') inventory = 0 totalinventory = len(ps5_elems) for ps5_elem in ps5_elems: add_to_cart_text = ps5_elem.text.lower() in_stock = re.search(stock_available, add_to_cart_text) if in_stock: inventory += 1 link = 'https://www.bestbuy.com' + ps5_elem.find( 'a')['href'] if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('PS5', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} PS5 found: {}'.format(getTime(), link)) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve bestbuy data. [{}]'.format(e))
def getNewEgg(self): print('Checking Newegg...\t', end='', flush='True') URL = 'https://www.newegg.com/amd-ryzen-5-5600x/p/N82E16819113666?Description=ryzen%205600x&cm_re=ryzen_5600x-_-19-113-666-_-Product' try: page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') product = soup.find(class_='product-buy-box') inventory = 0 totalinventory = 1 price = Decimal(re.sub(r'[^\d.]', '', product.find('li', class_='price-current').text.strip())) in_stock = product.find(class_='btn btn-primary btn-wide') and price < 310 if in_stock: inventory += 1 if self.LINK_FLAG: webbrowser.open_new_tab(URL) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('5600X', URL, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} 5600X found: {}'.format(getTime(), URL)) # writeToFile(link) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except(ConnectionError, Exception) as e: print('Exception trying to retrieve Newegg data [{}]'.format(e))
def showRangeLogsCallback(self): temp = self.ids.customRangeTextInput.text.split('-') args = None try: i = int(temp[0]) j = int(temp[1]) if (j-i+1) > 15: raise Exception if j>len(self.logs): raise Exception args = (self.bars['names'][i:j+1], self.bars['baseBar'][i:j+1],\ self.bars['greenBar'][i:j+1], self.bars['redBar'][i:j+1],\ self.bars['y'][i:j+1]) if len(args[0]) == 0: raise Exception except Exception: Alert(title="Input Error", text='Invalid Range! Try Again') return length = len(args[0]) argv = str(length)+' ' for item in args: for n in item: if type(n) == str: argv += ''.join(n.split()) + ' ' else: argv += str(n) + ' ' runCommand('python ./modules/turtles.py '+argv[:-1])
def recv(self): msg = self.s.recv(4092) if msg == b'': self.close() return None if int.from_bytes(msg[0:1], 'big') == TLS_ALERT_RECORD_TYPE: return Alert(parse=msg)
def showDescribtionCallback(self, text): text = text.strip() if len(text) == 0: text = '-- No Describtion --' Alert(title="Transaction Describtion", text=text, time=3, linesNumber=1)
def signUpCallback(self): if len(self.usernameTextInput.text.strip()) == 0 \ or len(self.passwordTextInput.text.strip()) == 0\ or len(self.repeatPasswordTextInput.text.strip()) == 0: Alert(title="Input Error", text='Empty Fields are not Allowed Here! Try Again') return if not self.passwordTextInput.text.strip() ==\ self.repeatPasswordTextInput.text.strip(): Alert(title="Input Error", text='Passwords do not match! Try Again') return try: resultCode = signUp(readToken(), self.usernameTextInput.text.strip(), self.passwordTextInput.text.strip()) if resultCode == INVALID_TOKEN_CODE: removeToken() self.app.screenManager.current = LOGIN_SCREEN Alert(title="Authentication Error", text='Please Login Again') elif resultCode == INVALID_CODE: Alert(title="Input Error", text='User with this Username Already Exists!') elif resultCode == POST_SUCCESS_CODE: self.app.screenManager.current = MENU_SCREEN Alert(title="Success", text='New Clerk Successfully Registered') else: self.app.screenManager.current = MENU_SCREEN Alert(title="Register Error", text='Please Try Again Later') except Exception: Alert(title="Connection Error", text='Connection Error, Try Again Later')
def showLogsCallback(self, accountID, ownerName): logs = getAccountLogs(readToken(), int(accountID)) if logs == None: removeToken() self.app.screenManager.current = LOGIN_SCREEN Alert(title="Authentication Error", text='Please Login Again') return currentCredit = logs['currentCredit'] logs = logs['logs'] if len(logs) == 0: Alert(title="Account Logs", text='There are no logs to show!', time=3, linesNumber=1) return logsPopup = ShowLogsPopUp(logs, currentCredit, accountID, ownerName) popUpWindow = Popup(title="Logs", content=logsPopup, size_hint = (None, None), size=(400,400)) popUpWindow.open() return
def getWalmart(self): print('Checking Walmart...\t', end='', flush='True') try: # PS5 Digital Edition URL = 'https://www.walmart.com/ip/Sony-PlayStation-5-Digital-Edition/493824815' page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') inventory = 0 totalinventory = 2 in_stock = not soup.find( 'span', class_='prod-product-cta-add-to-cart display-inline-block' ).__eq__(None) if in_stock: inventory += 1 if self.LINK_FLAG: webbrowser.open_new_tab(URL) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('PS5 Digital', URL, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} PS5 found: {}'.format(getTime(), URL)) # writeToFile(URL) # return 1 # PS5 Disc Edition URL = 'https://www.walmart.com/ip/PlayStation-5-Console/363472942' page = requests.get(URL, headers=self.HEADERS) soup = BeautifulSoup(page.content, 'html.parser') in_stock = not soup.find( 'span', class_='prod-product-cta-add-to-cart display-inline-block' ).__eq__(None) if in_stock: inventory += 1 if self.LINK_FLAG: webbrowser.open_new_tab(URL) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('PS5', URL, self.EMAIL_FLAG, self.SMS_FLAG) print('{} PS5 found: {}'.format(getTime(), URL)) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print('Exception trying to retrieve walmart data. [{}]'.format(e))
def run(self, context): self.log = context["log"] self.config = context["systemConfig"] self.log.debug("Started alerts processing.") #self.log.debug("Alert config: " + self.config.toString(True)) ## Determine ReDBox version in system-config self.redboxVersion = self.config.getString(None, "redbox.version.string") self.log.debug("ReDBox version is %s" % self.redboxVersion) if self.redboxVersion is None: self.log.debug("ReDBox version was not provided in the config") raise AlertException("Unable to determine configuration") tmpConf = self.config.getObject('new-alerts') if tmpConf is None: self.log.info("No alert configuration was provided") return False self.alertsConfig = mapMapFromJava(tmpConf) baseline = {} if "baseline" in self.alertsConfig: baseline = self.alertsConfig["baseline"] if not 'alertSet' in self.alertsConfig: raise AlertException("Unable to determine configuration") for alertItem in self.alertsConfig["alertSet"]: self.log.info("Processing alert: %s." % alertItem["name"]) try: alert = Alert(self.redboxVersion, alertItem, baseline, self.log) alert.processAlert() except Exception, e: #The Alert class will log this for us so continue to the next alert #Some exceptions stop an alert from running at all so log them just in case self.log.error( "Alert [%s] encountered problems - please review the log files in the associated .processed directory. Exception was: %s" % (alertItem["name"], e.message))
def setup_class(self): """ Setup code run before any tests are run """ self.alert = Alert({ 'id': None, 'onsetDate': None, 'expireDate': None, 'isUpdate': False, 'isCancel': False, 'locations':[] })
def setup_class(self): """ Setup code run before any tests are run """ self.alert = Alert({ 'id': 'testAlert', 'onsetDate': datetime(1997, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'expireDate': datetime(2000, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'isUpdate': False, 'isCancel': False, 'locations':[] })
def __init__(self, app, **kwargs): super(TransactionsListScreen, self).__init__(**kwargs) self.app = app self.ids.rv.data = [] result = getAllTransactions(readToken()) self.allResults = [] if result == None: removeToken() self.app.screenManager.current = LOGIN_SCREEN Alert(title="Authentication Error", text='Please Login Again') else: self.allResults = result[:]
def createAccountCallback(self): if len(self.firstNameTextInput.text.strip()) == 0 \ or len(self.lastNameTextInput.text.strip()) == 0\ or len(self.phoneNumberTextInput.text.strip()) == 0\ or len(self.nationalCodeTextInput.text.strip()) == 0: Alert(title="Input Error", text='Empty Fields are not Allowed Here! Try Again') return try: resultCode = createAccount(readToken(), \ self.firstNameTextInput.text.strip(), \ self.lastNameTextInput.text.strip(), \ self.phoneNumberTextInput.text.strip(), \ self.nationalCodeTextInput.text.strip()) if resultCode == INVALID_TOKEN_CODE: removeToken() self.app.screenManager.current = LOGIN_SCREEN Alert(title="Authentication Error", text='Please Login Again') elif resultCode == DUPLICATE_CODE: Alert(title="Input Error", text='Owner with this ID Already Exists!') elif resultCode == POST_SUCCESS_CODE: self.app.screenManager.current = MENU_SCREEN Alert(title="Success", text='New Account Successfully Created') else: self.app.screenManager.current = MENU_SCREEN Alert(title="Create Account Error", text='Please Try Again Later') except Exception: Alert(title="Connection Error", text='Connection Error, Try Again Later')
def run(self, context): self.log = context["log"] self.config = context["systemConfig"] self.log.debug("Started alerts processing.") #self.log.debug("Alert config: " + self.config.toString(True)) ## Determine ReDBox version in system-config self.redboxVersion = self.config.getString(None, "redbox.version.string") self.log.debug("ReDBox version is %s" % self.redboxVersion) if self.redboxVersion is None: self.log.debug("ReDBox version was not provided in the config") raise AlertException("Unable to determine configuration") tmpConf = self.config.getObject('new-alerts') if tmpConf is None: self.log.info("No alert configuration was provided") return False self.alertsConfig = mapMapFromJava(tmpConf) baseline = {} if "baseline" in self.alertsConfig: baseline = self.alertsConfig["baseline"] if not 'alertSet' in self.alertsConfig: raise AlertException("Unable to determine configuration") for alertItem in self.alertsConfig["alertSet"]: self.log.info("Processing alert: %s." % alertItem["name"]) try: alert = Alert(self.redboxVersion, alertItem, baseline, self.log) alert.processAlert() except Exception, e: #The Alert class will log this for us so continue to the next alert #Some exceptions stop an alert from running at all so log them just in case self.log.error("Alert [%s] encountered problems - please review the log files in the associated .processed directory. Exception was: %s" % (alertItem["name"], e.message))
def index(): if request.method == 'GET': alertParam = request.args.get("alert") alert = None if alertParam: alertData = urllib.parse.unquote(alertParam) alertData = alertData.split("|") alert = Alert(alertData[0], alertData[1], alertData[2]) resp = make_response(render_template('index.html', signedIn = request.cookies.get("signedIn"), user = request.cookies.get("user"), alert = alert)) return resp
def update_total_request_report(self, nb_logs): """ Function that computes the report for the average total traffic. The function manage also alerts if any. Parameters ---------- nb_logs : int number of new logs that appeared since last update """ # update the total traffic using a fixed size queue if len(self.sliding_requests_number) == 120: self.total_traffic_120 -= self.sliding_requests_number.popleft() self.sliding_requests_number.append(nb_logs) self.total_traffic_120 += nb_logs # compute the average traffic avg_total_traffic = self.total_traffic_120 / 120 # create report and update traffic report report = f"Average total taffic: {avg_total_traffic:.2f} req/s over 2min-sliding window" if True: report += f" (last update: {format_time(time.time()+self.stream.get_offset_ms())})" report += "\n" self.avg_total_traffic_report = report # Handle alerts if self.alert: # resolve alert if the condition is satisfied if avg_total_traffic < self.avg_trafic_threshold: self.alert = False alert_time = time.time() + self.stream.get_offset_ms() self.alert_list[-1].resolve(alert_time) self.update_alert_report() else: # trigger and alert if the threshold was exceeded if avg_total_traffic >= self.avg_trafic_threshold: self.alert = True alert_time = time.time() + self.stream.get_offset_ms() self.alert_list.append(Alert(alert_time, avg_total_traffic)) self.update_alert_report()
def getAmazon(self): # Amazon requires a special header amazon_headers = { 'authority': 'www.amazon.com', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'dnt': '1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'document', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } print('Checking Amazon...\t', end='', flush='True') URL = 'https://www.amazon.com/AMD-Ryzen-5600X-12-Thread-Processor/dp/B08166SLDF?ref_=ast_sto_dp' stock_text = re.compile('currently unavailable|available from these') try: page = requests.get(URL, headers=amazon_headers) soup = BeautifulSoup(page.content, 'html.parser') inventory = 0 totalinventory = 1 # Digital unavailable_text = soup.select("span.a-size-medium")[0].text.lower().strip() in_stock = not re.search(stock_text, unavailable_text) if in_stock: inventory += 1 link = URL if self.LINK_FLAG: webbrowser.open_new_tab(link) if self.EMAIL_FLAG or self.SMS_FLAG: Alert('R5600X', link, self.EMAIL_FLAG, self.SMS_FLAG) print('\n{} R5600X found: {}'.format(getTime(), link)) # writeToFile(URL) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except(ConnectionError, Exception) as e: print('Exception trying to retrieve amazon data. [{}]'.format(e))
class Test_gets(object): @classmethod def setup_class(self): """ Setup code run before any tests are run """ self.alert = Alert({ 'id': 'testAlert', 'onsetDate': datetime(1997, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'expireDate': datetime(2000, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'isUpdate': False, 'isCancel': False, 'locations':[] }) self.alert.add_all_locations([(00.00, 00.00), (11.11, 11.11)]) @classmethod def teardown_class(self): """ Teardown code run after all tests are run """ self.alert = None def test_get_id_happy_path(self): assert_equal(self.alert.get_id(), 'testAlert') assert_equal(self.alert.get_id(), self.alert.id) def test_get_onsetDate_happy_path(self): assert_equal(self.alert.get_onsetDate(), datetime(1997, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600))) assert_equal(self.alert.get_onsetDate(), self.alert.onsetDate) def test_get_expireDate_happy_path(self): assert_equal(self.alert.get_expireDate(), datetime(2000, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600))) assert_equal(self.alert.get_expireDate(), self.alert.expireDate) def test_get_locations_happy_path(self): assert_equal(self.alert.get_locations(), [(00.00, 00.00), (11.11, 11.11)]) assert_equal(self.alert.get_locations(), self.alert.locations) def test_get_isUpdate_happy_path(self): assert_equal(self.alert.get_isUpdate(), False) assert_equal(self.alert.get_isUpdate(), self.alert.isUpdate)
def getSamsClub(self): print('Checking Sams Club...\t', end='', flush='True') URL = 'https://www.samsclub.com/b/Playstation%205/1206?clubId=6636&offset=0&rootDimension=pcs_availability%253AOnlinepipsymbprice%253A%255B500%2520TO%2520750%255D&searchCategoryId=1206&selectedFilter=all&sortKey=relevance&sortOrder=1' try: page = requests.get(URL, headers=self.headers) soup = BeautifulSoup(page.content, 'html.parser') ps5_elems = soup.find_all( class_='sc-pc-medium-desktop-card sc-plp-cards-card') inventory = 0 totalinventory = len(ps5_elems) for ps5_elem in ps5_elems: in_stock = not ps5_elem.find( 'button', class_= 'sc-btn sc-btn-primary sc-btn-block sc-pc-action-button sc-pc-add-to-cart' ).has_attr('disabled') if in_stock: inventory += 1 link = 'https://www.samsclub.com' + ps5_elem.find( 'a')['href'] webbrowser.open_new_tab(link) Alert('PS5', link) print( colored( '{} PS5 found: {}'.format(self.getTime(), link), 'green')) # writeToFile(link) # return 1 print('[{} / {}]'.format(inventory, totalinventory)) self.stock += inventory except (ConnectionError, Exception) as e: print( 'Exception trying to retrieve Sam\'s club data [{}]'.format(e)) return 0
def account_settings(user): if request.method == 'GET': udao = UserDAO() valid_key = udao.check_user_session_key(user, request.cookies.get("session_key")) if valid_key: alertParam = request.args.get("alert") alert = None if alertParam: alertData = urllib.parse.unquote(alertParam) alertData = alertData.split("|") alert = Alert(alertData[0], alertData[1], alertData[2]) u = udao.get_user(user) if u.email_auth == 1 and u.can_edit_settings == 0 and not alertParam: eh = EmailHandler(u.email) code = eh.send_settings_code() if code: udao.set_user_settings_code(u.id, code) return render_template("settings.html", signedIn = request.cookies.get("signedIn"), user = request.cookies.get("user"), alert = alert, userobj = u) else: return "Not Your Page to Edit" elif request.method == 'POST': inputted_code = request.form['email_auth'] udao = UserDAO() actual_code = udao.get_user_settings_code(user) if inputted_code == actual_code: udao.allow_edit_settings(user) return redirect(f"/account/{user}/settings") return redirect(f"/account/{user}/settings?alert=Incorrect Code!|Try inputting the code again.|alert-fail")
class Test_updates(object): @classmethod def setup_class(self): """ Setup code run before any tests are run """ self.alert = Alert({ 'id': 'testAlert', 'onsetDate': datetime(1997, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'expireDate': datetime(2000, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'isUpdate': False, 'isCancel': False, 'locations':[] }) @classmethod def teardown_class(self): """ Teardown code run after all tests are run """ self.alert = None def setUp(self): """ Run before each test method is run """ del self.alert.locations[:] self.alert.add_all_locations([(00.00, 00.00), (11.11, 11.11)]) self.alert.onsetDate = datetime(1997, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)) self.alert.expireDate = datetime(2000, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)) self.alert.isUpdate = False def test_update_onsetDate_happy_path(self): assert_equal(self.alert.onsetDate, parse("1997-07-16T19:20+01:00")) self.alert.update_onsetDate("1998-07-16T19:20+01:00") assert_equal(self.alert.onsetDate, parse("1998-07-16T19:20+01:00")) def test_update_expireDate_happy_path(self): assert_equal(self.alert.expireDate, parse("2000-07-16T19:20+01:00")) self.alert.update_expireDate("1997-08-16T19:20+01:00") assert_equal(self.alert.expireDate, parse("1997-08-16T19:20+01:00")) def test_update_locations_happy_path(self): assert_equal(len(self.alert.locations), 2) self.alert.update_locations([(90, 180)]) assert_equal(len(self.alert.locations), 1) assert_true((90, 180) in self.alert.locations) assert_false((11.11, 11.11) in self.alert.locations) def test_update_alert_happy_path(self): self.alert.update_alert({ 'id': 'testAlert', 'onsetDate': datetime(1998, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'expireDate': datetime(1998, 7, 23, 19, 20, tzinfo=tzoffset(None, 3600)), 'isUpdate': True, 'locations': [(33.33, 33.33), (44.44, 44.44), (55.55, 55.55)] }) assert_equal(self.alert.onsetDate, parse("1998-07-16T19:20+01:00")) assert_equal(self.alert.expireDate, parse("1998-07-23T19:20+01:00")) assert_true(self.alert.isUpdate) assert_equal(len(self.alert.locations), 3) assert_false((11.11, 11.11) in self.alert.locations) assert_true((33.33, 33.33) in self.alert.locations) def test_update_alert_non_matching_id(self): self.alert.update_alert({ 'id': 'differentAlert', 'onsetDate': datetime(1998, 7, 16, 19, 20, tzinfo=tzoffset(None, 3600)), 'expireDate': datetime(1998, 7, 23, 19, 20, tzinfo=tzoffset(None, 3600)), 'isUpdate': True, 'locations': [(33.33, 33.33), (44.44, 44.44), (55.55, 55.55)] }) assert_not_equal(self.alert.onsetDate, parse("1998-07-16T19:20+01:00")) assert_not_equal(self.alert.expireDate, parse("1998-07-23T19:20+01:00")) assert_false(self.alert.isUpdate) assert_not_equal(len(self.alert.locations), 3) assert_true((11.11, 11.11) in self.alert.locations) assert_false((33.33, 33.33) in self.alert.locations)
class Test_add_and_remove_locations(object): @classmethod def setup_class(self): """ Setup code run before any tests are run """ self.alert = Alert({ 'id': None, 'onsetDate': None, 'expireDate': None, 'isUpdate': False, 'isCancel': False, 'locations':[] }) @classmethod def teardown_class(self): """ Teardown code run after all tests are run """ self.alert = None def setUp(self): """ Run before each test method is run """ del self.alert.locations[:] def test_add_location_happy_path(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((00.00, 00.00)) assert_equal(len(self.alert.locations), 1) def test_add_location_max_vals(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((90, 180)) assert_equal(len(self.alert.locations), 1) def test_add_location_min_vals(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((-90, -180)) assert_equal(len(self.alert.locations), 1) def test_add_location_latitude_too_high(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((91, 180)) assert_equal(len(self.alert.locations), 0) def test_add_location_latitude_too_low(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((-91, 180)) assert_equal(len(self.alert.locations), 0) def test_add_location_longitude_too_high(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((90, 181)) assert_equal(len(self.alert.locations), 0) def test_add_location_longitude_too_low(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((90, -181)) assert_equal(len(self.alert.locations), 0) def test_add_location_latitude_string(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location(('90', 180)) assert_equal(len(self.alert.locations), 0) def test_add_location_longitide_string(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location((90, '180')) assert_equal(len(self.alert.locations), 0) def test_add_location_both_string(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location(('90', '180')) assert_equal(len(self.alert.locations), 0) def test_add_location_both_non_numeric(self): assert_equal(len(self.alert.locations), 0) self.alert.add_location(('aaaa', 'bbbb')) assert_equal(len(self.alert.locations), 0) def test_remove_location_happy_path(self): self.alert.add_location((00.00, 00.00)) assert_equal(len(self.alert.locations), 1) self.alert.remove_location((00.00, 00.00)) assert_equal(len(self.alert.locations), 0) def test_remove_location_not_present(self): self.alert.add_location((00.00, 00.00)) assert_equal(len(self.alert.locations), 1) self.alert.remove_location((90.00, 90.00)) assert_equal(len(self.alert.locations), 1) def test_add_all_locations_happy_path(self): assert_equal(len(self.alert.locations), 0) self.alert.add_all_locations([(00.00, 00.00), (30.23, 40.89), (11.11,22.22)]) assert_equal(len(self.alert.locations), 3) def test_add_all_locations_empty_list(self): assert_equal(len(self.alert.locations), 0) self.alert.add_all_locations([]) assert_equal(len(self.alert.locations), 0)
def __init__(self): """ Constructor """ Alert.__init__(self)