예제 #1
0
def getTransactionNumber(cookies: dict, session_id: str) -> str:
    headers = {
            'authority': 'secure.newegg.com',
            'accept': 'application/json, text/plain, */*',
            'x-sessionid': session_id,
            'x-requested-with': 'XMLHttpRequest',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57',
            'content-type': 'application/json',
            'origin': 'https://secure.newegg.com',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://secure.newegg.com/shop/checkout?sessionId=' + session_id,
            'accept-language': 'en-US,en;q=0.9'
            }
    data = '{"SessionID":"' + session_id + '","Actions":[{"ActionType":"AlterPanelStatus","JsonContent":"{\\"ActionType\\":\\"AlterPanelStatus\\",\\"PanelStatus\\":{\\"ShippingAddress\\":\\"Done\\",\\"DeliveryMethod\\":\\"Done\\",\\"TaxID\\":\\"Done\\",\\"Payment\\":\\"Todo\\"}}"}],"EnableAsyncToken":true}'
    responseObj = requests.post('https://secure.newegg.com/shop/api/InitOrderReviewApi', headers=headers, cookies=cookies, data=data)
    if responseObj.status_code != 200:
        printFail("ERROR GETTING TRANSACTION NUMBER, TRYING AGAIN")
        return getTransactionNumber(cookies, session_id)
    else:
        colors.printInfo("GOT TRANSACTION NUMBER")
        try:
            return str(responseObj.json()['PaymentOption']['CreditCardList'][0]['TransactionNumber'])
        except:
            colors.printFail("ERROR GETTING TRANSACTION NUMBER, PLEASE RUN THE GENCOOKIE UTILITY!!!")
            return None
예제 #2
0
def exitWithError(error):
    """ Exit with formatted error message and exit code 1

    @param error String: Error message/reason for exit
    """
    colors.printFail('[+] Error occurred: {}'.format(error))
    sys.exit(1)
예제 #3
0
    def processMessages(self, msg_ids):
        """Process all the messages corresponding to the items in msg_ids for
        links containing key words/phrases specified in self.link_keys. If any
        links are found, call self.notify() to notify the notification_emails.

        @param msg_ids List[String]: msg_ids obtained from getMessages()
        """
        for msg_id in msg_ids:
            print('{} Processing message with id {}'.format(getTime(), msg_id))
            try:
                response = self.service.users().messages().get(
                    userId=self.user_id, id=msg_id, format='raw').execute()
            except Exception as error:
                printFail("{} Error retrieving message with id {}: {}".format(
                    getTime(), id, error))
                return

            msg_body = messageutils.getMimeMessage(response['raw'])

            found_links = messageutils.findLinks(str(msg_body), self.link_keys)
            if len(found_links) > 0:
                print('{} Found {} links containing key words/phrases'.format(
                    getTime(), len(found_links)))
                self.notify(found_links)
            else:
                print('{} Found 0 links containing key words'.format(
                    getTime()))

            self.inbox_manager.markProcessed(msg_id, self.label_ids)
예제 #4
0
def getCurrIp() -> str:
    r = requests.get('https://api.ipify.org?format=json')
    if r.status_code != 200:
        colors.printFail('Failed to detect IP address, retrying...')
        time.sleep(1)
        return getCurrIp()
    else:
        colors.printInfo('detected IP: ' + r.json()['ip'])
        return r.text
예제 #5
0
def inStock(s_id: str, price: float) -> bool:
    url = 'https://www.newegg.com/product/api/ProductRealtime?ItemNumber=' + s_id
    try:
        r = requests.get(url)
    except:
        colors.printFail('Failed to make request to instock API, trying again...')
        return inStock(s_id, price)
    if r.status_code == 200:
        try:
            j = r.json()
            inStock = j['MainItem']['Instock']
            acceptPrice = j['MainItem']['FinalPrice'] <= price
            if inStock and acceptPrice:
                colors.printSuccess('ITEM IN STOCK FOR GOOD PRICE!!!')
            elif inStock and not acceptPrice:
                colors.printFail('Item in stock, price too high...')
            else:
                colors.printInfo('Item not in stock...')
            return inStock and acceptPrice
        except:
            colors.printFail('Invalid response, IP block?')
            return False
    else:
        colors.printFail('Unsuccessful request made, IP block?')
        return False
