|
@@ -1,263 +1,50 @@
|
1
|
|
-import requests
|
2
|
|
-from requests.auth import HTTPBasicAuth
|
3
|
1
|
from flask import Flask, request, jsonify
|
|
2
|
+from auth import login, get_csrf_token
|
|
3
|
+from milestone import get_milestone, append_item_to_identifier
|
|
4
|
+from utils import find_username_id, generate_evoluz_link, find_task_type
|
4
|
5
|
|
5
|
6
|
app = Flask(__name__)
|
6
|
7
|
|
7
|
|
-# Config
|
8
|
|
-LOGIN_URL = "http://localhost:7777/user/login"
|
9
|
|
-EDIT_MILESTONE_URL = "http://localhost:7777/setyotontowi/experiments/milestones/1/edit"
|
10
|
|
-EVOLUZ_URL = "http://192.168.1.33:5050/apps/team/detail?"
|
11
|
8
|
USERNAME = "setyotontowi"
|
12
|
9
|
PASSWORD = "nasipadang"
|
13
|
|
-
|
14
|
|
-session = requests.Session() # Keep session across requests
|
15
|
|
-
|
16
|
|
-def login():
|
17
|
|
- """Log in and store session cookies."""
|
18
|
|
- print("Logging in...")
|
19
|
|
- payload = {
|
20
|
|
- "user_name": USERNAME,
|
21
|
|
- "password": PASSWORD
|
22
|
|
- }
|
23
|
|
- response = session.post(LOGIN_URL, data=payload)
|
24
|
|
-
|
25
|
|
- if response.status_code == 200:
|
26
|
|
- print("Login successful.")
|
27
|
|
- return True
|
28
|
|
- else:
|
29
|
|
- print(f"Login failed: {response.status_code} - {response.text}")
|
30
|
|
- return False
|
31
|
|
-
|
32
|
|
-def get_csrf_token():
|
33
|
|
- """Fetch CSRF token from the edit milestone page."""
|
34
|
|
- print("Fetching CSRF token...")
|
35
|
|
-
|
36
|
|
- response = session.get(EDIT_MILESTONE_URL)
|
37
|
|
- if response.status_code == 200:
|
38
|
|
- token = extract_csrf_token(response.text)
|
39
|
|
- if token:
|
40
|
|
- print(f"CSRF token obtained: {token}")
|
41
|
|
- return token
|
42
|
|
- else:
|
43
|
|
- print("Failed to extract CSRF token.")
|
44
|
|
- return None
|
45
|
|
- elif response.status_code == 401: # Unauthorized → Need to re-login
|
46
|
|
- print("Session expired, re-logging in...")
|
47
|
|
- if login():
|
48
|
|
- return get_csrf_token()
|
49
|
|
- else:
|
50
|
|
- print("Failed to log in while fetching CSRF token.")
|
51
|
|
- return None
|
52
|
|
- else:
|
53
|
|
- print(f"Failed to get CSRF token: {response.status_code} - {response.text}")
|
54
|
|
- return None
|
55
|
|
-
|
56
|
|
-def extract_csrf_token(html):
|
57
|
|
- """Extract CSRF token from HTML using regex."""
|
58
|
|
- import re
|
59
|
|
- match = re.search(r'name="_csrf" value="(.*?)"', html)
|
60
|
|
- if match:
|
61
|
|
- return match.group(1)
|
62
|
|
- return None
|
63
|
|
-
|
64
|
|
-def update_milestone(pr_data):
|
65
|
|
- login()
|
66
|
|
- """Update milestone with PR title using CSRF token."""
|
67
|
|
- csrf_token = get_csrf_token()
|
68
|
|
- if not csrf_token:
|
69
|
|
- print("Failed to get CSRF token.")
|
70
|
|
- return False
|
71
|
|
-
|
72
|
|
- content = create_milestone_content(pr_data)
|
73
|
|
-
|
74
|
|
- with open("content.md", "w") as file:
|
75
|
|
- file.write(content)
|
76
|
|
-
|
77
|
|
- payload = {
|
78
|
|
- "_csrf": csrf_token,
|
79
|
|
- "title":"Should change perhaps",
|
80
|
|
- "content": content,
|
81
|
|
- "deadline": "2025-03-31"
|
82
|
|
- }
|
83
|
|
- headers = {
|
84
|
|
- "Content-Type": "application/x-www-form-urlencoded"
|
85
|
|
- }
|
86
|
|
-
|
87
|
|
- response = session.post(EDIT_MILESTONE_URL, data=payload, headers=headers)
|
88
|
|
-
|
89
|
|
- if response.status_code == 200:
|
90
|
|
- print("Milestone updated successfully!")
|
91
|
|
- return True
|
92
|
|
- elif response.status_code == 401: # Unauthorized → Need to re-login
|
93
|
|
- print("Session expired, re-logging in...")
|
94
|
|
- if login():
|
95
|
|
- return update_milestone(pr_data)
|
96
|
|
- else:
|
97
|
|
- print(f"Failed to update milestone: {response.status_code} - {response.text}")
|
98
|
|
- return False
|
99
|
|
-
|
100
|
|
-def create_milestone_content(pr_data):
|
101
|
|
- content = get_milestone()
|
102
|
|
- if content:
|
103
|
|
- # From PR Data, get branch type, and username to assign it to identifier. like feature owi, then it should be
|
104
|
|
- # in feature_lambda
|
105
|
|
- type_task = pr_data.get("task_type")
|
106
|
|
- squad = "sigma"
|
107
|
|
- identifier = f'{type_task}_{squad}'
|
108
|
|
- content['content'] = append_item_to_identifier(content['content'], identifier, pr_data)
|
109
|
|
- return f"{content['content']}\n"
|
110
|
|
- else:
|
111
|
|
- return f"- [] {pr_data['title']}"
|
112
|
|
-
|
113
|
|
-def get_milestone():
|
114
|
|
- import re
|
115
|
|
- response = session.get(EDIT_MILESTONE_URL)
|
116
|
|
- if response.status_code == 200:
|
117
|
|
- title_match = re.search(r'<input[^>]*name=["\']title["\'][^>]*value=["\'](.*?)["\']', response.text, re.IGNORECASE)
|
118
|
|
- content_match = re.search(r'<textarea[^>]*name=["\']content["\'][^>]*>(.*?)</textarea>', response.text, re.IGNORECASE | re.DOTALL)
|
119
|
|
- title = title_match.group(1) if title_match else None
|
120
|
|
- content = content_match.group(1).strip() if content_match else None
|
121
|
|
- return {'title': title, 'content': content}
|
122
|
|
- else:
|
123
|
|
-
|
124
|
|
- return None
|
125
|
|
-
|
126
|
|
-def append_item_to_identifier(encoded_content, identifier, new_item):
|
127
|
|
- # Extract the block delimited by the identifier markers
|
128
|
|
- import re
|
129
|
|
- import html
|
130
|
|
- content = html.unescape(encoded_content)
|
131
|
|
- block_pattern = rf'(<!--\s*{identifier}\s*-->)(.*?)(<!--\s*/{identifier}\s*-->)'
|
132
|
|
- block_match = re.search(block_pattern, content, re.DOTALL)
|
133
|
|
- if not block_match:
|
134
|
|
- print(f"Block with identifier '{identifier}' not found.")
|
135
|
|
- return False
|
136
|
|
-
|
137
|
|
- # Extract the parts of the block
|
138
|
|
- start_marker = block_match.group(1)
|
139
|
|
- block_content = block_match.group(2).strip()
|
140
|
|
- end_marker = block_match.group(3)
|
141
|
|
-
|
142
|
|
- # Append the new item to the block content
|
143
|
|
- formatted_item = f"- [x] {new_item['username']}: [{new_item['title']}]({new_item['link_evoluz']})"
|
144
|
|
- print(formatted_item)
|
145
|
|
- updated_block_content = f"{block_content}\n{formatted_item}"
|
146
|
|
-
|
147
|
|
- # Reconstruct the content with the updated block
|
148
|
|
- updated_content = f"{start_marker}\n{updated_block_content}\n{end_marker}"
|
149
|
|
- content = content.replace(block_match.group(0), updated_content)
|
150
|
|
-
|
151
|
|
- print(f"New item appended to '{identifier}' block.")
|
152
|
|
- return content
|
153
|
|
-
|
154
|
|
-def find_username_id(username):
|
155
|
|
- """
|
156
|
|
- Finds the ID for a given username from the username_id file.
|
157
|
|
-
|
158
|
|
- Args:
|
159
|
|
- username (str): The username to look up.
|
160
|
|
- file_path (str): Path to the username_id file.
|
161
|
|
-
|
162
|
|
- Returns:
|
163
|
|
- str: The ID of the username, or None if not found.
|
164
|
|
- """
|
165
|
|
- try:
|
166
|
|
- with open("username_id", "r", encoding="utf-8") as file:
|
167
|
|
- for line in file:
|
168
|
|
- if line.strip(): # Skip empty lines
|
169
|
|
- user, user_id = line.strip().split(":")
|
170
|
|
- if user == username:
|
171
|
|
- return user_id
|
172
|
|
- print(f"Username '{username}' not found.")
|
173
|
|
- return None
|
174
|
|
- except FileNotFoundError:
|
175
|
|
- print(f"File not found: {file_path}")
|
176
|
|
- return None
|
177
|
|
- except Exception as e:
|
178
|
|
- print(f"An error occurred: {e}")
|
179
|
|
- return None
|
180
|
|
-
|
181
|
|
-def generate_evoluz_link(username_id, task_id) :
|
182
|
|
- team_id = f"teamID={username_id}"
|
183
|
|
- update_team_id = f"updateTeamId={task_id}"
|
184
|
|
-
|
185
|
|
- full_url = f"{EVOLUZ_URL}{team_id}&{update_team_id}"
|
186
|
|
- return full_url
|
187
|
|
-
|
188
|
|
-def find_task_type(branch_name) :
|
189
|
|
- """
|
190
|
|
- Extracts the branch type and task ID from the branch name.
|
191
|
|
-
|
192
|
|
- Args:
|
193
|
|
- branch_name (str): The branch name (e.g., "feature/1234_task_name").
|
194
|
|
-
|
195
|
|
- Returns:
|
196
|
|
- dict: A dictionary with 'branch_type' and 'task_id', or None if invalid format.
|
197
|
|
- """
|
198
|
|
- try:
|
199
|
|
- # Split the branch name by "/"
|
200
|
|
- parts = branch_name.split("/")
|
201
|
|
- if len(parts) >= 2:
|
202
|
|
- branch_type = parts[0] # The first part is the branch type
|
203
|
|
- task = parts[1]
|
204
|
|
- task_id = task.split("_")[0] # The second part is the task ID
|
205
|
|
- return {"task_type": branch_type, "task_id": task_id}
|
206
|
|
- else:
|
207
|
|
- print(f"Invalid branch name format: {branch_name}")
|
208
|
|
- return None
|
209
|
|
- except Exception as e:
|
210
|
|
- print(f"Error extracting task type: {e}")
|
211
|
|
- return None
|
|
10
|
+EVOLUZ_URL = "http://192.168.1.33:5050/apps/team/detail?"
|
212
|
11
|
|
213
|
12
|
@app.route('/webhook', methods=['POST'])
|
214
|
13
|
def handle_webhook():
|
215
|
|
- if request.method != 'POST':
|
216
|
|
- return 'Invalid request method', 405
|
217
|
|
-
|
218
|
14
|
try:
|
219
|
15
|
payload = request.get_json()
|
220
|
16
|
if not payload:
|
221
|
17
|
return 'Invalid JSON payload', 400
|
222
|
18
|
|
223
|
|
- # Handle Pull Request Event
|
224
|
19
|
if 'pull_request' in payload:
|
225
|
20
|
pr = payload.get('pull_request', {})
|
226
|
|
-
|
227
|
21
|
pr_title = pr.get('title')
|
228
|
22
|
pr_username = pr.get('user').get('username')
|
229
|
|
- pr_username_id = find_username_id(pr_username)
|
230
|
23
|
pr_branch = pr.get('head_branch')
|
231
|
24
|
pr_branch_data = find_task_type(pr_branch)
|
232
|
|
-
|
|
25
|
+
|
233
|
26
|
pr_data = {
|
234
|
27
|
'title': pr_title,
|
235
|
28
|
'username': pr_username.capitalize(),
|
236
|
29
|
'branch': pr_branch,
|
237
|
30
|
'task_type': pr_branch_data.get("task_type"),
|
238
|
31
|
'user_id': find_username_id(pr_username),
|
239
|
|
- 'link_evoluz': generate_evoluz_link(pr_username_id, pr_branch_data.get("task_id"))
|
|
32
|
+ 'link_evoluz': generate_evoluz_link(find_username_id(pr_username), pr_branch_data.get("task_id"), EVOLUZ_URL)
|
240
|
33
|
}
|
241
|
34
|
|
242
|
|
- print(f"Received PR: {pr_title}")
|
243
|
|
-
|
244
|
|
- # Update milestone with PR title
|
245
|
35
|
if update_milestone(pr_data):
|
246
|
|
- print("Milestone updated with PR title.")
|
|
36
|
+ print("Milestone updated successfully.")
|
247
|
37
|
else:
|
248
|
38
|
print("Failed to update milestone.")
|
249
|
39
|
|
250
|
40
|
return jsonify({'status': 'success'}), 200
|
251
|
|
-
|
252
|
41
|
except Exception as e:
|
253
|
42
|
print(f"Error: {e}")
|
254
|
43
|
return 'Internal server error', 500
|
255
|
44
|
|
256
|
45
|
if __name__ == '__main__':
|
257
|
|
- if login(): # Attempt login at startup
|
|
46
|
+ if login(USERNAME, PASSWORD):
|
258
|
47
|
print("Initial login successful.")
|
259
|
|
- milestone = get_milestone()
|
260
|
|
- print(milestone)
|
261
|
48
|
else:
|
262
|
49
|
print("Initial login failed.")
|
263
|
|
- app.run(port=4001)
|
|
50
|
+ app.run(port=4001)
|