Advertisement
Guest User

stack overflow help code

a guest
Jun 24th, 2023
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.61 KB | None | 0 0
  1. import requests
  2. from tkinter import *
  3. from tkinter import ttk
  4. import webbrowser
  5. import threading
  6. from geopy.geocoders import Nominatim
  7.  
  8. root = Tk()
  9. root.title("Timer App")
  10. root.geometry("495x595")
  11.  
  12. # Replace with your actual values
  13. GOOGLE_CLIENT_ID = "1097287749447-lutelaoi15qk923thbcqd5mn0dttnfg6.apps.googleusercontent.com"
  14. REDIRECT_URI = "http://localhost:8000/auth"
  15. GOOGLE_MAPS_API_KEY = "AIzaSyABK7Jhl0R1R-rxDN0qK8YiUSqaxBavs5U"
  16. GOOGLE_CLIENT_SECRET = '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'
  17.  
  18. # Construct the authentication URL
  19. auth_url = f"https://accounts.google.com/o/oauth2/auth?client_id={GOOGLE_CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code&scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
  20. access_token = None
  21. server = None
  22.  
  23.  
  24. def get_public_ip():
  25.     try:
  26.         response = requests.get('http://ip-api.com/json')
  27.         data = response.json()
  28.         ip_address = data['query']
  29.         return ip_address
  30.     except requests.exceptions.RequestException as e:
  31.         print("Error: ", e)
  32.         return None
  33.  
  34.  
  35. def track_gps(ip_address):
  36.     url = "https://www.googleapis.com/geolocation/v1/geolocate?key={GOOGLE_MAPS_API_KEY}"
  37.  
  38.     payload = {
  39.         "considerIp": False,
  40.         "wifiAccessPoints": [],
  41.         "cellTowers": [],
  42.         "fallbacks": {
  43.             "ipGeoLocation": True
  44.         }
  45.     }
  46.  
  47.     headers = {
  48.         "Content-Type": "application/json"
  49.     }
  50.  
  51.     try:
  52.         response = requests.post(url, json=payload, headers=headers)
  53.         data = response.json()
  54.         print(data)
  55.  
  56.         if 'location' in data and 'lat' in data['location'] and 'lng' in data['location']:
  57.             latitude = data["location"]["lat"]
  58.             longitude = data["location"]["lng"]
  59.             return latitude, longitude, data
  60.         else:
  61.             print("Latitude and longitude not found in the response.")
  62.             return None
  63.     except requests.exceptions.RequestException as e:
  64.         print(f"An error occurred: {e}")
  65.         return None
  66.  
  67.  
  68. def exchange_code_for_token(code):
  69.     try:
  70.         token_url = "https://oauth2.googleapis.com/token"
  71.         data = {
  72.             "code": code,
  73.             "client_id": GOOGLE_CLIENT_ID,
  74.             "client_secret": GOOGLE_CLIENT_SECRET,  # Replace with your client secret
  75.             "redirect_uri": REDIRECT_URI,
  76.             "grant_type": "authorization_code",
  77.         }
  78.  
  79.         response = requests.post(token_url, data=data)
  80.         response_data = response.json()
  81.  
  82.         if 'access_token' in response_data:
  83.             global access_token
  84.             access_token = response_data["access_token"]
  85.             start_timer()  # Start the timer
  86.         else:
  87.             print("Token exchange failed.")
  88.             if 'error' in response_data:
  89.                 error_message = response_data['error_description']
  90.                 print(f"Error message: {error_message}")
  91.  
  92.     except requests.exceptions.RequestException as e:
  93.         print("Token exchange failed.")
  94.         print(f"An error occurred: {e}")
  95.  
  96.  
  97. def fetch_user_profile():
  98.     if access_token:
  99.         profile_url = "https://www.googleapis.com/oauth2/v1/userinfo"
  100.         headers = {"Authorization": f"Bearer {access_token}"}
  101.  
  102.         try:
  103.             response = requests.get(profile_url, headers=headers)
  104.             if response.status_code == 200:
  105.                 profile_data = response.json()
  106.                 print("User Profile:")
  107.                 print(f"Name: {profile_data['name']}")
  108.                 print(f"Email: {profile_data['email']}")
  109.             else:
  110.                 print("Failed to fetch user profile.")
  111.                 if 'error' in response.json():
  112.                     error_message = response.json()['error']
  113.                     print(f"Error message: {error_message}")
  114.         except requests.exceptions.RequestException as e:
  115.             print("Failed to fetch user profile.")
  116.             print(f"An error occurred: {e}")
  117.     else:
  118.         print("Access token not available.")
  119.  
  120.  
  121. def format_time(elapsed_time):
  122.     hours = elapsed_time // 3600000
  123.     minutes = (elapsed_time // 60000) % 60
  124.     seconds = (elapsed_time // 1000) % 60
  125.     milliseconds = elapsed_time % 1000
  126.  
  127.     return f"{hours:02d}:{minutes:02d}:{seconds:02d}:{milliseconds:03d}"
  128.  
  129.  
  130. def start_timer():
  131.     global elapsed_time, is_running
  132.     is_running = True
  133.     timer_tick()
  134.  
  135.  
  136. def stop_timer():
  137.     global is_running
  138.  
  139.     if is_running:
  140.         if access_token:
  141.             result = track_gps(get_public_ip())
  142.  
  143.             if result:
  144.                 latitude, longitude, data = result
  145.                 print(f"Latitude: {latitude}")
  146.                 print(f"Longitude: {longitude}")
  147.                 print("Google Maps API Response:")
  148.                 print(data)
  149.  
  150.                 geolocator = Nominatim(user_agent="timer-app")
  151.                 location = geolocator.reverse(f"{latitude}, {longitude}")
  152.                 if location:
  153.                     address = location.address
  154.                     print(f"Address: {address}")
  155.                 else:
  156.                     print("Failed to obtain location address.")
  157.             else:
  158.                 print("GPS tracking failed.")
  159.         else:
  160.             print("Failed to obtain the access token.")
  161.  
  162.         fetch_user_profile()
  163.  
  164.     is_running = False
  165.  
  166.  
  167. def timer_tick():
  168.     global elapsed_time, is_running
  169.     if is_running:
  170.         elapsed_time += 10
  171.         timer_label.config(text=format_time(elapsed_time))
  172.     timer_label.after(10, timer_tick)
  173.  
  174.  
  175. elapsed_time = 0
  176. is_running = False
  177.  
  178. timer_label = ttk.Label(root, text="00:00:00:000", font=("Arial", 20))
  179. timer_label.pack(pady=10)
  180.  
  181.  
  182. def start_auth_flow():
  183.     global server
  184.     server = threading.Thread(target=start_flask_server)
  185.     server.start()
  186.     webbrowser.open(auth_url)
  187.  
  188.  
  189. def start_flask_server():
  190.     from flask import Flask, request
  191.  
  192.     app = Flask(__name__)
  193.  
  194.     @app.route('/auth', methods=['GET'])
  195.     def auth_callback():
  196.         # Get the authorization code from the query parameters
  197.         code = request.args.get('code')
  198.         exchange_code_for_token(code)  # Exchange the code for an access token
  199.         server.join()  # Wait for the Flask server to finish
  200.         root.quit()  # Exit the application
  201.         return 'Authorization successful!'  # Respond with a success message
  202.  
  203.     app.run(port=8000)
  204.  
  205.  
  206. start_button = ttk.Button(
  207.     root, text="Start", width=10, command=start_auth_flow)
  208. start_button.pack(side=LEFT, padx=10)
  209.  
  210. stop_button = ttk.Button(root, text="Stop", width=10, command=stop_timer)
  211. stop_button.pack(side=LEFT)
  212.  
  213.  
  214. root.mainloop()
  215.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement