CORVO-AI commited on
Commit
678d88b
·
verified ·
1 Parent(s): 2f62045

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -84
app.py CHANGED
@@ -1,88 +1,69 @@
1
  import requests
2
  from flask import Flask, request, jsonify
3
  from datetime import datetime
4
- import base64
5
  import json
6
 
7
  app = Flask(__name__)
8
 
9
- # PythonAnywhere API endpoint
10
  PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
11
 
12
- # GitHub API and file information
13
- GITHUB_TOKEN = "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" # Store this in .env in production
14
- REPO_OWNER = "omarnuwrar"
15
- REPO_NAME = "api"
16
- FILE_PATH = "user.json"
17
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- def fetch_user_data():
20
- """Fetch user data from GitHub repo."""
21
- url = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{FILE_PATH}"
22
- headers = {
23
- "Authorization": f"token {GITHUB_TOKEN}",
24
- "Accept": "application/vnd.github.v3+json",
25
- }
26
-
27
- response = requests.get(url, headers=headers)
28
- if response.status_code == 200:
29
- content = response.json()
30
- file_content = content["content"]
31
- file_decoded = base64.b64decode(file_content).decode("utf-8")
32
- return json.loads(file_decoded)
33
- else:
34
- print(f"Failed to fetch file: {response.status_code}")
35
- print(response.json())
36
- return None
37
-
38
-
39
- def is_token_valid(token):
40
- """
41
- Check if the provided token is valid and unexpired.
42
- """
43
- user_data = fetch_user_data()
44
- if not user_data:
45
- return False, "Unable to fetch user data."
46
-
47
- for user in user_data:
48
- if user["token"] == token:
49
- # Parse token expiration time
50
- expiration_time = datetime.fromisoformat(user["token_expiration_time"])
51
- if datetime.now() <= expiration_time:
52
- return True, None
53
-
54
- return False, "Your token has expired. Please subscribe to continue."
55
-
56
- return False, "Invalid token. Please log in or create an account."
57
-
58
 
59
  @app.route('/chat', methods=['POST'])
60
  def chat():
61
- """
62
- Chat endpoint. Requires a valid token.
63
- """
64
  try:
65
- # Ensure the request contains JSON
66
  if not request.is_json:
67
- return jsonify({"error": "Invalid request format. JSON expected."}), 400
68
 
69
- # Extract message and token from the request body
70
  user_input = request.json.get("message", "")
71
- user_token = request.json.get("token", "")
72
 
73
  if not user_input:
74
- return jsonify({"error": "No message provided."}), 400
75
 
76
- if not user_token:
77
- return jsonify({"error": "No token provided."}), 400
78
 
79
  # Validate the token
80
- is_valid, error_message = is_token_valid(user_token)
81
- if not is_valid:
82
- return jsonify({"error": error_message}), 403
83
 
84
- # Forward the request to PythonAnywhere
85
  data = {"message": user_input}
 
 
86
  response = requests.post(PYTHONANYWHERE_URL, json=data)
87
 
88
  if response.status_code == 200:
@@ -91,37 +72,15 @@ def chat():
91
  ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
92
  return jsonify({"response": ai_response})
93
  else:
 
94
  return jsonify({
95
  "error": "Error from PythonAnywhere",
96
  "details": response.text
97
  }), response.status_code
98
 
99
  except Exception as e:
 
100
  return jsonify({"error": "An error occurred", "details": str(e)}), 500
101
 
102
-
103
- @app.route('/get-payload', methods=['GET'])
104
- def get_payload():
105
- """
106
- Get payload from the request body. Requires a valid token.
107
- """
108
- try:
109
- # Extract token from query parameters
110
- user_token = request.args.get("token", "")
111
-
112
- if not user_token:
113
- return jsonify({"error": "No token provided."}), 400
114
-
115
- # Validate the token
116
- is_valid, error_message = is_token_valid(user_token)
117
- if not is_valid:
118
- return jsonify({"error": error_message}), 403
119
-
120
- return jsonify({"payload": "This is a demo payload response."})
121
-
122
- except Exception as e:
123
- return jsonify({"error": "An error occurred", "details": str(e)}), 500
124
-
125
-
126
  if __name__ == "__main__":
127
  app.run(host="0.0.0.0", port=7860)
 
1
  import requests
2
  from flask import Flask, request, jsonify
3
  from datetime import datetime
 
4
  import json
5
 
6
  app = Flask(__name__)
7
 
8
+ # Your PythonAnywhere API endpoint
9
  PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
10
 
11
+ # URL of the GitHub-hosted JSON database
12
+ USER_DB_URL = "https://raw.githubusercontent.com/omarnuwrar/api/refs/heads/main/user.json"
 
 
 
13
 
14
+ def get_users_from_db():
15
+ """Fetch user data from the GitHub JSON file."""
16
+ try:
17
+ response = requests.get(USER_DB_URL)
18
+ if response.status_code == 200:
19
+ return response.json()
20
+ else:
21
+ raise Exception("Failed to fetch the user database.")
22
+ except Exception as e:
23
+ raise Exception(f"Error fetching user database: {str(e)}")
24
 
25
+ def validate_token(token):
26
+ """Validate the token from the GitHub-hosted database."""
27
+ try:
28
+ users = get_users_from_db()
29
+ # Look for the token in the database
30
+ for user in users:
31
+ if user["token"] == token:
32
+ # Check if the token is expired
33
+ expiration_time = datetime.fromisoformat(user["token_expiration_time"])
34
+ if datetime.now() < expiration_time:
35
+ return True, None # Token is valid
36
+ else:
37
+ return False, "Token is expired."
38
+ return False, "Token not found." # Token not found in the database
39
+ except Exception as e:
40
+ return False, f"Error validating token: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  @app.route('/chat', methods=['POST'])
43
  def chat():
 
 
 
44
  try:
45
+ # Ensure the request contains JSON and a "message" and "token" key
46
  if not request.is_json:
47
+ return jsonify({"error": "Request must be in JSON format."}), 400
48
 
 
49
  user_input = request.json.get("message", "")
50
+ token = request.json.get("token", "")
51
 
52
  if not user_input:
53
+ return jsonify({"error": "No message provided in the request."}), 400
54
 
55
+ if not token:
56
+ return jsonify({"error": "No token provided in the request."}), 400
57
 
58
  # Validate the token
59
+ token_valid, token_message = validate_token(token)
60
+ if not token_valid:
61
+ return jsonify({"error": "Invalid token.", "details": token_message}), 401
62
 
63
+ # Create the payload to send to PythonAnywhere
64
  data = {"message": user_input}
65
+
66
+ # Forward the request to PythonAnywhere
67
  response = requests.post(PYTHONANYWHERE_URL, json=data)
68
 
69
  if response.status_code == 200:
 
72
  ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
73
  return jsonify({"response": ai_response})
74
  else:
75
+ # Handle errors from PythonAnywhere
76
  return jsonify({
77
  "error": "Error from PythonAnywhere",
78
  "details": response.text
79
  }), response.status_code
80
 
81
  except Exception as e:
82
+ # Catch any unexpected errors
83
  return jsonify({"error": "An error occurred", "details": str(e)}), 500
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  if __name__ == "__main__":
86
  app.run(host="0.0.0.0", port=7860)