ZidCopilotApp / main.py
Upto12forenglish's picture
Upload 5 files
f31a243 verified
raw
history blame contribute delete
No virus
10.8 kB
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.responses import RedirectResponse, HTMLResponse
import urllib.parse
import requests, json, time
from password_generator import generate_password
import threading
user_credentials_google_apps_script_url = "https://script.google.com/macros/s/AKfycbzm5dC7jMJ4y7Cdu-sW05kozA6HgcTp2zoHi7BjJQ7Hhvp0exihsllgBsiqMoa68i6-XA/exec"
app_link = "https://huggingface.co/spaces/Upto12forenglish/ZidTurboApp/edit/main/main.py"
def send_email_credentials(email, username, password, app_link):
url = "https://hook.eu2.make.com/soremxx4ove87uk7hmghfuhvtl3gaqc6"
payload = {
"email": email,
"username": username,
"password": password,
"app_link": app_link
}
try:
response = requests.post(url, json=payload)
response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code
print(f"Status Code: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if e.response is not None:
print(f"Response Content: {e.response.content.decode()}")
# On getting the store credentials, Get the store id and info using "https://api.zid.sa/v1/managers/account/profile" endpoint
def get_store_id(access_token, authorization):
print("Entered get store id function")
time.sleep(0.5)
# Set up the authorization header
headers = {
'Authorization': 'Bearer ' + authorization,
'X-Manager-Token': access_token,
}
# Make the GET request to the API endpoint
response = requests.get('https://api.zid.sa/v1/managers/account/profile', headers=headers)
response_data = response.json()
store_name = response_data['user']['name']
store_id = response_data['user']['store']['id']
store_username = response_data['user']['username']
store_manager_email = response_data['user']['email']
store_manager_mobile = response_data['user']['mobile']
# Print the JSON response
print("Store name is ", store_name)
print("Store id is ", store_id)
print("Username is ", store_username)
print("Email is ", store_manager_email)
print("Phone is ", store_manager_mobile)
print("Exited get store id function")
return store_name, store_id, store_username, store_manager_email, store_manager_mobile
# On new app installation, add the store info to the database sheet
def create_new_user(access_token, authorization, refresh_token, expires_in):
print("Entered create new user function")
# Call get_store_id to retreive store information
store_name, store_id, username, email, mobile = get_store_id(access_token, authorization)
time.sleep(0.5)
# Generate user password
password = generate_password()
print("Password was generated successfully, ", password)
time.sleep(0.5)
# Send the store info to google app script to register the new user information to the user database
try:
response = requests.get(user_credentials_google_apps_script_url, params={"accessToken": access_token, "authorization": authorization, "refreshToken":refresh_token, "expiresIn": expires_in, "storeName": store_name, "storeID": store_id, "username": username, "storeManagerEmail": email, "mobileNumber": mobile, "storeManagerpassword": password})
responseData = json.loads(response.text)
print(responseData) # Put the result in the queue
except Exception as e:
print(str(e)) # Put the error message in the queue
time.sleep(0.5)
print("Now sending the credentials email to the store owner")
# Send an email with user credentials
# send_email(email, username, password, app_link)
send_email_credentials(email, username, password, app_link)
print("Exited create new user function")
def process_oauth_response(response_data):
try:
# Extract data
access_token = response_data["access_token"]
token_type = response_data["token_type"]
expires_in = response_data["expires_in"]
authorization = response_data["authorization"]
refresh_token = response_data["refresh_token"]
print("Access Token: ", access_token)
print("Authorization: ", authorization)
print("Refresh Token: ", refresh_token)
print("Expires in: ", expires_in)
create_new_user(access_token, authorization, refresh_token, expires_in)
except KeyError as e:
print(f"Missing expected key in response data: {e}")
except Exception as e:
print(f"An error occurred while processing the response: {e}")
app = FastAPI()
class Message(BaseModel):
message: str
@app.get("/", response_class=HTMLResponse)
async def read_root():
return """
<!DOCTYPE html>
<html>
<head>
<title>Zid-Copilot</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
text-align: center;
}
.container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 600px;
width: 100%;
}
h1 {
color: #333;
}
ul {
list-style-type: none; /* Remove default bullet points */
padding: 0;
}
li {
margin-bottom: 10px;
background-color: #fff;
color: #333;
padding: 10px 20px;
border-radius: 5px;
cursor: default;
border: 1px solid #ccc;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
li:hover {
background-color: #f9f9f9;
}
.start-button {
background-color: #28a745;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
width: 100%;
margin-top: 20px;
}
.start-button:hover {
background-color: #218838;
}
.hidden-buttons {
display: none;
margin-top: 20px;
}
.hidden-buttons input {
width: calc(100% - 22px);
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}
.hidden-buttons label {
display: block;
margin-bottom: 5px;
color: #333;
}
.hidden-buttons button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
margin: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.hidden-buttons button:hover {
background-color: #0056b3;
}
</style>
<script>
function showButtons() {
document.getElementById('hidden-buttons').style.display = 'block';
}
function handleSubmit(event) {
event.preventDefault();
const messageDiv = document.getElementById('message');
messageDiv.textContent = 'File submitted successfully, now processing';
messageDiv.style.display = 'block';
}
function openReferenceFile() {
window.open('https://docs.google.com/spreadsheets/d/1L9pUbj8V9lm6g9Fqy-9viRQzon0YtExXNE77SozuHns/edit?usp=drive_link', '_blank');
}
</script>
</head>
<body>
<div class="container">
<h1>Welcome to Zid-Copilot!</h1>
<p>Your ultimate assistant for effortless product management.</p>
<ul>
<li>Unlimited ease in adding and modifying your store's products</li>
<li>Intuitive interface for seamless navigation</li>
<li>24/7 support for any assistance you may need</li>
<li>Stay ahead with our cutting-edge technology</li>
<li>Effortlessly boost your store's performance</li>
<li>Join thousands of satisfied users today!</li>
</ul>
<button class="start-button" onclick="showButtons()">Start Now</button>
<div id="hidden-buttons" class="hidden-buttons">
<form onsubmit="handleSubmit(event)">
<label for="file-link">Insert your products Google Sheet file link:</label>
<input type="text" id="file-link" name="file-link" required>
<button type="submit">Submit</button>
<button type="button" onclick="openReferenceFile()">Use Reference File</button>
</form>
<div id="message" style="display: none; margin-top: 20px; color: green;"></div>
</div>
</div>
</body>
</html>
"""
@app.post("/update")
async def receive_message(message: Message):
print("Received message:", message.message)
return {"message": "Message received successfully"}
@app.get("/redirect")
def redirect_to_oauth():
queries = {
'client_id': '3365',
'redirect_uri': 'https://upto12forenglish-zidturboapp.hf.space/oauth/callback',
'response_type': 'code'
}
query_string = urllib.parse.urlencode(queries)
oauth_url = f'https://oauth.zid.sa/oauth/authorize?{query_string}'
return RedirectResponse(url=oauth_url)
@app.get("/oauth/callback")
def callback(code):
payload = {
'grant_type': 'authorization_code',
'client_id': 3365,
'client_secret': 'YAZTkOvz0EkHOZuuEbisoeLrqPVC4bWVDcSwexLS',
'redirect_uri': 'https://upto12forenglish-zidturboapp.hf.space/oauth/callback', # Your Application's Callback URI
'code': code # grant code
}
response = requests.post('https://oauth.zid.sa/oauth/token', data=payload)
response_data = response.json()
# Start a new thread to process the response data
processing_thread = threading.Thread(target=process_oauth_response, args=(response_data,))
processing_thread.start()
return RedirectResponse(url=app_link)