Beispiel #1
0
def check_fuellock(accessToken, deviceSecret, DEVICE_ID):
    # Generate the tssa
    tssa = functions.generateTssa(functions.BASE_URL + "FuelLock/List", "GET",
                                  None, accessToken)

    # Assign the headers and then request the fuel prices.
    headers = {
        'User-Agent': 'Apache-HttpClient/UNAVAILABLE (java 1.4)',
        'Authorization': '%s' % tssa,
        'X-OsVersion': functions.OS_VERSION,
        'X-OsName': 'Android',
        'X-DeviceID': DEVICE_ID,
        'X-VmobID': functions.des_encrypt_string(DEVICE_ID),
        'X-AppVersion': functions.APP_VERSION,
        'X-DeviceSecret': deviceSecret
    }

    # Send the request and get the response into a JSON array
    response = requests.get(functions.BASE_URL + "FuelLock/List",
                            headers=headers)
    returnContent = json.loads(response.content)

    config = configparser.ConfigParser()
    config.read("./autolock.ini")
    # If the Status of our last fuel lock is 0 (ACTIVE) set it to True, otherwise it has EXPIRED (1) or
    # was REDEEMED (2), so we haven't got a fuel lock saved.
    if (returnContent[0]['Status'] == 0):
        config.set('Account', 'fuel_lock_saved', "True")
    else:
        config.set('Account', 'fuel_lock_saved', "False")

    # Return our fuel lock saved boolean
    return config['Account'].getboolean('fuel_lock_saved')
Beispiel #2
0
def logout():

    # The logout payload is an empty string but it is still needed
    payload = '""'
    tssa = functions.generateTssa(functions.BASE_URL + "account/logout",
                                  "POST", payload, session['accessToken'])

    headers = {
        'User-Agent': 'Apache-HttpClient/UNAVAILABLE (java 1.4)',
        'Authorization': '%s' % tssa,
        'X-OsVersion': functions.OS_VERSION,
        'X-OsName': 'Android',
        'X-DeviceID': session['DEVICE_ID'],
        'X-AppVersion': functions.APP_VERSION,
        'X-DeviceSecret': session['deviceSecret'],
        'Content-Type': 'application/json; charset=utf-8'
    }

    response = requests.post(functions.BASE_URL + "account/logout",
                             data=payload,
                             headers=headers)

    # Clear all of the previously set session variables and then redirect to the index page
    session.clear()

    return redirect(url_for('index'))