예제 #6
0
def addToCart(p_id: str, cookies: dict) -> bool:
    try:
        add = requests.get('https://secure.newegg.com/Shopping/AddtoCart.aspx?Submit=ADD&ItemList=' + p_id, cookies=cookies)
    except:
        colors.printFail("Failed to add to cart, IP block?")
        time.sleep(2)
        return addToCart(p_id, cookies)
    if p_id not in add.url: #fail
        colors.printFail("Couldn't add to cart, retrying in 1 sec")
        time.sleep(2)
        return addToCart(p_id, cookies)
    else:
        colors.printInfo("Added to cart")
        return True
예제 #7
0
def testCookies() -> bool:
    cookies = loadCookies()
    config = configparser.ConfigParser()
    config.read('config.ini')
    product_id = config['ALWAYSWORKS']['primaryId']
    secondary_product_id = config['ALWAYSWORKS']['secondaryId']
    cvv = config['CREDENTIALS']['cvv']
    colors.printInfo('Running in always successful mode (no buying)')
    addToCart(product_id, cookies)
    transactionComplete = checkout(config, cookies, product_id, secondary_product_id, cvv, True)
    if not transactionComplete:
        colors.printFail('Need to update cookies!')
    else:
        colors.printSuccess('Cookies working...')
    return transactionComplete
예제 #8
0
def switchVPN(vpn_id: str, username: str, password: str) -> None:
    formerIP = getCurrIp()
    colors.printInfo('Swapping IP address...')
    killVPN()
    newConfigFile = getConfigFileName(vpn_id)
    res = os.system('./vpnConnector.sh ' + newConfigFile + ' ' + username +
                    ' ' + password)
    if res != 0:
        colors.printFail('Failed to connect to VPN. Trying again...')
        switchVPN(vpn_id, username, password)
    else:
        time.sleep(10)
    if formerIP == getCurrIp():
        colors.printFail('Unsuccessful swap...trying again in 5 seconds')
        time.sleep(5)
        switchVPN(vpn_id, username, password)
    else:
        colors.printSuccess('Successful swap of IP address...')
예제 #9
0
    def markProcessed(self, msg_id, label_ids):
        label_updates = {
            'addLabelIds': [
                label_ids['processed']
            ],
            'removeLabelIds': [
                label_ids['unprocessed'],
                ['INBOX']
            ]
        }

        try:
            response = self.service.users().messages().modify(userId=self.user_id, id=msg_id, body=label_updates).execute()
        except Exception as error:
            colors.printFail('{} Unable to mark message with id {} as processed: {}'.format(getTime(), msg_id, error))
            return None

        colors.printGreen('{} Marked message with id {} as processed'.format(getTime(), msg_id))
        return response
예제 #10
0
    def getMessages(self):
        """Retrieve new messages to be process from the haro_unprocessed label

        @return List[message objects]: list of new messages to be processed
        """
        # needs service, user_id, label_ids
        label_id = [self.label_ids['unprocessed']]
        try:
            response = self.service.users().messages().list(
                userId=self.user_id, labelIds=label_id).execute()
        except Exception as error:
            printFail('{} Error getting messages: {}'.format(getTime(), error))
            return []

        if 'messages' in response:
            msg_ids = [message['id'] for message in response['messages']]
            print('{} Received {} messages'.format(getTime(), len(msg_ids)))
            return msg_ids

        print('{} Received 0 messages'.format(getTime()))
        return []
예제 #11
0
    def notify(self, found_links):
        """Notify the notification_emails of the links processMessages() found.

        @param found_links List[String]: Links found containing key words/phrases
        """
        for email in self.notification_emails:
            encoded_msg = self.createMessage(found_links, email)
            try:
                response = self.service.users().messages().send(
                    userId=self.user_id, body=encoded_msg).execute()
            except Exception as error:
                printFail('{} Error sending notification: {}'.format(
                    getTime(), error))
                response = None
            if response is None:
                printFail(
                    '{} Error sending notification email to {}: {}'.format(
                        getTime(), email, error))
            else:
                printGreen(
                    '{} Successfully sent notification email to {}'.format(
                        getTime(), email))
