forked from AndyEverything/openproject-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
1701 lines (1393 loc) · 55.1 KB
/
Copy pathclient.py
File metadata and controls
1701 lines (1393 loc) · 55.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
OpenProject API Client
A comprehensive async client for OpenProject API v3 with proxy support.
"""
import os
import json
import logging
from typing import Dict, List, Optional, Any
from datetime import datetime
import asyncio
import aiohttp
from urllib.parse import quote
import base64
import ssl
# Configure logging
logger = logging.getLogger(__name__)
# Version information
__version__ = "2.0.0"
class OpenProjectClient:
"""Client for the OpenProject API v3 with optional proxy support"""
def __init__(self, base_url: str, api_key: str, proxy: Optional[str] = None):
"""
Initialize the OpenProject client.
Args:
base_url: The base URL of the OpenProject instance
api_key: API key for authentication
proxy: Optional HTTP proxy URL
"""
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.proxy = proxy
# Setup headers with Basic Auth
self.headers = {
"Authorization": f"Basic {self._encode_api_key()}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": f"OpenProject-MCP/{__version__}",
}
logger.info(f"OpenProject Client initialized for: {self.base_url}")
if self.proxy:
logger.info(f"Using proxy: {self.proxy}")
def _encode_api_key(self) -> str:
"""Encode API key for Basic Auth"""
credentials = f"apikey:{self.api_key}"
return base64.b64encode(credentials.encode()).decode()
async def _request(
self, method: str, endpoint: str, data: Optional[Dict] = None
) -> Dict:
"""
Execute an API request.
Args:
method: HTTP method (GET, POST, etc.)
endpoint: API endpoint path
data: Optional request body data
Returns:
Dict: Response data from the API
Raises:
Exception: If the request fails
"""
url = f"{self.base_url}/api/v3{endpoint}"
logger.debug(f"API Request: {method} {url}")
if data:
logger.debug(f"Request body: {json.dumps(data, indent=2)}")
# Configure SSL and timeout
ssl_context = ssl.create_default_context()
connector = aiohttp.TCPConnector(ssl=ssl_context)
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(
connector=connector, timeout=timeout
) as session:
try:
# Build request parameters
request_params = {
"method": method,
"url": url,
"headers": self.headers,
"json": data,
}
# Add proxy if configured
if self.proxy:
request_params["proxy"] = self.proxy
async with session.request(**request_params) as response:
response_text = await response.text()
logger.debug(f"Response status: {response.status}")
# Parse response
try:
response_json = (
json.loads(response_text) if response_text else {}
)
except json.JSONDecodeError:
logger.error(f"Invalid JSON response: {response_text[:200]}...")
response_json = {}
# Handle errors
if response.status >= 400:
error_msg = self._format_error_message(
response.status, response_text
)
raise Exception(error_msg)
return response_json
except aiohttp.ClientError as e:
logger.error(f"Network error: {str(e)}")
raise Exception(f"Network error accessing {url}: {str(e)}")
def _format_error_message(self, status: int, response_text: str) -> str:
"""Format error message based on HTTP status code"""
base_msg = f"API Error {status}: {response_text}"
error_hints = {
401: "Authentication failed. Please check your API key.",
403: "Access denied. The user lacks required permissions.",
404: "Resource not found. Please verify the URL and resource exists.",
407: "Proxy authentication required.",
500: "Internal server error. Please try again later.",
502: "Bad gateway. The server or proxy is not responding correctly.",
503: "Service unavailable. The server might be under maintenance.",
}
if status in error_hints:
base_msg += f"\n\n{error_hints[status]}"
return base_msg
async def test_connection(self) -> Dict:
"""Test the API connection and authentication"""
logger.info("Testing API connection...")
return await self._request("GET", "")
async def get_projects(self, filters: Optional[str] = None) -> Dict:
"""
Retrieve all projects.
Args:
filters: Optional JSON-encoded filter string
Returns:
Dict: API response containing projects
"""
endpoint = "/projects"
if filters:
encoded_filters = quote(filters)
endpoint += f"?filters={encoded_filters}"
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_work_packages(
self,
project_id: Optional[int] = None,
filters: Optional[str] = None,
offset: Optional[int] = None,
page_size: Optional[int] = None,
) -> Dict:
"""
Retrieve work packages.
Args:
project_id: Optional project ID to filter by
filters: Optional JSON-encoded filter string
offset: Optional starting index for pagination
page_size: Optional number of results per page
Returns:
Dict: API response containing work packages
"""
if project_id:
endpoint = f"/projects/{project_id}/work_packages"
else:
endpoint = "/work_packages"
# Build query parameters
query_params = []
if filters:
encoded_filters = quote(filters)
query_params.append(f"filters={encoded_filters}")
if offset is not None:
query_params.append(f"offset={offset}")
if page_size is not None:
query_params.append(f"pageSize={page_size}")
if query_params:
endpoint += "?" + "&".join(query_params)
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def create_work_package(self, data: Dict) -> Dict:
"""
Create a new work package.
Args:
data: Work package data including project, subject, type, etc.
Returns:
Dict: Created work package data
"""
# Prepare initial payload for form
form_payload = {"_links": {}}
# Set required links
if "project" in data:
form_payload["_links"]["project"] = {
"href": f"/api/v3/projects/{data['project']}"
}
if "type" in data:
form_payload["_links"]["type"] = {"href": f"/api/v3/types/{data['type']}"}
# Set subject if provided
if "subject" in data:
form_payload["subject"] = data["subject"]
# Get form with initial payload
form = await self._request("POST", "/work_packages/form", form_payload)
# Use form payload and add additional fields
payload = form.get("payload", form_payload)
payload["lockVersion"] = form.get("lockVersion", 0)
# Add optional fields
if "description" in data:
payload["description"] = {"raw": data["description"]}
if "priority_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["priority"] = {
"href": f"/api/v3/priorities/{data['priority_id']}"
}
if "assignee_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["assignee"] = {
"href": f"/api/v3/users/{data['assignee_id']}"
}
if "version_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["version"] = {
"href": f"/api/v3/versions/{data['version_id']}"
}
# Add date fields (ISO 8601 format: YYYY-MM-DD)
if "startDate" in data:
payload["startDate"] = data["startDate"]
if "dueDate" in data:
payload["dueDate"] = data["dueDate"]
if "date" in data:
payload["date"] = data["date"]
# Custom fields (customField1, customField2, ...): list/user/version-type
# values arrive as {"href": ...} and go under _links; text/number/date
# values are set directly on the payload.
for key, value in data.items():
if key.startswith("customField"):
if isinstance(value, dict) and "href" in value:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"][key] = value
else:
payload[key] = value
# Create work package
return await self._request("POST", "/work_packages", payload)
async def get_types(self, project_id: Optional[int] = None) -> Dict:
"""
Retrieve available work package types.
Args:
project_id: Optional project ID to filter types by
Returns:
Dict: API response containing types
"""
if project_id:
endpoint = f"/projects/{project_id}/types"
else:
endpoint = "/types"
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_users(self, filters: Optional[str] = None) -> Dict:
"""
Retrieve users.
Args:
filters: Optional JSON-encoded filter string
Returns:
Dict: API response containing users
"""
endpoint = "/users"
if filters:
encoded_filters = quote(filters)
endpoint += f"?filters={encoded_filters}"
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_user(self, user_id: int) -> Dict:
"""
Retrieve a specific user by ID.
Args:
user_id: The user ID
Returns:
Dict: User data
"""
return await self._request("GET", f"/users/{user_id}")
async def get_memberships(
self, project_id: Optional[int] = None, user_id: Optional[int] = None
) -> Dict:
"""
Retrieve memberships.
Args:
project_id: Optional project ID to filter memberships by project
user_id: Optional user ID to filter memberships by user
Returns:
Dict: API response containing memberships
"""
endpoint = "/memberships"
# Use filters instead of path-based filtering for better compatibility
filters = []
if project_id:
filters.append({"project": {"operator": "=", "values": [project_id]}})
if user_id:
filters.append({"user": {"operator": "=", "values": [str(user_id)]}})
if filters:
filter_string = quote(json.dumps(filters))
endpoint += f"?filters={filter_string}"
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_statuses(self) -> Dict:
"""
Retrieve available work package statuses.
Returns:
Dict: API response containing statuses
"""
result = await self._request("GET", "/statuses")
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_priorities(self) -> Dict:
"""
Retrieve available work package priorities.
Returns:
Dict: API response containing priorities
"""
result = await self._request("GET", "/priorities")
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_work_package(self, work_package_id: int) -> Dict:
"""
Retrieve a specific work package by ID.
Args:
work_package_id: The work package ID
Returns:
Dict: Work package data
"""
return await self._request("GET", f"/work_packages/{work_package_id}")
async def update_work_package(self, work_package_id: int, data: Dict) -> Dict:
"""
Update an existing work package.
Args:
work_package_id: The work package ID
data: Update data including fields to modify
Returns:
Dict: Updated work package data
"""
# First get current work package to get lock version
current_wp = await self.get_work_package(work_package_id)
# Prepare payload with lock version
payload = {"lockVersion": current_wp.get("lockVersion", 0)}
# Add fields to update
if "subject" in data:
payload["subject"] = data["subject"]
if "description" in data:
payload["description"] = {"raw": data["description"]}
if "type_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["type"] = {"href": f"/api/v3/types/{data['type_id']}"}
if "status_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["status"] = {
"href": f"/api/v3/statuses/{data['status_id']}"
}
if "priority_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["priority"] = {
"href": f"/api/v3/priorities/{data['priority_id']}"
}
if "assignee_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["assignee"] = {
"href": f"/api/v3/users/{data['assignee_id']}"
}
if "version_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["version"] = {
"href": f"/api/v3/versions/{data['version_id']}"
}
if "percentage_done" in data:
payload["percentageDone"] = data["percentage_done"]
if "schedule_manually" in data:
payload["scheduleManually"] = data["schedule_manually"]
if "parent_id" in data:
if "_links" not in payload:
payload["_links"] = {}
if data["parent_id"] is None:
# Remove parent
payload["_links"]["parent"] = {"href": None}
else:
# Set parent
payload["_links"]["parent"] = {
"href": f"/api/v3/work_packages/{data['parent_id']}"
}
# Add date fields (ISO 8601 format: YYYY-MM-DD)
if "startDate" in data:
payload["startDate"] = data["startDate"]
if "dueDate" in data:
payload["dueDate"] = data["dueDate"]
if "date" in data:
payload["date"] = data["date"]
# Custom fields (customField1, customField2, ...): list/user/version-type
# values arrive as {"href": ...} and go under _links; text/number/date
# values are set directly on the payload.
for key, value in data.items():
if key.startswith("customField"):
if isinstance(value, dict) and "href" in value:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"][key] = value
else:
payload[key] = value
return await self._request(
"PATCH", f"/work_packages/{work_package_id}", payload
)
async def delete_work_package(self, work_package_id: int) -> bool:
"""
Delete a work package.
Args:
work_package_id: The work package ID
Returns:
bool: True if successful
"""
await self._request("DELETE", f"/work_packages/{work_package_id}")
return True
async def add_work_package_comment(
self, work_package_id: int, comment: str, internal: bool = False
) -> Dict:
"""
Add a comment/activity to a work package.
Args:
work_package_id: The work package ID
comment: Comment text (supports markdown)
internal: Whether the comment is internal (visible only to team members)
Returns:
Dict: API response containing the created activity
"""
payload = {
"comment": {
"format": "markdown",
"raw": comment
}
}
if internal:
payload["internal"] = internal
return await self._request(
"POST", f"/work_packages/{work_package_id}/activities", payload
)
async def get_work_package_activities(self, work_package_id: int) -> Dict:
"""
Retrieve activities (comments, changes) for a work package.
Args:
work_package_id: The work package ID
Returns:
Dict: API response containing activities
"""
result = await self._request(
"GET", f"/work_packages/{work_package_id}/activities"
)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_time_entries(self, filters: Optional[str] = None) -> Dict:
"""
Retrieve time entries.
Args:
filters: Optional JSON-encoded filter string
Returns:
Dict: API response containing time entries
"""
endpoint = "/time_entries"
if filters:
encoded_filters = quote(filters)
endpoint += f"?filters={encoded_filters}"
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def create_time_entry(self, data: Dict) -> Dict:
"""
Create a new time entry.
Args:
data: Time entry data including work package, hours, etc.
Returns:
Dict: Created time entry data
"""
# Prepare payload
payload = {}
# Set required fields
if "work_package_id" in data:
payload["_links"] = {
"workPackage": {
"href": f"/api/v3/work_packages/{data['work_package_id']}"
}
}
if "hours" in data:
payload["hours"] = f"PT{data['hours']}H"
if "spent_on" in data:
payload["spentOn"] = data["spent_on"]
if "comment" in data:
payload["comment"] = {"raw": data["comment"]}
if "activity_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["activity"] = {
"href": f"/api/v3/time_entries/activities/{data['activity_id']}"
}
if "user_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["user"] = {
"href": f"/api/v3/users/{data['user_id']}"
}
return await self._request("POST", "/time_entries", payload)
async def update_time_entry(self, time_entry_id: int, data: Dict) -> Dict:
"""
Update an existing time entry.
Args:
time_entry_id: The time entry ID
data: Update data including fields to modify
Returns:
Dict: Updated time entry data
"""
# First get current time entry to get lock version
current_te = await self._request("GET", f"/time_entries/{time_entry_id}")
# Prepare payload with lock version
payload = {"lockVersion": current_te.get("lockVersion", 0)}
# Add fields to update
if "hours" in data:
payload["hours"] = f"PT{data['hours']}H"
if "spent_on" in data:
payload["spentOn"] = data["spent_on"]
if "comment" in data:
payload["comment"] = {"raw": data["comment"]}
if "activity_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["activity"] = {
"href": f"/api/v3/time_entries/activities/{data['activity_id']}"
}
return await self._request("PATCH", f"/time_entries/{time_entry_id}", payload)
async def delete_time_entry(self, time_entry_id: int) -> bool:
"""
Delete a time entry.
Args:
time_entry_id: The time entry ID
Returns:
bool: True if successful
"""
await self._request("DELETE", f"/time_entries/{time_entry_id}")
return True
async def get_time_entry_activities(self) -> Dict:
"""
Retrieve available time entry activities.
Returns:
Dict: API response containing activities
"""
result = await self._request("GET", "/time_entries/activities")
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_versions(self, project_id: Optional[int] = None) -> Dict:
"""
Retrieve project versions.
Args:
project_id: Optional project ID to filter versions by project
Returns:
Dict: API response containing versions
"""
if project_id:
endpoint = f"/projects/{project_id}/versions"
else:
endpoint = "/versions"
result = await self._request("GET", endpoint)
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def create_version(self, project_id: int, data: Dict) -> Dict:
"""
Create a new project version.
Args:
project_id: The project ID
data: Version data including name, description, etc.
Returns:
Dict: Created version data
"""
# Prepare payload
payload = {
"_links": {"definingProject": {"href": f"/api/v3/projects/{project_id}"}}
}
# Set required fields
if "name" in data:
payload["name"] = data["name"]
if "description" in data:
payload["description"] = {"raw": data["description"]}
if "start_date" in data:
payload["startDate"] = data["start_date"]
if "end_date" in data:
payload["endDate"] = data["end_date"]
if "status" in data:
payload["status"] = data["status"]
return await self._request("POST", "/versions", payload)
async def check_permissions(self) -> Dict:
"""
Check user permissions and capabilities.
Returns:
Dict: User information including permissions
"""
try:
# Get current user info which includes permissions
return await self._request("GET", "/users/me")
except Exception as e:
logger.error(f"Failed to check permissions: {e}")
return {}
async def create_project(self, data: Dict) -> Dict:
"""
Create a new project.
Args:
data: Project data including name, identifier, description, etc.
Returns:
Dict: Created project data
"""
# Prepare payload
payload = {}
# Set required fields
if "name" in data:
payload["name"] = data["name"]
if "identifier" in data:
payload["identifier"] = data["identifier"]
if "description" in data:
payload["description"] = {"raw": data["description"]}
if "public" in data:
payload["public"] = data["public"]
if "status" in data:
payload["status"] = data["status"]
if "parent_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["parent"] = {
"href": f"/api/v3/projects/{data['parent_id']}"
}
return await self._request("POST", "/projects", payload)
async def update_project(self, project_id: int, data: Dict) -> Dict:
"""
Update an existing project.
Args:
project_id: The project ID
data: Update data including fields to modify
Returns:
Dict: Updated project data
"""
# First get current project to get lock version if needed
try:
current_project = await self.get_project(project_id)
lock_version = current_project.get("lockVersion", 0)
except:
lock_version = 0
# Prepare payload with lock version
payload = {"lockVersion": lock_version}
# Add fields to update
if "name" in data:
payload["name"] = data["name"]
if "identifier" in data:
payload["identifier"] = data["identifier"]
if "description" in data:
payload["description"] = {"raw": data["description"]}
if "public" in data:
payload["public"] = data["public"]
if "status" in data:
payload["status"] = data["status"]
if "parent_id" in data:
if "_links" not in payload:
payload["_links"] = {}
payload["_links"]["parent"] = {
"href": f"/api/v3/projects/{data['parent_id']}"
}
return await self._request("PATCH", f"/projects/{project_id}", payload)
async def delete_project(self, project_id: int) -> bool:
"""
Delete a project.
Args:
project_id: The project ID
Returns:
bool: True if successful
"""
await self._request("DELETE", f"/projects/{project_id}")
return True
async def get_project(self, project_id: int) -> Dict:
"""
Retrieve a specific project by ID.
Args:
project_id: The project ID
Returns:
Dict: Project data
"""
return await self._request("GET", f"/projects/{project_id}")
async def get_subprojects(self, parent_id: int) -> Dict:
"""
Retrieve direct subprojects of a parent project.
Args:
parent_id: The parent project ID
Returns:
Dict: API response containing direct child projects
"""
# Use parent_id filter for direct children only
filters = json.dumps([{
"parent_id": {"operator": "=", "values": [str(parent_id)]}
}])
return await self.get_projects(filters)
async def validate_parent_project(self, parent_id: int, child_id: Optional[int] = None) -> bool:
"""
Validate if a project can be a parent.
Uses the available_parent_projects endpoint.
Args:
parent_id: The parent project ID to validate
child_id: Optional child project ID (for existing projects)
Returns:
bool: True if valid parent
"""
endpoint = "/projects/available_parent_projects"
if child_id:
endpoint += f"?of={child_id}"
result = await self._request("GET", endpoint)
candidates = result.get("_embedded", {}).get("elements", [])
return any(p.get("id") == parent_id for p in candidates)
async def get_roles(self) -> Dict:
"""
Retrieve available roles.
Returns:
Dict: API response containing roles
"""
result = await self._request("GET", "/roles")
# Ensure proper response structure
if "_embedded" not in result:
result["_embedded"] = {"elements": []}
elif "elements" not in result.get("_embedded", {}):
result["_embedded"]["elements"] = []
return result
async def get_role(self, role_id: int) -> Dict:
"""
Retrieve a specific role by ID.
Args:
role_id: The role ID
Returns:
Dict: Role data
"""
return await self._request("GET", f"/roles/{role_id}")
async def create_membership(self, data: Dict) -> Dict:
"""
Create a new membership.
Args:
data: Membership data including project, user/group, and roles
Returns:
Dict: Created membership data
"""
# Prepare payload
payload = {"_links": {}}
# Set required fields
if "project_id" in data:
payload["_links"]["project"] = {
"href": f"/api/v3/projects/{data['project_id']}"
}
if "user_id" in data:
payload["_links"]["principal"] = {
"href": f"/api/v3/users/{data['user_id']}"
}
elif "group_id" in data:
payload["_links"]["principal"] = {
"href": f"/api/v3/groups/{data['group_id']}"
}
if "role_ids" in data:
payload["_links"]["roles"] = [
{"href": f"/api/v3/roles/{role_id}"} for role_id in data["role_ids"]
]
elif "role_id" in data:
payload["_links"]["roles"] = [{"href": f"/api/v3/roles/{data['role_id']}"}]
if "notification_message" in data:
payload["notificationMessage"] = {"raw": data["notification_message"]}
return await self._request("POST", "/memberships", payload)
async def update_membership(self, membership_id: int, data: Dict) -> Dict:
"""