Beispiel #3
0
def start_lockin():
    config = configparser.ConfigParser()
    config.read("./autolock.ini")
    # Get the setting if auto_lock is true or false
    auto_lock_enabled = config['General'].getboolean('auto_lock_enabled')
    # Get the maximum price we want to pay for fuel
    max_price = config['General']['max_price']
    # Get our account details
    deviceSecret = config['Account']['deviceSecret']
    accessToken = config['Account']['accessToken']
    cardBalance = config['Account']['cardBalance']
    DEVICE_ID = config['Account']['DEVICE_ID']

    # Check if we have saved a fuel lock. We make a proper check here in case we have already locked in a price
    # without updating the autolock.ini for some reason.
    fuel_lock_saved = check_fuellock(accessToken, deviceSecret, DEVICE_ID)

    # If we have auto lock enabled, and are logged in but haven't saved a fuel lock yet, then proceed.
    if (auto_lock_enabled and deviceSecret and not fuel_lock_saved):

        # Search OzBargain for a new deal first, it may be posted there first
        if (not search_ozbargain()):
            # Search ProjectZeroThree since OzBargain has no results
            search_pzt()

        # If there is a location deal
        if (suburb):
            # Open the stores.json file so we can search it to find a store that (hopefully) matches
            with open('./stores.json', 'r') as f:
                stores = json.load(f)

            # For each store in "Diffs" read the postcode
            for store in stores['Diffs']:
                if (store['Suburb'] == suburb):
                    # Since we have a match, return the latitude + longitude of our store and add a random number to it.
                    latitude = store['Latitude']
                    latitude += (random.uniform(0.01, 0.000001) *
                                 random.choice([-1, 1]))
                    longitude = store['Longitude']
                    longitude += (random.uniform(0.01, 0.000001) *
                                  random.choice([-1, 1]))

            # The payload to start the lock in process.
            payload = '{"LastStoreUpdateTimestamp":' + str(int(
                time.time())) + ',"Latitude":"' + str(
                    latitude) + '","Longitude":"' + str(longitude) + '"}'
            tssa = functions.generateTssa(
                functions.BASE_URL + "FuelLock/StartSession", "POST", payload,
                accessToken)

            # Now we start the request header
            headers = {
                'User-Agent': 'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                'Authorization': '%s' % tssa,
                'X-OsVersion': functions.OS_VERSION,
                'X-OsName': 'Android',
                'X-DeviceID': DEVICE_ID,
                'X-VmobID': functions.des_encrypt_string(DEVICE_ID),
                'X-AppVersion': functions.APP_VERSION,
                'X-DeviceSecret': deviceSecret,
                'Content-Type': 'application/json; charset=utf-8'
            }

            # Send the request
            response = requests.post(functions.BASE_URL +
                                     "FuelLock/StartSession",
                                     data=payload,
                                     headers=headers)

            # Get the response content so we can check the fuel price
            returnContent = response.content

            # Move the response json into an array so we can read it
            returnContent = json.loads(returnContent)

            # If there is a fuel lock already in place we get an error!
            try:
                if returnContent['ErrorType'] == 0:
                    # Print that we have a lock in already
                    print(
                        "Tried to lock in, but we already have a lock in saved."
                    )
            except:
                # Get the fuel price of all the types of fuel
                for each in returnContent['CheapestFuelTypeStores']:
                    x = each['FuelPrices']
                    for i in x:
                        # If the fuel type is premium 98
                        if (i['Ean'] == 56):
                            # Save the fuel pump price
                            pump_price = i['Price']

                # If the price that we tried to lock in is more expensive than scripts price, we return an error
                if (float(pump_price) >= float(max_price)):
                    print(
                        "There was a new deal posted, but the fuel price was too expensive. You want to fill up for less than {0}c, it would have been {1}c."
                        .format(str(max_price), str(pump_price)))
                else:
                    # Now we want to lock in the maximum litres we can.
                    NumberOfLitres = int(
                        float(config['Account']['cardbalance']) / pump_price *
                        100)

                    # Lets start the actual lock in process
                    payload = '{"AccountId":"' + config['Account'][
                        'account_id'] + '","FuelType":"56","NumberOfLitres":"' + str(
                            NumberOfLitres) + '"}'

                    tssa = functions.generateTssa(
                        functions.BASE_URL + "FuelLock/Confirm", "POST",
                        payload, accessToken)

                    headers = {
                        'User-Agent':
                        'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                        'Authorization': '%s' % tssa,
                        'X-OsVersion': functions.OS_VERSION,
                        'X-OsName': 'Android',
                        'X-DeviceID': DEVICE_ID,
                        'X-VmobID': functions.des_encrypt_string(DEVICE_ID),
                        'X-AppVersion': functions.APP_VERSION,
                        'X-DeviceSecret': deviceSecret,
                        'Content-Type': 'application/json; charset=utf-8'
                    }

                    # Send through the request and get the response
                    response = requests.post(functions.BASE_URL +
                                             "FuelLock/Confirm",
                                             data=payload,
                                             headers=headers)
                    returnContent = json.loads(response.content)

                    try:
                        if (returnContent['Message']):
                            print("Error: There was an error locking in.")
                    except:
                        print("Success! Locked in {0}L at {1} cents per litre".
                              format(str(returnContent['TotalLitres']),
                                     str(returnContent['CentsPerLitre'])))