예제 #12
0
def submitCardInfo(transactionNumber: str, cookies: dict, cvv: str, session_id: str, trans_number: str) -> bool:
    headers = {
            'authority': 'secure.newegg.com',
            'accept': 'application/json, text/plain, */*',
            'x-sessionid': session_id,
            'x-requested-with': 'XMLHttpRequest',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57',
            'content-type': 'application/json',
            'origin': 'https://secure.newegg.com',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://secure.newegg.com/shop/checkout?sessionId=' + session_id,
            'accept-language': 'en-US,en;q=0.9'
            }
    data = '{"SessionID":"' + session_id + '","Actions":[{"ActionType":"ConfirmPayment","JsonContent":"{\\"ActionType\\":\\"ConfirmPayment\\",\\"Cvv2\\":\\"' + cvv + '\\",\\"TransactionNumber\\":' + trans_number + ',\\"PaytermsCode\\":\\"Discover\\"}"}],"EnableAsyncToken":true}'
    responseObj = requests.post('https://secure.newegg.com/shop/api/InitOrderReviewApi', headers=headers, cookies=cookies, data=data)
    if responseObj.status_code != 200:
        colors.printFail("ERROR SUBMITTING CARD INFO, TRYING AGAIN")
        return submitCardInfo(transactionNumber, cookies, cvv, session_id, trans_number)
    else:
        colors.printInfo("CARD INFO SUBMITTED")
        return True
예제 #13
0
def genSessionID(cookies: dict, s_id: str) -> str:
    req_url = 'https://secure.newegg.com/shop/api/CheckoutApi'
    headers = {
            'authority': 'secure.newegg.com',
            'accept': 'application/json, text/plain, */*',
            'x-requested-with': 'XMLHttpRequest',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57',
            'content-type': 'application/json',
            'origin': 'https://secure.newegg.com',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://secure.newegg.com/shop/cart',
            'accept-language': 'en-US,en;q=0.9'
            }
    data = genDataString(s_id)
    requestObj = requests.post(req_url, headers=headers, cookies=cookies, data=data)
    if requestObj.status_code != 200:
        colors.printFail("ERROR GENERATING SESSION ID, TRYING AGAIN")
        return genSessionID(cookies, s_id)
    else:
        colors.printInfo("GOT SESSION ID")
        return requestObj.json()['SessionID']
예제 #14
0
def checkout(config: dict, cookies: dict, p_id: str, s_id: str, cvv: str, test: bool) -> bool:
    sessionId = genSessionID(cookies, s_id)
    url = 'https://secure.newegg.com/shop/checkout?sessionId=' + sessionId
    transactionNumber = getTransactionNumber(cookies, sessionId)
    if transactionNumber == None:
        return False
    if submitCardInfo(transactionNumber, cookies, cvv, sessionId, transactionNumber):
        if validateAddress(config, cookies, sessionId, transactionNumber):
            if not test:
                if submit_order(cookies, sessionId):
                    colors.printSuccess("Success! Check your inbox")
                    return True
            else:
                colors.printInfo('session_id: ' + sessionId)
                colors.printInfo('transaction_number: ' + transactionNumber)
                return True
        else:
            return checkout(config, cookies, p_id, s_id, cvv)

    else:
        colors.printFail("Couldnt check out, retrying")
        return checkout(config, cookies, p_id, s_id)
    return True
예제 #15
0
def validateAddress(config: dict, cookies: dict, s_id: str, trans_number: str) -> bool:
    headers = {
            'authority': 'secure.newegg.com',
            'accept': 'application/json, text/plain, */*',
            'x-sessionid': s_id,
            'x-requested-with': 'XMLHttpRequest',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57',
            'content-type': 'application/json',
            'origin': 'https://secure.newegg.com',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://secure.newegg.com/shop/checkout?sessionId=' + s_id,
            'accept-language': 'en-US,en;q=0.9'
            }

    data = getBillingData(config, trans_number)
    response = requests.post('https://secure.newegg.com/shop/api/ValidateAddress', headers=headers, data=data, cookies=cookies)
    if response.status_code != 200:
        colors.printFail("ERROR VALIDATING BILLING ADDRESS, RETRYING...")
        return validateAddress(config, cookies, s_id)
    else:
        colors.printInfo("BILLING ADDRESS VALIDATED")
        return True
