Spaces:
Sleeping
Sleeping
File size: 22,087 Bytes
1def50b | 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 | # ============================================================================
# PM TOOL CLIENT
# ============================================================================
import asyncio
import os
import base64
from typing import Dict, Any, List, Optional, Tuple
import aiohttp
from fastapi import HTTPException
from app.config import Config
from app.models.enums import TaskType
from app.models.schemas import Credentials
from app.utils.logger import logger
from app.utils.cache import token_cache
from app.utils.http_client import http_client
class PMToolClient:
"""Async client for PM Tool API"""
# Additional endpoints
PROJECTS_ENDPOINT = f"{Config.PM_TOOL_BASE_URL}/Projects"
PROJECT_BY_NAME_ENDPOINT = f"{Config.PM_TOOL_BASE_URL}/Projects/ByName"
ATTACHMENT_DOWNLOAD_ENDPOINT = f"{Config.PM_TOOL_ATTACHMENTS_ENDPOINT}/Download"
@staticmethod
async def login(credentials: Credentials) -> Dict[str, Any]:
"""Authenticate and get token"""
# Check cache first
cached_token = await token_cache.get(credentials.email)
if cached_token:
return {"token": cached_token, "from_cache": True}
session = http_client.get_session()
for attempt in range(Config.MAX_RETRY_ATTEMPTS):
try:
async with session.post(
Config.PM_TOOL_LOGIN_ENDPOINT,
json={"email": credentials.email, "password": credentials.password},
headers={"Content-Type": "application/json"}
) as response:
if response.status == 401:
raise HTTPException(
status_code=401,
detail="Invalid credentials for PM Tool"
)
response.raise_for_status()
data = await response.json()
# Cache token
await token_cache.set(credentials.email, data['token'])
logger.info(f"β
Logged in as {data.get('firstName')} {data.get('lastName')}")
return data
except aiohttp.ClientError as e:
if attempt == Config.MAX_RETRY_ATTEMPTS - 1:
logger.error(f"Login failed after {Config.MAX_RETRY_ATTEMPTS} attempts: {e}")
raise HTTPException(
status_code=503,
detail=f"PM Tool API unreachable: {str(e)}"
)
logger.warning(f"Login attempt {attempt + 1} failed, retrying...")
await asyncio.sleep(Config.RETRY_DELAY)
@staticmethod
async def fetch_tasks(
token: str,
task_type: TaskType = TaskType.TASK,
task_ids: Optional[List[int]] = None
) -> List[Dict[str, Any]]:
"""Fetch tasks from PM Tool"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
params = {"type": task_type.value}
try:
async with session.get(
Config.PM_TOOL_TASKS_ENDPOINT,
headers=headers,
params=params
) as response:
if response.status == 401:
raise HTTPException(status_code=401, detail="Token expired")
response.raise_for_status()
tasks = await response.json()
# Filter by task IDs if provided
if task_ids:
tasks = [t for t in tasks if t.get('id') in task_ids]
logger.info(f"π₯ Fetched {len(tasks)} tasks")
return tasks
except aiohttp.ClientError as e:
logger.error(f"Failed to fetch tasks: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch tasks: {str(e)}"
)
@staticmethod
async def fetch_attachments(
token: str,
project_id: Optional[int] = None,
task_id: Optional[int] = None
) -> List[Dict[str, Any]]:
"""Fetch attachments for project or task"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
# Determine endpoint
if project_id:
url = f"{Config.PM_TOOL_ATTACHMENTS_ENDPOINT}/Project/{project_id}"
elif task_id:
url = f"{Config.PM_TOOL_ATTACHMENTS_ENDPOINT}/Task/{task_id}"
else:
return []
try:
async with session.get(url, headers=headers) as response:
if response.status == 404:
logger.debug(f"No attachments found for project/task")
return []
response.raise_for_status()
attachments = await response.json()
logger.debug(f"π Fetched {len(attachments)} attachments")
return attachments
except aiohttp.ClientError as e:
logger.warning(f"Failed to fetch attachments: {e}")
return [] # Don't fail the whole request
@staticmethod
async def fetch_projects(token: str) -> List[Dict[str, Any]]:
"""Fetch all projects from PM Tool"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
try:
async with session.get(
PMToolClient.PROJECTS_ENDPOINT,
headers=headers
) as response:
if response.status == 401:
raise HTTPException(status_code=401, detail="Token expired")
response.raise_for_status()
projects = await response.json()
logger.info(f"π Fetched {len(projects)} projects")
return projects
except aiohttp.ClientError as e:
logger.error(f"Failed to fetch projects: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch projects: {str(e)}"
)
@staticmethod
async def fetch_issues(token: str) -> List[Dict[str, Any]]:
"""Fetch all issues from PM Tool
Issues contain projectId which links tasks to projects.
"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
url = f"{Config.PM_TOOL_BASE_URL}/Issues"
try:
async with session.get(url, headers=headers) as response:
if response.status == 401:
raise HTTPException(status_code=401, detail="Token expired")
response.raise_for_status()
issues = await response.json()
logger.info(f"π Fetched {len(issues)} issues")
return issues
except aiohttp.ClientError as e:
logger.error(f"Failed to fetch issues: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch issues: {str(e)}"
)
@staticmethod
def build_project_name_id_mapping(
tasks: List[Dict[str, Any]],
issues: List[Dict[str, Any]]
) -> Dict[str, int]:
"""Build projectName -> projectId mapping from tasks and issues
Task has 'issuesId' -> Issue has 'projectId'
This bridges the gap between task projectName and attachment entityId.
"""
issues_lookup = {i['id']: i for i in issues}
mapping = {}
for task in tasks:
issue_id = task.get('issuesId')
if issue_id and issue_id in issues_lookup:
project_id = issues_lookup[issue_id].get('projectId')
project_name = task.get('projectName')
if project_name and project_id:
mapping[project_name] = project_id
logger.info(f"π Built projectName->projectId mapping for {len(mapping)} projects")
return mapping
@staticmethod
async def fetch_project_by_name(token: str, project_name: str) -> Optional[Dict[str, Any]]:
"""Fetch project by name (case-insensitive partial match)"""
projects = await PMToolClient.fetch_projects(token)
# Try exact match first
for project in projects:
if project.get('name', '').lower() == project_name.lower():
logger.info(f"π― Found project by exact name: {project.get('name')}")
return project
# Try partial match
for project in projects:
if project_name.lower() in project.get('name', '').lower():
logger.info(f"π― Found project by partial name: {project.get('name')}")
return project
logger.warning(f"β οΈ Project not found: {project_name}")
return None
@staticmethod
async def fetch_project_by_id(token: str, project_id: int) -> Optional[Dict[str, Any]]:
"""Fetch project by ID"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
url = f"{PMToolClient.PROJECTS_ENDPOINT}/{project_id}"
try:
async with session.get(url, headers=headers) as response:
if response.status == 404:
logger.warning(f"Project not found: {project_id}")
return None
response.raise_for_status()
project = await response.json()
logger.info(f"π Found project: {project.get('name')}")
return project
except aiohttp.ClientError as e:
logger.error(f"Failed to fetch project {project_id}: {e}")
return None
@staticmethod
async def resolve_project(
token: str,
project_id: Optional[int] = None,
project_name: Optional[str] = None
) -> Optional[Dict[str, Any]]:
"""Resolve project by ID or name (auto-select)"""
if project_id:
return await PMToolClient.fetch_project_by_id(token, project_id)
elif project_name:
return await PMToolClient.fetch_project_by_name(token, project_name)
return None
@staticmethod
async def fetch_tasks_by_project(
token: str,
project_id: int,
task_type: TaskType = TaskType.TASK
) -> List[Dict[str, Any]]:
"""Fetch all tasks for a specific project"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
# Some APIs support project filter directly
url = f"{Config.PM_TOOL_TASKS_ENDPOINT}/Project/{project_id}"
try:
async with session.get(url, headers=headers) as response:
if response.status == 404:
# Fallback: fetch all and filter
all_tasks = await PMToolClient.fetch_tasks(token, task_type)
return [t for t in all_tasks if t.get('projectId') == project_id]
response.raise_for_status()
tasks = await response.json()
logger.info(f"π₯ Fetched {len(tasks)} tasks for project {project_id}")
return tasks
except aiohttp.ClientError as e:
# Fallback: fetch all and filter
logger.warning(f"Direct project tasks fetch failed, using filter: {e}")
all_tasks = await PMToolClient.fetch_tasks(token, task_type)
return [t for t in all_tasks if t.get('projectId') == project_id]
@staticmethod
async def download_attachment(
token: str,
attachment_id: str,
download_dir: str = None
) -> Tuple[Optional[str], Optional[bytes]]:
"""Download attachment content from PM Tool
Returns: (file_path, file_bytes) - file_path if saved, file_bytes if in-memory
"""
session = http_client.get_session()
headers = {
"Accept": "application/octet-stream",
"Authorization": f"Bearer {token}"
}
url = f"{PMToolClient.ATTACHMENT_DOWNLOAD_ENDPOINT}/{attachment_id}"
try:
async with session.get(url, headers=headers) as response:
if response.status == 404:
logger.warning(f"Attachment not found: {attachment_id}")
return None, None
response.raise_for_status()
content = await response.read()
# Get filename from header if available
content_disp = response.headers.get('Content-Disposition', '')
filename = None
if 'filename=' in content_disp:
filename = content_disp.split('filename=')[1].strip('"')
# Save to disk if download_dir provided
if download_dir:
os.makedirs(download_dir, exist_ok=True)
if not filename:
filename = f"attachment_{attachment_id}"
# Sanitize filename for Windows (remove invalid chars)
import re
filename = re.sub(r'[<>:"/\\|?*()]', '_', filename)
filename = filename[:200] # Limit length
filepath = os.path.join(download_dir, filename)
with open(filepath, 'wb') as f:
f.write(content)
logger.info(f"π₯ Downloaded attachment: {filename} ({len(content)} bytes)")
return filepath, None
logger.info(f"π₯ Fetched attachment: {attachment_id} ({len(content)} bytes in-memory)")
return None, content
except aiohttp.ClientError as e:
logger.error(f"Failed to download attachment {attachment_id}: {e}")
return None, None
@staticmethod
async def fetch_attachments_by_project(token: str, project_name: str) -> List[Dict[str, Any]]:
"""Fetch all attachments for a project by name
Uses dynamic mapping: Task -> issuesId -> Issue -> projectId
Uses cache to avoid repeated API calls.
"""
from app.utils.cache import attachment_cache
# Check cache first
cached = await attachment_cache.get_attachments(project_name)
if cached is not None:
logger.info(f"π Using cached attachments for: {project_name}")
return cached
# Build dynamic mapping from tasks and issues (with cache)
mapping = await attachment_cache.get_mapping()
if mapping is None:
tasks = await PMToolClient.fetch_tasks(token)
issues = await PMToolClient.fetch_issues(token)
mapping = PMToolClient.build_project_name_id_mapping(tasks, issues)
await attachment_cache.set_mapping(mapping)
# Get project ID from dynamic mapping
project_id = mapping.get(project_name)
if not project_id:
logger.info(f"No project ID mapping found for: {project_name}")
return []
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
url = f"{Config.PM_TOOL_ATTACHMENTS_ENDPOINT}/Project/{project_id}"
try:
async with session.get(url, headers=headers) as response:
if response.status == 404:
logger.info(f"No attachments found for project: {project_name} (ID: {project_id})")
return []
if response.status == 401:
raise HTTPException(status_code=401, detail="Token expired")
response.raise_for_status()
attachments = await response.json()
logger.info(f"π Fetched {len(attachments)} attachments for project: {project_name} (ID: {project_id})")
# Cache the result
await attachment_cache.set_attachments(project_name, attachments)
return attachments
except aiohttp.ClientError as e:
logger.error(f"Failed to fetch attachments for project {project_name}: {e}")
return []
@staticmethod
async def fetch_all_attachments(token: str) -> List[Dict[str, Any]]:
"""Fetch ALL attachments from PM Tool
Returns all 315+ attachments with their entityId (project ID).
Used to build project attachment cache.
"""
session = http_client.get_session()
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}"
}
url = f"{Config.PM_TOOL_ATTACHMENTS_ENDPOINT}"
try:
async with session.get(url, headers=headers) as response:
if response.status == 401:
raise HTTPException(status_code=401, detail="Token expired")
response.raise_for_status()
attachments = await response.json()
logger.info(f"π Fetched {len(attachments)} total attachments")
return attachments
except aiohttp.ClientError as e:
logger.error(f"Failed to fetch all attachments: {e}")
return []
@staticmethod
def build_project_attachment_cache(attachments: List[Dict[str, Any]]) -> Dict[int, List[Dict[str, Any]]]:
"""Build cache of attachments grouped by project ID
Returns: {project_id: [attachment1, attachment2, ...]}
"""
cache = {}
for att in attachments:
entity_type = att.get('entityType', '')
if entity_type == 'Project':
project_id = att.get('entityId')
if project_id:
if project_id not in cache:
cache[project_id] = []
cache[project_id].append(att)
logger.info(f"π Built attachment cache for {len(cache)} projects")
return cache
@staticmethod
async def fetch_and_download_attachments(
token: str,
project_id: Optional[int] = None,
task_id: Optional[int] = None,
download_dir: str = None,
attachment_configs: List[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
"""Fetch attachments list and optionally download them
Returns list with attachment info + downloaded file path (if applicable)
"""
# Fetch attachment list
attachments = await PMToolClient.fetch_attachments(
token=token,
project_id=project_id,
task_id=task_id
)
if not attachments:
return []
# Build config lookup
config_lookup = {}
if attachment_configs:
for cfg in attachment_configs:
# Match by ID or filename
key = cfg.get('attachment_id') or cfg.get('filename')
if key:
config_lookup[key] = cfg
result = []
for att in attachments:
att_id = str(att.get('id', ''))
filename = att.get('fileName', att.get('name', ''))
# Check for skip config
att_config = config_lookup.get(att_id) or config_lookup.get(filename)
skip = False
skip_reason = None
if att_config:
skip = att_config.get('skip', False)
skip_reason = att_config.get('skip_reason')
att_result = {
"attachment_id": att_id,
"filename": filename,
"file_type": att.get('fileType', att.get('contentType', '')),
"size": att.get('size', att.get('fileSize', 0)),
"description": att.get('description', ''),
"skip": skip,
"skip_reason": skip_reason,
"file_path": None,
"downloaded": False
}
# Download if not skipped
if not skip:
filepath, _ = await PMToolClient.download_attachment(
token=token,
attachment_id=att_id,
download_dir=download_dir
)
if filepath:
att_result["file_path"] = filepath
att_result["downloaded"] = True
result.append(att_result)
logger.info(f"π Processed {len(result)} attachments ({sum(1 for a in result if a['downloaded'])} downloaded)")
return result
|