Beispiel #4
0
def lockin():
    if request.method == 'POST':
        # Variable used to search for a manual price
        priceOveride = False
        # Get the form submission method
        submissionMethod = request.form['submit']

        # If we didn't try to confirm a manual price
        if(submissionMethod != "confirm_price"):

            # Get the fuel type we want
            fuelType = str(request.form['fueltype'])
            session['fuelType'] = fuelType

            # Clear previous messages
            session.pop('ErrorMessage', None)
            session.pop('SuccessMessage', None)

            # Get the postcode and price of the cheapest fuel
            locationResult = functions.cheapestFuel(fuelType)

            # They tried to do something different from the manual and automatic form, so throw up an error
            if(submissionMethod != "manual" and submissionMethod != "automatic"):
                session['ErrorMessage'] = "Invalid form submission. Either use the manual or automatic one on the main page."
                return redirect(url_for('index'))

            # If they have manually chosen a postcode/suburb set the price overide to true
            if(submissionMethod == "manual"):
                postcode = str(request.form['postcode'])
                priceOveride = True
                # Get the latitude and longitude from the store
                storeLatLng = functions.getStoreAddress(postcode)
                # If we have a match, set the coordinates. If we don't, use Google Maps
                if (storeLatLng):
                    locLat = float(storeLatLng[0])
                    locLat += (random.uniform(0.01,0.000001) * random.choice([-1,1]))

                    locLong = float(storeLatLng[1])
                    locLong += (random.uniform(0.01,0.000001) * random.choice([-1,1]))
                else:
                    # If we have entered the wrong manual postcode for a store, and haven't
                    # set the Google Maps API, return an error since we cant use the API
                    if not custom_coords:
                        # If it is, get the error message and return back to the index
                        session['ErrorMessage'] = "Error: You entered a manual postcode where no 7-Eleven store is. Please set a Google Maps API key or enter a valid postcode."
                        return redirect(url_for('index'))
                    # Initiate the Google Maps API
                    gmaps = googlemaps.Client(key = API_KEY)
                    # Get the longitude and latitude from the submitted postcode
                    geocode_result = gmaps.geocode(str(request.form['postcode']) + ', Australia')
                    locLat  = geocode_result[0]['geometry']['location']['lat']
                    locLong = geocode_result[0]['geometry']['location']['lng']
            else:
                # It was an automatic submission so we will now get the coordinates of the store
                # and add a random value to it so we don't appear to lock in from the service station
                locLat = locationResult[2]
                locLat += (random.uniform(0.01,0.000001) * random.choice([-1,1]))

                locLong = locationResult[3]
                locLong += (random.uniform(0.01,0.000001) * random.choice([-1,1]))

            # The payload to start the lock in process.
            payload = '{"LastStoreUpdateTimestamp":' + str(int(time.time())) + ',"Latitude":"' + str(locLat) + '","Longitude":"' + str(locLong) + '"}'
            tssa = functions.generateTssa(functions.BASE_URL + "FuelLock/StartSession", "POST", payload, session['accessToken'])

            # Now we start the request header
            headers = {'User-Agent':'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                       'Authorization':'%s' % tssa,
                       'X-OsVersion':functions.OS_VERSION,
                       'X-OsName':'Android',
                       'X-DeviceID':session['DEVICE_ID'],
                       'X-VmobID':functions.des_encrypt_string(session['DEVICE_ID']),
                       'X-AppVersion':functions.APP_VERSION,
                       'X-DeviceSecret':session['deviceSecret'],
                       'Content-Type':'application/json; charset=utf-8'}

            # Send the request
            response = requests.post(functions.BASE_URL + "FuelLock/StartSession", data=payload, headers=headers)

            # Get the response content so we can check the fuel price
            returnContent = response.content

            # Move the response json into an array so we can read it
            returnContent = json.loads(returnContent)

            # If there is a fuel lock already in place we get an error!
            try:
              if returnContent['ErrorType'] == 0:
                  session['ErrorMessage'] = "An error has occured. This is most likely due to a fuel lock already being in place."
                  return redirect(url_for('index'))
            except:
                pass

            # Get the fuel price of all the types of fuel
            for each in returnContent['CheapestFuelTypeStores']:
                x = each['FuelPrices']
                for i in x:
                    if(str(i['Ean']) == fuelType):
                        LockinPrice = i['Price']
                        session['LockinPrice'] = LockinPrice

            # If we have performed an automatic search we run the lowest price check
            # LockinPrice = the price from the 7/11 website
            # locationResult[1] = the price from the master131 script
            # If the price that we tried to lock in is more expensive than scripts price, we return an error
            if not(priceOveride):
                if not(float(LockinPrice) <= float(locationResult[1])):
                    session['ErrorMessage'] = "The fuel price is too high compared to the cheapest available. The cheapest we found was at " + locationResult[0] + ". Try locking in there!"
                    return redirect(url_for('index'))

            if(priceOveride):
                return redirect(url_for('confirm'))

        # Now we want to lock in the maximum litres we can.
        NumberOfLitres = int(float(session['cardBalance']) / session['LockinPrice'] * 100)

        # Lets start the actual lock in process
        payload = '{"AccountId":"' + session['accountID'] + '","FuelType":"' + session['fuelType'] + '","NumberOfLitres":"' + str(NumberOfLitres) + '"}'

        tssa = functions.generateTssa(functions.BASE_URL + "FuelLock/Confirm", "POST", payload, session['accessToken'])

        headers = {'User-Agent':'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                   'Authorization':'%s' % tssa,
                   'X-OsVersion':functions.OS_VERSION,
                   'X-OsName':'Android',
                   'X-DeviceID':session['DEVICE_ID'],
                   'X-VmobID':functions.des_encrypt_string(session['DEVICE_ID']),
                   'X-AppVersion':functions.APP_VERSION,
                   'X-DeviceSecret':session['deviceSecret'],
                   'Content-Type':'application/json; charset=utf-8'}

        # Send through the request and get the response
        response = requests.post(functions.BASE_URL + "FuelLock/Confirm", data=payload, headers=headers)

        # Get the response into a json array
        returnContent = json.loads(response.content)
        try:
            # Check if the response was an error message
            if(returnContent['Message']):
                # If it is, get the error message and return back to the index
                session['ErrorMessage'] = returnContent['Message']
                return redirect(url_for('index'))
            # Otherwise we most likely locked in the price!
            if(returnContent['Status'] == "0"):
                # Update the fuel prices that are locked in
                functions.lockedPrices()
                # Get amoount of litres that was locked in from the returned JSON array
                session['TotalLitres'] = returnContent['TotalLitres']
                session['SuccessMessage'] = "The price was locked in for " + str(session['LockinPrice']) + " cents per litre"

                # Pop our fueltype and lock in price variables
                session.pop('fuelType', None)
                session.pop('LockinPrice', None)
                return redirect(url_for('index'))

        # For whatever reason it saved our lock in anyway and return to the index page
        except:
            # Update the fuel prices that are locked in
            functions.lockedPrices()
            session['SuccessMessage'] = "The price was locked in for " + str(session['LockinPrice']) + " cents per litre"
            # Get amoount of litres that was locked in from the returned JSON array
            session['TotalLitres'] = returnContent['TotalLitres']

            # Pop our fueltype and lock in price variables
            session.pop('fuelType', None)
            session.pop('LockinPrice', None)
            return redirect(url_for('index'))
    else:
        # They just tried to load the lock in page without sending any data
        session['ErrorMessage'] = "Unknown error occured. Please try again!"
        return redirect(url_for('index'))