예제 #16
0
def submit_order(cookies: dict, s_id: str) -> bool:
    headers = {
            'authority': 'secure.newegg.com',
            'accept': 'application/json, text/plain, */*',
            'x-sessionid': s_id,
            'x-requested-with': 'XMLHttpRequest',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57',
            'content-type': 'application/json',
            'origin': 'https://secure.newegg.com',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://secure.newegg.com/shop/checkout?sessionId=' + s_id,
            'accept-language': 'en-US,en;q=0.9'
            }

    data = '{"SessionID":"' + s_id + '","IsAcceptNSCCAuth":false,"SubscribeNewsletterFlag":false,"CreactAccount":false,"Password":"","MobileSubscribe":{},"LanguageCode":"en-us","Cvv2":""}'
    response = requests.post('https://secure.newegg.com/shop/api/PlaceOrderApi', headers=headers, data=data, cookies=cookies)
    if response.status_code != 200:
        colors.printFail("FAILED TO PLACE. RETRYING...")
        return submit_order(cookies, s_id)
    else:
        colors.printInfo("ORDER PLACED")
        return True
예제 #17
0
            return inStock and acceptPrice
        except:
            colors.printFail('Invalid response, IP block?')
            return False
    else:
        colors.printFail('Unsuccessful request made, IP block?')
        return False


profile = ''
if len(sys.argv) == 1:
    profile = 'TEST'
    colors.printInfo('Running in test mode...')
else:
    profile = sys.argv[1]
    colors.printFail('CONFIRM YOU WANT TO RUN THE ACTUAL SCRIPT FOR CONFIG: ' + profile)
    input()
config = configparser.ConfigParser()
config.read('config.ini')
secondary_product_id = config[profile]['secondaryId']
price = float(config[profile]['priceThreshold'])
phoneNumber = config['CREDENTIALS']['phoneNumber']
email = config['CREDENTIALS']['email']
emailPassword = config['CREDENTIALS']['emailPassword']
server = config['CREDENTIALS']['server']
bought = False
iterationsUntilCookieTest = 90
iterations = 0
while not bought:
   if iterations == iterationsUntilCookieTest:
       notify("Need to refresh cookies!", email, emailPassword, server, phoneNumber)
예제 #18
0
    zipCode = billData['zipCode']
    return f'{{"TransNumber":{transNumber},"AddressLabel":"Untitled","ContactWith":"{name}","Phone":"{phone}","Fax":"","Country":"{country}","State":"{state}","City":"{city}","Address1":"{address}","Address2":"","ZipCode":"{zipCode}","IsDefault":false,"DisplayLines":["{address}","{city}, {state} {zipCode}","{countryLong}","{phone}"],"AddressVerifyMark":"Verified","Email":null,"DisableEmail":false,"CompanyName":"","LanguageCode":null,"IsSelected":false,"SaveAddress":false,"QASDisplayLines":["{address}","{city}, {state} {zipCode}","{countryLong}"]}}'


def main(profile: str) -> None:
    cookies = loadCookies()
    transactionComplete = False
    config = configparser.ConfigParser()
    config.read('config.ini')
    product_id = config[profile]['primaryId']
    secondary_product_id = config[profile]['secondaryId']
    cvv = config['CREDENTIALS']['cvv']
    test = False
    if profile == 'TEST':
        colors.printInfo('Running in test mode (no buying)')
        test = True
    
    while not transactionComplete:
        if addToCart(product_id, cookies):
            transactionComplete = checkout(config, cookies, product_id, secondary_product_id, cvv, test)


if __name__ == "__main__":
        if len(sys.argv) != 1:
            colors.printFail('CONFIRM YOU WANT TO RUN THE ACTUAL SCRIPT FOR PROFILE: ' + sys.argv[1])
            input()
            main(sys.argv[1])
        else:
            main('TEST')