chrono/chrono/utils/lingo.py

78 lines
2.2 KiB
Python

# chrono - agendas system
# Copyright (C) 2022 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import dataclasses
import json
from django.conf import settings
from requests.exceptions import RequestException
from chrono.utils.requests_wrapper import requests
def is_lingo_enabled():
return hasattr(settings, 'KNOWN_SERVICES') and settings.KNOWN_SERVICES.get('lingo')
def get_lingo_service():
if not is_lingo_enabled():
return {}
return list(settings.KNOWN_SERVICES.get('lingo').values())[0]
def get_lingo_json(path, log_errors=True):
lingo_site = get_lingo_service()
if lingo_site is None:
return
try:
response = requests.get(
path,
remote_service=lingo_site,
without_user=True,
headers={'accept': 'application/json'},
log_errors=log_errors,
)
response.raise_for_status()
except RequestException as e:
if e.response is not None:
try:
# return json if available (on 404 responses by example)
return e.response.json()
except json.JSONDecodeError:
pass
return
return response.json()
@dataclasses.dataclass
class CheckType:
slug: str
label: str
kind: str
def get_agenda_check_types(agenda):
result = get_lingo_json('api/agenda/%s/check-types/' % agenda.slug)
if result is None:
return []
if result.get('data') is None:
return []
check_types = []
for ct in result['data']:
check_types.append(CheckType(slug=ct['id'], label=ct['text'], kind=ct['kind']))
return check_types