Dooratre commited on
Commit
63162af
·
verified ·
1 Parent(s): e4a8c93

Update db_signals.py

Browse files
Files changed (1) hide show
  1. db_signals.py +137 -137
db_signals.py CHANGED
@@ -1,138 +1,138 @@
1
- import requests
2
- from bs4 import BeautifulSoup
3
- import json
4
-
5
- # NOTE: Keep this token safe. If you rotate it, update here.
6
- TOKEN = "_device_id=0038e28d4f7d4f9baf8f76b6b9fb8980; GHCC=Required:1-Analytics:1-SocialMedia:1-Advertising:1; MicrosoftApplicationsTelemetryDeviceId=c58113b4-9acb-4ba8-b9f2-4217bdef379a; MSFPC=GUID=79b87b010d464a8783fbf43e19eccddf&HASH=79b8&LV=202408&V=4&LU=1723654762596; _octo=GH1.1.1517954811.1753352111; cpu_bucket=lg; preferred_color_mode=dark; tz=Africa%2FTripoli; ai_session=v+6N2XPmhlxugZWyisQ+ZD|1753646990500|1753646990500; saved_user_sessions=155741452%3ASnvRnrrf0nAjVGrTz3q28Oda2y6wCt6rCADoDwrCx2M6pORt; user_session=SnvRnrrf0nAjVGrTz3q28Oda2y6wCt6rCADoDwrCx2M6pORt; __Host-user_session_same_site=SnvRnrrf0nAjVGrTz3q28Oda2y6wCt6rCADoDwrCx2M6pORt; tz=Africa%2FTripoli; 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; logged_in=yes; dotcom_user=omarnuwrar; _gh_sess=7FzMK5K8ffnmyyh5LKKv%2FOXiqZJR4qLXxTdaV66E844ZCPq5qw%2FClaVmXHNfu8oc61N461wsjEr7d8vhEwrs0N0X7ITUed9Zj01RnwHGT8mMRUn6oYSv94LpIh2FwmotPwp8jkSQkZ%2BotdEpdYtp3ZoJZKfiZOcpHBtT7g2VwIPgoW2Qx5RpnKNdI3Hq31C6IIPaSzAqqny7O7c6L8nWv1nfx%2FAbF4UFSo7UfW%2F9JLUYF5lVJ2kXdYoesKOL7c2KItGDTaZCwjYr9cHKlHWD4E9wLo22GjFveVKxrEz5dgIrNdAj8WxWXuY5Ou4eYmxaBn2ovIhvnFz8%2F6qLURX81YxLLZbymGERA3MaRzDDzY3yE76U8y8lLPve0Duqc0lr34R3XUiMKE5A3%2FNPQ273e36yNlLsgBGDyuYIEcsQ84XLq2IQygBxX4y%2B6WSPwXAgOku6MiEP8Ro9ihF6scOhbJRrVCPp0toSY3RmJToUy6XRmBF2B0oyJstKbqLPfmZI8p%2B2bQo8DBKARHWWUzTJdjF%2BfgZtm%2Flb3qijcKT5I6SPU%2BiLMH%2Fl2GwHw73d1OFGUNy4tdLT5SO5vCFrf1GIiV7qUhhQdA21dXsAeQ4qoF5LHiGftyhOUBHto3ZZB%2FJ87uqACflXOfbbTCQCAYNa2u4o8I9iKQp9r2ripVxqQF1oyVu12FSIN%2BS%2Fd4Rm%2FN7E1tOw3tcVgYcsFEcbsOViUZBXXmo1Qfd9H%2B4IGnbv3hZe%2FPeJqb33SxWeQpamEWhLjVJL2hMCbZ8v79azeUL93QzkLXuryStKTXOdoyrbD2n93V36z5Sxhzi9Ku6OxVK1PCZW0R7JiYtQOWoeMAMd4oe3Bqrxyc%2BdAdb0sW3L%2FOD8J2nbvJ5gGA%3D%3D--Ngvrt5zzlDZazWNi--k%2F8wjhX57aMmLOJc8i6L7w%3D%3D"
7
-
8
- EDIT_URL = "https://github.com/omarnuwrar/Trading/edit/main/signals.json"
9
- SAVE_URL = "https://github.com/omarnuwrar/Trading/tree-save/main/signals.json"
10
- BLOB_URL = "https://github.com/omarnuwrar/Trading/blob/main/signals.json"
11
-
12
- # ------------------------------------------------------------
13
- # 1) Fetch authenticity_token and commitOid from the edit page
14
- # ------------------------------------------------------------
15
- def fetch_authenticity_token_and_commit_oid():
16
- headers = {
17
- "cookie": TOKEN,
18
- "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",
19
- "x-github-target": "dotcom",
20
- "x-react-router": "json",
21
- "x-requested-with": "XMLHttpRequest",
22
- }
23
- response = requests.get(EDIT_URL, headers=headers)
24
- if response.status_code != 200:
25
- print(f"Error: Failed to fetch the page. Status code: {response.status_code}")
26
- return None, None
27
-
28
- soup = BeautifulSoup(response.text, 'html.parser')
29
- script_tag = soup.find("script", {"type": "application/json", "data-target": "react-app.embeddedData"})
30
- if not script_tag:
31
- print("Error: Could not find the required <script> tag.")
32
- return None, None
33
-
34
- try:
35
- json_data = json.loads(script_tag.string.strip())
36
- authenticity_token = json_data["payload"]["csrf_tokens"]["/omarnuwrar/Trading/tree-save/main/signals.json"]["post"]
37
- commit_oid = json_data["payload"]["webCommitInfo"]["commitOid"]
38
- return authenticity_token, commit_oid
39
- except (KeyError, json.JSONDecodeError) as e:
40
- print(f"Error: Failed to extract data. Details: {str(e)}")
41
- return None, None
42
-
43
- # ------------------------------------------------------------
44
- # 2) Update the signals.json file with new content (string)
45
- # ------------------------------------------------------------
46
- def update_user_json_file(authenticity_token, commit_oid, new_content: str):
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": TOKEN,
53
- }
54
-
55
- payload = {
56
- "message": "Update signals.json",
57
- "placeholder_message": "Update signals.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": "signals.json",
68
- "new_filename": "signals.json",
69
- "value": new_content,
70
- "authenticity_token": authenticity_token,
71
- }
72
-
73
- response = requests.post(SAVE_URL, headers=headers, data=payload)
74
- if response.status_code == 200:
75
- return {"success": True, "message": "signals.json has been updated!"}
76
- else:
77
- return {"success": False, "message": f"Request failed with status code {response.status_code}", "details": response.text}
78
-
79
- # ------------------------------------------------------------
80
- # 3) Read the current signals.json content (as text), robustly
81
- # ------------------------------------------------------------
82
- def get_user_json_file(authenticity_token: str = None, commit_oid: str = None) -> dict:
83
- """
84
- Returns:
85
- {"success": True, "content": "<raw json text>"} on success
86
- {"success": False, "message": "..."} on failure
87
-
88
- We scrape the blob page and extract the embedded rawLines, joining them safely.
89
- This works whether signals.json is an object {"scenario": ...}, an array [ ... ], or [].
90
- """
91
- headers = {
92
- "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",
93
- "Cookie": TOKEN,
94
- }
95
- try:
96
- resp = requests.get(BLOB_URL, headers=headers)
97
- resp.raise_for_status()
98
- soup = BeautifulSoup(resp.text, 'html.parser')
99
- script_tag = soup.find('script', {'type': 'application/json', 'data-target': 'react-app.embeddedData'})
100
- if not script_tag:
101
- return {"success": False, "message": "Embedded JSON script tag not found"}
102
- embedded_data = json.loads(script_tag.string)
103
- raw_lines = embedded_data.get("payload", {}).get("blob", {}).get("rawLines", [])
104
- if not raw_lines:
105
- # Empty file or cannot parse; treat as empty
106
- return {"success": True, "content": ""}
107
- # Join lines into full JSON text; rawLines is a list of strings comprising the file content lines.
108
- # In many cases signals.json is one line, but we join generally.
109
- json_text = "\n".join(raw_lines)
110
- return {"success": True, "content": json_text}
111
- except requests.exceptions.RequestException as e:
112
- return {"success": False, "message": f"HTTP error fetching blob: {e}"}
113
- except json.JSONDecodeError as je:
114
- return {"success": False, "message": f"Error parsing embedded JSON: {je}"}
115
- except Exception as ex:
116
- return {"success": False, "message": f"Unexpected error: {ex}"}
117
-
118
- # ------------------------------------------------------------
119
- # 4) Convenience: return parsed JSON (object or list), or defaults
120
- # ------------------------------------------------------------
121
- def read_signals_json():
122
- """
123
- Returns a tuple (ok: bool, data: object, note: str)
124
- - If ok=True, data is parsed JSON (dict or list).
125
- - If ok=False, data is None and note explains why.
126
- """
127
- res = get_user_json_file()
128
- if not res.get("success"):
129
- return False, None, res.get("message", "Unknown error")
130
- raw = res.get("content", "")
131
- if not raw:
132
- # Empty file -> treat as empty array by convention
133
- return True, [], "Empty content"
134
- try:
135
- parsed = json.loads(raw)
136
- return True, parsed, "OK"
137
- except Exception as e:
138
  return False, None, f"JSON parse error: {e}"
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import json
4
+
5
+ # NOTE: Keep this token safe. If you rotate it, update here.
6
+ TOKEN = "_device_id=0038e28d4f7d4f9baf8f76b6b9fb8980; GHCC=Required:1-Analytics:1-SocialMedia:1-Advertising:1; MicrosoftApplicationsTelemetryDeviceId=c58113b4-9acb-4ba8-b9f2-4217bdef379a; MSFPC=GUID=79b87b010d464a8783fbf43e19eccddf&HASH=79b8&LV=202408&V=4&LU=1723654762596; _octo=GH1.1.1517954811.1753352111; cpu_bucket=lg; preferred_color_mode=dark; tz=Africa%2FTripoli; ai_session=v+6N2XPmhlxugZWyisQ+ZD|1753646990500|1753646990500; saved_user_sessions=155741452%3ASnvRnrrf0nAjVGrTz3q28Oda2y6wCt6rCADoDwrCx2M6pORt; user_session=SnvRnrrf0nAjVGrTz3q28Oda2y6wCt6rCADoDwrCx2M6pORt; __Host-user_session_same_site=SnvRnrrf0nAjVGrTz3q28Oda2y6wCt6rCADoDwrCx2M6pORt; tz=Africa%2FTripoli; 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; logged_in=yes; dotcom_user=omarnuwrar; _gh_sess=7FzMK5K8ffnmyyh5LKKv%2FOXiqZJR4qLXxTdaV66E844ZCPq5qw%2FClaVmXHNfu8oc61N461wsjEr7d8vhEwrs0N0X7ITUed9Zj01RnwHGT8mMRUn6oYSv94LpIh2FwmotPwp8jkSQkZ%2BotdEpdYtp3ZoJZKfiZOcpHBtT7g2VwIPgoW2Qx5RpnKNdI3Hq31C6IIPaSzAqqny7O7c6L8nWv1nfx%2FAbF4UFSo7UfW%2F9JLUYF5lVJ2kXdYoesKOL7c2KItGDTaZCwjYr9cHKlHWD4E9wLo22GjFveVKxrEz5dgIrNdAj8WxWXuY5Ou4eYmxaBn2ovIhvnFz8%2F6qLURX81YxLLZbymGERA3MaRzDDzY3yE76U8y8lLPve0Duqc0lr34R3XUiMKE5A3%2FNPQ273e36yNlLsgBGDyuYIEcsQ84XLq2IQygBxX4y%2B6WSPwXAgOku6MiEP8Ro9ihF6scOhbJRrVCPp0toSY3RmJToUy6XRmBF2B0oyJstKbqLPfmZI8p%2B2bQo8DBKARHWWUzTJdjF%2BfgZtm%2Flb3qijcKT5I6SPU%2BiLMH%2Fl2GwHw73d1OFGUNy4tdLT5SO5vCFrf1GIiV7qUhhQdA21dXsAeQ4qoF5LHiGftyhOUBHto3ZZB%2FJ87uqACflXOfbbTCQCAYNa2u4o8I9iKQp9r2ripVxqQF1oyVu12FSIN%2BS%2Fd4Rm%2FN7E1tOw3tcVgYcsFEcbsOViUZBXXmo1Qfd9H%2B4IGnbv3hZe%2FPeJqb33SxWeQpamEWhLjVJL2hMCbZ8v79azeUL93QzkLXuryStKTXOdoyrbD2n93V36z5Sxhzi9Ku6OxVK1PCZW0R7JiYtQOWoeMAMd4oe3Bqrxyc%2BdAdb0sW3L%2FOD8J2nbvJ5gGA%3D%3D--Ngvrt5zzlDZazWNi--k%2F8wjhX57aMmLOJc8i6L7w%3D%3D"
7
+
8
+ EDIT_URL = "https://github.com/omarnuwrar/Trading/edit/main/signals2.json"
9
+ SAVE_URL = "https://github.com/omarnuwrar/Trading/tree-save/main/signals2.json"
10
+ BLOB_URL = "https://github.com/omarnuwrar/Trading/blob/main/signals2.json"
11
+
12
+ # ------------------------------------------------------------
13
+ # 1) Fetch authenticity_token and commitOid from the edit page
14
+ # ------------------------------------------------------------
15
+ def fetch_authenticity_token_and_commit_oid():
16
+ headers = {
17
+ "cookie": TOKEN,
18
+ "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",
19
+ "x-github-target": "dotcom",
20
+ "x-react-router": "json",
21
+ "x-requested-with": "XMLHttpRequest",
22
+ }
23
+ response = requests.get(EDIT_URL, headers=headers)
24
+ if response.status_code != 200:
25
+ print(f"Error: Failed to fetch the page. Status code: {response.status_code}")
26
+ return None, None
27
+
28
+ soup = BeautifulSoup(response.text, 'html.parser')
29
+ script_tag = soup.find("script", {"type": "application/json", "data-target": "react-app.embeddedData"})
30
+ if not script_tag:
31
+ print("Error: Could not find the required <script> tag.")
32
+ return None, None
33
+
34
+ try:
35
+ json_data = json.loads(script_tag.string.strip())
36
+ authenticity_token = json_data["payload"]["csrf_tokens"]["/omarnuwrar/Trading/tree-save/main/signals2.json"]["post"]
37
+ commit_oid = json_data["payload"]["webCommitInfo"]["commitOid"]
38
+ return authenticity_token, commit_oid
39
+ except (KeyError, json.JSONDecodeError) as e:
40
+ print(f"Error: Failed to extract data. Details: {str(e)}")
41
+ return None, None
42
+
43
+ # ------------------------------------------------------------
44
+ # 2) Update the signals2.json file with new content (string)
45
+ # ------------------------------------------------------------
46
+ def update_user_json_file(authenticity_token, commit_oid, new_content: str):
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": TOKEN,
53
+ }
54
+
55
+ payload = {
56
+ "message": "Update signals2.json",
57
+ "placeholder_message": "Update signals2.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": "signals2.json",
68
+ "new_filename": "signals2.json",
69
+ "value": new_content,
70
+ "authenticity_token": authenticity_token,
71
+ }
72
+
73
+ response = requests.post(SAVE_URL, headers=headers, data=payload)
74
+ if response.status_code == 200:
75
+ return {"success": True, "message": "signals2.json has been updated!"}
76
+ else:
77
+ return {"success": False, "message": f"Request failed with status code {response.status_code}", "details": response.text}
78
+
79
+ # ------------------------------------------------------------
80
+ # 3) Read the current signals2.json content (as text), robustly
81
+ # ------------------------------------------------------------
82
+ def get_user_json_file(authenticity_token: str = None, commit_oid: str = None) -> dict:
83
+ """
84
+ Returns:
85
+ {"success": True, "content": "<raw json text>"} on success
86
+ {"success": False, "message": "..."} on failure
87
+
88
+ We scrape the blob page and extract the embedded rawLines, joining them safely.
89
+ This works whether signals2.json is an object {"scenario": ...}, an array [ ... ], or [].
90
+ """
91
+ headers = {
92
+ "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",
93
+ "Cookie": TOKEN,
94
+ }
95
+ try:
96
+ resp = requests.get(BLOB_URL, headers=headers)
97
+ resp.raise_for_status()
98
+ soup = BeautifulSoup(resp.text, 'html.parser')
99
+ script_tag = soup.find('script', {'type': 'application/json', 'data-target': 'react-app.embeddedData'})
100
+ if not script_tag:
101
+ return {"success": False, "message": "Embedded JSON script tag not found"}
102
+ embedded_data = json.loads(script_tag.string)
103
+ raw_lines = embedded_data.get("payload", {}).get("blob", {}).get("rawLines", [])
104
+ if not raw_lines:
105
+ # Empty file or cannot parse; treat as empty
106
+ return {"success": True, "content": ""}
107
+ # Join lines into full JSON text; rawLines is a list of strings comprising the file content lines.
108
+ # In many cases signals2.json is one line, but we join generally.
109
+ json_text = "\n".join(raw_lines)
110
+ return {"success": True, "content": json_text}
111
+ except requests.exceptions.RequestException as e:
112
+ return {"success": False, "message": f"HTTP error fetching blob: {e}"}
113
+ except json.JSONDecodeError as je:
114
+ return {"success": False, "message": f"Error parsing embedded JSON: {je}"}
115
+ except Exception as ex:
116
+ return {"success": False, "message": f"Unexpected error: {ex}"}
117
+
118
+ # ------------------------------------------------------------
119
+ # 4) Convenience: return parsed JSON (object or list), or defaults
120
+ # ------------------------------------------------------------
121
+ def read_signals_json():
122
+ """
123
+ Returns a tuple (ok: bool, data: object, note: str)
124
+ - If ok=True, data is parsed JSON (dict or list).
125
+ - If ok=False, data is None and note explains why.
126
+ """
127
+ res = get_user_json_file()
128
+ if not res.get("success"):
129
+ return False, None, res.get("message", "Unknown error")
130
+ raw = res.get("content", "")
131
+ if not raw:
132
+ # Empty file -> treat as empty array by convention
133
+ return True, [], "Empty content"
134
+ try:
135
+ parsed = json.loads(raw)
136
+ return True, parsed, "OK"
137
+ except Exception as e:
138
  return False, None, f"JSON parse error: {e}"