Browse Source

works, troubleshooting

Tontowi Prasetyo 5 months ago
parent
commit
0e7929e7c3
7 changed files with 144 additions and 13 deletions
  1. 6 3
      auth.py
  2. 1 0
      content.md
  3. 2 4
      gogmilestone2.py
  4. 68 6
      milestone.py
  5. 12 0
      testcase.md
  6. 36 0
      uninstall.sh
  7. 19 0
      utils.py

+ 6 - 3
auth.py

@@ -4,12 +4,15 @@ LOGIN_URL = "http://localhost:7777/user/login"
4 4
 EDIT_MILESTONE_URL = "http://localhost:7777/setyotontowi/experiments/milestones/1/edit"
5 5
 session = requests.Session()
6 6
 
7
-def login(username, password):
7
+USERNAME = "setyotontowi"
8
+PASSWORD = "nasipadang"
9
+
10
+def login():
8 11
     """Log in and store session cookies."""
9 12
     print("Logging in...")
10 13
     payload = {
11
-        "user_name": username,
12
-        "password": password
14
+        "user_name": USERNAME,
15
+        "password": PASSWORD
13 16
     }
14 17
     response = session.post(LOGIN_URL, data=payload)
15 18
     if response.status_code == 200:

+ 1 - 0
content.md

