-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtkUser.py
More file actions
132 lines (116 loc) · 4.14 KB
/
tkUser.py
File metadata and controls
132 lines (116 loc) · 4.14 KB
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
# NOTE: This script is designed to Test the API for uploading images from an Alternative Client.
"""
PIP installs:
pip install requests python-dotenv
"""
import os
import uuid
from datetime import datetime
import requests
import tkinter as tk
from tkinter import filedialog
from dotenv import load_dotenv
load_dotenv()
API_BASE = os.getenv('API_URL', 'http://127.0.0.1:8080')
SOURCE = 'TKINTER'
# Identifier for this source (e.g., your configured TKINTER_ID in .env)
IDENTIFIER = os.getenv('TKINTER_ID')
if not IDENTIFIER:
IDENTIFIER = input("Enter your identifier (e.g. 'jcp-tech'): ").strip()
def ensure_registration():
"""Check or register this identifier with the API.
Returns (primary_id, session_id) or (None, None) on failure."""
resp = requests.get(f"{API_BASE}/get_primary", params={
'source': SOURCE,
'identifier': IDENTIFIER
})
if resp.status_code == 200:
primary = resp.json().get('primary_id')
sess = None
try:
r = requests.get(f"{API_BASE}/get_user", params={'primary_id': primary})
if r.ok:
sess = r.json().get('session_id')
except Exception:
pass
return primary, sess
print("You are not registered for TKINTER uploads.")
if input("Register now? (yes/no): ").lower().startswith('y'):
# Ask for desired primary ID
primary = input(f"Enter desired primary ID (default '{IDENTIFIER}'): ").strip() or IDENTIFIER
r2 = requests.post(f"{API_BASE}/register", json={
'source': SOURCE,
'identifier': IDENTIFIER,
'primary_id': primary
})
if r2.ok:
data = r2.json()
sess = data.get('session_id')
print(f"Registered under primary ID: {primary}")
return primary, sess
else:
print("Registration failed:", r2.text)
return None, None
def get_user_data(primary_id):
"""Fetch user data from the API for a given primary_id."""
try:
r = requests.get(f"{API_BASE}/get_user", params={'primary_id': primary_id})
if r.ok:
return r.json()
except Exception:
pass
return None
def ensure_authenticated(primary, session_id):
"""Ensure the user has completed OAuth login."""
while True:
try:
user_doc = get_user_data(primary)
# print(f"User document for {primary}: {user_doc}")
if user_doc:
if 'auth' in user_doc:
return True
session_id = user_doc.get('session_id', session_id)
except Exception:
pass
login_link = f"{API_BASE}/login/TRUE/{session_id}"
print(f"Please complete OAuth login: {login_link}")
input("Press Enter once logged in...")
def select_and_send():
primary, session_id = ensure_registration()
if not primary:
print("Cannot proceed without registration.")
return
if not ensure_authenticated(primary, session_id):
print("Authentication required. Try again after logging in.")
return
# Hide root UI
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(
title="Select Image File",
filetypes=[("Image Files", "*.png *.jpg *.jpeg *.bmp *.gif")]
)
if not file_path:
print("No file selected.")
return
upload_session_id = str(uuid.uuid4())
timestamp = datetime.utcnow().isoformat()
file_name = os.path.basename(file_path)
ext = file_name.split('.')[-1].lower()
mime_type = f"image/{{ext if ext != 'jpg' else 'jpeg'}}"
with open(file_path, 'rb') as f:
files = {'file': (file_name, f, mime_type)}
data = {
'session_id': upload_session_id,
'identifier': IDENTIFIER,
'source': SOURCE,
'timestamp': timestamp
}
print(f"Uploading session {upload_session_id}...")
r = requests.post(f"{API_BASE}/upload", files=files, data=data)
if r.ok:
print("✅ Processing started:", r.json())
else:
print("❌ Upload failed:", r.status_code, r.text)
if __name__ == '__main__':
select_and_send()