Files
redmine_tracker/api/redmine.py

87 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import logging
from colorama import Fore
import requests
from tqdm import tqdm
from config import RedmineConfig, config
from classes import Activity, ActivityType
from enums import ActivityTypes
from exceptions import InvalidToken
logger = logging.getLogger(__name__)
WORKSPACE_ID = config.WORKSPACE_ID
USER_ID = config.USER_ID
class RedmineAPI(RedmineConfig):
"""API клиент для взаимодействия с Redmine.
Позволяет заносить трудочасы и получать виды деятельности.
"""
def __init__(self, token):
super().__init__()
self.token = self._check_token(token)
def track_activities(self, activities: list[Activity]) -> list[Activity]:
"""Заносит трудочасы на сервер Redmine"""
if len(activities) == 0:
logger.info(Fore.YELLOW + "Нет задач для занесения трудочасов" + Fore.RESET)
return
tracked = []
for activity in tqdm(activities, desc="Занесение трудочасов"):
if not(not activity.is_tracked and activity.date_end):
continue
try:
resp = requests.post(
self.base_url + self.time_entries_url,
headers={"X-Redmine-Api-Key": self.token},
json={
"time_entry": {
"issue_id": activity.task_id,
"hours": activity.time_spent,
"activity_id": ActivityTypes.DEVELOPMENT,
"comments": activity.description,
"spent_on": activity.date_start.strftime(self.datetime_format)
}
}
)
if resp.ok:
activity.is_tracked = True
tracked.append(activity)
logger.debug(activity)
else:
logger.error(Fore.RED + f"{activity} Не была затрекана" + Fore.RED)
logger.error(f"{resp.json()['errors']} {resp.status_code}")
except Exception as e:
logger.error(e)
continue
if len(activities) == len(tracked):
logger.info(Fore.GREEN + "Все задачи были успешно занесены в Redmine" + Fore.RESET)
else:
logger.info(f"{Fore.YELLOW}Не все задачи были занесены в Redmine. Занесено {len(tracked)}{Fore.RESET}")
return tracked
def get_time_entry_activities(self) -> list[ActivityTypes]:
"""Получает виды Деятельности с сервера Redmine"""
resp = requests.get(self.base_url + self.time_entry_activities, headers={"X-Redmine-API-KEY": self.token})
logging.debug(resp.json())
if resp.ok:
return [
ActivityType(id=act.get("id"), title=act.get("name"))
for act in resp.json().get("time_entry_activities")
if act.get("active")
]
def _check_token(self, token):
"""Проверяет токен"""
resp = requests.get(self.base_url + self.my_account_url, headers={"X-Redmine-Api-Key": token})
if not resp.ok:
logger.error("Invalid Token for RedmineAPI")
raise InvalidToken
resp = resp.json()['user']
logger.debug({"login": resp["login"], "email": resp["mail"], "full_name": f'{resp["firstname"]} {resp["lastname"]}'})
return token