@@ -7,4 +7,5 @@ Team Sigma Σ
7 7
 - [ ] Lambang: [Klinik | PCARE - Analisis Bridging PCARE ke SIMRS](http://192.168.1.33:5050/apps/team/detail?teamId=22&updateTeamId=3619)
8 8
 - [x] Hilyas: [RSI Banjarnegara | Tambah filter sesuai kelas pasien di tab tindakan edoc seperti di SIMRS](http://192.168.1.33:5050/apps/team/detail?teamId=8&updateTeamId=2580)
9 9
 - [x] Setyotontowi: [Add Something](http://192.168.1.33:5050/apps/team/detail?teamID=20&updateTeamId=1232)
10
+- [x] Setyotontowi: [Add Something](http://192.168.1.33:5050/apps/team/detail?teamID=40&updateTeamId=1232)
10 11
 <!-- /feature_sigma -->

+ 2 - 4
gogmilestone2.py

@@ -1,12 +1,10 @@
1 1
 from flask import Flask, request, jsonify
2 2
 from auth import login, get_csrf_token
3
-from milestone import get_milestone, append_item_to_identifier
3
+from milestone import update_milestone, get_milestone, append_item_to_identifier
4 4
 from utils import find_username_id, generate_evoluz_link, find_task_type
5 5
 
6 6
 app = Flask(__name__)
7 7
 
8
-USERNAME = "setyotontowi"
9
-PASSWORD = "nasipadang"
10 8
 EVOLUZ_URL = "http://192.168.1.33:5050/apps/team/detail?"
11 9
 
12 10
 @app.route('/webhook', methods=['POST'])
@@ -47,7 +45,7 @@ def index():
47 45
     return "Webhook server is running."
48 46
 
49 47
 if __name__ == '__main__':
50
-    if login(USERNAME, PASSWORD):
48
+    if login():
51 49
         print("Initial login successful.")
52 50
     else:
53 51
         print("Initial login failed.")

+ 68 - 6
milestone.py

@@ -1,21 +1,77 @@
1 1
 import re
2 2
 import html
3
+from utils import find_squad
4
+from auth import login, get_csrf_token, EDIT_MILESTONE_URL, session
3 5
 
4
-def get_milestone(session, edit_milestone_url):
6
+def update_milestone(pr_data):
7
+    login()
8
+    """Update milestone with PR title using CSRF token."""
9
+    csrf_token = get_csrf_token()
10
+    if not csrf_token:
11
+        print("Failed to get CSRF token.")
12
+        return False
13
+
14
+    meta = get_milestone(session)
15
+    content = create_milestone_content(meta.get("content"), pr_data)
16
+
17
+    print(f"Updating milestone with content:\n")
18
+
19
+    with open("content.md", "w") as file:
20
+        file.write(content)
21
+
22
+    payload = {
23
+        "_csrf": csrf_token,
24
+        "title": meta.get("title"),
25
+        "content": content,
26
+        "deadline": meta.get("deadline")
27
+    }
28
+    headers = {
29
+        "Content-Type": "application/x-www-form-urlencoded"
30
+    }
31
+
32
+
33
+    response = session.post(EDIT_MILESTONE_URL, data=payload, headers=headers)
34
+
35
+    if response.status_code == 200:
36
+        print("Milestone updated successfully!")
37
+        return True
38
+    elif response.status_code == 401:  # Unauthorized → Need to re-login
39
+        print("Session expired, re-logging in...")
40
+        if login():
41
+            return update_milestone(pr_data)
42
+    else:
43
+        print(f"Failed to update milestone: {response.status_code} - {response.text}")
44
+        return False
45
+
46
+def create_milestone_content(content, pr_data):
47
+    if content:
48
+        # From PR Data, get branch type, and username to assign it to identifier. like feature owi, then it should be
49
+        # in feature_lambda
50
+        type_task = pr_data.get("task_type")
51
+        squad = "sigma"
52
+        identifier = f'{type_task}_{squad}'
53
+        content = append_item_to_identifier(content, identifier, pr_data)
54
+        return f"{content}\n"
55
+    else:
56
+        return f"- [] {pr_data['title']}"
57
+
58
+def get_milestone(session):
5 59
     """Fetch milestone details."""
6
-    response = session.get(edit_milestone_url)
60
+    response = session.get(EDIT_MILESTONE_URL)
7 61
     if response.status_code == 200:
8
-        title_match = re.search(r'<input[^>]*name=["\']title["\'][^>]*value=["\'](.*?)["\']', response.text, re.IGNORECASE)
62
+        title_match = re.search(r'<input[^>]*name=["\']title["\'][^>]*value=["\'](.* ?)["\']', response.text, re.IGNORECASE)
9 63
         content_match = re.search(r'<textarea[^>]*name=["\']content["\'][^>]*>(.*?)</textarea>', response.text, re.IGNORECASE | re.DOTALL)
64
+        deadline_match = re.search(r'<input[^>]*name=["\']deadline["\'][^>]*value=["\'](.*?)["\']', response.text, re.IGNORECASE)
10 65
         title = title_match.group(1) if title_match else None
11 66
         content = content_match.group(1).strip() if content_match else None
12
-        return {'title': title, 'content': content}
67
+        deadline = deadline_match.group(1) if deadline_match else None
68
+        return {'title': title, 'content': content, 'deadline': deadline}
13 69
     else:
14 70
         print(f"Failed to fetch milestone: {response.status_code}")
15 71
         return None
16 72
 
17 73
 def append_item_to_identifier(encoded_content, identifier, new_item):
18
-    """Append a new item to the block identified by the given identifier."""
74
+    # Extract the block delimited by the identifier markers
19 75
     content = html.unescape(encoded_content)
20 76
     block_pattern = rf'(<!--\s*{identifier}\s*-->)(.*?)(<!--\s*/{identifier}\s*-->)'
21 77
     block_match = re.search(block_pattern, content, re.DOTALL)
@@ -23,12 +79,18 @@ def append_item_to_identifier(encoded_content, identifier, new_item):
23 79
         print(f"Block with identifier '{identifier}' not found.")
24 80
         return False
25 81
 
82
+    # Extract the parts of the block
26 83
     start_marker = block_match.group(1)
27 84
     block_content = block_match.group(2).strip()
28 85
     end_marker = block_match.group(3)
29 86
 
87
+    # Append the new item to the block content
30 88
     formatted_item = f"- [x] {new_item['username']}: [{new_item['title']}]({new_item['link_evoluz']})"
31 89
     updated_block_content = f"{block_content}\n{formatted_item}"
32 90
 
91
+    # Reconstruct the content with the updated block
33 92
     updated_content = f"{start_marker}\n{updated_block_content}\n{end_marker}"
34
-    return updated_content
93
+    content = content.replace(block_match.group(0), updated_content)
94
+
95
+    print(f"New item appended to '{identifier}' block.")
96
+    return content

+ 12 - 0
testcase.md

@@ -0,0 +1,12 @@
1
+### Happy Path
2
+- [ ] Create PR, it should add the data to milestone
3
+
4
+### Side case
5
+- [ ] Sprint Transition
6
+- [ ] Add new people
7
+
8
+### Negative
9
+- [ ] Unmerged PR
10
+
11
+### Thinking
12
+- if repo is production

+ 36 - 0
uninstall.sh

@@ -0,0 +1,36 @@
1
+#!/bin/bash
2
+
3
+# filepath: /home/setyotontowi/BackendProject/gogsmilestone/uninstall.sh
4
+
5
+# Dynamically determine the project directory
6
+PROJECT_DIR=$(dirname "$(realpath "$0")")
7
+
8
+echo "Uninstalling the project from $PROJECT_DIR..."
9
+
10
+# Step 1: Stop and disable the systemd service
11
+SERVICE_FILE="/etc/systemd/system/gogmilestone.service"
12
+if [ -f "$SERVICE_FILE" ]; then
13
+    echo "Stopping the gogmilestone service..."
14
+    sudo systemctl stop gogmilestone
15
+
16
+    echo "Disabling the gogmilestone service..."
17
+    sudo systemctl disable gogmilestone
18
+
19
+    echo "Removing the gogmilestone service file..."
20
+    sudo rm -f "$SERVICE_FILE"
21
+
22
+    echo "Reloading systemd daemon..."
23
+    sudo systemctl daemon-reload
24
+else
25
+    echo "Service file not found. Skipping service removal."
26
+fi
27
+
28
+# Step 2: Delete the virtual environment
29
+if [ -d "$PROJECT_DIR/venv" ]; then
30
+    echo "Removing the virtual environment..."
31
+    rm -rf "$PROJECT_DIR/venv"
32
+else
33
+    echo "Virtual environment not found. Skipping removal."
34
+fi
35
+
36
+echo "Uninstallation complete."

+ 19 - 0
utils.py

@@ -35,4 +35,23 @@ def find_task_type(branch_name):
35 35
             return None
36 36
     except Exception as e:
37 37
         print(f"Error extracting task type: {e}")
38
+        return None
39
+
40
+def find_squad(username):
41
+    """Find the squad for a given username from the username_squad file."""
42
+    file_path = "username_squad"
43
+    try:
44
+        with open(file_path, "r", encoding="utf-8") as file:
45
+            for line in file:
46
+                if line.strip():
47
+                    user, squad = line.strip().split(":")
48
+                    if user.lower() == username.lower():
49
+                        return squad.lower()
50
+        print(f"Username '{username}' not found in squad file.")
51
+        return None
52
+    except FileNotFoundError:
53
+        print(f"Squad file not found: {file_path}")
54
+        return None
55
+    except Exception as e:
56
+        print(f"An error occurred while finding squad: {e}")
38 57
         return None