Beispiel #5
0
def login():
    # Clear the error and success message
    session.pop('ErrorMessage', None)
    session.pop('SuccessMessage', None)
    session.pop('fuelType', None)

    if request.method == 'POST':
        # If the device ID field was left blank, set a random one
        if ((request.form['device_id']) in [None,""]):
            session['DEVICE_ID'] = os.getenv('DEVICE_ID', ''.join(random.choice('0123456789abcdef') for i in range(16)))
        else:
            # Since it was filled out, we will use that for the rest of the session
            session['DEVICE_ID'] = os.getenv('DEVICE_ID', request.form['device_id'])

        # Get the email and password from the login form
        password = str(request.form['password'])
        email = str(request.form['email'])

        # The payload that we use to login
        payload = '{"Email":"' + email + '","Password":"******","DeviceName":"' + functions.DEVICE_NAME + '","DeviceOsNameVersion":"' + functions.OS_VERSION +'"}'

        # Generate the tssa string
        tssa = functions.generateTssa(functions.BASE_URL + "account/login", "POST", payload)

        # Assign the headers
        headers = {'User-Agent':'Apache-HttpClient/UNAVAILABLE (java 1.4)',
                   'Authorization':'%s' % tssa,
                   'X-OsVersion':functions.OS_VERSION,
                   'X-OsName':'Android',
                   'X-DeviceID':session['DEVICE_ID'],
                   'X-VmobID':functions.des_encrypt_string(session['DEVICE_ID']),
                   'X-AppVersion':functions.APP_VERSION,
                   'Content-Type':'application/json; charset=utf-8'}

        # Login now!
        response = requests.post(functions.BASE_URL + "account/login", data=payload, headers=headers)

        returnHeaders = response.headers
        returnContent = json.loads(response.text)

        try:
            # If there was an error logging in, redirect to the index page with the 7Eleven response
            if(returnContent['Message']):
                session['ErrorMessage'] = returnContent['Message']
                return redirect(url_for('index'))

        except:

            # We need the AccessToken from the response header
            accessToken = str(returnHeaders).split("'X-AccessToken': '")
            accessToken = accessToken[1].split("'")
            accessToken = accessToken[0]

            # DeviceSecretToken and accountID are both needed to lock in a fuel price
            deviceSecret = returnContent['DeviceSecretToken']
            accountID    = returnContent['AccountId']
            # Save the users first name and their card balance so we can display it
            firstName    = returnContent['FirstName']
            cardBalance  = str(returnContent['DigitalCard']['Balance'])

            session['deviceSecret'] = deviceSecret
            session['accessToken'] = accessToken
            session['accountID'] = accountID
            session['firstName'] = firstName
            session['cardBalance'] = cardBalance


            functions.lockedPrices()


            # If we have ticked enable auto lock in, then set boolean to true
            if(request.form.getlist('auto_lockin')):
                config.set('General', 'auto_lock_enabled', "True")
                session['auto_lock'] = True
            else:
                # We didn't want to save it, so set to false
                config.set('General', 'auto_lock_enabled', "False")
                session['auto_lock'] = False

            # Save their log in anyway, so we can update the auto lock option later if needed
            config.set('Account', 'deviceSecret', session['deviceSecret'])
            config.set('Account', 'accessToken', session['accessToken'])
            config.set('Account', 'cardBalance', session['cardBalance'])
            config.set('Account', 'account_ID', session['accountID'])
            config.set('Account', 'DEVICE_ID', session['DEVICE_ID'])

            # If we have an active fuel lock, set fuel_lock_saved to true, otherwise false
            if(session['fuelLockStatus'] == 0):
                config.set('Account', 'fuel_lock_saved', "True")
            else:
                config.set('Account', 'fuel_lock_saved', "False")
            # Write the config to file
            with open('./autolock.ini', 'w') as configfile:
                config.write(configfile)

            return redirect(url_for('index'))
    else:
        # They didn't submit a POST request, so we will redirect to index
        return redirect(url_for('index'))