CORVO-AI commited on
Commit
d5ee326
·
verified ·
1 Parent(s): d160967

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -70
app.py CHANGED
@@ -1,82 +1,100 @@
1
- import requests
2
  from flask import Flask, request, jsonify
3
- from datetime import datetime
 
 
4
 
5
  app = Flask(__name__)
6
 
7
- # Your PythonAnywhere API endpoint
8
- PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
 
9
 
10
- # URL of GitHub-hosted user database
11
- USER_DB_URL = "https://raw.githubusercontent.com/omarnuwrar/api/refs/heads/main/user.json"
 
 
 
 
 
 
 
 
12
 
13
- def get_users_from_db():
14
- """Fetch user data from the GitHub JSON file."""
15
- response = requests.get(USER_DB_URL)
16
  if response.status_code == 200:
17
- return response.json()
18
- else:
19
- raise Exception("Failed to fetch the user database.")
20
-
21
- def validate_token(token):
22
- """Validate the provided token."""
23
- users = get_users_from_db()
24
- for user in users:
25
- if user["token"] == token:
26
- # Parse the expiration time from the database
27
- expiration_time = datetime.fromisoformat(user["token_expiration_time"])
28
-
29
- # Get the current time in the same format
30
- current_time = datetime.now()
31
-
32
- print(f"Token Expiration Time: {expiration_time}")
33
- print(f"Current Time: {current_time}")
34
-
35
- # Check if the token has expired
36
- if current_time < expiration_time:
37
- return True, None # Token is valid
38
- else:
39
- return False, "Token has expired."
40
- return False, "Token not found."
41
-
42
- @app.route('/chat', methods=['POST'])
43
- def chat():
44
- try:
45
- # Ensure the request contains JSON with "message" and "token" keys
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 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
- # Forward the message to the PythonAnywhere endpoint
64
- data = {"message": [{"role": "user", "content": user_input}]}
65
- response = requests.post(PYTHONANYWHERE_URL, json=data)
66
-
67
- if response.status_code == 200:
68
- response_json = response.json()
69
- ai_response = response_json.get("response", "No 'response' key found in the JSON.")
70
- ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
71
- return jsonify({"response": ai_response})
72
  else:
73
- return jsonify({
74
- "error": "Error from PythonAnywhere",
75
- "details": response.text
76
- }), response.status_code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- except Exception as e:
79
- return jsonify({"error": "An error occurred", "details": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  if __name__ == "__main__":
82
  app.run(host="0.0.0.0", port=7860)
 
 
1
  from flask import Flask, request, jsonify
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import json
5
 
6
  app = Flask(__name__)
7
 
8
+ # Step 1: Fetch the authenticity_token and commitOid from the GitHub edit page
9
+ def fetch_authenticity_token_and_commit_oid():
10
+ url = "https://github.com/omarnuwrar/api/edit/main/user.json"
11
 
12
+ headers = {
13
+ "cookie": "_octo=GH1.1.1509769180.1721774314; _device_id=0038e28d4f7d4f9baf8f76b6b9fb8980; _gh_sess=XxMNHmqq58kaNJpj3HKllufdyrUNNjxg3%2FW7rJNFwdwO%2FHbrcT2QcSEdzfhBTWdu3PrkDAVy6vs46R6I5kEENdJ%2Bhixu1gb5HiLv1uKh4lKCiwbG16TlJfbkGXUhvou9zTc9Bszn%2F4HOPD0%2FlG%2BauN1hu2MYcajmfMV%2Fb2R%2FvM8tABljOethGPx5CzrGE1b8EgZxMeOP5wNBrZH4KHPIAD6IAb2z7j%2FJaXHAImK9tmU5CIb5Q9fi9FH6l%2BjWdmSYXekDVHzrKK8mXmO2%2B8N%2BaG0r%2BqoBACKdpj3rbC9x1%2BSKMZjSmu0uNrCmJAPymukisTHFRVtuMikNtEZtVx8QYH%2F9j4hDPs6fOE7wAegPTG7xYeBM1QCNJgiHHGHzoawBFbs0DtEcZwIvRQgVCXYpE0YIUbp6LCEoVxxQeSiTYrBZcoXZ%2F%2BFvw7J7mZSG5pBfo%2FuZ6xQSblzlWpzg--SXX57IvnIMkLdZCr--s5FjBmuKtrEf71mhHx1g2g%3D%3D; saved_user_sessions=155741452%3Avhq2fotRhM6ixLZuU8plCTagdBxOI9UGuu5XwPf569UWHPOg; user_session=vhq2fotRhM6ixLZuU8plCTagdBxOI9UGuu5XwPf569UWHPOg; __Host-user_session_same_site=vhq2fotRhM6ixLZuU8plCTagdBxOI9UGuu5XwPf569UWHPOg; logged_in=yes; dotcom_user=omarnuwrar; color_mode=%7B%22color_mode%22%3A%22auto%22%2C%22light_theme%22%3A%7B%22name%22%3A%22light%22%2C%22color_mode%22%3A%22light%22%7D%2C%22dark_theme%22%3A%7B%22name%22%3A%22dark%22%2C%22color_mode%22%3A%22dark%22%7D%7D; cpu_bucket=lg; preferred_color_mode=light; tz=Africa%2FTripoli",
14
+ "if-none-match": 'W/"2ff86bd1792cfee5ed79ee070b3b46de"',
15
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
16
+ "x-github-target": "dotcom",
17
+ "x-react-router": "json",
18
+ "x-requested-with": "XMLHttpRequest",
19
+ }
20
+
21
+ response = requests.get(url, headers=headers)
22
 
 
 
 
23
  if response.status_code == 200:
24
+ soup = BeautifulSoup(response.text, 'html.parser')
25
+ script_tag = soup.find("script", {"type": "application/json", "data-target": "react-app.embeddedData"})
26
+
27
+ if script_tag:
28
+ try:
29
+ json_data = json.loads(script_tag.string.strip())
30
+ authenticity_token = json_data["payload"]["csrf_tokens"]["/omarnuwrar/api/tree-save/main/user.json"]["post"]
31
+ commit_oid = json_data["payload"]["webCommitInfo"]["commitOid"]
32
+ return authenticity_token, commit_oid
33
+ except (KeyError, json.JSONDecodeError) as e:
34
+ print(f"Error: Failed to extract data. Details: {str(e)}")
35
+ return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  else:
37
+ print("Error: Could not find the required <script> tag.")
38
+ return None, None
39
+ else:
40
+ print(f"Error: Failed to fetch the page. Status code: {response.status_code}")
41
+ return None, None
42
+
43
+ # Step 2: Send the POST request to update the user.json file
44
+ def update_user_json_file(authenticity_token, commit_oid, new_content):
45
+ url = "https://github.com/omarnuwrar/api/tree-save/main/user.json"
46
+
47
+ headers = {
48
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
49
+ "x-requested-with": "XMLHttpRequest",
50
+ "github-verified-fetch": "true",
51
+ "content-type": "application/x-www-form-urlencoded",
52
+ "cookie": "_octo=GH1.1.1509769180.1721774314; _device_id=0038e28d4f7d4f9baf8f76b6b9fb8980; _gh_sess=XxMNHmqq58kaNJpj3HKllufdyrUNNjxg3%2FW7rJNFwdwO%2FHbrcT2QcSEdzfhBTWdu3PrkDAVy6vs46R6I5kEENdJ%2Bhixu1gb5HiLv1uKh4lKCiwbG16TlJfbkGXUhvou9zTc9Bszn%2F4HOPD0%2FlG%2BauN1hu2MYcajmfMV%2Fb2R%2FvM8tABljOethGPx5CzrGE1b8EgZxMeOP5wNBrZH4KHPIAD6IAb2z7j%2FJaXHAImK9tmU5CIb5Q9fi9FH6l%2BjWdmSYXekDVHzrKK8mXmO2%2B8N%2BaG0r%2BqoBACKdpj3rbC9x1%2BSKMZjSmu0uNrCmJAPymukisTHFRVtuMikNtEZtVx8QYH%2F9j4hDPs6fOE7wAegPTG7xYeBM1QCNJgiHHGHzoawBFbs0DtEcZwIvRQgVCXYpE0YIUbp6LCEoVxxQeSiTYrBZcoXZ%2F%2BFvw7J7mZSG5pBfo%2FuZ6xQSblzlWpzg--SXX57IvnIMkLdZCr--s5FjBmuKtrEf71mhHx1g2g%3D%3D; saved_user_sessions=155741452%3Avhq2fotRhM6ixLZuU8plCTagdBxOI9UGuu5XwPf569UWHPOg; user_session=vhq2fotRhM6ixLZuU8plCTagdBxOI9UGuu5XwPf569UWHPOg; __Host-user_session_same_site=vhq2fotRhM6ixLZuU8plCTagdBxOI9UGuu5XwPf569UWHPOg; logged_in=yes; dotcom_user=omarnuwrar; color_mode=%7B%22color_mode%22%3A%22auto%22%2C%22light_theme%22%3A%7B%22name%22%3A%22light%22%2C%22color_mode%22%3A%22light%22%7D%2C%22dark_theme%22%3A%7B%22name%22%3A%22dark%22%2C%22color_mode%22%3A%22dark%22%7D%7D; cpu_bucket=lg; preferred_color_mode=light; tz=Africa%2FTripoli",
53
+ }
54
+
55
+ payload = {
56
+ "message": "Update user.json",
57
+ "placeholder_message": "Update user.json",
58
+ "description": "",
59
+ "commit-choice": "direct",
60
+ "target_branch": "main",
61
+ "quick_pull": "",
62
+ "guidance_task": "",
63
+ "commit": commit_oid,
64
+ "same_repo": "1",
65
+ "pr": "",
66
+ "content_changed": "true",
67
+ "filename": "user.json",
68
+ "new_filename": "user.json",
69
+ "value": new_content,
70
+ "authenticity_token": authenticity_token,
71
+ }
72
+
73
+ response = requests.post(url, headers=headers, data=payload)
74
 
75
+ if response.status_code == 200:
76
+ return {"success": True, "message": "user.json has been updated!"}
77
+ else:
78
+ return {"success": False, "message": f"Request failed with status code {response.status_code}", "details": response.text}
79
+
80
+
81
+ # API Endpoint to update user.json
82
+ @app.route('/update_user_json', methods=['POST'])
83
+ def update_user_json():
84
+ data = request.json
85
+
86
+ if not data or 'content' not in data:
87
+ return jsonify({"success": False, "message": "Invalid request. 'content' field is required."}), 400
88
+
89
+ # Step 1: Fetch the authenticity_token and commitOid
90
+ authenticity_token, commit_oid = fetch_authenticity_token_and_commit_oid()
91
+
92
+ if authenticity_token and commit_oid:
93
+ # Step 2: Perform the file update
94
+ result = update_user_json_file(authenticity_token, commit_oid, data['content'])
95
+ return jsonify(result)
96
+ else:
97
+ return jsonify({"success": False, "message": "Failed to fetch required tokens."}), 500
98
 
99
  if __name__ == "__main__":
100
  app.run(host="0.0.0.0", port=7860)