Spaces:
Sleeping
Sleeping
File size: 10,830 Bytes
f31a243 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
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) |