Compare commits
118
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f498bb754 | ||
|
|
0ea7713f05 | ||
|
|
7613569711 | ||
|
|
63db1c9564 | ||
|
|
cac2d81b5c | ||
|
|
0b9f325045 | ||
|
|
d1255deaec | ||
|
|
6dd57bfe2b | ||
|
|
25988d6c46 | ||
|
|
f8228c5ea7 | ||
|
|
f19059164e | ||
|
|
aaab04596d | ||
|
|
6c4688185f | ||
|
|
647eb55a88 | ||
|
|
2603580587 | ||
|
|
42ecebb27f | ||
|
|
f383952547 | ||
|
|
6db4c80258 | ||
|
|
f0173cbf8a | ||
|
|
7bd8659638 | ||
|
|
074e237c84 | ||
|
|
7e8a796623 | ||
|
|
5432d814c6 | ||
|
|
9e5b2c1a21 | ||
|
|
1fa755769b | ||
|
|
cfac12e218 | ||
|
|
2ec9047565 | ||
|
|
b499fd2877 | ||
|
|
e5599845ba | ||
|
|
249fb080e9 | ||
|
|
050c68ea5e | ||
|
|
67d5306c6e | ||
|
|
64ab9325a0 | ||
|
|
5126e530e6 | ||
|
|
8b7f8b7d6a | ||
|
|
a0cd8d0904 | ||
|
|
7e11738481 | ||
|
|
ab18134c58 | ||
|
|
1113a6a2be | ||
|
|
3702b216a0 | ||
|
|
dbaabeb9a5 | ||
|
|
05eb9a3b50 | ||
|
|
9388ad9bdb | ||
|
|
eb8780e9f9 | ||
|
|
ff54ebd438 | ||
|
|
c847c286dd | ||
|
|
e76c0b8187 | ||
|
|
677ef59440 | ||
|
|
c259635bdf | ||
|
|
17931a82b0 | ||
|
|
0502a9a553 | ||
|
|
4b8256b56e | ||
|
|
095a4c8bac | ||
|
|
473bc96e90 | ||
|
|
642fda7542 | ||
|
|
1fdd5339fa | ||
|
|
ae92c44092 | ||
|
|
97ba57b9a2 | ||
|
|
5a91887861 | ||
|
|
dfa9c70a25 | ||
|
|
9c3530744e | ||
|
|
7b2834a177 | ||
|
|
415ee39198 | ||
|
|
e206f40822 | ||
|
|
84b3ec4148 | ||
|
|
98777eb620 | ||
|
|
4d85562088 | ||
|
|
65bb29ecd8 | ||
|
|
aca6ae20b2 | ||
|
|
5cd5383476 | ||
|
|
da35417778 | ||
|
|
ac27fe3cf8 | ||
|
|
24d73b8434 | ||
|
|
d25f470217 | ||
|
|
4a1d07cf83 | ||
|
|
c840818433 | ||
|
|
c8179d44f6 | ||
|
|
1019cedb97 | ||
|
|
4b6ad1ec3d | ||
|
|
0648e1774c | ||
|
|
b993862afb | ||
|
|
f951eba7e4 | ||
|
|
d5122a5eb7 | ||
|
|
1351264c80 | ||
|
|
7b13db6dbf | ||
|
|
b4257f2efa | ||
|
|
52a567df3e | ||
|
|
901cca5eb9 | ||
|
|
a1b1cf0473 | ||
|
|
653dcb0a14 | ||
|
|
5887138457 | ||
|
|
78ef52e3a6 | ||
|
|
8ee9aa00bf | ||
|
|
91ec7d841c | ||
|
|
d8a991cc3a | ||
|
|
6d25d5c51f | ||
|
|
3d8fc2431f | ||
|
|
8390764ff4 | ||
|
|
699dc32b0d | ||
|
|
d81c1da331 | ||
|
|
d1bb1363c0 | ||
|
|
17037668d8 | ||
|
|
1205ebb1c0 | ||
|
|
bea26c70ec | ||
|
|
40fcdba595 | ||
|
|
6aca99c994 | ||
|
|
3d0e9dfff4 | ||
|
|
4b895dc26f | ||
|
|
81441dc588 | ||
|
|
9e0fa9c979 | ||
|
|
b2efe968ea | ||
|
|
4b7c9db930 | ||
|
|
12c2cf4f69 | ||
|
|
7ad3e080b6 | ||
|
|
12377749c2 | ||
|
|
68bc0cde7f | ||
|
|
e3c1c567bf | ||
|
|
50dbf0dc2f |
+7
-3
@@ -12,9 +12,13 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"uvicorn~=0.29.0" \
|
||||
"pytest~=8.1.0" \
|
||||
"httpx~=0.27.0" \
|
||||
"python-multipart~=0.0.19"\
|
||||
"elasticsearch~=9.4.0" \
|
||||
"openai~=2.41.0"
|
||||
"python-multipart~=0.0.19" \
|
||||
"beautifulsoup4==4.12.3" \
|
||||
"openai~=2.41.0" \
|
||||
"websockets==12.0" \
|
||||
"partial-json-parser==0.2.1.1.post7" \
|
||||
"sqlmodel~=0.0.33" \
|
||||
"argon2-cffi~=25.1.0"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
COPY [ "src/data", "/data" ]
|
||||
|
||||
@@ -7,7 +7,6 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"cryptography~=42.0.0",
|
||||
"dotenv>=0.9.9",
|
||||
"elasticsearch~=9.4.0",
|
||||
"fastapi~=0.115.0",
|
||||
"httpx~=0.27.0",
|
||||
"openai~=2.41.0",
|
||||
@@ -17,10 +16,11 @@ dependencies = [
|
||||
"pytest~=8.1.0",
|
||||
"python-multipart~=0.0.19",
|
||||
"pyyaml~=6.0.1",
|
||||
"sqlalchemy~=2.0.0",
|
||||
"uvicorn~=0.29.0",
|
||||
"sentence-transformers~=5.5.1",
|
||||
"torch",
|
||||
"sqlmodel~=0.0.33",
|
||||
"argon2-cffi~=25.1.0",
|
||||
]
|
||||
|
||||
[[tool.uv.index]]
|
||||
|
||||
@@ -8,7 +8,7 @@ Usage (run once from project root):
|
||||
"""
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
|
||||
MODEL_NAME = "intfloat/multilingual-e5-base"
|
||||
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
print("Done.")
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"organizations": [
|
||||
{
|
||||
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||
"name": "The Super Admin Organization"
|
||||
},
|
||||
{
|
||||
"name": "Universität Duisburg-Essen",
|
||||
"openalex_institution_id": "I62318514"
|
||||
},
|
||||
{
|
||||
"name": "Ruhr-Universität Bochum",
|
||||
"openalex_institution_id": "I904495901"
|
||||
},
|
||||
{
|
||||
"name": "TU Dortmund",
|
||||
"openalex_institution_id": "I200332995"
|
||||
}
|
||||
],
|
||||
"accounts": [
|
||||
{
|
||||
"email": "super@admin.com",
|
||||
"password": "superadmin",
|
||||
"name": "Super Admin",
|
||||
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||
"role": "SUPER_ADMIN"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"username": "superadmin",
|
||||
"password": "superadmin",
|
||||
"email": "some_email@uni-due.de",
|
||||
"account": 0,
|
||||
"organization": 0,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": true
|
||||
},
|
||||
{
|
||||
"username": "user",
|
||||
"password": "user",
|
||||
"email": "user_email@uni-due.de",
|
||||
"account": 1,
|
||||
"organization": 1,
|
||||
"organization_name": "University of Duisburg-Essen",
|
||||
"superadmin": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
@@ -8,15 +5,15 @@ LLM_MODEL=gemma4-e4b
|
||||
# Patent search (EPO + USPTO)
|
||||
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
|
||||
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
|
||||
# Sentence Transformers Configuration
|
||||
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
|
||||
|
||||
TOKEN_ISSUER_ID=inse
|
||||
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
|
||||
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module contains the validation logic for
|
||||
user names and passwords.
|
||||
"""
|
||||
import typing
|
||||
import logging
|
||||
from . import model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def _get_users() -> typing.List[model.User]:
|
||||
''' Returns the list of users from the user configuration file. '''
|
||||
try:
|
||||
with open('../data/users.json') as file:
|
||||
config = model.UserFile.model_validate_json(file.read())
|
||||
return config.users
|
||||
except Exception as e:
|
||||
logger.error('Could not read user configuration file.', exc_info=e)
|
||||
return []
|
||||
|
||||
def get_user(username: str) -> typing.Optional[model.User]:
|
||||
''' Returns the user with the given username. '''
|
||||
for user in _get_users():
|
||||
if user.username == username:
|
||||
return user
|
||||
return None
|
||||
|
||||
def validate_user(username: str, password: str) -> typing.Optional[model.User]:
|
||||
''' Validates the user with the given username and password. '''
|
||||
user = get_user(username)
|
||||
if user and user.password == password:
|
||||
return user
|
||||
return None
|
||||
|
||||
def create_user(username, password, email, institution, superadmin) -> typing.Optional[model.User]:
|
||||
''' Adds a new user to the user configuration file. '''
|
||||
users = _get_users()
|
||||
if any(u.username == username for u in users):
|
||||
logger.warning("Attempt to create duplicate user: %s", username)
|
||||
return None
|
||||
|
||||
# Determine new IDs
|
||||
next_account = max((u.account for u in users), default=0) + 1
|
||||
next_org = max((u.organization for u in users), default=0) + 1
|
||||
|
||||
new_user = model.User(
|
||||
username=username,
|
||||
password=password,
|
||||
email=email,
|
||||
account=next_account,
|
||||
organization=next_org,
|
||||
organization_name=institution,
|
||||
superadmin=superadmin
|
||||
)
|
||||
|
||||
users.append(new_user)
|
||||
user_file = model.UserFile(users=users)
|
||||
try:
|
||||
with open('../data/users.json', 'w') as file:
|
||||
file.write(user_file.model_dump_json(indent=4))
|
||||
return new_user
|
||||
except Exception as e:
|
||||
logger.error('Could not write user configuration file.', exc_info=e)
|
||||
return None
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Data models for the standalone account sub-app.
|
||||
"""
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from pydantic import StrictInt
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
''' An entry in the user configuration file. '''
|
||||
username: str = Field(description="The username of the user.")
|
||||
password: str = Field(description="The password of the user.")
|
||||
email: str = Field(description="The email of the user.")
|
||||
account: StrictInt = Field(description="The account id of the user.")
|
||||
organization: StrictInt = Field(description="The organization id of the user.")
|
||||
organization_name: str = Field(description="The organization name of the user.")
|
||||
superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.")
|
||||
|
||||
|
||||
class UserFile(BaseModel):
|
||||
''' The data model for the file containing the user configuration. '''
|
||||
users: List[User] = Field(default=[], description="The list of users.")
|
||||
|
||||
|
||||
class AuthAccount(BaseModel):
|
||||
i: int
|
||||
l: str
|
||||
o: int
|
||||
e: str
|
||||
on: str
|
||||
|
||||
|
||||
class AuthScope(BaseModel):
|
||||
t: str
|
||||
a: AuthAccount
|
||||
d: Optional[int] = None
|
||||
r: List[str] = []
|
||||
|
||||
|
||||
class IdentityGrant(BaseModel):
|
||||
token_type: str
|
||||
access_token: str
|
||||
expires_in: int
|
||||
scope: AuthScope
|
||||
|
||||
|
||||
class AccessGrant(BaseModel):
|
||||
token_type: str
|
||||
access_token: str
|
||||
expires_in: int
|
||||
scope: AuthScope
|
||||
refresh_token: str
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the security-related code.
|
||||
"""
|
||||
from typing import Optional
|
||||
from typing import Dict
|
||||
from typing import Literal
|
||||
import jwt
|
||||
import time
|
||||
import logging
|
||||
from .. import config
|
||||
from .. import security
|
||||
from . import model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def principal(id_token: str) -> Optional[security.Principal]:
|
||||
''' Extracts the principal from the id token. '''
|
||||
return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH'])
|
||||
|
||||
def id_token(user: model.User, exp: int) -> str:
|
||||
''' Creates a new identity token for the specified user. '''
|
||||
return _encode(_payload(user, 'ID', exp))
|
||||
|
||||
def access_token(user: model.User, exp: int) -> str:
|
||||
''' Creates a new access token for the specified user. '''
|
||||
return _encode(_payload(user, 'ACCESS', exp))
|
||||
|
||||
def refresh_token(user: model.User, exp: int) -> str:
|
||||
''' Creates a new refresh token for the specified user. '''
|
||||
return _encode(_payload(user, 'REFRESH', exp))
|
||||
|
||||
def _encode(payload: Dict[str, any]) -> str:
|
||||
''' Creates a valid web token that encodes the contents with the symmetric key. '''
|
||||
headers = {
|
||||
"kid" : "sym",
|
||||
}
|
||||
return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers)
|
||||
|
||||
def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str:
|
||||
''' Creates the payload of the token for the specified user and token type. '''
|
||||
now = int(time.time())
|
||||
roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ]
|
||||
payload = {
|
||||
"iss" : "my-app",
|
||||
"exp" : now + exp,
|
||||
"iat" : now,
|
||||
"nbf" : now,
|
||||
"inse" : {
|
||||
"t" : type,
|
||||
"a" : {
|
||||
"i" : user.account,
|
||||
"l" : user.username,
|
||||
"o" : user.organization
|
||||
},
|
||||
"d" : None,
|
||||
"r" : roles if type == 'ACCESS' else []
|
||||
}
|
||||
}
|
||||
return payload
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Standalone account service that provides identity and access
|
||||
token endpoints for authentication.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import fastapi
|
||||
import typing
|
||||
from . import logic
|
||||
from . import model
|
||||
from . import security
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_403_FORBIDDEN
|
||||
from starlette.status import HTTP_200_OK
|
||||
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = fastapi.APIRouter(
|
||||
prefix="/inse-account",
|
||||
tags=["INSE Account Service"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/auth/id",
|
||||
operation_id="getIdentityGrant",
|
||||
responses={
|
||||
HTTP_200_OK: {"model": model.IdentityGrant},
|
||||
HTTP_400_BAD_REQUEST: {
|
||||
"model": None,
|
||||
"description": "Invalid request parameters.",
|
||||
},
|
||||
HTTP_403_FORBIDDEN: {
|
||||
"model": None,
|
||||
"description": "Account login not successful.",
|
||||
},
|
||||
HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"model": None,
|
||||
"description": "Token generation failed.",
|
||||
},
|
||||
},
|
||||
)
|
||||
async def get_identity_grant(
|
||||
username: typing.Annotated[str, fastapi.Form()],
|
||||
password: typing.Annotated[str, fastapi.Form()],
|
||||
):
|
||||
user = logic.validate_user(username, password)
|
||||
if user is None:
|
||||
logger.info("Invalid login attempt (%s).", username)
|
||||
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
try:
|
||||
exp = 12 * 60 * 60
|
||||
token = security.id_token(user, exp=exp)
|
||||
account = model.AuthAccount(
|
||||
i=user.account,
|
||||
l=user.username,
|
||||
o=user.organization,
|
||||
e=user.email,
|
||||
on=user.organization_name,
|
||||
)
|
||||
scope = model.AuthScope(t="ID", a=account, d=None, r=[])
|
||||
grant = model.IdentityGrant(
|
||||
token_type="bearer", access_token=token, expires_in=exp, scope=scope
|
||||
)
|
||||
logger.info("Identity token generated (%s).", username)
|
||||
return grant
|
||||
except Exception as e:
|
||||
logger.error("Token generation failed (%s).", username, exc_info=e)
|
||||
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/auth/access",
|
||||
operation_id="getAccessGrant",
|
||||
responses={
|
||||
HTTP_200_OK: {"model": model.AccessGrant},
|
||||
HTTP_400_BAD_REQUEST: {
|
||||
"model": None,
|
||||
"description": "Invalid request parameters.",
|
||||
},
|
||||
HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."},
|
||||
HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"model": None,
|
||||
"description": "Token generation failed.",
|
||||
},
|
||||
},
|
||||
)
|
||||
async def get_access_grant(
|
||||
secret: typing.Annotated[str, fastapi.Form()],
|
||||
account: typing.Annotated[int, fastapi.Form()],
|
||||
organization: typing.Annotated[int, fastapi.Form()],
|
||||
):
|
||||
principal = security.principal(secret)
|
||||
if principal is None:
|
||||
logger.info("Invalid access attempt without principal (%s).", account)
|
||||
raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST)
|
||||
user = logic.get_user(principal.account.login)
|
||||
if user is None:
|
||||
logger.info("Invalid access attempt without user (%s).", account)
|
||||
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
if user.organization != organization or user.account != account:
|
||||
logger.info("Invalid personation attempt (%s).", account)
|
||||
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
try:
|
||||
exp = 10 * 60
|
||||
token = security.access_token(user, exp=exp)
|
||||
refresh = security.refresh_token(user, exp=exp)
|
||||
auth_account = model.AuthAccount(
|
||||
i=user.account,
|
||||
l=user.username,
|
||||
o=user.organization,
|
||||
e=user.email,
|
||||
on=user.organization_name,
|
||||
)
|
||||
scope = model.AuthScope(
|
||||
t="ACCESS",
|
||||
a=auth_account,
|
||||
d=None,
|
||||
r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"],
|
||||
)
|
||||
grant = model.AccessGrant(
|
||||
token_type="bearer",
|
||||
access_token=token,
|
||||
expires_in=exp,
|
||||
scope=scope,
|
||||
refresh_token=refresh,
|
||||
)
|
||||
logger.info("Access token generated (%s).", user.username)
|
||||
return grant
|
||||
except Exception as e:
|
||||
logger.error("Token generation failed (%s).", user.username, exc_info=e)
|
||||
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/create",
|
||||
operation_id="createUser",
|
||||
responses={
|
||||
HTTP_200_OK: {"model": model.User},
|
||||
HTTP_400_BAD_REQUEST: {
|
||||
"model": None,
|
||||
"description": "User creation failed (e.g. duplicate username).",
|
||||
},
|
||||
HTTP_500_INTERNAL_SERVER_ERROR: {
|
||||
"model": None,
|
||||
"description": "Internal server error.",
|
||||
},
|
||||
},
|
||||
)
|
||||
async def create_user(
|
||||
username: typing.Annotated[str, fastapi.Body()],
|
||||
password: typing.Annotated[str, fastapi.Body()],
|
||||
email: typing.Annotated[str, fastapi.Body()],
|
||||
institution: typing.Annotated[str, fastapi.Body()],
|
||||
superadmin: typing.Annotated[bool, fastapi.Body()] = False,
|
||||
):
|
||||
user = logic.create_user(username, password, email, institution, superadmin)
|
||||
if user is None:
|
||||
logger.info("User creation failed for (%s).", username)
|
||||
raise fastapi.HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="User creation failed. Username might already exist."
|
||||
)
|
||||
logger.info("User created successfully (%s).", username)
|
||||
return user
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.auth.model import UserRole
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
openalex_institution_id: Optional[str] = None
|
||||
|
||||
|
||||
class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
role: UserRole
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
activated: bool
|
||||
is_current: bool = False
|
||||
is_real_account: bool = False
|
||||
is_impersonating: bool = False
|
||||
|
||||
|
||||
class AccountPage(BaseModel):
|
||||
items: List[AccountProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class CreateAccountRequest(BaseModel):
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
role: UserRole = UserRole.USER
|
||||
organization_id: uuid.UUID
|
||||
password: str = Field(min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
|
||||
|
||||
class UpdateAccountRequest(BaseModel):
|
||||
email: Optional[str] = Field(default=None, min_length=3)
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
role: Optional[UserRole] = None
|
||||
organization_id: Optional[uuid.UUID] = None
|
||||
password: Optional[str] = Field(default=None, min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
activated: Optional[bool] = None
|
||||
@@ -0,0 +1,125 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from . import service
|
||||
from .model import (
|
||||
AccountPage,
|
||||
AccountProfile,
|
||||
CreateAccountRequest,
|
||||
OrganizationProfile,
|
||||
UpdateAccountRequest,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/me",
|
||||
operation_id="getCurrentAccount",
|
||||
response_model=AccountProfile,
|
||||
)
|
||||
async def get_current_account(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountProfile:
|
||||
return service.get_current_account(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
operation_id="listAccounts",
|
||||
response_model=AccountPage,
|
||||
)
|
||||
async def list_accounts(
|
||||
page: int = Query(default=0, ge=0),
|
||||
page_size: int = Query(default=25, ge=1, le=100),
|
||||
offset: Optional[int] = Query(default=None, ge=0),
|
||||
search: Optional[str] = Query(default=None),
|
||||
organization_id: Optional[uuid.UUID] = Query(default=None),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountPage:
|
||||
return service.list_accounts(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
offset=offset,
|
||||
search=search,
|
||||
organization_id=organization_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
operation_id="createAccount",
|
||||
response_model=AccountProfile,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_account(
|
||||
payload: CreateAccountRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountProfile:
|
||||
return service.create_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/organizations",
|
||||
operation_id="listAccountOrganizations",
|
||||
response_model=list[OrganizationProfile],
|
||||
)
|
||||
async def list_organizations(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> list[OrganizationProfile]:
|
||||
return service.list_organizations(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{account_id}",
|
||||
operation_id="updateAccount",
|
||||
response_model=AccountProfile,
|
||||
)
|
||||
async def update_account(
|
||||
account_id: uuid.UUID,
|
||||
payload: UpdateAccountRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountProfile:
|
||||
return service.update_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
account_id=account_id,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{account_id}",
|
||||
operation_id="deleteAccount",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_account(
|
||||
account_id: uuid.UUID,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
account_id=account_id,
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,325 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, or_, select
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
||||
|
||||
from .model import (
|
||||
AccountPage,
|
||||
AccountProfile,
|
||||
CreateAccountRequest,
|
||||
OrganizationProfile,
|
||||
UpdateAccountRequest,
|
||||
)
|
||||
|
||||
|
||||
def _is_admin(role: UserRole) -> bool:
|
||||
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
|
||||
|
||||
|
||||
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
||||
if editor_role == UserRole.SUPER_ADMIN:
|
||||
return True
|
||||
if editor_role == UserRole.ADMIN:
|
||||
return role in {UserRole.MANAGER, UserRole.USER}
|
||||
return False
|
||||
|
||||
|
||||
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
|
||||
organization_name = account.organization.name if account.organization else ""
|
||||
return AccountProfile(
|
||||
id=account.id,
|
||||
email=account.email,
|
||||
name=account.name,
|
||||
role=account.role,
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
activated=account.activated,
|
||||
is_current=account.id == token.effective_account_id,
|
||||
is_real_account=account.id == token.real_account_id,
|
||||
is_impersonating=token.is_impersonating(),
|
||||
)
|
||||
|
||||
|
||||
def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
|
||||
account = session.get(Account, account_id)
|
||||
if account is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found.",
|
||||
)
|
||||
return account
|
||||
|
||||
|
||||
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
|
||||
if token.effective_role == UserRole.SUPER_ADMIN:
|
||||
return
|
||||
if (
|
||||
token.effective_role == UserRole.ADMIN
|
||||
and account.organization_id == token.effective_organization_id
|
||||
):
|
||||
return
|
||||
if account.id == token.effective_account_id:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is outside your scope.",
|
||||
)
|
||||
|
||||
|
||||
def _ensure_email_available(
|
||||
session: Session,
|
||||
email: str,
|
||||
excluded_account_id: Optional[uuid.UUID] = None,
|
||||
) -> None:
|
||||
normalized_email = email.lower().strip()
|
||||
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Invalid email address.",
|
||||
)
|
||||
|
||||
statement = select(Account).where(Account.email == normalized_email)
|
||||
if excluded_account_id is not None:
|
||||
statement = statement.where(Account.id != excluded_account_id)
|
||||
|
||||
existing = session.exec(statement).first()
|
||||
if existing is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Email address is already used by another account.",
|
||||
)
|
||||
|
||||
|
||||
def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile:
|
||||
account = _get_account_or_404(session, access_token.effective_account_id)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def list_accounts(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
) -> AccountPage:
|
||||
if access_token.effective_role not in {
|
||||
UserRole.SUPER_ADMIN,
|
||||
UserRole.ADMIN,
|
||||
UserRole.MANAGER,
|
||||
}:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only managers and admins can list accounts.",
|
||||
)
|
||||
|
||||
statement = select(Account)
|
||||
count_statement = select(func.count()).select_from(Account)
|
||||
|
||||
filters = []
|
||||
if access_token.effective_role in {UserRole.ADMIN, UserRole.MANAGER}:
|
||||
filters.append(Account.organization_id == access_token.effective_organization_id)
|
||||
elif organization_id is not None:
|
||||
filters.append(Account.organization_id == organization_id)
|
||||
|
||||
if search:
|
||||
pattern = f"%{search.lower().strip()}%"
|
||||
filters.append(
|
||||
or_(
|
||||
func.lower(Account.name).like(pattern),
|
||||
func.lower(Account.email).like(pattern),
|
||||
)
|
||||
)
|
||||
|
||||
for filter_expression in filters:
|
||||
statement = statement.where(filter_expression)
|
||||
count_statement = count_statement.where(filter_expression)
|
||||
|
||||
total = session.exec(count_statement).one()
|
||||
effective_offset = offset if offset is not None else page * page_size
|
||||
accounts = session.exec(
|
||||
statement.order_by(Account.name).offset(effective_offset).limit(page_size)
|
||||
).all()
|
||||
|
||||
return AccountPage(
|
||||
items=[_account_to_profile(account, access_token) for account in accounts],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def create_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
payload: CreateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can create accounts.",
|
||||
)
|
||||
|
||||
if (
|
||||
access_token.effective_role == UserRole.ADMIN
|
||||
and payload.organization_id != access_token.effective_organization_id
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admins can only create accounts in their own organization.",
|
||||
)
|
||||
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
|
||||
organization = session.get(Organization, payload.organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
|
||||
email = payload.email.lower().strip()
|
||||
_ensure_email_available(session, email)
|
||||
|
||||
account = Account(
|
||||
email=email,
|
||||
name=payload.name.strip(),
|
||||
role=payload.role,
|
||||
organization_id=payload.organization_id,
|
||||
password_hash=auth_service._hash_password(payload.password),
|
||||
openalex_person_id=payload.openalex_person_id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def list_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
) -> list[OrganizationProfile]:
|
||||
if access_token.effective_role == UserRole.SUPER_ADMIN:
|
||||
organizations = session.exec(
|
||||
select(Organization)
|
||||
.where(Organization.deleted.is_not(True))
|
||||
.order_by(Organization.name)
|
||||
).all()
|
||||
elif access_token.effective_role == UserRole.ADMIN:
|
||||
organization = session.get(Organization, access_token.effective_organization_id)
|
||||
organizations = [organization] if organization and not organization.deleted else []
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return [
|
||||
OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
openalex_institution_id=organization.openalex_institution_id,
|
||||
)
|
||||
for organization in organizations
|
||||
]
|
||||
|
||||
|
||||
def update_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
account_id: uuid.UUID,
|
||||
payload: UpdateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
account = _get_account_or_404(session, account_id)
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
is_self_update = account.id == access_token.effective_account_id
|
||||
can_admin_update = _is_admin(access_token.effective_role)
|
||||
|
||||
if not can_admin_update and not is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if payload.email is not None:
|
||||
email = payload.email.lower().strip()
|
||||
_ensure_email_available(session, email, excluded_account_id=account.id)
|
||||
account.email = email
|
||||
|
||||
if payload.name is not None:
|
||||
account.name = payload.name.strip()
|
||||
|
||||
if payload.password is not None:
|
||||
account.password_hash = auth_service._hash_password(payload.password)
|
||||
account.epoch += 1
|
||||
|
||||
if payload.openalex_person_id is not None:
|
||||
account.openalex_person_id = payload.openalex_person_id
|
||||
|
||||
if payload.role is not None:
|
||||
if not can_admin_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
account.role = payload.role
|
||||
account.epoch += 1
|
||||
|
||||
if payload.organization_id is not None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
organization = session.get(Organization, payload.organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
account.organization_id = payload.organization_id
|
||||
account.epoch += 1
|
||||
|
||||
if payload.deleted is not None:
|
||||
if not can_admin_update or is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
account.deleted = payload.deleted
|
||||
account.epoch += 1
|
||||
|
||||
if payload.activated is not None and payload.activated != account.activated:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN or is_self_update:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only super admins can activate or deactivate other accounts.",
|
||||
)
|
||||
account.activated = payload.activated
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def delete_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
account_id: uuid.UUID,
|
||||
) -> None:
|
||||
account = _get_account_or_404(session, account_id)
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
if (
|
||||
not _is_admin(access_token.effective_role)
|
||||
or account.id == access_token.effective_account_id
|
||||
):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
account.deleted = True
|
||||
account.epoch += 1
|
||||
session.add(account)
|
||||
session.commit()
|
||||
@@ -0,0 +1,180 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.account_management import service
|
||||
from inse.account_management.model import UpdateAccountRequest
|
||||
from inse.auth.model import Account, Organization, UserRole
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as database_session:
|
||||
yield database_session
|
||||
|
||||
|
||||
def access_token(role, account_id, organization_id):
|
||||
return SimpleNamespace(
|
||||
effective_role=role,
|
||||
effective_account_id=account_id,
|
||||
real_account_id=account_id,
|
||||
effective_organization_id=organization_id,
|
||||
is_impersonating=lambda: False,
|
||||
)
|
||||
|
||||
|
||||
def create_accounts(session):
|
||||
organization = Organization(name="Test organization")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
superadmin = Account(
|
||||
email="superadmin@example.org",
|
||||
name="Superadmin",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
role=UserRole.SUPER_ADMIN,
|
||||
)
|
||||
user = Account(
|
||||
email="user@example.org",
|
||||
name="User",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
)
|
||||
session.add(superadmin)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return organization, superadmin, user
|
||||
|
||||
|
||||
def test_accounts_are_activated_by_default(session):
|
||||
_, _, user = create_accounts(session)
|
||||
assert user.activated is True
|
||||
|
||||
|
||||
def test_superadmin_can_deactivate_and_reactivate_account(session):
|
||||
organization, superadmin, user = create_accounts(session)
|
||||
token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id)
|
||||
|
||||
profile = service.update_account(
|
||||
session, token, user.id, UpdateAccountRequest(activated=False)
|
||||
)
|
||||
assert profile.activated is False
|
||||
assert user.epoch == 1
|
||||
|
||||
profile = service.update_account(
|
||||
session, token, user.id, UpdateAccountRequest(activated=True)
|
||||
)
|
||||
assert profile.activated is True
|
||||
assert user.epoch == 2
|
||||
|
||||
|
||||
def test_non_superadmin_cannot_change_activation(session):
|
||||
organization, superadmin, user = create_accounts(session)
|
||||
admin = Account(
|
||||
email="admin@example.org",
|
||||
name="Admin",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
role=UserRole.ADMIN,
|
||||
)
|
||||
session.add(admin)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.update_account(
|
||||
session,
|
||||
access_token(UserRole.ADMIN, admin.id, organization.id),
|
||||
user.id,
|
||||
UpdateAccountRequest(activated=False),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
assert user.activated is True
|
||||
|
||||
|
||||
def test_superadmin_cannot_deactivate_own_account(session):
|
||||
organization, superadmin, _ = create_accounts(session)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.update_account(
|
||||
session,
|
||||
access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id),
|
||||
superadmin.id,
|
||||
UpdateAccountRequest(activated=False),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
assert superadmin.activated is True
|
||||
|
||||
|
||||
def test_manager_only_lists_accounts_from_own_organization(session):
|
||||
organization, superadmin, user = create_accounts(session)
|
||||
manager = Account(
|
||||
email="manager@example.org",
|
||||
name="Manager",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
role=UserRole.MANAGER,
|
||||
)
|
||||
other_organization = Organization(name="Other organization")
|
||||
session.add(other_organization)
|
||||
session.flush()
|
||||
other_user = Account(
|
||||
email="other@example.org",
|
||||
name="Other User",
|
||||
password_hash="hash",
|
||||
organization_id=other_organization.id,
|
||||
)
|
||||
session.add(manager)
|
||||
session.add(other_user)
|
||||
session.commit()
|
||||
|
||||
result = service.list_accounts(
|
||||
session,
|
||||
access_token(UserRole.MANAGER, manager.id, organization.id),
|
||||
page=0,
|
||||
page_size=25,
|
||||
organization_id=other_organization.id,
|
||||
)
|
||||
|
||||
assert {profile.id for profile in result.items} == {
|
||||
account.id for account in [superadmin, user, manager]
|
||||
}
|
||||
assert other_user.id not in {profile.id for profile in result.items}
|
||||
|
||||
|
||||
def test_user_cannot_list_accounts(session):
|
||||
organization, _, user = create_accounts(session)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.list_accounts(
|
||||
session,
|
||||
access_token(UserRole.USER, user.id, organization.id),
|
||||
page=0,
|
||||
page_size=25,
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_superadmin_lists_all_active_organizations_for_selectbox(session):
|
||||
first = Organization(name="Alpha")
|
||||
second = Organization(name="Beta")
|
||||
deleted = Organization(name="Deleted", deleted=True)
|
||||
session.add(first)
|
||||
session.add(second)
|
||||
session.add(deleted)
|
||||
session.commit()
|
||||
|
||||
organizations = service.list_organizations(
|
||||
session,
|
||||
access_token(UserRole.SUPER_ADMIN, first.id, first.id),
|
||||
)
|
||||
|
||||
assert [organization.name for organization in organizations] == ["Alpha", "Beta"]
|
||||
@@ -0,0 +1,29 @@
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
|
||||
|
||||
def send_email(
|
||||
recipient: str,
|
||||
subject: str,
|
||||
body: str,
|
||||
smtp_server: str = "localhost",
|
||||
smtp_port: int = 25,
|
||||
sender: str = "no-reply@smartguide.local",
|
||||
username: str | None = None,
|
||||
password: str | None = None,
|
||||
use_tls: bool = False,
|
||||
):
|
||||
msg = EmailMessage()
|
||||
msg["From"] = sender
|
||||
msg["To"] = recipient
|
||||
msg["Subject"] = subject
|
||||
msg.set_content(body)
|
||||
|
||||
with smtplib.SMTP(smtp_server, smtp_port) as server:
|
||||
if use_tls:
|
||||
server.starttls()
|
||||
|
||||
if username and password:
|
||||
server.login(username, password)
|
||||
|
||||
server.send_message(msg)
|
||||
@@ -0,0 +1,218 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
class UserRole(StrEnum):
|
||||
SUPER_ADMIN = "SUPER_ADMIN"
|
||||
ADMIN = "ADMIN"
|
||||
MANAGER = "MANAGER"
|
||||
USER = "USER"
|
||||
|
||||
|
||||
class TokenType(StrEnum):
|
||||
ID_TOKEN = "ID"
|
||||
REFRESH_TOKEN = "REFRESH"
|
||||
ACCESS_TOKEN = "ACCESS"
|
||||
|
||||
|
||||
class Durable(SQLModel):
|
||||
deleted: bool = Field(
|
||||
default=False,
|
||||
nullable=False,
|
||||
index=True,
|
||||
description="Indicates whether the record is marked as deleted.",
|
||||
)
|
||||
|
||||
|
||||
class Organization(Durable, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The unique name of the organization.",
|
||||
)
|
||||
openalex_institution_id: str | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The OpenAlex ID of the institution associated with the organization.",
|
||||
)
|
||||
|
||||
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the account. Generated automatically if not provided.",
|
||||
)
|
||||
email: str = Field(
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The email address associated with the account.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The name of the account holder.",
|
||||
)
|
||||
openalex_person_id: str | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The OpenAlex ID of the person associated with the account.",
|
||||
)
|
||||
epoch: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The epoch value for the account. Used for versioning of tokens.",
|
||||
)
|
||||
activated: bool = Field(
|
||||
default=True,
|
||||
nullable=False,
|
||||
index=True,
|
||||
description="Indicates whether the account is allowed to authenticate.",
|
||||
)
|
||||
password_hash: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The hashed password for the account using Argon2id algorithm.",
|
||||
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
|
||||
)
|
||||
|
||||
organization_id: uuid.UUID = Field(
|
||||
foreign_key="organization.id",
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this account holds within its organization.",
|
||||
)
|
||||
|
||||
organization: Organization = Relationship(back_populates="accounts")
|
||||
|
||||
|
||||
class Secret(SQLModel, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the secret. Generated automatically if not provided.",
|
||||
)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id",
|
||||
unique=True, # Ensure that each account can have only one associated secret
|
||||
nullable=False,
|
||||
description="The unique identifier of the account associated with this secret.",
|
||||
)
|
||||
secret_value: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The actual secret value. This should be stored securely and encrypted.",
|
||||
)
|
||||
expires_at: datetime = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the secret will expire.",
|
||||
)
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
token_type: TokenType = Field(
|
||||
description="The type of the token (ID, Refresh, or Access).",
|
||||
)
|
||||
real_account_id: uuid.UUID = Field(
|
||||
nullable=False,
|
||||
description="The unique identifier of the real account associated with this token.",
|
||||
)
|
||||
expires_at: datetime = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the token will expire.",
|
||||
)
|
||||
epoch: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The epoch value for the token. Used for versioning of tokens.",
|
||||
)
|
||||
user_fingerprint_hash: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||
)
|
||||
raw_token: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The raw token string.",
|
||||
)
|
||||
|
||||
|
||||
class IdToken(Token):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ID_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always ID_TOKEN for this class.",
|
||||
)
|
||||
|
||||
|
||||
class AccessToken(Token):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ACCESS_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
||||
)
|
||||
effective_account_id: uuid.UUID = Field(
|
||||
nullable=False,
|
||||
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
||||
)
|
||||
effective_role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_organization_id: uuid.UUID = Field(
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization associated with this access token.",
|
||||
)
|
||||
|
||||
def is_impersonating(self) -> bool:
|
||||
"""Determine if the access token is being used for impersonation.
|
||||
|
||||
Returns:
|
||||
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
|
||||
"""
|
||||
return self.effective_account_id != self.real_account_id
|
||||
|
||||
|
||||
class RefreshToken(AccessToken):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.REFRESH_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||
)
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
id_token: IdToken = Field(description="The ID token issued upon successful login.")
|
||||
|
||||
|
||||
class AccessResponse(BaseModel):
|
||||
access_token: AccessToken = Field(
|
||||
description="The access token issued upon successful authentication."
|
||||
)
|
||||
refresh_token: RefreshToken = Field(
|
||||
description="The refresh token issued alongside the access token for obtaining new access tokens."
|
||||
)
|
||||
@@ -0,0 +1,162 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
import inse.auth.service as auth_service
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
IdToken,
|
||||
LoginResponse,
|
||||
RefreshToken,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/request-otk",
|
||||
summary="Request One-Time Key",
|
||||
description="Request a one-time key (OTK) for authentication using email and password.",
|
||||
operation_id="requestOtk",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
|
||||
},
|
||||
)
|
||||
async def request_otk(
|
||||
session: SessionDep,
|
||||
email: Annotated[str, Body(description="User's email address")],
|
||||
password: Annotated[str, Body(description="User's password")],
|
||||
):
|
||||
return auth_service.request_otk(session=session, email=email, password=password)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
summary="Login with One-Time Key",
|
||||
description="Login using a one-time key (OTK) sent to the user's email.",
|
||||
operation_id="login",
|
||||
responses={status.HTTP_200_OK: {"description": "Login successful."}},
|
||||
)
|
||||
async def login(
|
||||
session: SessionDep,
|
||||
response: Response,
|
||||
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
email_code: Annotated[
|
||||
str, Body(embed=True, description="One-time code sent to user's email")
|
||||
],
|
||||
) -> LoginResponse:
|
||||
return auth_service.login(
|
||||
session=session, response=response, account_id=account_id, email_code=email_code
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/access",
|
||||
summary="Get Access Token",
|
||||
description="Retrieve an access token for the authenticated user.",
|
||||
operation_id="getAccessToken",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
|
||||
},
|
||||
)
|
||||
async def get_action_tokens(
|
||||
response: Response,
|
||||
session: SessionDep,
|
||||
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
effective_account_id: Annotated[
|
||||
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||
],
|
||||
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||
) -> AccessResponse:
|
||||
logger.debug(
|
||||
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||
real_account_id,
|
||||
effective_account_id,
|
||||
id_token,
|
||||
)
|
||||
|
||||
return auth_service.get_access_token(
|
||||
response=response,
|
||||
session=session,
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
id_token=id_token,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/refresh",
|
||||
summary="Refresh Access Token",
|
||||
description="Refresh the access token using a valid refresh token.",
|
||||
operation_id="refreshAccessToken",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
|
||||
},
|
||||
)
|
||||
async def refresh_access_token(
|
||||
refresh_token: Annotated[
|
||||
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||
],
|
||||
) -> AccessToken:
|
||||
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/logout",
|
||||
summary="Logout",
|
||||
description="Logout the authenticated user.",
|
||||
operation_id="logout",
|
||||
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
|
||||
)
|
||||
async def logout(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.logout(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/change-password",
|
||||
summary="Change Password",
|
||||
description="Change the user's password and invalidate existing tokens.",
|
||||
operation_id="changePassword",
|
||||
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
|
||||
)
|
||||
async def change_password(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
current_password: Annotated[
|
||||
str,
|
||||
Body(description="Current password"),
|
||||
],
|
||||
new_password: Annotated[
|
||||
str,
|
||||
Body(description="New password", min_length=8),
|
||||
],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.change_password(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
current_password=current_password,
|
||||
new_password=new_password,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,546 @@
|
||||
import inse.config as config_module
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
|
||||
|
||||
from fastapi import Response, HTTPException
|
||||
import datetime as _dt
|
||||
from datetime import timedelta
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import (
|
||||
Account,
|
||||
Organization,
|
||||
Secret,
|
||||
IdToken,
|
||||
AccessToken,
|
||||
RefreshToken,
|
||||
UserRole,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def settings_backup():
|
||||
orig = config_module.get_settings()
|
||||
backup = config_module.Settings(**orig.model_dump())
|
||||
yield backup
|
||||
for k, v in backup.model_dump().items():
|
||||
setattr(config_module.settings, k, v)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def in_memory_session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
|
||||
def create_org_and_account(
|
||||
session: Session, email: str, password: str, role=UserRole.USER
|
||||
):
|
||||
org = Organization(name=f"Test Org {email}")
|
||||
session.add(org)
|
||||
session.flush()
|
||||
assert org.id is not None
|
||||
pwd_hash = auth_service._hash_password(password)
|
||||
acc = Account(
|
||||
email=email,
|
||||
name="Tester",
|
||||
organization_id=org.id,
|
||||
password_hash=pwd_hash,
|
||||
role=role,
|
||||
)
|
||||
session.add(acc)
|
||||
session.commit()
|
||||
session.refresh(acc)
|
||||
return org, acc
|
||||
|
||||
|
||||
def test_hash_and_verify_password():
|
||||
pw = "s3cret-password"
|
||||
h = auth_service._hash_password(pw)
|
||||
assert auth_service._verify_password(pw, h) is True
|
||||
assert auth_service._verify_password("wrong", h) is False
|
||||
|
||||
|
||||
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "test-hmac-key"
|
||||
config_module.settings.token_issuer_id = "test-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "user@example.com"
|
||||
password = "hunter2"
|
||||
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
resp = auth_service.request_otk(in_memory_session, email, password)
|
||||
assert resp["status"] == "ok"
|
||||
assert resp["account_id"] == str(acc.id)
|
||||
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
response = Response()
|
||||
|
||||
login_result = auth_service.login(
|
||||
in_memory_session, response, acc.id, secret.secret_value
|
||||
)
|
||||
assert isinstance(login_result.id_token, IdToken)
|
||||
assert login_result.id_token.real_account_id == acc.id
|
||||
assert login_result.id_token.user_fingerprint_hash is not None
|
||||
|
||||
|
||||
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "another-key"
|
||||
config_module.settings.token_issuer_id = "issuer-2"
|
||||
|
||||
email = "fp@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
assert isinstance(id_token, IdToken)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
assert cookie_header is not None
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0]
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
|
||||
payload = auth_service._verify_fp_token(
|
||||
request=req,
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
||||
|
||||
with pytest.raises(Exception):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({}),
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "flow-key"
|
||||
config_module.settings.token_issuer_id = "flow-issuer"
|
||||
|
||||
email = "flow@example.com"
|
||||
password = "pwflow"
|
||||
org, acc = create_org_and_account(
|
||||
in_memory_session, email, password, role=UserRole.ADMIN
|
||||
)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
access_response = auth_service.get_access_token(
|
||||
response, in_memory_session, id_token, acc.id
|
||||
)
|
||||
assert isinstance(access_response.access_token, AccessToken)
|
||||
assert isinstance(access_response.refresh_token, RefreshToken)
|
||||
|
||||
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
|
||||
assert isinstance(refreshed, AccessToken)
|
||||
assert refreshed.real_account_id == access_response.access_token.real_account_id
|
||||
|
||||
|
||||
def test_logout_and_change_password(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "logout-key"
|
||||
config_module.settings.token_issuer_id = "logout-issuer"
|
||||
|
||||
email = "logout@example.com"
|
||||
password = "oldpw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
access_resp = auth_service.get_access_token(
|
||||
response, in_memory_session, id_token, acc.id
|
||||
)
|
||||
|
||||
before_epoch = acc.epoch
|
||||
out = auth_service.logout(in_memory_session, access_resp.access_token)
|
||||
assert out["status"] == "ok"
|
||||
in_memory_session.refresh(acc)
|
||||
assert acc.epoch == before_epoch + 1
|
||||
|
||||
new_pw = "newpw123"
|
||||
acc.password_hash = auth_service._hash_password(password)
|
||||
in_memory_session.add(acc)
|
||||
in_memory_session.commit()
|
||||
|
||||
change_out = auth_service.change_password(
|
||||
in_memory_session, access_resp.access_token, password, new_pw
|
||||
)
|
||||
assert change_out["status"] == "ok"
|
||||
in_memory_session.refresh(acc)
|
||||
assert auth_service._verify_password(new_pw, acc.password_hash)
|
||||
|
||||
|
||||
def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
|
||||
email = "nope@example.com"
|
||||
password = "rightpw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
||||
|
||||
|
||||
def test_deactivated_account_cannot_request_otk(in_memory_session):
|
||||
email = "inactive@example.com"
|
||||
password = "rightpw"
|
||||
_, account = create_org_and_account(in_memory_session, email, password)
|
||||
account.activated = False
|
||||
in_memory_session.add(account)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
assert error.value.detail == "Account is deactivated and cannot log in."
|
||||
|
||||
|
||||
def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_session):
|
||||
_, account = create_org_and_account(
|
||||
in_memory_session, "inactive-lookup@example.com", "password"
|
||||
)
|
||||
account.activated = False
|
||||
in_memory_session.add(account)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
auth_service._get_active_account(in_memory_session, account.id)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "expired-key"
|
||||
config_module.settings.token_issuer_id = "expired-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "expired@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.login(in_memory_session, Response(), acc.id, "000000")
|
||||
|
||||
|
||||
def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "cookie-key"
|
||||
config_module.settings.token_issuer_id = "cookie-issuer"
|
||||
|
||||
email = "cookie@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_token_epoch_mismatch(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "epoch-key"
|
||||
config_module.settings.token_issuer_id = "epoch-issuer"
|
||||
|
||||
email = "epoch@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
acc.epoch += 1
|
||||
in_memory_session.add(acc)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_token_signature_raises(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "sig-key"
|
||||
config_module.settings.token_issuer_id = "sig-issuer"
|
||||
|
||||
email = "sig@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
bad_token = id_token.raw_token + "x"
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=bad_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_impersonation_rules(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "imp-key"
|
||||
config_module.settings.token_issuer_id = "imp-issuer"
|
||||
|
||||
org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw")
|
||||
assert real_acc.id is not None
|
||||
org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw")
|
||||
assert eff_acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch)
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.get_access_token(
|
||||
response,
|
||||
in_memory_session,
|
||||
id_token,
|
||||
real_acc.id,
|
||||
effective_account_id=eff_acc.id,
|
||||
)
|
||||
|
||||
real_acc.role = UserRole.SUPER_ADMIN
|
||||
in_memory_session.add(real_acc)
|
||||
in_memory_session.commit()
|
||||
|
||||
access_resp = auth_service.get_access_token(
|
||||
response,
|
||||
in_memory_session,
|
||||
id_token,
|
||||
real_acc.id,
|
||||
effective_account_id=eff_acc.id,
|
||||
)
|
||||
assert isinstance(access_resp.access_token, AccessToken)
|
||||
|
||||
|
||||
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "regen-key"
|
||||
config_module.settings.token_issuer_id = "regen-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "regen@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret1 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert secret1 is not None
|
||||
first_value = secret1.secret_value
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret2 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
|
||||
assert secret2 is not None
|
||||
assert first_value != secret2.secret_value
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.login(in_memory_session, Response(), acc.id, first_value)
|
||||
|
||||
login_res = auth_service.login(
|
||||
in_memory_session, Response(), acc.id, secret2.secret_value
|
||||
)
|
||||
assert isinstance(login_res.id_token, IdToken)
|
||||
|
||||
|
||||
def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "del-key"
|
||||
config_module.settings.token_issuer_id = "del-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "single@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||
post = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert post is None
|
||||
|
||||
|
||||
def test_access_token_fp_mismatch(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "act-key"
|
||||
config_module.settings.token_issuer_id = "act-issuer"
|
||||
|
||||
email = "act@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
raw = auth_service._set_act_fp_cookie(response)
|
||||
|
||||
access_token = auth_service._build_access_token(
|
||||
real_account_id=acc.id,
|
||||
effective_account_id=acc.id,
|
||||
effective_role=acc.role,
|
||||
effective_organization_id=acc.organization_id,
|
||||
epoch=acc.epoch,
|
||||
user_fingerprint_hash=raw,
|
||||
)
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
|
||||
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
|
||||
token=access_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "exp-key"
|
||||
config_module.settings.token_issuer_id = "exp-issuer"
|
||||
|
||||
email = "exp@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
cookie_raw = auth_service._set_id_fp_cookie(response)
|
||||
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||
payload = {
|
||||
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||
auth_service.EPOCH_KEY: acc.epoch,
|
||||
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
|
||||
}
|
||||
bad_token = auth_service._build_token(
|
||||
payload=payload,
|
||||
expiration_datetime=past,
|
||||
token_type=auth_service.TokenType.ID_TOKEN,
|
||||
)
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq(
|
||||
{
|
||||
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
|
||||
.split("=")[1]
|
||||
.split(";")[0]
|
||||
}
|
||||
), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=bad_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_missing_hmac_key_raises_value_error(settings_backup):
|
||||
orig = config_module.get_settings()
|
||||
saved = orig.token_hmac_key
|
||||
config_module.settings.token_hmac_key = None
|
||||
with pytest.raises(ValueError):
|
||||
auth_service._build_token(
|
||||
payload={},
|
||||
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
|
||||
token_type=auth_service.TokenType.ID_TOKEN,
|
||||
)
|
||||
config_module.settings.token_hmac_key = saved
|
||||
|
||||
|
||||
def test_get_account_epoch_not_found(in_memory_session):
|
||||
random_id = uuid.uuid4()
|
||||
with pytest.raises(Exception):
|
||||
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||
@@ -1,12 +1,9 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from . import model
|
||||
from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
|
||||
from .search_client import CompanyConnectionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -23,22 +20,10 @@ async def get_company_connections_by_author_id(
|
||||
) -> model.CompanyConnectionsResponse:
|
||||
search_client = client or CompanyConnectionsSearchClient()
|
||||
|
||||
try:
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex author lookup failed for %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex author lookup failed.",
|
||||
) from exc
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
|
||||
if author_hit is None:
|
||||
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
|
||||
raise NotFoundException(f"Author {author_id} not found.")
|
||||
|
||||
source = author_hit.get("_source", {})
|
||||
display_name = _clean(source.get("display_name"))
|
||||
@@ -59,21 +44,9 @@ async def get_company_connections_by_author_id(
|
||||
connections=[],
|
||||
)
|
||||
|
||||
try:
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("Handelsregister lookup failed for %s.", display_name)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Handelsregister lookup failed.",
|
||||
) from exc
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
|
||||
company_count, company_count_relation = _parse_total(hr_response)
|
||||
connections = _parse_company_connections(
|
||||
|
||||
@@ -1,64 +1,45 @@
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class CompanyConnectionsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
openalex_index: str = "openalex-authors",
|
||||
handelsregister_index: str = "handelsregister",
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (
|
||||
base_url
|
||||
or config.settings.elasticsearch_url
|
||||
or ""
|
||||
).rstrip("/")
|
||||
self.api_key = (
|
||||
api_key
|
||||
if api_key is not None
|
||||
else config.settings.elasticsearch_api_key
|
||||
)
|
||||
)
|
||||
self.openalex_index = openalex_index
|
||||
self.handelsregister_index = handelsregister_index
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
@staticmethod
|
||||
def openalex_doc_id(author_id: str) -> str:
|
||||
return author_id.strip().removeprefix("https://openalex.org/")
|
||||
|
||||
async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
doc_id = self.openalex_doc_id(author_id)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
f"/{self.openalex_index}/_doc/{doc_id}",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
try:
|
||||
return await elasticsearch.get(
|
||||
index=self.openalex_index,
|
||||
doc_id=doc_id,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except ElasticsearchNotFoundException:
|
||||
return None
|
||||
|
||||
async def search_handelsregister_by_officer_name(
|
||||
self,
|
||||
@@ -66,27 +47,16 @@ class CompanyConnectionsSearchClient:
|
||||
size: int = 10000,
|
||||
track_total_hits: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
payload = self.handelsregister_officer_name_query(
|
||||
officer_name=officer_name,
|
||||
size=size,
|
||||
track_total_hits=track_total_hits,
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.handelsregister_index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(
|
||||
index=self.handelsregister_index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def handelsregister_officer_name_query(
|
||||
|
||||
@@ -7,7 +7,7 @@ that can be adjusted via environment variables.
|
||||
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
from typing import Dict, List, Literal, Optional
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -34,19 +34,17 @@ class Settings(BaseSettings):
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
|
||||
# Patent Elasticsearch config
|
||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||
patent_elasticsearch_api_key: Optional[str] = None
|
||||
|
||||
|
||||
# LLM config
|
||||
llm_api_url: Optional[str] = None
|
||||
llm_api_key: Optional[str] = None
|
||||
llm_model: Optional[str] = None
|
||||
|
||||
# Sentence Transformers config
|
||||
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
|
||||
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
|
||||
|
||||
# Elasticsearch config
|
||||
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
||||
@@ -64,6 +62,21 @@ class Settings(BaseSettings):
|
||||
|
||||
logging_level: str = "DEBUG"
|
||||
|
||||
environment: Literal["dev", "prod"] = "dev"
|
||||
|
||||
token_issuer_id: Optional[str] = None
|
||||
token_hmac_key: Optional[str] = None
|
||||
|
||||
skip_otk_validation: bool = True
|
||||
# SMTP / email config
|
||||
send_otk_email: bool = False
|
||||
smtp_server: str = "localhost"
|
||||
smtp_port: int = 25
|
||||
smtp_sender: str = "no-reply@smartguide.local"
|
||||
smtp_username: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
smtp_use_tls: bool = False
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
|
||||
@@ -1,25 +1,43 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module contains the code to bootstrap the database
|
||||
using our schema and sqlalchemy.
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from . import schema
|
||||
from . import config
|
||||
from typing import Annotated
|
||||
|
||||
engine = create_engine(config.settings.database_url, echo=config.settings.database_debug)
|
||||
from fastapi import Depends
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlmodel import SQLModel, Session, create_engine
|
||||
|
||||
if config.settings.database_init:
|
||||
schema.Base.metadata.create_all(engine)
|
||||
from inse import config
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
def get():
|
||||
''' Returns a database connection and closes it when done. '''
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
settings = config.get_settings()
|
||||
|
||||
connect_args = {"check_same_thread": False}
|
||||
engine = create_engine(
|
||||
url=settings.database_url,
|
||||
echo=settings.database_debug,
|
||||
connect_args=connect_args,
|
||||
)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
"""Creates the database and tables based on the SQLModel metadata."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("account")}
|
||||
if "activated" not in columns:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"ALTER TABLE account ADD COLUMN activated "
|
||||
"BOOLEAN NOT NULL DEFAULT TRUE"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_session():
|
||||
"""Yields a database session for use in FastAPI endpoints.
|
||||
|
||||
Yields:
|
||||
Session: A SQLModel session connected to the database.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
|
||||
SessionDep = Annotated[Session, Depends(get_session)]
|
||||
|
||||
@@ -1,3 +1,41 @@
|
||||
class NotFoundException(Exception):
|
||||
"""Exception raised when a requested resource is not found.
|
||||
|
||||
Args:
|
||||
Exception (_type_): Base exception class.
|
||||
"""
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ElasticsearchException(Exception):
|
||||
"""Base exception for all Elasticsearch integrations."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
|
||||
"""Raised when an Elasticsearch document or index is not found."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchConnectionException(ElasticsearchException):
|
||||
"""Raised when connecting to Elasticsearch fails."""
|
||||
pass
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
"""Raised when a required API key is missing."""
|
||||
pass
|
||||
|
||||
|
||||
class UpstreamAPIException(Exception):
|
||||
"""Raised when an upstream third-party service (e.g. REST API) fails."""
|
||||
def __init__(self, message: str, status_code: int = 502):
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class BadRequestException(Exception):
|
||||
"""Raised when request parameters are invalid or validation fails."""
|
||||
pass
|
||||
|
||||
@@ -5,29 +5,22 @@
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class FundedPublicationsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
index: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
|
||||
self.index = index or config.settings.openalex_works_search_index
|
||||
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
||||
self.transport = transport
|
||||
|
||||
@staticmethod
|
||||
def indexed_author_id(author_id: str) -> str:
|
||||
@@ -177,15 +170,8 @@ class FundedPublicationsSearchClient:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
@@ -6,16 +6,11 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from . import model
|
||||
from .elastic_search_client import FundedPublicationsSearchClient
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -62,7 +57,7 @@ async def get_funders_by_author_id(
|
||||
funder_counts: dict[str, dict[str, Any]] = {}
|
||||
|
||||
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
|
||||
author_name = _get_author_name(author_id)
|
||||
author_name = await _get_author_name(author_id)
|
||||
|
||||
try:
|
||||
_, all_hits = await _fetch_all_author_work_hits(
|
||||
@@ -92,9 +87,9 @@ async def get_funders_by_author_id(
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("Funders response could not be validated for author %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Funders response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="Funders response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -144,26 +139,13 @@ async def _search_funded_publications(
|
||||
*,
|
||||
funded_only: bool = False,
|
||||
) -> dict:
|
||||
try:
|
||||
payload = search_client.publications_by_author_query(
|
||||
author_id,
|
||||
page,
|
||||
page_size,
|
||||
funded_only=funded_only,
|
||||
)
|
||||
return await search_client.search(payload)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
payload = search_client.publications_by_author_query(
|
||||
author_id,
|
||||
page,
|
||||
page_size,
|
||||
funded_only=funded_only,
|
||||
)
|
||||
return await search_client.search(payload)
|
||||
|
||||
|
||||
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
@@ -180,9 +162,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
return total, results
|
||||
|
||||
|
||||
def _get_author_name(author_id: str) -> str | None:
|
||||
async def _get_author_name(author_id: str) -> str | None:
|
||||
short_author_id = author_id.replace("https://openalex.org/", "")
|
||||
search_result = person_logic.search_persons(author_id=short_author_id)
|
||||
search_result = await person_logic.search_persons(author_id=short_author_id)
|
||||
|
||||
if not search_result.results:
|
||||
return None
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
from inse.funders import logic
|
||||
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
|
||||
@@ -68,201 +66,177 @@ def _funded_publication_hit(
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json.loads(request.content.decode("utf-8"))
|
||||
assert payload["from"] == 0
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
async def test_get_funders_by_author_id_aggregates_funders_and_awards():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
mock_author_result = type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]}
|
||||
)()
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 2
|
||||
assert response.funders[0].funder_id == "https://openalex.org/F123"
|
||||
assert response.funders[0].funder_name == "Funder A"
|
||||
assert response.funders[0].publication_count == 2
|
||||
assert response.funders[0].author_position_count.first == 1
|
||||
assert response.funders[0].author_position_count.last == 1
|
||||
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
|
||||
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
publication_detail = response.funders[0].publication_details["https://openalex.org/W1"]
|
||||
assert publication_detail.title == "Example publication: full detail"
|
||||
assert publication_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert publication_detail.abstract == "This is an abstract."
|
||||
assert publication_detail.publication_date == "2020-05-10"
|
||||
assert publication_detail.publication_type == "article"
|
||||
assert publication_detail.source_name == "Example Journal"
|
||||
assert publication_detail.source_type == "journal"
|
||||
assert publication_detail.is_open_access is True
|
||||
assert publication_detail.open_access_status == "gold"
|
||||
assert publication_detail.has_fulltext is True
|
||||
assert publication_detail.license == "cc-by"
|
||||
assert publication_detail.cited_by_count == 12
|
||||
assert publication_detail.primary_topic == "Clinical Trials"
|
||||
assert publication_detail.topic_field == "Health Sciences"
|
||||
assert publication_detail.topic_subfield == "Medicine"
|
||||
assert publication_detail.topic_domain == "Life Sciences"
|
||||
assert publication_detail.topics == ["Trials", "Guidelines"]
|
||||
assert publication_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert publication_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [
|
||||
"Project Grant"
|
||||
]
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 2
|
||||
|
||||
funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123")
|
||||
assert funder_a.funder_name == "Funder A"
|
||||
assert funder_a.publication_count == 2
|
||||
assert funder_a.author_position_count.first == 1
|
||||
assert funder_a.author_position_count.last == 1
|
||||
assert funder_a.publication_ids.first == ["https://openalex.org/W1"]
|
||||
assert funder_a.publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
|
||||
pub1_detail = funder_a.publication_details["https://openalex.org/W1"]
|
||||
assert pub1_detail.title == "Example publication: full detail"
|
||||
assert pub1_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert pub1_detail.abstract == "This is an abstract."
|
||||
assert pub1_detail.publication_date == "2020-05-10"
|
||||
assert pub1_detail.publication_type == "article"
|
||||
assert pub1_detail.source_name == "Example Journal"
|
||||
assert pub1_detail.source_type == "journal"
|
||||
assert pub1_detail.is_open_access is True
|
||||
assert pub1_detail.open_access_status == "gold"
|
||||
assert pub1_detail.has_fulltext is True
|
||||
assert pub1_detail.license == "cc-by"
|
||||
assert pub1_detail.cited_by_count == 12
|
||||
assert pub1_detail.primary_topic == "Clinical Trials"
|
||||
assert pub1_detail.topic_field == "Health Sciences"
|
||||
assert pub1_detail.topic_subfield == "Medicine"
|
||||
assert pub1_detail.topic_domain == "Life Sciences"
|
||||
assert pub1_detail.topics == ["Trials", "Guidelines"]
|
||||
assert pub1_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert pub1_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
|
||||
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded():
|
||||
requested_pages: list[int] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json.loads(request.content.decode("utf-8"))
|
||||
size = payload["size"]
|
||||
offset = payload["from"]
|
||||
async def mock_search_func(index, body, cluster=None):
|
||||
size = body["size"]
|
||||
offset = body["from"]
|
||||
page = offset // size + 1
|
||||
requested_pages.append(page)
|
||||
total = size + 1
|
||||
@@ -284,115 +258,87 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m
|
||||
)
|
||||
]
|
||||
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": total},
|
||||
"hits": hits,
|
||||
},
|
||||
return {
|
||||
"hits": {
|
||||
"total": {"value": total},
|
||||
"hits": hits,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert requested_pages == [1, 2]
|
||||
assert response.funder_count > 1
|
||||
funder_names = {funder.funder_name for funder in response.funders}
|
||||
assert "Funder 1" in funder_names
|
||||
assert requested_pages == [1, 2]
|
||||
assert response.funder_count > 1
|
||||
funder_names = {funder.funder_name for funder in response.funders}
|
||||
assert "Funder 1" in funder_names
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Bundesministerium",
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
async def test_get_funders_by_author_id_ignores_publications_without_funders():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Bundesministerium",
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
assert response.funder_count == 1
|
||||
assert response.funders[0].funder_name == "Bundesministerium"
|
||||
assert response.funders[0].publication_count == 1
|
||||
assert response.funder_count == 1
|
||||
assert response.funders[0].funder_name == "Bundesministerium"
|
||||
assert response.funders[0].publication_count == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"hits": {"total": {"value": 0}, "hits": []}},
|
||||
)
|
||||
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders():
|
||||
mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
assert response.funder_count == 0
|
||||
assert response.funders == []
|
||||
assert response.funder_count == 0
|
||||
assert response.funders == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="")
|
||||
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable():
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
assert exc.value.status_code == 503
|
||||
client = FundedPublicationsSearchClient(api_key="")
|
||||
|
||||
with pytest.raises(MissingApiKeyError):
|
||||
await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
@@ -20,7 +20,7 @@ class InstitutionsSearchClient:
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
"""Retrieves an institution by its raw OpenAlex institution ID.
|
||||
|
||||
Args:
|
||||
@@ -38,7 +38,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
res = await elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
@@ -72,7 +72,7 @@ class InstitutionsSearchClient:
|
||||
# TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache.
|
||||
return cache.get(raw_institution_id)
|
||||
|
||||
def get_institutions_by_name(
|
||||
async def get_institutions_by_name(
|
||||
self,
|
||||
name: str,
|
||||
page: int = 0,
|
||||
@@ -122,7 +122,7 @@ class InstitutionsSearchClient:
|
||||
query,
|
||||
)
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
offset=page * size,
|
||||
size=size,
|
||||
@@ -189,7 +189,7 @@ class InstitutionsSearchClient:
|
||||
query,
|
||||
)
|
||||
|
||||
res = elasticsearch.search(index="openalex-authors", query=query)
|
||||
res = await elasticsearch.search(index="openalex-authors", query=query)
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
|
||||
# Extracting display_name directly from the author document source
|
||||
@@ -200,7 +200,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
return list(authors)
|
||||
|
||||
def search_institutions(
|
||||
async def search_institutions(
|
||||
self,
|
||||
query_text: str,
|
||||
country_code: str | None = None,
|
||||
@@ -265,7 +265,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=limit,
|
||||
@@ -288,7 +288,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
return [Institution.from_dict(hit["_source"]) for hit in hits]
|
||||
|
||||
def get_institution_aliases_by_oa_institution_id(
|
||||
async def get_institution_aliases_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> List[str]:
|
||||
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
|
||||
@@ -299,7 +299,7 @@ class InstitutionsSearchClient:
|
||||
Returns:
|
||||
List[str]: A list of aliases for the given institution ID.
|
||||
"""
|
||||
institution = self.get_institution_by_id(raw_oa_institution_id)
|
||||
institution = await self.get_institution_by_id(raw_oa_institution_id)
|
||||
aliases = list(
|
||||
self.augment_aliases(set(institution.display_name_alternatives or []))
|
||||
| self.get_predefined_institution_aliases(raw_oa_institution_id)
|
||||
@@ -426,7 +426,7 @@ class InstitutionsSearchClient:
|
||||
)
|
||||
return None
|
||||
|
||||
def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
async def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Optional[List[str]]:
|
||||
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
|
||||
@@ -439,7 +439,7 @@ class InstitutionsSearchClient:
|
||||
"""
|
||||
|
||||
institution_aliases = set(
|
||||
self.get_institution_aliases_by_oa_institution_id(
|
||||
await self.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id=raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
@@ -476,7 +476,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
try:
|
||||
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="cordis_eu_*_organizations", body=body, cluster="inse"
|
||||
)
|
||||
except Exception as e:
|
||||
|
||||
@@ -9,10 +9,8 @@ from copy import deepcopy
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
@@ -41,7 +39,7 @@ _VALID_INSTITUTION_TYPES = {
|
||||
async def get_institution_by_id(
|
||||
raw_institution_id: str, client: InstitutionsSearchClient
|
||||
) -> Institution:
|
||||
return client.get_institution_by_id(raw_institution_id)
|
||||
return await client.get_institution_by_id(raw_institution_id)
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
@@ -58,10 +56,7 @@ async def list_institutions(
|
||||
client: OpenAlexInstitutionsClient | None = None,
|
||||
) -> InstitutionsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexInstitutionsClient()
|
||||
|
||||
@@ -86,12 +81,12 @@ async def list_institutions(
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex institutions request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions request failed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
@@ -102,9 +97,9 @@ async def list_institutions(
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex institutions response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -120,7 +115,7 @@ async def autocomplete_institutions(
|
||||
Returns institution options for autocomplete inputs using the local
|
||||
Elasticsearch cluster via the provided client.
|
||||
"""
|
||||
institutions = client.search_institutions(
|
||||
institutions = await client.search_institutions(
|
||||
query_text=query,
|
||||
country_code=country_code,
|
||||
institution_type=institution_type,
|
||||
|
||||
@@ -72,7 +72,7 @@ async def search_institutions_by_name(
|
||||
),
|
||||
] = "asc",
|
||||
) -> InstitutionPage:
|
||||
return client.get_institutions_by_name(
|
||||
return await client.get_institutions_by_name(
|
||||
name=name,
|
||||
page=page,
|
||||
size=size,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
@@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
|
||||
@@ -1,13 +1,37 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.exceptions import (
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
MissingApiKeyError,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from .. import config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[httpx.AsyncClient] = None
|
||||
_loop = None
|
||||
|
||||
|
||||
def get_client() -> httpx.AsyncClient:
|
||||
global _client, _loop
|
||||
try:
|
||||
import asyncio
|
||||
current_loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
current_loop = None
|
||||
|
||||
if _client is None or _loop is not current_loop:
|
||||
_client = httpx.AsyncClient(timeout=httpx.Timeout(30.0))
|
||||
_loop = current_loop
|
||||
return _client
|
||||
|
||||
|
||||
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
|
||||
@@ -21,22 +45,23 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
Returns:
|
||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||
"""
|
||||
|
||||
|
||||
if cluster == ESCluster.NES:
|
||||
if (
|
||||
not config.settings.elasticsearch_url
|
||||
or not config.settings.elasticsearch_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||
)
|
||||
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == ESCluster.INSE:
|
||||
if (
|
||||
not config.settings.elasticsearch_inse_url
|
||||
or not config.settings.elasticsearch_inse_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
|
||||
)
|
||||
|
||||
@@ -80,8 +105,18 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
return None
|
||||
|
||||
|
||||
def search(
|
||||
index: ESIndex | List[ESIndex],
|
||||
def _wrap_exception(e: Exception) -> Exception:
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
||||
elif isinstance(e, httpx.RequestError):
|
||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||
|
||||
|
||||
async def search(
|
||||
index: ESIndex | List[ESIndex] | str | List[str],
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List] = None,
|
||||
size: Optional[int] = None,
|
||||
@@ -112,10 +147,11 @@ def search(
|
||||
clusters = set()
|
||||
if isinstance(index, list):
|
||||
for idx in index:
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
else:
|
||||
if isinstance(idx, ESIndex):
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
elif isinstance(index, ESIndex):
|
||||
cluster_for_index = _index_to_cluster(index)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
@@ -156,24 +192,125 @@ def search(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
|
||||
)
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(index)
|
||||
else:
|
||||
index_str = index
|
||||
client = get_client()
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(str(idx) for idx in index)
|
||||
else:
|
||||
index_str = str(index)
|
||||
|
||||
response = client.post(
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def get(
|
||||
index: ESIndex,
|
||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_pit",
|
||||
params={"keep_alive": keep_alive},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["id"]
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
"""Closes a previously opened point-in-time."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.request(
|
||||
"DELETE",
|
||||
f"{elasticsearch_url}/_pit",
|
||||
json={"id": pit_id},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def scan(
|
||||
index: str,
|
||||
query: Dict,
|
||||
source: Optional[List] = None,
|
||||
page_size: int = 1000,
|
||||
keep_alive: str = "1m",
|
||||
cluster: str = "nes",
|
||||
) -> AsyncIterator[Dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
search_after: Optional[List] = None
|
||||
try:
|
||||
client = get_client()
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
"size": page_size,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": keep_alive},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
"track_total_hits": False,
|
||||
}
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
result = response.json()
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
yield hit
|
||||
|
||||
# The pit id can be refreshed between requests; keep the latest.
|
||||
pit_id = result.get("pit_id", pit_id)
|
||||
search_after = hits[-1].get("sort")
|
||||
if search_after is None or len(hits) < page_size:
|
||||
break
|
||||
finally:
|
||||
try:
|
||||
await close_point_in_time(pit_id, cluster=cluster)
|
||||
except Exception:
|
||||
logger.exception("Failed to close Elasticsearch point-in-time.")
|
||||
|
||||
|
||||
async def get(
|
||||
index: ESIndex | str,
|
||||
doc_id: str,
|
||||
source: Optional[list] = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
@@ -187,9 +324,56 @@ def get(
|
||||
if source is not None:
|
||||
params["_source_includes"] = ",".join(source)
|
||||
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def update(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
doc: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_update/{doc_id}",
|
||||
json={"doc": doc},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def index_doc(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
document: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.put(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
json=document,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
model: str = None,
|
||||
timeout: int = 30,
|
||||
json_schema = None,
|
||||
schema_name = None,
|
||||
timeout: int = 120,
|
||||
temperature: float = 1.0,
|
||||
top_p: float = 0.95,
|
||||
) -> str:
|
||||
|
||||
if model is None:
|
||||
model = config.settings.llm_model
|
||||
|
||||
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
|
||||
|
||||
client = OpenAI(
|
||||
base_url=config.settings.llm_api_url,
|
||||
api_key=config.settings.llm_api_key,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
try:
|
||||
response = client.chat.completions.create(
|
||||
model=model,
|
||||
@@ -27,10 +33,10 @@ def call(
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
response_format=response_format
|
||||
)
|
||||
except APIConnectionError:
|
||||
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
|
||||
@@ -38,3 +44,73 @@ def call(
|
||||
return response.choices[0].message.content or (
|
||||
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
|
||||
)
|
||||
|
||||
def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str, Any]:
|
||||
response_format = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": schema_name or "response",
|
||||
"strict": True,
|
||||
"schema": schema,
|
||||
},
|
||||
}
|
||||
return response_format
|
||||
|
||||
|
||||
|
||||
|
||||
async def call_stream(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
emit, # EventCallback
|
||||
model: str = None,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
timeout: int = 120,
|
||||
temperature: float = 1.0,
|
||||
top_p: float = 0.95,
|
||||
) -> str:
|
||||
if model is None:
|
||||
model = config.settings.llm_model
|
||||
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = _get_response_format(schema=json_schema, schema_name=schema_name)
|
||||
|
||||
client = AsyncOpenAI(
|
||||
base_url=config.settings.llm_api_url,
|
||||
api_key=config.settings.llm_api_key,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
full_content = ""
|
||||
try:
|
||||
stream = await client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
response_format=response_format,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
|
||||
except APIConnectionError as e:
|
||||
print(f"Connection error: {e}")
|
||||
return ""
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||
traceback.print_exc()
|
||||
return ""
|
||||
|
||||
return full_content
|
||||
@@ -0,0 +1,444 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for persons / authors.
|
||||
"""
|
||||
import asyncio
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import partial_json_parser
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from pydantic import ValidationError
|
||||
from typing import Awaitable, Callable
|
||||
from inse.keywords.prompts import KeywordsPrompt
|
||||
from inse.integrations import llm
|
||||
from inse.keywords.model import (
|
||||
ExtractedKeywords,
|
||||
ExtractedKeywordsLLM,
|
||||
ExtractedKeywordsResponse,
|
||||
KeywordEntry,
|
||||
KeywordEntryWithTopic,
|
||||
KeywordsWsEvent,
|
||||
)
|
||||
from inse.topics.logic import vector_search_topics_batch
|
||||
logger = logging.getLogger(__name__)
|
||||
EventCallback = Callable[[dict], Awaitable[None]]
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
|
||||
def _build_enriched_snapshot(
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]],
|
||||
) -> ExtractedKeywords:
|
||||
return ExtractedKeywords.model_validate(
|
||||
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||
)
|
||||
|
||||
|
||||
async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords:
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {
|
||||
level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)]
|
||||
for level in LEVELS
|
||||
}
|
||||
|
||||
keywords: List[str] = []
|
||||
positions: List[tuple[str, int]] = []
|
||||
for level in LEVELS:
|
||||
for idx, entry in enumerate(getattr(results, level)):
|
||||
keywords.append(entry.keyword)
|
||||
positions.append((level, idx))
|
||||
|
||||
if keywords:
|
||||
matches = await vector_search_topics_batch(keywords=keywords, search_type="hybrid")
|
||||
for (level, idx), match in zip(positions, matches.results):
|
||||
confirmed[level][idx].topic_mapping = match
|
||||
|
||||
return _build_enriched_snapshot(confirmed)
|
||||
|
||||
async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywordsResponse:
|
||||
"""
|
||||
Extracts keywords from the given text or URL using a language model.
|
||||
"""
|
||||
start_time = time.time()
|
||||
if mode == "url":
|
||||
text = await _get_text_content(query)
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
|
||||
else:
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
text = query
|
||||
|
||||
|
||||
user_prompt = f"""
|
||||
Now analyze the following text and return ONLY the JSON object.\n"""
|
||||
|
||||
if limit:
|
||||
user_prompt +=f"Extract exactly {limit} keywords for each level (broad, coarse, fine) from the text below.\n"
|
||||
|
||||
user_prompt += f"""Input:{text}"""
|
||||
|
||||
keywords = llm.call(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema = ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name = "extracted_keywords",
|
||||
temperature=0.8,
|
||||
top_p=0.95,
|
||||
)
|
||||
keywords_json = json.loads(keywords)
|
||||
validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
||||
enriched = await _enrich_llm_keywords(validated)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.info(f"Keyword extraction took {elapsed_time:.2f} seconds")
|
||||
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
|
||||
|
||||
|
||||
async def _get_text_content(url: str) -> str:
|
||||
"""
|
||||
Fetches the HTML content from the given URL using httpx and extracts visible text.
|
||||
"""
|
||||
try:
|
||||
headers = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/91.0.4472.124 Safari/537.36"
|
||||
)
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
response = await client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
|
||||
soup = BeautifulSoup(response.text, "html.parser")
|
||||
for element in soup(["script", "style"]):
|
||||
element.decompose()
|
||||
text = soup.get_text(separator=" ", strip=True)
|
||||
text = " ".join(text.split())
|
||||
return text
|
||||
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"HTTP error for {url}: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing {url}: {e}")
|
||||
|
||||
|
||||
async def extract_keywords_stream(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 60 # configurable
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await _get_text_content(query)
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
user_prompt = "\nNow analyze the following text and return ONLY the JSON object.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level (broad, coarse, fine).\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
# Holds only fully validated KeywordEntry dicts for each level
|
||||
confirmed: Dict[str, List[Dict[str, Any]]] = {level: [] for level in LEVELS}
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
"""Attempt to build and validate the full ExtractedKeywordsLLM model and emit it."""
|
||||
# Build a dict with all three fields, using empty lists for missing ones
|
||||
data = {level: confirmed.get(level, []) for level in LEVELS}
|
||||
try:
|
||||
validated = ExtractedKeywordsLLM.model_validate(data)
|
||||
except ValidationError:
|
||||
# Should not happen if all items are valid, but guard against it
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
# adds completed keyword chunks to the confirmed dict and emits the full results when new valid items are found
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
idx = len(confirmed[level])
|
||||
|
||||
while idx < len(current):
|
||||
raw_item = current[idx]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break # item not complete yet
|
||||
confirmed[level].append(validated_item.model_dump())
|
||||
idx += 1
|
||||
grew = True
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
# Accumulate full_content for incremental parsing
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||
if event["type"] == "llm_chunk":
|
||||
full_content_holder["value"] += event["content"]
|
||||
event = {**event, "_full_content": full_content_holder["value"]}
|
||||
await on_chunk(event)
|
||||
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.8,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||
raise RuntimeError("LLM streaming call timed out")
|
||||
except asyncio.CancelledError:
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
if not keywords:
|
||||
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
||||
raise RuntimeError("LLM streaming call returned empty content")
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
try:
|
||||
keywords_json = json.loads(keywords)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||
raise RuntimeError("LLM response is not valid JSON")
|
||||
|
||||
# Final emission of the full results (in case the last chunk didn't trigger it)
|
||||
final_data = {level: confirmed.get(level, []) for level in LEVELS}
|
||||
try:
|
||||
final_validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
||||
except ValidationError:
|
||||
# Fallback: use our confirmed data
|
||||
final_validated = ExtractedKeywordsLLM.model_validate(final_data)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=text,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def extract_keywords_stream_enriched(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 120
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await _get_text_content(query)
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
|
||||
user_prompt = "\nNow analyze the following text.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
# Holds enriched keyword wrappers for each level
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||
|
||||
# Track background enrichment tasks
|
||||
enrichment_tasks: List[asyncio.Task] = []
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
"""Attempt to build and emit the full enriched keyword model."""
|
||||
try:
|
||||
validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
||||
"""
|
||||
Fetch/enrich metadata for a single keyword.
|
||||
Runs concurrently without blocking the LLM stream.
|
||||
"""
|
||||
try:
|
||||
topic = await vector_search_topics_batch(
|
||||
keywords=[item.keyword],
|
||||
search_type="hybrid",
|
||||
)
|
||||
# Update the shared confirmed list in-place (safe in asyncio)
|
||||
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
||||
|
||||
# Emit the full updated set after each enrichment so the frontend sees progress.
|
||||
await emit_full_results()
|
||||
|
||||
except asyncio.CancelledError:
|
||||
# If the whole request is cancelled, we can just re-raise
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||
await emit_full_results()
|
||||
|
||||
# ---------- on_chunk: parses LLM stream and appends new keywords ----------
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
start_idx = len(confirmed[level]) # Where we start appending
|
||||
|
||||
while len(confirmed[level]) < len(current):
|
||||
raw_item = current[len(confirmed[level])]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break # item not complete yet
|
||||
|
||||
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
||||
grew = True
|
||||
|
||||
# Launch openalex topic mapping
|
||||
for idx in range(start_idx, len(confirmed[level])):
|
||||
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="enriching",
|
||||
message=f"Extracting topic for keyword '{keyword_text}'",
|
||||
).model_dump()
|
||||
)
|
||||
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
|
||||
enrichment_tasks.append(task)
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
# ---------- Accumulate full_content for incremental parsing ----------
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||
if event["type"] == "llm_chunk":
|
||||
full_content_holder["value"] += event["content"]
|
||||
event = {**event, "_full_content": full_content_holder["value"]}
|
||||
await on_chunk(event)
|
||||
|
||||
# ---------- Call the LLM ----------
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.0,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||
raise RuntimeError("LLM streaming call timed out")
|
||||
except asyncio.CancelledError:
|
||||
# Cancel all pending enrichment tasks to avoid dangling background work
|
||||
for task in enrichment_tasks:
|
||||
task.cancel()
|
||||
if enrichment_tasks:
|
||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
# ---------- Finalize ----------
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
try:
|
||||
keywords_json = json.loads(keywords)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||
raise RuntimeError("LLM response is not valid JSON")
|
||||
|
||||
# ---------- Wait for ALL pending enrichments to complete ----------
|
||||
if enrichment_tasks:
|
||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
||||
|
||||
await emit_full_results()
|
||||
|
||||
# Build final response
|
||||
try:
|
||||
final_validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
final_validated = ExtractedKeywords.model_validate(
|
||||
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||
)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=text,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Data models for persons / authors.
|
||||
"""
|
||||
from typing import List, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.topics.model import KeywordTopicMatch
|
||||
class KeywordsRequest(BaseModel):
|
||||
query: str = Field(description="The input text from which to extract keywords.")
|
||||
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
|
||||
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
|
||||
|
||||
class KeywordEntry(BaseModel):
|
||||
keyword: str = Field(description="The extracted keyword.")
|
||||
relevance_score: float = Field(description="The relevance score of the keyword.")
|
||||
|
||||
class KeywordEntryWithTopic(BaseModel):
|
||||
llm_keyword: KeywordEntry = Field(description="The keyword extracted by the LLM.")
|
||||
topic_mapping: KeywordTopicMatch | None = Field(
|
||||
default=None,
|
||||
description="The corresponding OpenAlex topic match for the keyword, if any.",
|
||||
)
|
||||
|
||||
class ExtractedKeywords(BaseModel):
|
||||
broad_keywords: List[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: List[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: List[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.")
|
||||
|
||||
class ExtractedKeywordsLLM(BaseModel):
|
||||
broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
|
||||
|
||||
class ExtractedKeywordsResponse(BaseModel):
|
||||
results_llm: ExtractedKeywordsLLM | None = None
|
||||
results: ExtractedKeywords | None = None
|
||||
source: str = Field(description="The source of the input text, e.g., 'url', 'text', or 'keywords'.")
|
||||
source_url: str | None = Field(default=None, description="The URL from which keywords were extracted, if applicable.")
|
||||
source_content: str = Field(description="The actual content from which keywords were extracted.")
|
||||
duration: float | None = Field(default=None, description="The time taken to extract keywords, in seconds.")
|
||||
|
||||
class KeywordsWsEvent(BaseModel):
|
||||
type: str
|
||||
step: str | None = None
|
||||
message: str | None = None
|
||||
result: ExtractedKeywordsResponse | None = None
|
||||
keywords: ExtractedKeywords | ExtractedKeywordsLLM | None = None
|
||||
duration: float | None = None
|
||||
completed: str | None = None
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
from enum import StrEnum
|
||||
class KeywordsPrompt(StrEnum):
|
||||
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
|
||||
|
||||
Your task is to extract keywords from a given text and organize them into three hierarchical levels suitable for technology scouting, innovation discovery, scientific literature search, and OpenAlex-based research retrieval.
|
||||
|
||||
The extracted keywords should prioritize:
|
||||
|
||||
* Scientific domains
|
||||
* Technologies
|
||||
* Research fields
|
||||
* Methods
|
||||
* Applications
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Industrial sectors
|
||||
* Technical concepts
|
||||
|
||||
Avoid generic business terms unless they are core topics of the text.
|
||||
|
||||
Examples of terms to avoid:
|
||||
|
||||
* Solution
|
||||
* Platform
|
||||
* Improvement
|
||||
* Capability
|
||||
* Innovation
|
||||
* Process
|
||||
* Service
|
||||
* Performance
|
||||
* Efficiency
|
||||
|
||||
unless they represent an actual searchable concept.
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## 1. broad_keywords
|
||||
|
||||
High-level domains, disciplines, industries, or technology areas.
|
||||
|
||||
Examples:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Biotechnology
|
||||
* Renewable Energy
|
||||
* Materials Science
|
||||
* Robotics
|
||||
|
||||
These should represent the major themes of the document.
|
||||
|
||||
---
|
||||
|
||||
## 2. coarse_grained
|
||||
|
||||
Mid-level concepts, technologies, research areas, methods, or applications.
|
||||
|
||||
Examples:
|
||||
|
||||
* Machine Learning
|
||||
* Drug Discovery
|
||||
* Computer Vision
|
||||
* Predictive Maintenance
|
||||
* Smart Manufacturing
|
||||
* Gene Editing
|
||||
|
||||
These should provide more specific context within the broad domains.
|
||||
|
||||
---
|
||||
|
||||
## 3. fine_grained
|
||||
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
|
||||
|
||||
Examples:
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* Retrieval-Augmented Generation
|
||||
* Lithium Iron Phosphate
|
||||
* YOLOv8
|
||||
* OPC UA
|
||||
|
||||
These should be the most specific and actionable concepts for literature retrieval.
|
||||
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
|
||||
Each keyword must include a relevance score.
|
||||
|
||||
Definition:
|
||||
|
||||
* 1.0 = central concept of the text
|
||||
* 0.9 = extremely important concept
|
||||
* 0.8 = highly relevant concept
|
||||
* 0.7 = important supporting concept
|
||||
* 0.6 = relevant secondary concept
|
||||
* below 0.6 = use sparingly
|
||||
|
||||
Guidelines:
|
||||
|
||||
* Scores must be between 0.0 and 1.0.
|
||||
* Use decimal precision up to 3 digits.
|
||||
* Rank keywords by importance.
|
||||
* The most important keywords should appear first.
|
||||
* Broad keywords generally receive higher scores than secondary topics.
|
||||
* Only include keywords with meaningful relevance.
|
||||
|
||||
---
|
||||
|
||||
# Extraction Rules
|
||||
|
||||
* Extract only concepts explicitly mentioned or strongly implied.
|
||||
* Prefer noun phrases.
|
||||
* Avoid complete sentences.
|
||||
* Avoid duplicates across levels whenever possible.
|
||||
* Do not invent technologies not supported by the text.
|
||||
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||
|
||||
---
|
||||
|
||||
# Output Schema
|
||||
|
||||
Return ONLY valid JSON.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Example 1
|
||||
|
||||
Input:
|
||||
|
||||
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
||||
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]}
|
||||
|
||||
---
|
||||
|
||||
# Example 2
|
||||
|
||||
Input:
|
||||
|
||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]}
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
|
||||
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
||||
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||
|
||||
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||
|
||||
The extracted text may contain:
|
||||
|
||||
* Navigation menus
|
||||
* Headers and footers
|
||||
* Cookie notices
|
||||
* Marketing language
|
||||
* Contact information
|
||||
* Repeated sections
|
||||
* Calls to action
|
||||
* Legal disclaimers
|
||||
* Product pages
|
||||
* Blog articles
|
||||
* News articles
|
||||
* Landing pages
|
||||
|
||||
Your first task is to identify the actual content and purpose of the webpage.
|
||||
|
||||
Ignore:
|
||||
|
||||
* Navigation elements
|
||||
* Cookie banners
|
||||
* Legal notices
|
||||
* Copyright text
|
||||
* Generic marketing statements
|
||||
* Contact information
|
||||
* Login/signup content
|
||||
* Careers pages unless they contain relevant technical information
|
||||
* Repeated website boilerplate
|
||||
|
||||
Focus only on content that helps identify:
|
||||
|
||||
* Technologies
|
||||
* Scientific concepts
|
||||
* Research areas
|
||||
* Technical methods
|
||||
* Products
|
||||
* Applications
|
||||
* Industrial sectors
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Engineering disciplines
|
||||
* Innovation domains
|
||||
|
||||
---
|
||||
|
||||
# Step 1: Determine Page Type
|
||||
|
||||
Determine which type of page is represented:
|
||||
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
|
||||
Use this classification internally only.
|
||||
|
||||
Do not include it in the output.
|
||||
|
||||
---
|
||||
|
||||
# Step 2: Extract Searchable Concepts
|
||||
|
||||
Prioritize concepts that are useful for:
|
||||
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
|
||||
Prefer canonical scientific terminology over marketing language.
|
||||
|
||||
Examples:
|
||||
|
||||
Prefer:
|
||||
|
||||
* Large Language Models
|
||||
|
||||
Instead of:
|
||||
|
||||
* AI Assistant
|
||||
|
||||
Prefer:
|
||||
|
||||
* Smart Manufacturing
|
||||
|
||||
Instead of:
|
||||
|
||||
* Factory Optimization Solution
|
||||
|
||||
Prefer:
|
||||
|
||||
* Retrieval-Augmented Generation
|
||||
|
||||
Instead of:
|
||||
|
||||
* Intelligent Knowledge Assistant
|
||||
|
||||
Prefer:
|
||||
|
||||
* Predictive Maintenance
|
||||
|
||||
Instead of:
|
||||
|
||||
* Equipment Performance Optimization
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## broad_keywords
|
||||
|
||||
High-level domains, industries, disciplines, or technology areas.
|
||||
|
||||
Examples:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Manufacturing
|
||||
* Energy Storage
|
||||
* Biotechnology
|
||||
* Robotics
|
||||
|
||||
---
|
||||
|
||||
## coarse_grained
|
||||
|
||||
Technologies, methods, research fields, and applications.
|
||||
|
||||
Examples:
|
||||
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Computer Vision
|
||||
* Clinical Decision Support
|
||||
|
||||
---
|
||||
|
||||
## fine_grained
|
||||
|
||||
Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
|
||||
|
||||
Examples:
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* OPC UA
|
||||
* Retrieval-Augmented Generation
|
||||
* YOLOv8
|
||||
* Lithium Iron Phosphate
|
||||
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
|
||||
Guidelines:
|
||||
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
|
||||
---
|
||||
|
||||
# Additional Rules
|
||||
|
||||
* Extract only concepts supported by the page content.
|
||||
* Do not hallucinate technologies.
|
||||
* Avoid generic company descriptions.
|
||||
* Avoid generic business terminology.
|
||||
* Prefer terminology suitable for scientific literature search.
|
||||
* Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications.
|
||||
* Remove duplicates across hierarchy levels whenever possible.
|
||||
* Rank keywords by importance.
|
||||
|
||||
---
|
||||
# Example 3 — News Article
|
||||
|
||||
## Input
|
||||
|
||||
Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}```
|
||||
|
||||
---
|
||||
|
||||
# Example 4 — Product Page
|
||||
|
||||
## Input
|
||||
|
||||
The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}```
|
||||
|
||||
---
|
||||
|
||||
# Example 5 — Technical Documentation
|
||||
|
||||
## Input
|
||||
|
||||
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}```
|
||||
|
||||
---
|
||||
|
||||
# Example 6 — Company Website
|
||||
|
||||
## Input
|
||||
|
||||
Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}```
|
||||
|
||||
---
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
SIMPLE_TEXT_PROMPT = """
|
||||
You are a scientific and technology intelligence expert. Extract keywords from the given text into three hierarchical levels. Each keyword must include a relevance_score (0.0–1.0) indicating centrality.
|
||||
|
||||
**Levels:**
|
||||
- **broad_keywords** – high‑level domains/industries (e.g., Artificial Intelligence, Healthcare, Renewable Energy).
|
||||
- **coarse_grained** – mid‑level technologies/methods/applications (e.g., Machine Learning, Drug Discovery, Smart Manufacturing).
|
||||
- **fine_grained** – specific technical concepts, algorithms, materials, protocols (e.g., Transformer Architecture, CRISPR‑Cas9, Retrieval‑Augmented Generation).
|
||||
|
||||
**Guidelines:**
|
||||
- Prioritize scientific, technical, and research‑oriented terminology.
|
||||
- Avoid generic business fluff: "solution", "platform", "improvement", "service", "performance" – unless they are explicit searchable concepts.
|
||||
- Prefer noun phrases; avoid complete sentences.
|
||||
- Extract 5–15 keywords per level when possible.
|
||||
- Rank by importance (higher scores first).
|
||||
|
||||
**Relevance scores:**
|
||||
- 1.0 = central topic
|
||||
- 0.9 = extremely important
|
||||
- 0.8 = highly relevant
|
||||
- 0.7 = supporting concept
|
||||
- 0.6 = secondary
|
||||
- Below 0.6 – use sparingly.
|
||||
|
||||
**Output schema (JSON only):**
|
||||
{
|
||||
"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],
|
||||
"coarse_grained": [...],
|
||||
"fine_grained": [...]
|
||||
}
|
||||
|
||||
**Example:**
|
||||
Input: Researchers developed a transformer-based ML framework for predictive maintenance in smart factories using sensor fusion and anomaly detection.
|
||||
Output:
|
||||
{
|
||||
"broad_keywords": [{"keyword": "Artificial Intelligence", "relevance_score": 0.98}, {"keyword": "Manufacturing", "relevance_score": 0.94}],
|
||||
"coarse_grained": [{"keyword": "Predictive Maintenance", "relevance_score": 0.95}, {"keyword": "Anomaly Detection", "relevance_score": 0.85}],
|
||||
"fine_grained": [{"keyword": "Transformer Architecture", "relevance_score": 0.95}, {"keyword": "Sensor Fusion", "relevance_score": 0.82}]
|
||||
}
|
||||
|
||||
Return ONLY the JSON object, nothing else.
|
||||
"""
|
||||
SIMPLE_WEBSITE_PROMPT = """
|
||||
You are a technology scout and scientific analyst. The input is text scraped from a webpage (using BeautifulSoup or similar). Your goal: extract keywords into three hierarchical levels, just like the text prompt, but with extra care to ignore website boilerplate.
|
||||
|
||||
**Ignore:**
|
||||
- Navigation menus, headers/footers, cookie banners, legal disclaimers, copyright notices.
|
||||
- Generic marketing language, calls-to-action, contact details, login/signup content.
|
||||
- Repeated site templates or boilerplate.
|
||||
|
||||
**Focus only on:**
|
||||
- Technologies, research areas, scientific methods, products, applications, industrial sectors, materials, standards, diseases, engineering disciplines, innovation domains.
|
||||
- Prefer canonical scientific terms over marketing buzzwords (e.g., "Large Language Models" instead of "AI Assistant").
|
||||
|
||||
**Hierarchy and relevance scores** are the same as in the text prompt (broad → coarse → fine, scores 0.0–1.0).
|
||||
|
||||
**Output schema (JSON only):**
|
||||
'''{"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],"coarse_grained": [...],"fine_grained": [...]}'''
|
||||
|
||||
**Example (company website):**
|
||||
Input: Stripe provides payment infrastructure for businesses, supporting processing, billing, fraud prevention, and global commerce.
|
||||
Output:
|
||||
{"broad_keywords": [{"keyword": "Financial Technology", "relevance_score": 0.98}, {"keyword": "Business Services", "relevance_score": 0.91}],"coarse_grained": [{"keyword": "Payment Processing", "relevance_score": 0.97}, {"keyword": "Digital Payments", "relevance_score": 0.95}],"fine_grained": [{"keyword": "Stripe Platform", "relevance_score": 0.99}, {"keyword": "Fraud Prevention", "relevance_score": 0.91}]}
|
||||
|
||||
**Return ONLY the JSON object, nothing else.**
|
||||
- Nno leading/trailing spaces, newlines, or any text before or after. NO IDENTATION, justa stringified JSON
|
||||
"""
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for persons / authors.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||
|
||||
from . import logic
|
||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service",
|
||||
tags=["Keywords"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
@router.websocket("/keywords/extract/ws")
|
||||
async def extract_keywords_ws(websocket: WebSocket):
|
||||
print("WebSocket connection established for keyword extraction.")
|
||||
await websocket.accept()
|
||||
try:
|
||||
raw = await websocket.receive_json()
|
||||
request = KeywordsRequest(**raw)
|
||||
disconnected = asyncio.Event()
|
||||
|
||||
async def emit(event: dict):
|
||||
if disconnected.is_set():
|
||||
return
|
||||
await websocket.send_json(event)
|
||||
|
||||
async def watch_disconnect() -> None:
|
||||
while True:
|
||||
message = await websocket.receive()
|
||||
if message["type"] == "websocket.disconnect":
|
||||
disconnected.set()
|
||||
return
|
||||
|
||||
extraction_task = asyncio.create_task(
|
||||
logic.extract_keywords_stream_enriched(
|
||||
query=request.query,
|
||||
mode=request.mode,
|
||||
limit=request.limit,
|
||||
emit=emit,
|
||||
)
|
||||
)
|
||||
disconnect_task = asyncio.create_task(watch_disconnect())
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
{extraction_task, disconnect_task},
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
|
||||
if disconnect_task in done:
|
||||
disconnected.set()
|
||||
extraction_task.cancel()
|
||||
try:
|
||||
await extraction_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
return
|
||||
|
||||
disconnect_task.cancel()
|
||||
try:
|
||||
await disconnect_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
result = extraction_task.result()
|
||||
|
||||
await websocket.send_json({"type": "completed", "result": result.model_dump()})
|
||||
|
||||
except WebSocketDisconnect:
|
||||
print("WebSocket disconnected.")
|
||||
pass
|
||||
except Exception as e:
|
||||
await websocket.send_json({"type": "error", "message": str(e)})
|
||||
finally:
|
||||
if websocket.application_state.name != "DISCONNECTED":
|
||||
await websocket.close()
|
||||
|
||||
# @router.post(
|
||||
# "/keywords/extract",
|
||||
# operation_id="extractKeywords",
|
||||
# response_model=ExtractedKeywordsResponse,
|
||||
# )
|
||||
# async def extract_keywords(
|
||||
# request: Annotated[
|
||||
# KeywordsRequest,
|
||||
# Body(description="Input text for keyword extraction"),
|
||||
# ],
|
||||
# ):
|
||||
# async def noop(_: dict):
|
||||
# pass
|
||||
|
||||
# return await logic.extract_keywords_stream(
|
||||
# query=request.query,
|
||||
# mode=request.mode,
|
||||
# limit=request.limit,
|
||||
# emit=noop,
|
||||
# )
|
||||
|
||||
@router.post(
|
||||
"/keywords/extract",
|
||||
operation_id="extractKeywords",
|
||||
response_model=ExtractedKeywordsResponse,
|
||||
summary="Extracts keywords from text.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
async def extract_keywords(
|
||||
request: Annotated[
|
||||
KeywordsRequest,
|
||||
Body(description="Input text for keyword extraction")
|
||||
],
|
||||
|
||||
):
|
||||
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
|
||||
+35
-122
@@ -6,18 +6,11 @@ web service.
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
from typing import TypeVar
|
||||
from typing import Optional
|
||||
from typing import Type
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func
|
||||
import logging
|
||||
import httpx
|
||||
import json
|
||||
from . import schema
|
||||
from . import model
|
||||
|
||||
from . import config
|
||||
from inse.integrations import elasticsearch
|
||||
|
||||
|
||||
from inse.models.openalex.topic import Topic
|
||||
@@ -29,68 +22,13 @@ from inse.models.openalex.topic_domain import TopicDomain
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
topic_cache_filename: str = "topic_hierarchy_cache.json"
|
||||
|
||||
S = TypeVar('S', bound=schema.Base)
|
||||
M = TypeVar('M', bound=model.BaseModel)
|
||||
|
||||
def filter_none():
|
||||
return True
|
||||
|
||||
|
||||
def get_page(
|
||||
db: Session,
|
||||
schema_type: Type[S],
|
||||
model_type: Type[M],
|
||||
offset: int,
|
||||
limit: int,
|
||||
filter=filter_none,
|
||||
) -> model.Page[M]:
|
||||
result = model.Page[model_type]()
|
||||
result.offset = offset
|
||||
result.total = get_count(db, schema_type, filter)
|
||||
result.size = limit
|
||||
if result.total > result.offset:
|
||||
result.elements = get_elements(db, schema_type, offset, limit, filter)
|
||||
else:
|
||||
result.elements = []
|
||||
return result
|
||||
|
||||
|
||||
def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int:
|
||||
return db.scalar(select(func.count()).select_from(schema_type).where(filter))
|
||||
|
||||
|
||||
def get_elements(
|
||||
db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none
|
||||
) -> List[S]:
|
||||
return db.scalars(
|
||||
select(schema_type).where(filter).offset(offset).limit(limit)
|
||||
).all()
|
||||
|
||||
|
||||
def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]:
|
||||
return db.scalars(
|
||||
select(schema_type).where(schema_type.id == element_id).limit(1)
|
||||
).first()
|
||||
|
||||
|
||||
def delete_element(db: Session, schema_type: Type[S], element_id: int):
|
||||
element = get_element(db, schema_type, element_id)
|
||||
db.delete(element)
|
||||
|
||||
|
||||
def insert_element(db: Session, value: S) -> S:
|
||||
db.add(value)
|
||||
db.flush()
|
||||
db.refresh(value)
|
||||
return value
|
||||
|
||||
|
||||
def _load_topic_cache() -> dict:
|
||||
"""Loads the topic hierarchy cache from a JSON file."""
|
||||
import os
|
||||
|
||||
try:
|
||||
cache_path = "/data/" + topic_cache_filename
|
||||
if not os.path.exists(cache_path):
|
||||
@@ -103,56 +41,42 @@ def _load_topic_cache() -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict:
|
||||
async def build_topic_cache(save_json: bool = True) -> dict:
|
||||
"""
|
||||
Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task).
|
||||
|
||||
Arguments:
|
||||
page_size (int): Number of topics to fetch per request (default: 200)
|
||||
save_json (bool): Whether to save the cache as a JSON file (default: True)
|
||||
|
||||
Returns:
|
||||
taxonomy_cache (dict): The topic hierarchy dictionary.
|
||||
"""
|
||||
output_filename: str = "topic_hierarchy_cache.json"
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
taxonomy_cache = {}
|
||||
offset = 0
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
while True:
|
||||
payload = {"query": {"match_all": {}}, "from": offset, "size": page_size}
|
||||
response = client.post(
|
||||
config.settings.elasticsearch_url + "/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="openalex-topics",
|
||||
query={"match_all": {}},
|
||||
source=["display_name", "name", "id", "subfield", "field", "domain"],
|
||||
cluster="nes",
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name")
|
||||
if not topic_name:
|
||||
continue
|
||||
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
taxonomy_cache[topic_name] = {
|
||||
"topic_id": source.get("id") or hit.get("_id", ""),
|
||||
"subfield": source.get("subfield", {}).get("display_name", ""),
|
||||
"field": source.get("field", {}).get("display_name", ""),
|
||||
"domain": source.get("domain", {}).get("display_name", ""),
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.error("Failed to scan topics from Elasticsearch: %s", exc)
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name")
|
||||
if not topic_name:
|
||||
continue
|
||||
|
||||
taxonomy_cache[topic_name] = {
|
||||
"topic_id": source.get("id") or hit.get("_id", ""),
|
||||
"subfield": source.get("subfield", {}).get("display_name", ""),
|
||||
"field": source.get("field", {}).get("display_name", ""),
|
||||
"domain": source.get("domain", {}).get("display_name", ""),
|
||||
}
|
||||
|
||||
offset += len(hits)
|
||||
logger.info("Processed %s topics total", len(taxonomy_cache))
|
||||
logger.info("Processed %s topics total", len(taxonomy_cache))
|
||||
|
||||
if save_json:
|
||||
data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True)
|
||||
@@ -231,6 +155,7 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
def get_topic_hierarchy() -> dict:
|
||||
"""
|
||||
Builds and returns a hierarchical tree structure of topics:
|
||||
@@ -238,28 +163,25 @@ def get_topic_hierarchy() -> dict:
|
||||
"""
|
||||
flat_cache = _load_topic_cache()
|
||||
tree = {}
|
||||
|
||||
|
||||
for topic_name, info in flat_cache.items():
|
||||
domain = info.get("domain") or "Unbekannter Bereich"
|
||||
field = info.get("field") or "Unbekanntes Feld"
|
||||
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
|
||||
topic_id = info.get("topic_id", "")
|
||||
|
||||
|
||||
# Clean topic ID to just be the trailing ID or keep full URL
|
||||
# For querying, display name is used in persons search, but ID is useful
|
||||
|
||||
|
||||
if domain not in tree:
|
||||
tree[domain] = {}
|
||||
if field not in tree[domain]:
|
||||
tree[domain][field] = {}
|
||||
if subfield not in tree[domain][field]:
|
||||
tree[domain][field][subfield] = []
|
||||
|
||||
tree[domain][field][subfield].append({
|
||||
"id": topic_id,
|
||||
"name": topic_name
|
||||
})
|
||||
|
||||
|
||||
tree[domain][field][subfield].append({"id": topic_id, "name": topic_name})
|
||||
|
||||
formatted_domains = []
|
||||
for d_name, d_fields in tree.items():
|
||||
formatted_fields = []
|
||||
@@ -267,20 +189,11 @@ def get_topic_hierarchy() -> dict:
|
||||
formatted_subfields = []
|
||||
for sf_name, sf_topics in f_subfields.items():
|
||||
sf_topics.sort(key=lambda x: x["name"])
|
||||
formatted_subfields.append({
|
||||
"name": sf_name,
|
||||
"topics": sf_topics
|
||||
})
|
||||
formatted_subfields.append({"name": sf_name, "topics": sf_topics})
|
||||
formatted_subfields.sort(key=lambda x: x["name"])
|
||||
formatted_fields.append({
|
||||
"name": f_name,
|
||||
"subfields": formatted_subfields
|
||||
})
|
||||
formatted_fields.append({"name": f_name, "subfields": formatted_subfields})
|
||||
formatted_fields.sort(key=lambda x: x["name"])
|
||||
formatted_domains.append({
|
||||
"name": d_name,
|
||||
"fields": formatted_fields
|
||||
})
|
||||
formatted_domains.append({"name": d_name, "fields": formatted_fields})
|
||||
formatted_domains.sort(key=lambda x: x["name"])
|
||||
|
||||
|
||||
return {"domains": formatted_domains}
|
||||
|
||||
@@ -6,6 +6,7 @@ for fastapi that loads the service and the
|
||||
webapp.
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager, contextmanager
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
@@ -14,23 +15,36 @@ from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.company_connections.service import router as company_connections_router
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
ElasticsearchException,
|
||||
MissingApiKeyError,
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
)
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.router import router as university_ranking_router
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.patents.service import router as patents_service_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
from inse.auth.service import create_predefined_accounts
|
||||
from . import config
|
||||
from .account.service import router as account_router
|
||||
|
||||
from .service import router as service_router
|
||||
from inse.patents.org.service import router as org_patents_router
|
||||
from inse.patents.service import (
|
||||
@@ -45,12 +59,24 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
settings = config.get_settings()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("Starting up the application...")
|
||||
create_db_and_tables()
|
||||
with contextmanager(get_session)() as session:
|
||||
create_predefined_accounts(session, "../data/predefined_accounts.json")
|
||||
yield
|
||||
logger.info("Shutting down the application...")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
redoc_url=None,
|
||||
title="Innovation Search Engine API",
|
||||
description="API for the Innovation Search Engine (INSE) application.",
|
||||
version="0.1.0",
|
||||
servers=settings.servers,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(institution_patents_router)
|
||||
@@ -62,12 +88,17 @@ app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
app.include_router(news_service_router)
|
||||
app.include_router(company_connections_router)
|
||||
app.include_router(service_router)
|
||||
app.include_router(account_router)
|
||||
app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
app.include_router(patents_all_router)
|
||||
app.include_router(keywords_service_router)
|
||||
|
||||
app.include_router(service_router)
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
@@ -83,11 +114,37 @@ app.add_middleware(
|
||||
)
|
||||
|
||||
|
||||
# exception handlers
|
||||
|
||||
@app.exception_handler(NotFoundException)
|
||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(ElasticsearchException)
|
||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
||||
|
||||
|
||||
@app.exception_handler(MissingApiKeyError)
|
||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||
logger.error("Configuration error: %s", str(exc))
|
||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
||||
|
||||
|
||||
@app.exception_handler(UpstreamAPIException)
|
||||
async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException):
|
||||
logger.error("Upstream API error: %s", str(exc))
|
||||
return JSONResponse(status_code=exc.status_code, content={"message": exc.message})
|
||||
|
||||
|
||||
@app.exception_handler(BadRequestException)
|
||||
async def handle_bad_request(request: Request, exc: BadRequestException):
|
||||
logger.error("Bad Request: %s", str(exc))
|
||||
return JSONResponse(status_code=400, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
async def redirect(_, __):
|
||||
return RedirectResponse(url="/inse-webapp/")
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
# middleware/etag_cache.py
|
||||
import hashlib, json, time
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
|
||||
class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, ttl: int = 60):
|
||||
super().__init__(app)
|
||||
@@ -14,10 +18,19 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
# Include query params and relevant headers in the key
|
||||
return f"{request.url.path}?{request.url.query}"
|
||||
|
||||
def _content_type(self, response: Response) -> str | None:
|
||||
return response.headers.get("content-type")
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if request.method != "GET":
|
||||
return await call_next(request)
|
||||
|
||||
if request.url.path.startswith(("/api/auth", "/api/accounts")):
|
||||
return await call_next(request)
|
||||
|
||||
if request.headers.get("authorization"):
|
||||
return await call_next(request)
|
||||
|
||||
key = self._cache_key(request)
|
||||
entry = self.cache.get(key)
|
||||
client_etag = request.headers.get("if-none-match")
|
||||
@@ -25,34 +38,37 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
# Cache hit + not expired
|
||||
if entry and time.time() < entry["expires"]:
|
||||
if client_etag == entry["etag"]:
|
||||
return Response(
|
||||
status_code=entry["status_code"],
|
||||
headers={"ETag": entry["etag"]},
|
||||
)
|
||||
headers = {"ETag": entry["etag"]}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
# Client has stale ETag - return fresh cached body
|
||||
headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
||||
if entry.get("content_type"):
|
||||
headers["Content-Type"] = entry["content_type"]
|
||||
return Response(
|
||||
content=entry["body"],
|
||||
status_code=entry["status_code"],
|
||||
media_type="application/json",
|
||||
headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
# Cache miss or expired → hit the actual route
|
||||
response = await call_next(request)
|
||||
body = b"".join([chunk async for chunk in response.body_iterator])
|
||||
etag = f'"{hashlib.md5(body).hexdigest()}"'
|
||||
content_type = self._content_type(response)
|
||||
|
||||
if response.status_code < 400:
|
||||
self.cache[key] = {
|
||||
"body": body,
|
||||
"etag": etag,
|
||||
"expires": time.time() + self.ttl,
|
||||
"status_code": response.status_code,
|
||||
}
|
||||
self.cache[key] = {
|
||||
"body": body,
|
||||
"etag": etag,
|
||||
"expires": time.time() + self.ttl,
|
||||
"content_type": content_type,
|
||||
}
|
||||
headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
return Response(
|
||||
content=body,
|
||||
status_code=response.status_code,
|
||||
media_type="application/json",
|
||||
headers={"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
|
||||
)
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
@@ -8,41 +8,20 @@ our api using pydantic.
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import ConfigDict
|
||||
from pydantic import Field
|
||||
from typing import List
|
||||
from typing import TypeVar
|
||||
from typing import Generic
|
||||
from typing import Optional
|
||||
|
||||
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
|
||||
class Entity(BaseModel):
|
||||
id: int = Field(description="The id of the entity.")
|
||||
|
||||
|
||||
class Item(Entity):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
name: str = Field(description="The name of the item.")
|
||||
description: str = Field(description="The description of the item.")
|
||||
|
||||
|
||||
class ItemCreate(BaseModel):
|
||||
name: str = Field(description="The name of the item.")
|
||||
description: str = Field(description="The description of the item.")
|
||||
|
||||
|
||||
class Page(BaseModel, Generic[T]):
|
||||
elements: List[T] = Field(default=[], description="The elements of the page.")
|
||||
offset: int = Field(default=0, description="The page offset in elements.")
|
||||
total: int = Field(default=0, description="The total number of elements.")
|
||||
offset: int = Field(default=0, description="The page number. (0-based)")
|
||||
size: int = Field(default=20, description="The page size in elements.")
|
||||
|
||||
|
||||
class ItemPage(Page[Item]):
|
||||
pass
|
||||
total: int = Field(default=0, description="The total number of elements.")
|
||||
|
||||
|
||||
class ESCluster(StrEnum):
|
||||
|
||||
@@ -4,33 +4,69 @@
|
||||
Business logic for the "aktuell" news index on the INSE cluster.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
|
||||
from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOPIC_LIMIT = 4
|
||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
|
||||
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
|
||||
|
||||
async def get_news_page(
|
||||
page: int,
|
||||
page_size: int,
|
||||
sort_order: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
relevance_values: list | None = None,
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
response = _run_search(
|
||||
query={"match_all": {}},
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}}
|
||||
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
return await _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
async def search_news(
|
||||
query_text: str,
|
||||
page: int,
|
||||
page_size: int,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
relevance_values: list | None = None,
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
highlight = {
|
||||
@@ -40,8 +76,16 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
"encoder": "html",
|
||||
}
|
||||
|
||||
response = _run_search(
|
||||
query={"match": {"full_content": query_text}},
|
||||
# Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
exact_query = {
|
||||
"bool": {
|
||||
"must": [{"match": {"full_content": query_text}}],
|
||||
"filter": clauses,
|
||||
}
|
||||
}
|
||||
response = await _run_search(
|
||||
query=exact_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
@@ -49,9 +93,20 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
def get_news_by_author(
|
||||
if _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = await _exact_match_ids(exact_query)
|
||||
news_page.results.extend(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, extra_filters=clauses
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
async def get_news_by_author(
|
||||
author_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
@@ -59,11 +114,11 @@ def get_news_by_author(
|
||||
query_text: str | None = None,
|
||||
) -> NewsPage:
|
||||
|
||||
author_name = get_author_name_by_id(author_id)
|
||||
author_name = await get_author_name_by_id(author_id)
|
||||
if not author_name:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
news_ids = _find_news_ids_for_author(author_name)
|
||||
news_ids = await _find_news_ids_for_author(author_name)
|
||||
if not news_ids:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
@@ -74,7 +129,7 @@ def get_news_by_author(
|
||||
]
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=es_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
@@ -82,13 +137,71 @@ def get_news_by_author(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
if query_text and _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = await _exact_match_ids(es_query)
|
||||
news_page.results.extend(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
async def _filter_clauses(
|
||||
year_from: int | None,
|
||||
year_to: int | None,
|
||||
relevance_values: list | None,
|
||||
) -> list:
|
||||
clauses = []
|
||||
|
||||
if year_from is not None or year_to is not None:
|
||||
date_range = {}
|
||||
if year_from is not None:
|
||||
date_range["gte"] = year_from
|
||||
if year_to is not None:
|
||||
date_range["lte"] = year_to
|
||||
clauses.append({"range": {"date_year": date_range}})
|
||||
|
||||
relevant_ids = await _relevance_news_ids(relevance_values)
|
||||
if relevant_ids is not None:
|
||||
clauses.append({"ids": {"values": relevant_ids}})
|
||||
|
||||
return clauses
|
||||
|
||||
|
||||
async def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
selected = set(relevance_values or [])
|
||||
|
||||
if not selected or {"relevant", "not_relevant"} <= selected:
|
||||
return None
|
||||
|
||||
relevant_value = 1 if "relevant" in selected else 0
|
||||
|
||||
news_ids = []
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"relevant": relevant_value}},
|
||||
source=["news_id"],
|
||||
cluster="inse",
|
||||
):
|
||||
news_id = hit.get("_source", {}).get("news_id")
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
except Exception:
|
||||
logger.exception("Relevanz-IDs aus aktuell_postproc konnten nicht geladen werden.")
|
||||
return []
|
||||
|
||||
return news_ids
|
||||
|
||||
|
||||
async def _find_news_ids_for_author(author_name: str) -> list:
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"authors.keyword": author_name}},
|
||||
source=["news_id"],
|
||||
@@ -112,24 +225,29 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
|
||||
return NewsPage(total=0, page=page, page_size=page_size, results=[])
|
||||
|
||||
|
||||
def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
try:
|
||||
response = elasticsearch.get(
|
||||
response = await elasticsearch.get(
|
||||
index="aktuell",
|
||||
doc_id=news_id,
|
||||
source=["date", "maintitle", "author", "url", "full_content"],
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors = _get_postproc_labels(news_id)
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
cached_keywords,
|
||||
source.get("maintitle"),
|
||||
source.get("full_content"),
|
||||
)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
@@ -139,17 +257,131 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
url=source.get("url"),
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=_build_mentioned_persons(authors),
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
)
|
||||
|
||||
|
||||
def _build_mentioned_persons(author_names: list) -> list:
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
cached_keywords: list,
|
||||
maintitle: str | None,
|
||||
full_content: str | None,
|
||||
) -> list:
|
||||
if cached_keywords:
|
||||
return cached_keywords
|
||||
|
||||
text = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
raw = llm.call(
|
||||
system_prompt=KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt=f"Artikel:\n{text}",
|
||||
temperature=0.3,
|
||||
)
|
||||
keywords = _parse_keywords(raw)
|
||||
|
||||
if keywords:
|
||||
await _store_keywords(news_id, postproc_id, keywords)
|
||||
|
||||
return keywords
|
||||
|
||||
|
||||
def _parse_keywords(raw: str) -> list:
|
||||
raw = (raw or "").strip()
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
candidates = parsed if isinstance(parsed, list) else []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
term = str(item).strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
try:
|
||||
if postproc_id:
|
||||
await elasticsearch.update(
|
||||
index="aktuell_postproc",
|
||||
doc_id=postproc_id,
|
||||
doc={"keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
else:
|
||||
await elasticsearch.index_doc(
|
||||
index="aktuell_postproc",
|
||||
doc_id=news_id,
|
||||
document={"news_id": news_id, "keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
query_vector = get_model().encode(query_text).tolist()
|
||||
except Exception:
|
||||
logger.exception("Failed to encode text for topic vector search.")
|
||||
return []
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body={
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": k,
|
||||
"num_candidates": TOPIC_NUM_CANDIDATES,
|
||||
"similarity": TOPIC_SIMILARITY,
|
||||
},
|
||||
"_source": source_fields,
|
||||
"size": k,
|
||||
},
|
||||
cluster="nes",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Topic vector search failed.")
|
||||
return []
|
||||
|
||||
return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
|
||||
|
||||
|
||||
async def _build_mentioned_persons(author_names: list) -> list:
|
||||
|
||||
ude_persons = []
|
||||
other_persons = []
|
||||
|
||||
for name in author_names:
|
||||
match = find_ude_author_by_name(name)
|
||||
match = await find_ude_author_by_name(name)
|
||||
if match:
|
||||
ude_persons.append(
|
||||
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
|
||||
@@ -160,33 +392,35 @@ def _build_mentioned_persons(author_names: list) -> list:
|
||||
return ude_persons + other_persons
|
||||
|
||||
|
||||
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
|
||||
async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"news_id.keyword": news_id}},
|
||||
source=["relevant", "authors"],
|
||||
source=["relevant", "authors", "keywords"],
|
||||
size=1,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Postproc-Lookup for {news_id} failed.")
|
||||
return None, []
|
||||
return None, [], [], None
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None, []
|
||||
return None, [], [], None
|
||||
|
||||
postproc_source = hits[0].get("_source", {})
|
||||
hit = hits[0]
|
||||
postproc_source = hit.get("_source", {})
|
||||
relevant = bool(postproc_source.get("relevant", 0))
|
||||
authors = postproc_source.get("authors") or []
|
||||
keywords = postproc_source.get("keywords") or []
|
||||
|
||||
return relevant, authors
|
||||
return relevant, authors, keywords, hit.get("_id")
|
||||
|
||||
|
||||
def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
try:
|
||||
return elasticsearch.search(
|
||||
return await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query=query,
|
||||
source=source,
|
||||
@@ -197,15 +431,12 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig
|
||||
highlight=highlight,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
hits_section = response.get("hits", {})
|
||||
total = hits_section.get("total", {}).get("value", 0)
|
||||
hits = hits_section.get("hits", [])
|
||||
@@ -216,7 +447,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
|
||||
relevance_map = _get_relevance_map(news_ids)
|
||||
relevance_map = await _get_relevance_map(news_ids)
|
||||
|
||||
articles = []
|
||||
for hit in hits:
|
||||
@@ -232,12 +463,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
)
|
||||
|
||||
|
||||
def _get_relevance_map(news_ids: list) -> dict:
|
||||
async def _get_relevance_map(news_ids: list) -> dict:
|
||||
if not news_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"terms": {"news_id.keyword": news_ids}},
|
||||
source=["news_id", "relevant"],
|
||||
@@ -262,7 +493,11 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
snippet = fragments[0] if fragments else None
|
||||
|
||||
if fragments:
|
||||
snippet = fragments[0]
|
||||
else:
|
||||
snippet = _make_preview(source)
|
||||
|
||||
return NewsArticle(
|
||||
id=hit.get("_id"),
|
||||
@@ -272,3 +507,104 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
url=source.get("url"),
|
||||
snippet=snippet,
|
||||
)
|
||||
|
||||
|
||||
def _make_preview(source: dict) -> str | None:
|
||||
text = source.get("intro_content") or source.get("full_content")
|
||||
|
||||
if not text:
|
||||
return None
|
||||
|
||||
words = text.split()
|
||||
|
||||
PREVIEW_WORD_COUNT = 10
|
||||
preview = " ".join(words[:PREVIEW_WORD_COUNT])
|
||||
if len(words) > PREVIEW_WORD_COUNT:
|
||||
preview = preview + " …"
|
||||
return preview
|
||||
|
||||
|
||||
def _is_last_page(page: int, page_size: int, total: int) -> bool:
|
||||
return page * page_size >= total
|
||||
|
||||
|
||||
async def _exact_match_ids(query: dict) -> list:
|
||||
try:
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=[],
|
||||
size=EXACT_ID_CAP,
|
||||
offset=0,
|
||||
sort=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to collect exact-match ids for dedup.")
|
||||
return []
|
||||
|
||||
return [
|
||||
hit.get("_id")
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if hit.get("_id")
|
||||
]
|
||||
|
||||
|
||||
async def _related_articles(
|
||||
query_text: str,
|
||||
exclude_ids: list | None = None,
|
||||
filter_news_ids: list | None = None,
|
||||
extra_filters: list | None = None,
|
||||
k: int = RELATED_BLOCK_SIZE,
|
||||
) -> list:
|
||||
related_terms = await _related_search_terms(query_text)
|
||||
if not related_terms:
|
||||
return []
|
||||
|
||||
bool_query = {
|
||||
"should": [{"match": {"full_content": term}} for term in related_terms],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
if exclude_ids:
|
||||
bool_query["must_not"] = [{"ids": {"values": exclude_ids}}]
|
||||
if filter_news_ids is not None:
|
||||
bool_query["filter"] = [{"ids": {"values": filter_news_ids}}]
|
||||
if extra_filters:
|
||||
bool_query.setdefault("filter", []).extend(extra_filters)
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query={"bool": bool_query},
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=k,
|
||||
offset=0,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Related-articles search failed.")
|
||||
return []
|
||||
|
||||
articles = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
article = _parse_hit(hit)
|
||||
article.related = True
|
||||
articles.append(article)
|
||||
|
||||
relevance_map = await _get_relevance_map([article.id for article in articles])
|
||||
for article in articles:
|
||||
article.relevant = relevance_map.get(article.id)
|
||||
|
||||
return articles
|
||||
|
||||
|
||||
async def _related_search_terms(query_text: str) -> list:
|
||||
topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
|
||||
|
||||
seen = {query_text.lower()}
|
||||
terms = []
|
||||
for topic in topics:
|
||||
for term in [topic.get("display_name"), *(topic.get("keywords") or [])]:
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
terms.append(term)
|
||||
|
||||
return terms
|
||||
|
||||
@@ -14,6 +14,7 @@ class NewsArticle(BaseModel):
|
||||
url: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
snippet: Optional[str] = None
|
||||
related: Optional[bool] = None
|
||||
|
||||
|
||||
class MentionedPerson(BaseModel):
|
||||
@@ -26,6 +27,8 @@ class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
topics: List[str] = []
|
||||
keywords: List[str] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
|
||||
@@ -16,6 +16,15 @@ from .model import NewsArticleDetail, NewsPage
|
||||
|
||||
router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
|
||||
ALLOWED_RELEVANCE_VALUES = {"relevant", "not_relevant"}
|
||||
|
||||
|
||||
def _parse_relevance(relevance: str | None) -> list:
|
||||
if not relevance:
|
||||
return []
|
||||
values = [entry.strip() for entry in relevance.split(",")]
|
||||
return [value for value in values if value in ALLOWED_RELEVANCE_VALUES]
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
@@ -25,7 +34,7 @@ router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
summary="Returns a page of news articles, newest first.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def list_news(
|
||||
async def list_news(
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
@@ -35,8 +44,24 @@ def list_news(
|
||||
sort_order: Annotated[
|
||||
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
|
||||
] = "desc",
|
||||
relevance: Annotated[
|
||||
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||
] = None,
|
||||
year_from: Annotated[
|
||||
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_page(page, page_size, sort_order)
|
||||
return await logic.get_news_page(
|
||||
page,
|
||||
page_size,
|
||||
sort_order,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
relevance_values=_parse_relevance(relevance),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -47,7 +72,7 @@ def list_news(
|
||||
summary="Searches news articles by full text (full_content).",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def search_news(
|
||||
async def search_news(
|
||||
query: Annotated[
|
||||
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
|
||||
],
|
||||
@@ -57,8 +82,24 @@ def search_news(
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||
] = 10,
|
||||
relevance: Annotated[
|
||||
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||
] = None,
|
||||
year_from: Annotated[
|
||||
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.search_news(query, page, page_size)
|
||||
return await logic.search_news(
|
||||
query,
|
||||
page,
|
||||
page_size,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
relevance_values=_parse_relevance(relevance),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -69,7 +110,7 @@ def search_news(
|
||||
summary="Returns news articles in which the given person is mentioned.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_author(
|
||||
async def get_news_by_author(
|
||||
author_id: Annotated[
|
||||
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
|
||||
],
|
||||
@@ -86,7 +127,7 @@ def get_news_by_author(
|
||||
str | None, Query(description="Optional search term, matched against title/author.")
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
return await logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -97,9 +138,9 @@ def get_news_by_author(
|
||||
summary="Returns a single news article including its full content.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_id(
|
||||
async def get_news_by_id(
|
||||
news_id: Annotated[
|
||||
str, Path(description="The unique id of the news article (Elasticsearch _id).")
|
||||
],
|
||||
):
|
||||
return logic.get_news_by_id(news_id)
|
||||
return await logic.get_news_by_id(news_id)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Organization management API."""
|
||||
@@ -0,0 +1,30 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
other_inst_id: Optional[str] = None
|
||||
deleted: bool
|
||||
member_count: int
|
||||
|
||||
|
||||
class OrganizationPage(BaseModel):
|
||||
items: List[OrganizationProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class CreateOrganizationRequest(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
other_inst_id: Optional[str] = None
|
||||
|
||||
|
||||
class UpdateOrganizationRequest(BaseModel):
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
other_inst_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
@@ -0,0 +1,81 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from . import service
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
|
||||
|
||||
|
||||
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
|
||||
async def get_organizations(
|
||||
page: int = Query(default=0, ge=0),
|
||||
page_size: int = Query(default=25, ge=1, le=100),
|
||||
offset: Optional[int] = Query(default=None, ge=0),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationPage:
|
||||
return service.get_organizations(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
operation_id="createOrganisation",
|
||||
response_model=OrganizationProfile,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_organization(
|
||||
payload: CreateOrganizationRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationProfile:
|
||||
return service.create_organization(session, access_token, payload)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{organization_id}",
|
||||
operation_id="updateOrganisation",
|
||||
response_model=OrganizationProfile,
|
||||
)
|
||||
async def update_organization(
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationProfile:
|
||||
return service.update_organization(
|
||||
session, access_token, organization_id, payload
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{organization_id}",
|
||||
operation_id="deleteOrganisation",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_organization(
|
||||
organization_id: uuid.UUID,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_organization(session, access_token, organization_id)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,203 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
||||
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
def _require_super_admin(access_token: AccessToken) -> None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only superadmins can manage organizations.",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_name(name: str) -> str:
|
||||
normalized_name = name.strip()
|
||||
if not normalized_name:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Organization name must not be empty.",
|
||||
)
|
||||
return normalized_name
|
||||
|
||||
|
||||
def _ensure_name_available(
|
||||
session: Session,
|
||||
name: str,
|
||||
excluded_organization_id: Optional[uuid.UUID] = None,
|
||||
) -> None:
|
||||
statement = select(Organization).where(
|
||||
func.lower(Organization.name) == name.lower()
|
||||
)
|
||||
if excluded_organization_id is not None:
|
||||
statement = statement.where(Organization.id != excluded_organization_id)
|
||||
|
||||
if session.exec(statement).first() is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="An organization with this name already exists.",
|
||||
)
|
||||
|
||||
|
||||
def _get_organization_or_404(
|
||||
session: Session, organization_id: uuid.UUID
|
||||
) -> Organization:
|
||||
organization = session.get(Organization, organization_id)
|
||||
if organization is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
return organization
|
||||
|
||||
|
||||
def _member_counts(
|
||||
session: Session, organization_ids: list[uuid.UUID]
|
||||
) -> dict[uuid.UUID, int]:
|
||||
if not organization_ids:
|
||||
return {}
|
||||
|
||||
rows = session.exec(
|
||||
select(Account.organization_id, func.count(Account.id))
|
||||
.where(
|
||||
Account.organization_id.in_(organization_ids),
|
||||
Account.deleted == False, # noqa: E712
|
||||
Account.activated == True, # noqa: E712
|
||||
)
|
||||
.group_by(Account.organization_id)
|
||||
).all()
|
||||
return {organization_id: count for organization_id, count in rows}
|
||||
|
||||
|
||||
def _to_profile(
|
||||
organization: Organization, member_count: int
|
||||
) -> OrganizationProfile:
|
||||
return OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
other_inst_id=organization.openalex_institution_id,
|
||||
deleted=organization.deleted,
|
||||
member_count=member_count,
|
||||
)
|
||||
|
||||
|
||||
def _deactivate_organization_accounts(
|
||||
session: Session, organization_id: uuid.UUID
|
||||
) -> None:
|
||||
accounts = session.exec(
|
||||
select(Account).where(
|
||||
Account.organization_id == organization_id,
|
||||
Account.activated == True, # noqa: E712
|
||||
)
|
||||
).all()
|
||||
for account in accounts:
|
||||
account.activated = False
|
||||
account.epoch += 1
|
||||
session.add(account)
|
||||
|
||||
|
||||
def get_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
) -> OrganizationPage:
|
||||
statement = select(Organization)
|
||||
count_statement = select(func.count()).select_from(Organization)
|
||||
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
scope_filter = Organization.id == access_token.effective_organization_id
|
||||
statement = statement.where(scope_filter)
|
||||
count_statement = count_statement.where(scope_filter)
|
||||
|
||||
total = session.exec(count_statement).one()
|
||||
effective_offset = offset if offset is not None else page * page_size
|
||||
organizations = session.exec(
|
||||
statement.order_by(Organization.name)
|
||||
.offset(effective_offset)
|
||||
.limit(page_size)
|
||||
).all()
|
||||
organization_ids = [organization.id for organization in organizations]
|
||||
counts = _member_counts(session, organization_ids)
|
||||
|
||||
return OrganizationPage(
|
||||
items=[
|
||||
_to_profile(organization, counts.get(organization.id, 0))
|
||||
for organization in organizations
|
||||
],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def create_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
payload: CreateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name)
|
||||
|
||||
organization = Organization(
|
||||
name=name,
|
||||
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
|
||||
)
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
return _to_profile(organization, 0)
|
||||
|
||||
|
||||
def update_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
|
||||
if payload.name is not None:
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name, organization.id)
|
||||
organization.name = name
|
||||
if payload.other_inst_id is not None:
|
||||
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
||||
if payload.deleted is not None:
|
||||
if payload.deleted and not organization.deleted:
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = payload.deleted
|
||||
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
counts = _member_counts(session, [organization.id])
|
||||
return _to_profile(organization, counts.get(organization.id, 0))
|
||||
|
||||
|
||||
def delete_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
organization_id: uuid.UUID,
|
||||
) -> None:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
if not organization.deleted:
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = True
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
@@ -0,0 +1,241 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.auth.model import Account, Organization, UserRole
|
||||
from inse.organization_management import service
|
||||
from inse.organization_management.model import (
|
||||
CreateOrganizationRequest,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as database_session:
|
||||
yield database_session
|
||||
|
||||
|
||||
def token(role: UserRole, organization_id):
|
||||
return SimpleNamespace(
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
)
|
||||
|
||||
|
||||
def test_superadmin_lists_all_organizations_with_active_member_count(session):
|
||||
first = Organization(name="Alpha")
|
||||
second = Organization(name="Beta", deleted=True)
|
||||
session.add(first)
|
||||
session.add(second)
|
||||
session.flush()
|
||||
session.add(
|
||||
Account(
|
||||
email="active@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=first.id,
|
||||
)
|
||||
)
|
||||
session.add(
|
||||
Account(
|
||||
email="deleted@example.org",
|
||||
name="Deleted",
|
||||
password_hash="hash",
|
||||
organization_id=first.id,
|
||||
deleted=True,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
|
||||
result = service.get_organizations(
|
||||
session, token(UserRole.SUPER_ADMIN, first.id), page=0, page_size=10
|
||||
)
|
||||
|
||||
assert result.total == 2
|
||||
assert [item.name for item in result.items] == ["Alpha", "Beta"]
|
||||
assert result.items[0].member_count == 1
|
||||
assert result.items[1].deleted is True
|
||||
|
||||
|
||||
def test_non_superadmin_only_sees_own_organization(session):
|
||||
own = Organization(name="Own")
|
||||
session.add(own)
|
||||
session.add(Organization(name="Other"))
|
||||
session.commit()
|
||||
|
||||
result = service.get_organizations(
|
||||
session, token(UserRole.USER, own.id), page=0, page_size=10
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].id == own.id
|
||||
|
||||
|
||||
def test_superadmin_can_create_update_and_soft_delete(session):
|
||||
scope = Organization(name="Scope")
|
||||
session.add(scope)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, scope.id)
|
||||
|
||||
created = service.create_organization(
|
||||
session,
|
||||
access_token,
|
||||
CreateOrganizationRequest(name=" New tenant ", other_inst_id="I123"),
|
||||
)
|
||||
assert created.name == "New tenant"
|
||||
assert created.other_inst_id == "I123"
|
||||
|
||||
updated = service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
created.id,
|
||||
UpdateOrganizationRequest(name="Renamed", other_inst_id=""),
|
||||
)
|
||||
assert updated.name == "Renamed"
|
||||
assert updated.other_inst_id is None
|
||||
|
||||
service.delete_organization(session, access_token, created.id)
|
||||
assert session.get(Organization, created.id).deleted is True
|
||||
|
||||
|
||||
def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||
organization = Organization(name="Organization to delete")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
active_account = Account(
|
||||
email="active-delete@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
epoch=3,
|
||||
)
|
||||
inactive_account = Account(
|
||||
email="inactive-delete@example.org",
|
||||
name="Inactive",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
activated=False,
|
||||
epoch=5,
|
||||
)
|
||||
session.add(active_account)
|
||||
session.add(inactive_account)
|
||||
session.commit()
|
||||
|
||||
service.delete_organization(
|
||||
session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
|
||||
)
|
||||
|
||||
session.refresh(active_account)
|
||||
session.refresh(inactive_account)
|
||||
assert active_account.activated is False
|
||||
assert active_account.epoch == 4
|
||||
assert inactive_account.activated is False
|
||||
assert inactive_account.epoch == 5
|
||||
|
||||
|
||||
def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||
organization = Organization(name="Organization to update")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
account = Account(
|
||||
email="active-update@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
|
||||
service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(deleted=True),
|
||||
)
|
||||
|
||||
session.refresh(account)
|
||||
assert account.activated is False
|
||||
assert account.epoch == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||
def test_only_superadmin_can_create_organizations(session, role):
|
||||
organization = Organization(name="Scope")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.create_organization(
|
||||
session,
|
||||
token(role, organization.id),
|
||||
CreateOrganizationRequest(name="Forbidden"),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_organization_name_must_not_be_blank(session):
|
||||
organization = Organization(name="Scope")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.create_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
CreateOrganizationRequest(name=" "),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 422
|
||||
|
||||
|
||||
def test_organization_name_is_unique_ignoring_case(session):
|
||||
existing = Organization(name="Unique tenant")
|
||||
session.add(existing)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, existing.id)
|
||||
|
||||
with pytest.raises(HTTPException) as create_error:
|
||||
service.create_organization(
|
||||
session,
|
||||
access_token,
|
||||
CreateOrganizationRequest(name=" unique TENANT "),
|
||||
)
|
||||
|
||||
assert create_error.value.status_code == 409
|
||||
|
||||
other = Organization(name="Other tenant")
|
||||
session.add(other)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as update_error:
|
||||
service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
other.id,
|
||||
UpdateOrganizationRequest(name="UNIQUE TENANT"),
|
||||
)
|
||||
|
||||
assert update_error.value.status_code == 409
|
||||
|
||||
|
||||
def test_organization_can_keep_its_name_when_updating(session):
|
||||
organization = Organization(name="Same tenant")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
result = service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(name="same TENANT"),
|
||||
)
|
||||
|
||||
assert result.name == "same TENANT"
|
||||
@@ -18,11 +18,6 @@ from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClien
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
|
||||
|
||||
|
||||
def normalize_patent_date(date_str: str) -> str:
|
||||
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
|
||||
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
@@ -88,67 +83,3 @@ async def get_all_patents(
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
|
||||
async def _search_by_id(
|
||||
client: AllPatentsSearchClient,
|
||||
patent_id: str,
|
||||
prefix: str | None = None,
|
||||
filling_date: str | None = None
|
||||
) -> list[model.PatentEntry]:
|
||||
|
||||
if prefix == "US":
|
||||
data = await client.search_uspto(client.uspto_detail_query(patent_id, filling_date=filling_date))
|
||||
return parse_uspto_hits(data)
|
||||
data = await client.search_epo(client.epo_detail_query(patent_id, filling_date=filling_date))
|
||||
return parse_epo_hits(data)
|
||||
|
||||
|
||||
async def _search_by_title(
|
||||
client: AllPatentsSearchClient,
|
||||
title: str,
|
||||
prefix: str | None = None,
|
||||
filling_date: str | None = None
|
||||
) -> list[model.PatentEntry]:
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
client.search_epo(client.epo_title_query(title, filling_date=filling_date)),
|
||||
client.search_uspto(client.uspto_title_query(title,filling_date=filling_date)),
|
||||
)
|
||||
return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
|
||||
|
||||
async def get_patent_by_id(
|
||||
patent_id: str,
|
||||
title: str | None = None,
|
||||
prefix: str | None = None,
|
||||
filling_date: str | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.PatentEntry:
|
||||
all_patents_client = AllPatentsSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
if filling_date:
|
||||
filling_date = normalize_patent_date(filling_date)
|
||||
try:
|
||||
patents = await _search_by_id(all_patents_client, patent_id,prefix=prefix, filling_date=filling_date)
|
||||
|
||||
if not patents:
|
||||
patents = await _search_by_title(all_patents_client, title,prefix=prefix,filling_date=filling_date) if title else []
|
||||
|
||||
if not patents:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail="Patent not found.",
|
||||
)
|
||||
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
await enrich_patents_classifications(patents[:1], ipc_search_client)
|
||||
return patents[0]
|
||||
@@ -33,13 +33,3 @@ async def get_all_patents(
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/patents/{patent_id}",
|
||||
operation_id="getPatentById",
|
||||
response_model=model.PatentEntry,
|
||||
summary="Get a single patent by its identifier.",
|
||||
)
|
||||
async def get_patent_by_id(patent_id: str, title: str | None = None, prefix: str | None = None, filling_date: str | None = None):
|
||||
return await logic.get_patent_by_id(patent_id, title=title, prefix=prefix, filling_date=filling_date)
|
||||
@@ -5,10 +5,11 @@
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
@@ -17,15 +18,9 @@ USPTO_INDEX = "uspto_patents_3.0"
|
||||
class AllPatentsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
@@ -261,15 +256,4 @@ class AllPatentsSearchClient:
|
||||
return await self._search(USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{index}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
|
||||
@@ -1,2 +1,325 @@
|
||||
"""Backward-compatible re-exports."""
|
||||
from inse.patents.search_client import * # noqa: F403
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
|
||||
"""
|
||||
from typing import Any
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
import httpx
|
||||
import asyncio
|
||||
from .. import config
|
||||
from .name_matching import search_name_variants
|
||||
|
||||
DEFAULT_SEARCH_SIZE = 100
|
||||
|
||||
def remove_year(patent_number: str) -> str:
|
||||
"""Remove a 4-digit year from the end of a patent number, if present."""
|
||||
if len(patent_number) > 4 and patent_number[-4:].isdigit():
|
||||
return patent_number[:-4]
|
||||
return patent_number
|
||||
|
||||
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||
"""Match a name field, including transliterated variants (Müller/Mueller)."""
|
||||
variants = search_name_variants(name)
|
||||
if len(variants) <= 1:
|
||||
return {"match_phrase": {field: variants[0] if variants else name}}
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match_phrase": {field: variant}} for variant in variants],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class PatentSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def epo_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO index: first AND last name in the SAME inventor entry."""
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors_name_nested.inventor", last_name),
|
||||
_match_name_field("inventors_name_nested.inventor", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": _match_name_field("inventors_name_nested.inventor", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"application_number",
|
||||
"application_filing_date",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
"""Search USPTO index: first AND last name in the SAME inventor entry."""
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors.name", last_name),
|
||||
_match_name_field("inventors.name", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": _match_name_field("inventors.name", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"application_number",
|
||||
"application_date",
|
||||
"application_type",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"cpc",
|
||||
"number_of_claims",
|
||||
"status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
print("Searching EPO with payload:", payload)
|
||||
return await self._search(ESIndex.EPO_INDEX, payload)
|
||||
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
print("Searching USPTO with payload:", payload)
|
||||
return await self._search(ESIndex.USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
|
||||
return response
|
||||
|
||||
async def get_by_id_or_title(
|
||||
self,
|
||||
patent_id: str,
|
||||
prefix: str,
|
||||
title: str,
|
||||
filling_date: str | None = None,
|
||||
size: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO and USPTO by ID; fall back to match on title if no hits.
|
||||
|
||||
Args:
|
||||
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
|
||||
prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO.
|
||||
Both indices are always queried for the ID lookup.
|
||||
title: Used only when the ID lookup returns zero hits.
|
||||
size: Maximum number of results to return.
|
||||
"""
|
||||
epo_id_payload = self._epo_query_by_id(patent_id, size)
|
||||
uspto_id_payload = self._uspto_query_by_id(patent_id, size)
|
||||
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
self.search_epo(epo_id_payload),
|
||||
self.search_uspto(uspto_id_payload),
|
||||
)
|
||||
|
||||
epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0)
|
||||
uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
if epo_hits > 0 or uspto_hits > 0:
|
||||
if prefix.upper() == "EP" and epo_hits > 0:
|
||||
return epo_result
|
||||
if prefix.upper() == "US" and uspto_hits > 0:
|
||||
return uspto_result
|
||||
return epo_result if epo_hits > 0 else uspto_result
|
||||
|
||||
if prefix.upper() == "US":
|
||||
payload = self._uspto_query_by_title(title, filling_date, size)
|
||||
return await self.search_uspto(payload)
|
||||
|
||||
payload = self._epo_query_by_title(title,filling_date, size)
|
||||
return await self.search_epo(payload)
|
||||
|
||||
#query builders
|
||||
|
||||
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
|
||||
raw_id = patent_id.upper().removeprefix("EP")
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"doc_number": raw_id}},
|
||||
{"term": {"doc_number": remove_year(raw_id)}},
|
||||
{"term": {"application_number": remove_year(raw_id)}},
|
||||
{"term": {"application_number": raw_id}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against publication_number; tries the ID as-is."""
|
||||
raw_id = patent_id.upper().removeprefix("US")
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"publication_number": raw_id}},
|
||||
{"term": {"publication_number": remove_year(raw_id)}},
|
||||
{"term": {"application_number": raw_id}},
|
||||
{"term": {"application_number": remove_year(raw_id)}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"],
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def _epo_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
|
||||
"""match fallback on title_en (and title_de as a should clause)."""
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": title}},
|
||||
{"match_phrase": {"title_de": title}},
|
||||
{"match_phrase": {"title_fr": title}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": query
|
||||
}
|
||||
|
||||
def _uspto_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
|
||||
"""match fallback on title."""
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [{"match_phrase": {"title": title}}],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
@@ -7,15 +7,16 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from . import model
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .ipc_lookup import IpcHierarchyKeys
|
||||
from .ipc_lookup import build_ipc_classification
|
||||
from .ipc_lookup import parse_ipc_symbol
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
IPC_INDEX = "ipc"
|
||||
|
||||
_LEVELS: tuple[tuple[str, str, str], ...] = (
|
||||
@@ -29,15 +30,9 @@ _LEVELS: tuple[tuple[str, str, str], ...] = (
|
||||
class IpcSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
@@ -136,15 +131,4 @@ class IpcSearchClient:
|
||||
return found
|
||||
|
||||
async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{IPC_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Backward-compatible re-exports."""
|
||||
from inse.patents.all.logic import get_all_patents, get_patent_by_id
|
||||
from inse.patents.all.logic import get_all_patents
|
||||
from inse.patents.authors.logic import get_patents_by_author_id
|
||||
from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents
|
||||
from inse.patents.institutions.logic import (
|
||||
@@ -7,11 +7,316 @@ from inse.patents.institutions.logic import (
|
||||
get_patents_by_institution_id,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_deduplicate_patents",
|
||||
"_filter_patents_by_institution",
|
||||
"get_all_patents",
|
||||
"get_patent_by_id",
|
||||
"get_patents_by_author_id",
|
||||
"get_patents_by_institution_id",
|
||||
]
|
||||
import logging
|
||||
import asyncio
|
||||
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from ..models.openalex.author import Author
|
||||
from . import model
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException
|
||||
from .elastic_search_client import PatentSearchClient
|
||||
from .elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from .ipc_search_client import IpcSearchClient
|
||||
from .ipc_lookup import extract_ipc_symbol
|
||||
from .name_matching import name_matches
|
||||
from datetime import datetime
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def normalize_patent_date(date_str: str) -> str:
|
||||
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
|
||||
|
||||
async def get_patent(
|
||||
patent_id: str,
|
||||
title: str,
|
||||
prefix: str,
|
||||
filling_date: str | None = None,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentEntry:
|
||||
search_client = client or PatentSearchClient()
|
||||
|
||||
if filling_date:
|
||||
filling_date = normalize_patent_date(filling_date)
|
||||
data = await search_client.get_by_id_or_title(
|
||||
patent_id=patent_id,
|
||||
prefix=prefix,
|
||||
title=title,
|
||||
filling_date=filling_date,
|
||||
)
|
||||
|
||||
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
|
||||
elements = parse(data)
|
||||
|
||||
if not elements:
|
||||
return None
|
||||
return elements[0]
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = await _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
|
||||
if not last_name:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
epo_data, uspto_data = await _search_both_indices(
|
||||
search_client, last_name, first_name
|
||||
)
|
||||
|
||||
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
|
||||
if first_name and last_name:
|
||||
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||
|
||||
all_patents = _deduplicate_patents(all_patents)
|
||||
|
||||
await _enrich_patents_classifications(all_patents, ipc_search_client)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(all_patents),
|
||||
patents=all_patents,
|
||||
)
|
||||
|
||||
|
||||
async def _search_both_indices(client, last_name, first_name):
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
|
||||
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
|
||||
)
|
||||
return epo_result, uspto_result
|
||||
|
||||
|
||||
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=src.get("title_en") or src.get("title_de"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=src.get("application_filing_date"),
|
||||
kind=src.get("kind"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=src.get("title"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=str(src.get("application_date")) if src.get("application_date") else None,
|
||||
application_type=src.get("application_type"),
|
||||
number_of_claims=src.get("number_of_claims"),
|
||||
status=src.get("status"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _to_classification_strings(value) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
items = value if isinstance(value, list) else [value]
|
||||
return [str(item).strip() for item in items if item and str(item).strip()]
|
||||
|
||||
|
||||
def _descriptions_for_raw_codes(
|
||||
raw_codes: list[str],
|
||||
resolved: dict[str, model.IpcClassification],
|
||||
) -> list[model.IpcClassification]:
|
||||
return [
|
||||
resolved[extract_ipc_symbol(raw)]
|
||||
for raw in raw_codes
|
||||
if extract_ipc_symbol(raw) in resolved
|
||||
]
|
||||
|
||||
|
||||
async def _enrich_patents_classifications(
|
||||
patents: list[model.PatentEntry],
|
||||
ipc_client: IpcSearchClient,
|
||||
) -> None:
|
||||
symbols = list(dict.fromkeys(
|
||||
extract_ipc_symbol(raw)
|
||||
for patent in patents
|
||||
for raw in (*patent.ipc, *patent.cpc)
|
||||
))
|
||||
if not symbols:
|
||||
return
|
||||
|
||||
try:
|
||||
resolved = await ipc_client.resolve_symbols(symbols)
|
||||
except MissingApiKeyError:
|
||||
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
|
||||
return
|
||||
except ElasticsearchException as exc:
|
||||
logger.warning("Classification enrichment failed: %s", exc)
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
|
||||
return
|
||||
|
||||
for patent in patents:
|
||||
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
|
||||
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[model.PatentEntry],
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> list[model.PatentEntry]:
|
||||
return [
|
||||
patent for patent in patents
|
||||
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
|
||||
]
|
||||
|
||||
|
||||
def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
deduplicated: list[model.PatentEntry] = []
|
||||
|
||||
for patent in patents:
|
||||
key = _patent_dedup_key(patent)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
deduplicated.append(patent)
|
||||
|
||||
return deduplicated
|
||||
|
||||
|
||||
def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||
stage = patent.kind or patent.application_type or ""
|
||||
return (
|
||||
patent.source,
|
||||
patent.patent_id,
|
||||
patent.publication_date or "",
|
||||
stage,
|
||||
)
|
||||
|
||||
|
||||
async def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = await person_logic.search_persons(author_id=short_id)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
def _extract_last_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[-1] if parts else None
|
||||
|
||||
|
||||
def _extract_first_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[0] if len(parts) > 1 else None
|
||||
|
||||
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.AllPatentsResponse:
|
||||
all_patents_client = AllPatentsSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
if source == "EPO":
|
||||
epo_data = await all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, size, search, sort_direction)
|
||||
)
|
||||
patents = _parse_epo_hits(epo_data)
|
||||
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
elif source == "USPTO":
|
||||
uspto_data = await all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, size, search, sort_direction)
|
||||
)
|
||||
patents = _parse_uspto_hits(uspto_data)
|
||||
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
else:
|
||||
half = size // 2
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, half, search, sort_direction)
|
||||
),
|
||||
all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, half, search, sort_direction)
|
||||
),
|
||||
)
|
||||
patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
total = (
|
||||
epo_data.get("hits", {}).get("total", {}).get("value", 0) +
|
||||
uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
)
|
||||
|
||||
|
||||
await _enrich_patents_classifications(patents, ipc_search_client)
|
||||
|
||||
return model.AllPatentsResponse(
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,70 @@
|
||||
"""Aggregates patent API routers."""
|
||||
from fastapi import APIRouter
|
||||
from . import logic
|
||||
from . import model
|
||||
from typing import Annotated, Optional
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
|
||||
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||
|
||||
from inse.patents.all.service import router as all_patents_router
|
||||
from inse.patents.authors.service import router as author_patents_router
|
||||
from inse.patents.institutions.service import router as institution_patents_router
|
||||
|
||||
router = author_patents_router
|
||||
patents_router = all_patents_router
|
||||
institution_patents_router = institution_patents_router
|
||||
|
||||
@router.get(
|
||||
"/{author_id}/patents",
|
||||
operation_id="getPatentsByAuthor",
|
||||
summary="Get patents matched to an author by name.",
|
||||
)
|
||||
async def get_patents_by_author(author_id: str) -> model.PatentsByAuthorResponse:
|
||||
return await logic.get_patents_by_author_id(author_id)
|
||||
|
||||
|
||||
@patents_router.get(
|
||||
"/patents/{identifier}",
|
||||
operation_id="getPatentByIdOrTitle",
|
||||
summary="Returns one publication by OpenAlex ID or DOI.",
|
||||
)
|
||||
async def get_patent_by_identifier(
|
||||
identifier: Annotated[str, Path(description="")],
|
||||
prefix: Annotated[
|
||||
Optional[str], Query(description="Application Prefix (EP or US)")
|
||||
] = "",
|
||||
title: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description="Do we want to fallback to title search if ID and DOI dont work?"
|
||||
),
|
||||
] = "",
|
||||
filling_date: Annotated[
|
||||
Optional[str], Query(description="Filling date in YYYY-MM-DD format")
|
||||
] = "",
|
||||
) -> model.PatentEntry | None:
|
||||
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title,filling_date=filling_date)
|
||||
|
||||
|
||||
@patents_router.get(
|
||||
"/patents",
|
||||
operation_id="getAllPatents",
|
||||
summary="Get all patents with pagination and search.",
|
||||
)
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
) -> model.AllPatentsResponse:
|
||||
return await logic.get_all_patents(
|
||||
page=page,
|
||||
size=size,
|
||||
search=search,
|
||||
source=source,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from inse.model import ESIndex
|
||||
from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from inse.patents.elastic_search_client import (
|
||||
DEFAULT_SEARCH_SIZE,
|
||||
PatentSearchClient,
|
||||
@@ -33,53 +30,17 @@ def test_uspto_index_is_3_0():
|
||||
assert ESIndex.EPO_INDEX == "epo_index_1.0"
|
||||
|
||||
|
||||
def test_epo_query_by_applicant_uses_applicants_name_field():
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
payload = client.epo_query_by_applicant(
|
||||
["University of Duisburg-Essen", "Universität Duisburg-Essen"]
|
||||
)
|
||||
|
||||
assert payload["size"] == DEFAULT_SEARCH_SIZE
|
||||
assert "applicants_name" in str(payload["query"])
|
||||
assert payload["query"]["bool"]["minimum_should_match"] == 1
|
||||
|
||||
|
||||
def test_uspto_query_by_assignee_uses_assignees_orgs_field():
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
payload = client.uspto_query_by_assignee(["Harvard University"])
|
||||
|
||||
assert "assignees_orgs" in str(payload["query"])
|
||||
|
||||
|
||||
def test_detail_and_title_queries_skip_empty_date_filters():
|
||||
client = AllPatentsSearchClient(api_key="test-key")
|
||||
|
||||
epo_payload = client.epo_title_query("method for generating and using a map")
|
||||
uspto_payload = client.uspto_detail_query("US12508845")
|
||||
|
||||
assert "must" not in epo_payload["query"]["bool"]
|
||||
assert "must" not in uspto_payload["query"]["bool"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_epo_posts_to_correct_index():
|
||||
captured: list[dict] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
path_parts = request.url.path.strip("/").split("/")
|
||||
captured.append(
|
||||
{
|
||||
"index": path_parts[-2],
|
||||
"body": json.loads(request.content) if request.content else {},
|
||||
}
|
||||
)
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
def fake_search(index: str, body: dict, cluster=None):
|
||||
captured.append({"index": index, "body": body})
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
client = PatentSearchClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
|
||||
with patch("inse.integrations.elasticsearch.search", side_effect=fake_search):
|
||||
client = PatentSearchClient(api_key="test-key")
|
||||
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
|
||||
|
||||
assert len(captured) == 1
|
||||
assert captured[0]["index"] == ESIndex.EPO_INDEX
|
||||
@@ -1,4 +1,4 @@
|
||||
import httpx
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import pytest
|
||||
|
||||
from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient
|
||||
@@ -11,57 +11,51 @@ def anyio_backend():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_posts_to_ipc_index():
|
||||
requests: list[str] = []
|
||||
mock_response = {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"cpc_section_number": "H",
|
||||
"cpc_section_name": "ELECTRICITY",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_class_number": "H01L",
|
||||
"cpc_class_name": "SEMICONDUCTOR DEVICES",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_group_number": "H01L21/02",
|
||||
"cpc_group_name": "Manufacture or treatment of semiconductor devices",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request.url.path)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"cpc_section_number": "H",
|
||||
"cpc_section_name": "ELECTRICITY",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_class_number": "H01L",
|
||||
"cpc_class_name": "SEMICONDUCTOR DEVICES",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_group_number": "H01L21/02",
|
||||
"cpc_group_name": "Manufacture or treatment of semiconductor devices",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = mock_response
|
||||
client = IpcSearchClient()
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = IpcSearchClient(api_key="test-key", transport=transport)
|
||||
result = await client.resolve_symbols(["H01L 21/02"])
|
||||
|
||||
result = await client.resolve_symbols(["H01L 21/02"])
|
||||
|
||||
assert len(requests) >= 1
|
||||
assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests)
|
||||
assert "H01L 21/02" in result
|
||||
assert result["H01L 21/02"].section == "H - ELECTRICITY"
|
||||
assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
assert mock_search.call_count >= 1
|
||||
_, kwargs = mock_search.call_args
|
||||
assert kwargs.get("index") == IPC_INDEX
|
||||
assert "H01L 21/02" in result
|
||||
assert result["H01L 21/02"].section == "H - ELECTRICITY"
|
||||
assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_does_not_crash_for_subclass_codes():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"hits": []}}
|
||||
client = IpcSearchClient()
|
||||
result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
|
||||
|
||||
client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler))
|
||||
result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
|
||||
|
||||
assert "A61J 1/14" in result
|
||||
assert "C07D 319/06" in result
|
||||
assert "A61J 1/14" in result
|
||||
assert "C07D 319/06" in result
|
||||
|
||||
@@ -9,10 +9,14 @@ import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional, Callable, Any, List
|
||||
from elasticsearch import ApiError, NotFoundError
|
||||
import hashlib
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
BadRequestException,
|
||||
)
|
||||
|
||||
from inse.model import ESIndex
|
||||
from .. import config
|
||||
@@ -20,14 +24,12 @@ from .. import util
|
||||
from ..integrations import llm
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.authors_list_response import AuthorsListResponse
|
||||
from inse import util
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.persons.query_builder import build_authors_search_rescored
|
||||
from inse.persons.model import (
|
||||
CustomAuthor,
|
||||
CustomAuthorsListResponse,
|
||||
PersonSearchRequest,
|
||||
CareerMetrics,
|
||||
)
|
||||
|
||||
@@ -35,17 +37,13 @@ logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
|
||||
|
||||
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
query = {
|
||||
"_source": ["display_name"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match_phrase": {
|
||||
"display_name": display_name
|
||||
}
|
||||
},
|
||||
{"match_phrase": {"display_name": display_name}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
@@ -63,7 +61,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
data = await elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
except Exception:
|
||||
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
|
||||
return None
|
||||
@@ -89,7 +87,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
}
|
||||
|
||||
|
||||
def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
async def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
try:
|
||||
query = {
|
||||
"_source": ["id", "display_name"],
|
||||
@@ -99,7 +97,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
"size": 1,
|
||||
}
|
||||
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
data = await elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None
|
||||
@@ -109,7 +107,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def search_persons(
|
||||
async def search_persons(
|
||||
author_id: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
) -> AuthorsListResponse:
|
||||
@@ -131,7 +129,7 @@ def search_persons(
|
||||
else:
|
||||
return AuthorsListResponse(results=[], meta=Meta(count=0))
|
||||
|
||||
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
|
||||
authors = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
@@ -155,7 +153,7 @@ def search_persons(
|
||||
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
|
||||
|
||||
|
||||
def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
async def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
|
||||
query = {
|
||||
"query_string": {
|
||||
@@ -164,7 +162,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
}
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=INDEX_NAME,
|
||||
query=query,
|
||||
source=["display_name"],
|
||||
@@ -178,7 +176,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
return hits[0].get("_source", {}).get("display_name")
|
||||
|
||||
|
||||
def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
|
||||
WORK_SOURCE_FIELDS = [
|
||||
"title",
|
||||
@@ -221,7 +219,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
@@ -251,7 +249,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
return works, topics
|
||||
|
||||
|
||||
def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
async def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
author_url = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
body = {
|
||||
@@ -278,7 +276,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
@@ -359,8 +357,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
|
||||
)
|
||||
|
||||
|
||||
def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = _get_publication_years_for_author(author_id)
|
||||
async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = await _get_publication_years_for_author(author_id)
|
||||
return _compute_career_metrics(publication_years)
|
||||
|
||||
|
||||
@@ -382,13 +380,13 @@ def _build_papers(works: list) -> list:
|
||||
return papers
|
||||
|
||||
|
||||
def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
async def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
|
||||
display_name = _fetch_author_display_name(author_id)
|
||||
display_name = await _fetch_author_display_name(author_id)
|
||||
if display_name is None:
|
||||
return None
|
||||
|
||||
works, top_topics = _fetch_works_and_topics(author_id)
|
||||
works, top_topics = await _fetch_works_and_topics(author_id)
|
||||
papers = _build_papers(works)
|
||||
|
||||
author_data = {
|
||||
@@ -399,9 +397,9 @@ def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
return author_data
|
||||
|
||||
|
||||
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
start_time = time.time()
|
||||
author_data = get_data_for_bio(author_id)
|
||||
author_data = await get_data_for_bio(author_id)
|
||||
if author_data is None:
|
||||
return "No person found."
|
||||
|
||||
@@ -430,31 +428,27 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
|
||||
return bio
|
||||
|
||||
|
||||
def get_person_by_id(
|
||||
async def get_person_by_id(
|
||||
author_id: str, include: Optional[str] = None
|
||||
) -> CustomAuthorsListResponse:
|
||||
source = include.split(",") if include else None
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(
|
||||
hit = await elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
doc_id=author_id,
|
||||
source=source,
|
||||
)
|
||||
except NotFoundError:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"Person with id {author_id} not found"
|
||||
)
|
||||
except ApiError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
|
||||
except NotFoundException as e:
|
||||
raise NotFoundException(f"Person with id {author_id} not found") from e
|
||||
|
||||
author = util.get_persons_data(hit)
|
||||
start_time = time.time()
|
||||
career_metrics = get_career_metrics_for_author(author_id)
|
||||
career_metrics = await get_career_metrics_for_author(author_id)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
logger.info(
|
||||
f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds"
|
||||
f"Career metrics calculation for author {author_id} took {elapsed_time:.2f} seconds"
|
||||
)
|
||||
|
||||
custom_author = CustomAuthor(
|
||||
@@ -465,14 +459,14 @@ def get_person_by_id(
|
||||
return CustomAuthorsListResponse(results=[custom_author])
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
async def search_persons_by_name(
|
||||
author_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
page_offset: Optional[int] = 0,
|
||||
include: Optional[str] = None,
|
||||
) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(status_code=400, detail="name must be provided")
|
||||
raise BadRequestException("name must be provided")
|
||||
search_query = {
|
||||
"bool": {
|
||||
"should": [
|
||||
@@ -495,7 +489,7 @@ def search_persons_by_name(
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
offset=page_offset,
|
||||
@@ -504,10 +498,8 @@ def search_persons_by_name(
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -518,11 +510,11 @@ def search_persons_by_name(
|
||||
)
|
||||
|
||||
|
||||
def search_persons_autocomplete(
|
||||
async def search_persons_autocomplete(
|
||||
author_name: str, limit: Optional[int] = 5, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(status_code=400, detail="name must be provided")
|
||||
raise BadRequestException("name must be provided")
|
||||
search_query = {
|
||||
"function_score": {
|
||||
"query": {
|
||||
@@ -555,11 +547,9 @@ def search_persons_autocomplete(
|
||||
"collapse": collapse,
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(index="openalex-authors", body=body)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
response = await elasticsearch.search(index="openalex-authors", body=body)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -587,7 +577,7 @@ def search_persons_autocomplete(
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
|
||||
def search_persons_by_institution(
|
||||
async def search_persons_by_institution(
|
||||
institution_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
page_offset: Optional[int] = 0,
|
||||
@@ -595,7 +585,7 @@ def search_persons_by_institution(
|
||||
) -> AuthorsListResponse:
|
||||
|
||||
if not institution_name:
|
||||
raise HTTPException(status_code=400, detail="institution_name must be provided")
|
||||
raise BadRequestException("institution_name must be provided")
|
||||
|
||||
search_query = {
|
||||
"nested": {
|
||||
@@ -614,7 +604,7 @@ def search_persons_by_institution(
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
source=include.split(",") if include else True,
|
||||
@@ -624,10 +614,8 @@ def search_persons_by_institution(
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
@@ -679,7 +667,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
|
||||
return author
|
||||
|
||||
|
||||
def advanced_search_persons(
|
||||
async def advanced_search_persons(
|
||||
query: Optional[str] = None,
|
||||
institution_name: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
@@ -707,39 +695,20 @@ def advanced_search_persons(
|
||||
filter_mode=filter_mode,
|
||||
filter_year=filter_year,
|
||||
)
|
||||
response_dict = elasticsearch.search(
|
||||
response_dict = await elasticsearch.search(
|
||||
index=INDEX_NAME,
|
||||
body=query_body,
|
||||
)
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=0, page=page, per_page=page_size)
|
||||
)
|
||||
elif e.response.status_code == 400:
|
||||
logger.error(f"Elasticsearch request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"Elasticsearch request error: {str(e)}"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Elasticsearch API error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch API error: {str(e)}"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"Elasticsearch connection/request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}"
|
||||
except ElasticsearchNotFoundException:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=0, page=page, per_page=page_size)
|
||||
)
|
||||
except Exception as e:
|
||||
except ElasticsearchException as e:
|
||||
logger.error(f"Elasticsearch search failed: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
raise
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response_dict.get("hits", {}).get("hits", [])
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
include_career_metrics = include is None or "career_metrics" in include
|
||||
results = []
|
||||
@@ -749,7 +718,7 @@ def advanced_search_persons(
|
||||
if custom_author:
|
||||
if include_career_metrics:
|
||||
start_time = time.time()
|
||||
custom_author.career_metrics = get_career_metrics_for_author(
|
||||
custom_author.career_metrics = await get_career_metrics_for_author(
|
||||
custom_author.id
|
||||
)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
@@ -29,7 +29,7 @@ router = APIRouter(
|
||||
summary="Searches for persons by ID or name.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
def search_persons(
|
||||
async def search_persons(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
] = None,
|
||||
@@ -53,7 +53,7 @@ def search_persons(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.search_persons(author_id, query)
|
||||
return await logic.search_persons(author_id, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -62,7 +62,7 @@ def search_persons(
|
||||
response_model=model.PersonBio,
|
||||
summary="Generates a bio for a person by author ID.",
|
||||
)
|
||||
def generate_person_bio(
|
||||
async def generate_person_bio(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
],
|
||||
@@ -79,7 +79,7 @@ def generate_person_bio(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
bio = logic.generate_person_bio(author_id, include_set)
|
||||
bio = await logic.generate_person_bio(author_id, include_set)
|
||||
return model.PersonBio(bio=bio)
|
||||
|
||||
@router.get(
|
||||
@@ -89,7 +89,7 @@ def generate_person_bio(
|
||||
summary="Searches for person by ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def get_person_by_id(
|
||||
async def get_person_by_id(
|
||||
id: Annotated[
|
||||
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
|
||||
],
|
||||
@@ -104,7 +104,7 @@ def get_person_by_id(
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
return logic.get_person_by_id(author_id=id, include=include)
|
||||
return await logic.get_person_by_id(author_id=id, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -114,7 +114,7 @@ def get_person_by_id(
|
||||
summary="Searches for person by name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_name(
|
||||
async def search_persons_by_name(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
@@ -129,24 +129,25 @@ def search_persons_by_name(
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/persons/autocomplete',
|
||||
operation_id='searchPersonsAutocomplete',
|
||||
response_model=AuthorsListResponse,
|
||||
summary='Searches for person by name.',
|
||||
tags=[ 'Persons' ])
|
||||
def search_persons_autocomplete(
|
||||
tags=['Persons'])
|
||||
async def search_persons_autocomplete(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include : Annotated[Optional[str], Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return logic.search_persons_autocomplete(author_name=author_name,include=include)
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return await logic.search_persons_autocomplete(author_name=author_name, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -156,7 +157,7 @@ def search_persons_autocomplete(
|
||||
summary="Searches for persons by institution name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_institution(
|
||||
async def search_persons_by_institution(
|
||||
institution_name: Annotated[
|
||||
str, Query(description="Institution name (e.g., MIT, Oxford University)")
|
||||
],
|
||||
@@ -173,7 +174,8 @@ def search_persons_by_institution(
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/search-list",
|
||||
@@ -183,7 +185,7 @@ def search_persons_by_institution(
|
||||
response_model_exclude_none=True,
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_list(
|
||||
async def search_persons_list(
|
||||
query: Annotated[
|
||||
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
|
||||
] = None,
|
||||
@@ -227,7 +229,7 @@ def search_persons_list(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.advanced_search_persons(
|
||||
return await logic.advanced_search_persons(
|
||||
query=query,
|
||||
institution_name=institution_name,
|
||||
sort_by=sort_by,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import asyncio
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
from inse.config import get_settings
|
||||
@@ -85,7 +85,7 @@ _HEU_ENTITY_CONFIGS = [
|
||||
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
|
||||
]
|
||||
|
||||
def get_enriched_cordis_project_by_id(
|
||||
async def get_enriched_cordis_project_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
@@ -102,7 +102,7 @@ def get_enriched_cordis_project_by_id(
|
||||
|
||||
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -131,7 +131,7 @@ def get_enriched_cordis_project_by_id(
|
||||
logger.warning(f"Unknown programme type for index: {index}")
|
||||
return CordisEuProject.model_validate(source)
|
||||
|
||||
return enricher(project_id, source)
|
||||
return await enricher(project_id, source)
|
||||
|
||||
# helpers
|
||||
def _determine_program_type_from_index(index: str) -> str:
|
||||
@@ -146,10 +146,9 @@ def _determine_program_type_from_index(index: str) -> str:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _fetch_related_entities_parallel(
|
||||
async def _fetch_related_entities_parallel(
|
||||
project_id: str,
|
||||
entity_configs: List[Dict[str, Any]],
|
||||
max_workers: int = 8,
|
||||
) -> Dict[str, List[Any]]:
|
||||
"""
|
||||
Fetches all related entity types for a project in parallel.
|
||||
@@ -157,35 +156,35 @@ def _fetch_related_entities_parallel(
|
||||
Args:
|
||||
project_id: The project ID to fetch entities for.
|
||||
entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'.
|
||||
max_workers: Maximum number of concurrent Elasticsearch requests.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping each config 'key' to a list of validated entities.
|
||||
"""
|
||||
def _fetch_one(config: Dict[str, Any]):
|
||||
entities = _fetch_related_entities(
|
||||
async def _fetch_one(config: Dict[str, Any]):
|
||||
entities = await _fetch_related_entities(
|
||||
project_ids=[project_id],
|
||||
index_pattern=config["index_pattern"],
|
||||
model_class=config["model_class"],
|
||||
)
|
||||
return config["key"], entities.get(project_id, [])
|
||||
|
||||
tasks = [_fetch_one(cfg) for cfg in entity_configs]
|
||||
completed = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
results: Dict[str, List[Any]] = {}
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
futures = {executor.submit(_fetch_one, cfg): cfg["key"] for cfg in entity_configs}
|
||||
for future in as_completed(futures):
|
||||
try:
|
||||
key, data = future.result()
|
||||
results[key] = data
|
||||
except Exception as e:
|
||||
key = futures[future]
|
||||
logger.error(f"Parallel fetch failed for '{key}': {e}")
|
||||
results[key] = []
|
||||
for cfg, res in zip(entity_configs, completed):
|
||||
key = cfg["key"]
|
||||
if isinstance(res, Exception):
|
||||
logger.error(f"Parallel fetch failed for '{key}': {res}")
|
||||
results[key] = []
|
||||
else:
|
||||
key_name, data = res
|
||||
results[key_name] = data
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def _fetch_related_entities(
|
||||
async def _fetch_related_entities(
|
||||
project_ids: List[str],
|
||||
index_pattern: str,
|
||||
model_class: Any,
|
||||
@@ -204,7 +203,7 @@ def _fetch_related_entities(
|
||||
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=index_pattern,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -234,7 +233,7 @@ def _fetch_related_entities(
|
||||
return grouped
|
||||
|
||||
|
||||
def _enrich_fp7_project(
|
||||
async def _enrich_fp7_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[Fp7ProjectDetails]:
|
||||
@@ -245,12 +244,12 @@ def _enrich_fp7_project(
|
||||
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
|
||||
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
|
||||
|
||||
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
|
||||
|
||||
def _enrich_h2020_project(
|
||||
async def _enrich_h2020_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[H2020ProjectDetails]:
|
||||
@@ -261,12 +260,12 @@ def _enrich_h2020_project(
|
||||
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
|
||||
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
|
||||
|
||||
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
|
||||
|
||||
def _enrich_heu_project(
|
||||
async def _enrich_heu_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[HEUProjectDetails]:
|
||||
@@ -277,6 +276,6 @@ def _enrich_heu_project(
|
||||
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
|
||||
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
|
||||
|
||||
return HEUProjectDetails.from_project_with_relations(project=project, **related)
|
||||
@@ -2,7 +2,6 @@ import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
import httpx
|
||||
import urllib
|
||||
from inse.config import get_settings
|
||||
from inse.models.bund_project import BundProject
|
||||
@@ -101,7 +100,7 @@ DFG_PERSON_FIELDS: List[str] = [
|
||||
# BUND
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
async def search_bund_projects(
|
||||
filter_properties: ProjectsFilteringProperties,
|
||||
institution_names: List[str] = [],
|
||||
) -> BundProjectPage:
|
||||
@@ -160,7 +159,7 @@ def search_bund_projects(
|
||||
}
|
||||
]
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=query,
|
||||
sort=sort,
|
||||
@@ -194,7 +193,7 @@ def _complete_response_to_bund_project_page(
|
||||
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
"""Decodes project_id and fetches the details of a single Bund project based on its project ID.
|
||||
|
||||
Args:
|
||||
@@ -207,7 +206,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
decoded_id = urllib.parse.unquote(project_id)
|
||||
query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=query,
|
||||
size=1,
|
||||
@@ -224,7 +223,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
# EU
|
||||
|
||||
|
||||
def get_eu_organization_project_contributions(
|
||||
async def get_eu_organization_project_contributions(
|
||||
organization_names: List[str],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -241,11 +240,11 @@ def get_eu_organization_project_contributions(
|
||||
# For FUNDING_AMOUNT before on the organization project contributions
|
||||
# For the rest after the contributions are known on the real projects
|
||||
|
||||
organization_project_contributions = get_eu_organization_contributions(
|
||||
organization_project_contributions = await get_eu_organization_contributions(
|
||||
organization_names=organization_names,
|
||||
)
|
||||
|
||||
total_projects, projects = get_eu_organization_projects(
|
||||
total_projects, projects = await get_eu_organization_projects(
|
||||
project_contributions=list(organization_project_contributions.values()),
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -271,7 +270,7 @@ def get_eu_organization_project_contributions(
|
||||
)
|
||||
|
||||
|
||||
def get_eu_organization_contributions(
|
||||
async def get_eu_organization_contributions(
|
||||
organization_names: List[str],
|
||||
) -> Dict[str, EuOrganizationShort]:
|
||||
"""Fetches the contributions of EU organizations to projects based on the provided organization names.
|
||||
@@ -293,7 +292,7 @@ def get_eu_organization_contributions(
|
||||
}
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -343,7 +342,7 @@ def _process_organization_project_contributions(
|
||||
return project_contributions
|
||||
|
||||
|
||||
def get_eu_organization_projects(
|
||||
async def get_eu_organization_projects(
|
||||
project_contributions: List[EuOrganizationShort],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> Tuple[int, Dict[str, EuProjectShort]]:
|
||||
@@ -388,7 +387,7 @@ def get_eu_organization_projects(
|
||||
|
||||
# Project contributions have been filtered before based on ecContribution
|
||||
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -396,7 +395,7 @@ def get_eu_organization_projects(
|
||||
size=10000,
|
||||
)
|
||||
else:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -496,7 +495,7 @@ def _get_raw_doi(doi: str) -> str:
|
||||
return doi
|
||||
|
||||
|
||||
def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
async def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
"""Retrieves Cordis EU publications associated with the given list of DOIs.
|
||||
|
||||
Args:
|
||||
@@ -508,7 +507,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
raw_dois = [_get_raw_doi(doi) for doi in dois]
|
||||
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -519,7 +518,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
return response
|
||||
|
||||
|
||||
def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
"""Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs.
|
||||
|
||||
Args:
|
||||
@@ -528,7 +527,7 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
Returns:
|
||||
List[str]: The list of project IDs.
|
||||
"""
|
||||
response = get_cordis_eu_publications_by_dois(dois=dois)
|
||||
response = await get_cordis_eu_publications_by_dois(dois=dois)
|
||||
hits_block = response.get("hits", {})
|
||||
project_ids = set()
|
||||
for hit in hits_block.get("hits", []):
|
||||
@@ -539,12 +538,12 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
return list(project_ids)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_project_ids(
|
||||
async def get_cordis_eu_projects_by_project_ids(
|
||||
project_ids: List[str],
|
||||
) -> CordisEuProjectPage:
|
||||
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -561,7 +560,7 @@ def get_cordis_eu_projects_by_project_ids(
|
||||
)
|
||||
|
||||
|
||||
def get_eu_cordis_projects_by_id(
|
||||
async def get_eu_cordis_projects_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
@@ -573,14 +572,14 @@ def get_eu_cordis_projects_by_id(
|
||||
Returns:
|
||||
The enriched project details, or None if not found
|
||||
"""
|
||||
enriched_project = get_enriched_cordis_project_by_id(
|
||||
enriched_project = await get_enriched_cordis_project_by_id(
|
||||
project_id=project_id
|
||||
)
|
||||
return enriched_project
|
||||
# DFG
|
||||
|
||||
|
||||
def search_dfg_projects(
|
||||
async def search_dfg_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
names: Optional[List[str]] = None,
|
||||
@@ -750,7 +749,7 @@ def search_dfg_projects(
|
||||
|
||||
body["sort"] = [sort_config]
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
body=body,
|
||||
)
|
||||
@@ -776,7 +775,7 @@ def _complete_response_to_dfg_project_page(
|
||||
return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""Fetches the details of a single DFG project based on its project ID.
|
||||
|
||||
Args:
|
||||
@@ -787,7 +786,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""
|
||||
query = {"ids": {"values": [project_id]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
query=query,
|
||||
size=1,
|
||||
@@ -804,7 +803,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
# All
|
||||
|
||||
|
||||
def search_all_projects(
|
||||
async def search_all_projects(
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
) -> FundingProjectPage:
|
||||
@@ -882,7 +881,7 @@ def search_all_projects(
|
||||
size = projects_filtering_properties.size
|
||||
page = projects_filtering_properties.page
|
||||
offset = page * size
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
size=size,
|
||||
offset=offset,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from typing import Annotated, Optional, Set
|
||||
|
||||
@@ -51,13 +50,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_eu_projects_for_author(
|
||||
async def get_eu_projects_for_author(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
|
||||
) -> CordisEuProjectPage:
|
||||
logger.debug(
|
||||
f"Received request to get EU projects for author_id={raw_oa_author_id}"
|
||||
)
|
||||
return projects_service.search_cordis_eu_projects_for_author_id(
|
||||
return await projects_service.search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
)
|
||||
|
||||
@@ -85,7 +84,7 @@ async def search_bund_projects(
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> BundProjectPage:
|
||||
return projects_service.search_bund_projects(
|
||||
return await projects_service.search_bund_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
@@ -105,11 +104,11 @@ async def search_bund_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_dfg_project(
|
||||
async def get_single_dfg_project(
|
||||
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Received request to get single DFG project for id={id}")
|
||||
return projects_service.get_single_dfg_project(
|
||||
return await projects_service.get_single_dfg_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
@@ -128,11 +127,11 @@ def get_single_dfg_project(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_bund_project(
|
||||
async def get_single_bund_project(
|
||||
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Received request to get single BUND project for id={id}")
|
||||
return projects_service.get_single_bund_project(
|
||||
return await projects_service.get_single_bund_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
@@ -157,9 +156,7 @@ def get_single_bund_project(
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def get_single_eu_cordis_project(
|
||||
async def get_single_eu_cordis_project(
|
||||
id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
|
||||
) -> EuCordisProjectResponse:
|
||||
"""
|
||||
@@ -170,7 +167,7 @@ def get_single_eu_cordis_project(
|
||||
|
||||
try:
|
||||
# Get the project from the service
|
||||
project = projects_service.get_single_eu_cordis_project(project_id=id)
|
||||
project = await projects_service.get_single_eu_cordis_project(project_id=id)
|
||||
|
||||
# Check if project exists
|
||||
if project is None:
|
||||
@@ -216,6 +213,7 @@ def get_single_eu_cordis_project(
|
||||
error=f"Internal server error: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/bund/funding-over-time",
|
||||
summary="Get funding over time for bund projects.",
|
||||
@@ -230,7 +228,7 @@ def get_single_eu_cordis_project(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
async def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
@@ -238,7 +236,7 @@ def get_institution_bund_projects_funding_over_time(
|
||||
str, Query(description="The institution ID to filter by.")
|
||||
],
|
||||
) -> InstitutionFunderSummary:
|
||||
return projects_service.get_institution_bund_projects_funding_over_time(
|
||||
return await projects_service.get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
@@ -267,7 +265,7 @@ async def search_cordis_eu_projects(
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
return projects_service.search_cordis_eu_projects(
|
||||
return await projects_service.search_cordis_eu_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -359,7 +357,7 @@ async def get_dfg_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def search_projects(
|
||||
async def search_projects(
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 10,
|
||||
selected_project_types: Annotated[
|
||||
@@ -378,7 +376,7 @@ def search_projects(
|
||||
SortDirection, Query(description="The sort direction (asc or desc).")
|
||||
] = SortDirection.ASC,
|
||||
) -> FundingProjectPage:
|
||||
return projects_service.search_all_projects(
|
||||
return await projects_service.search_all_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
selected_project_types=selected_project_types,
|
||||
|
||||
@@ -35,7 +35,7 @@ from typing import Union
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def search_all_projects(
|
||||
async def search_all_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: ProjectsSortBy,
|
||||
@@ -43,7 +43,7 @@ def search_all_projects(
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> FundingProjectPage:
|
||||
return projects_search_client.search_all_projects(
|
||||
return await projects_search_client.search_all_projects(
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
|
||||
page=page,
|
||||
@@ -56,7 +56,7 @@ def search_all_projects(
|
||||
)
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
async def search_bund_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
@@ -69,13 +69,13 @@ def search_bund_projects(
|
||||
f"search_bund_projects called with filtering_properties: {filtering_properties}"
|
||||
)
|
||||
|
||||
return get_bund_projects_by_institution_id(
|
||||
return await get_bund_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_bund_projects_by_institution_id(
|
||||
async def get_bund_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
@@ -86,14 +86,14 @@ def get_bund_projects_by_institution_id(
|
||||
f"Fetching bund projects for institution_id={filtering_properties.raw_oa_institution_id}, page={filtering_properties.page}, size={filtering_properties.size}"
|
||||
)
|
||||
institution_aliases = (
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
filtering_properties.raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
response = await projects_search_client.search_bund_projects(
|
||||
institution_names=institution_aliases,
|
||||
filter_properties=filtering_properties,
|
||||
)
|
||||
@@ -101,7 +101,7 @@ def get_bund_projects_by_institution_id(
|
||||
return response
|
||||
|
||||
|
||||
def search_cordis_eu_projects(
|
||||
async def search_cordis_eu_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -110,13 +110,13 @@ def search_cordis_eu_projects(
|
||||
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
|
||||
)
|
||||
|
||||
return get_cordis_eu_projects_by_institution_id(
|
||||
return await get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_institution_id(
|
||||
async def get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -129,7 +129,7 @@ def get_cordis_eu_projects_by_institution_id(
|
||||
f"Fetching CORDIS EU projects for institution_id={projects_filtering_properties.raw_oa_institution_id}, page={projects_filtering_properties.page}, size={projects_filtering_properties.size}"
|
||||
)
|
||||
institution_aliases = (
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
projects_filtering_properties.raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
@@ -137,7 +137,7 @@ def get_cordis_eu_projects_by_institution_id(
|
||||
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
|
||||
page = get_eu_organization_project_contributions(
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -158,7 +158,7 @@ async def get_dfg_projects_by_author_id(
|
||||
logger.debug(
|
||||
f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}"
|
||||
)
|
||||
name = get_author_name_by_id(author_id)
|
||||
name = await get_author_name_by_id(author_id)
|
||||
if not name:
|
||||
logger.debug(f"No author name found for author_id={author_id}")
|
||||
raise NotFoundException(
|
||||
@@ -166,7 +166,7 @@ async def get_dfg_projects_by_author_id(
|
||||
)
|
||||
logger.debug(f"Found author name for author_id={author_id}: {name}")
|
||||
|
||||
response = projects_search_client.search_dfg_projects(
|
||||
response = await projects_search_client.search_dfg_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
names=[name],
|
||||
@@ -182,11 +182,11 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
institution_aliases = (
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
page = get_eu_organization_project_contributions(
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
@@ -204,7 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
async def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
@@ -212,14 +212,14 @@ def get_institution_bund_projects_funding_over_time(
|
||||
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
|
||||
)
|
||||
institution_aliases = (
|
||||
institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
response = await projects_search_client.search_bund_projects(
|
||||
filter_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.BUND,
|
||||
page=0,
|
||||
@@ -305,38 +305,40 @@ def _calculate_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
def get_single_dfg_project(
|
||||
async def get_single_dfg_project(
|
||||
project_id: str,
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Fetching single DFG project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_dfg_project_by_id(project_id)
|
||||
project = await projects_search_client.get_dfg_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"DFG project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
def get_single_bund_project(
|
||||
async def get_single_bund_project(
|
||||
project_id: str,
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Fetching single BUND project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_bund_project_by_id(project_id)
|
||||
project = await projects_search_client.get_bund_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"BUND project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
def get_single_eu_cordis_project(
|
||||
|
||||
async def get_single_eu_cordis_project(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
logger.debug(f"Fetching single EU Cordis project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_eu_cordis_projects_by_id(project_id)
|
||||
project = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"EU project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
def search_cordis_eu_projects_for_author_id(
|
||||
|
||||
async def search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id: str,
|
||||
) -> CordisEuProjectPage:
|
||||
|
||||
@@ -345,17 +347,17 @@ def search_cordis_eu_projects_for_author_id(
|
||||
# 2. CORDIS EU projects have associated publications with DOIs
|
||||
# 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author
|
||||
|
||||
dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
dois = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
|
||||
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
|
||||
|
||||
project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
|
||||
project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
|
||||
|
||||
logger.debug(
|
||||
f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}"
|
||||
)
|
||||
|
||||
funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
project_ids=project_ids
|
||||
)
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the schema for the database
|
||||
used by the service using sql alchemy.
|
||||
"""
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
from sqlalchemy.orm import Mapped
|
||||
from sqlalchemy.orm import mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
''' Base class for all data models. '''
|
||||
pass
|
||||
|
||||
class Item(Base):
|
||||
''' Data model to represent an item. '''
|
||||
__tablename__ = "item"
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(200))
|
||||
description: Mapped[str] = mapped_column(String(2000))
|
||||
def __repr__(self) -> str:
|
||||
return f"Item(id={self.id!r}, name={self.name!r})"
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module defines the security-related code.
|
||||
"""
|
||||
from typing import Optional
|
||||
from typing import List
|
||||
from typing import Callable
|
||||
from typing import Literal
|
||||
from typing import Union
|
||||
from starlette.status import HTTP_403_FORBIDDEN
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPBearer
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
from fastapi import HTTPException
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from sqlalchemy.orm import Session
|
||||
import jwt
|
||||
import logging
|
||||
from . import config
|
||||
from . import database
|
||||
|
||||
class Account(BaseModel):
|
||||
id: int = Field(description="The id of the account.")
|
||||
login: Optional[str] = Field(description="The optional login of the account.")
|
||||
organization: int = Field(description="The organization id of the account.")
|
||||
|
||||
class Principal(BaseModel):
|
||||
account: Account = Field(description="The account of the principal.")
|
||||
delegate: Optional[Account] = Field(default=None, description="The optional delegate of the principal.")
|
||||
roles: List[str] = Field(description="The roles of the principal.")
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
bearer = HTTPBearer(bearerFormat="JWT", scheme_name="bearer", description="JSON Web Token provided via bearer authorization.", auto_error=False)
|
||||
|
||||
def principal(credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer), db: Session = Depends(database.get)) -> Optional[Principal]:
|
||||
if config.settings.auth_disabled:
|
||||
account = Account(id=0, login="AUTH_DISABLED", organization=0)
|
||||
return Principal(account=account, delegate=None, roles=[ 'SUPER_ADMIN' ])
|
||||
if credentials is None or credentials.credentials is None:
|
||||
return None
|
||||
return _extract_principal(credentials.credentials, config.settings.auth_secret, 'HS256')
|
||||
|
||||
def _extract_principal(token: str, secret_key, algorithm: Literal['RS256', 'HS256'], token_types: List[Literal['ID', 'ACCESS', 'REFRESH']] = [ 'ACCESS' ]) -> Optional[Principal]:
|
||||
try:
|
||||
content = jwt.decode(token, secret_key, verify=True, issuer="my-app", algorithms=[ algorithm ], options={"require": [ "iss", "iat", "nbf", "exp", "inse"]})
|
||||
except jwt.exceptions.ExpiredSignatureError as e:
|
||||
logger.info(f'Received expired token, ignoring content ({e}).')
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.info(f'Received invalid token content, ignoring content ({e}).')
|
||||
return None
|
||||
scope = content.get("inse")
|
||||
if scope is None:
|
||||
return None
|
||||
token_type = scope.get('t')
|
||||
if token_type not in token_types:
|
||||
logger.info(f'Received invalid token type, ignoring content (Type was {token_type})')
|
||||
return None
|
||||
a = scope.get('a', {})
|
||||
account = Account(id=a.get('i', 0), login=a.get('l'), organization=a.get('o', 0))
|
||||
delegate = None
|
||||
d = scope.get('d')
|
||||
if d is not None:
|
||||
delegate = Account(id=d.get('i', 0), login=d.get('l'), organization=d.get('o', 0))
|
||||
return Principal(account=account, delegate=delegate, roles=scope.get('r', []))
|
||||
|
||||
def roles_allowed(roles: List[str]|str) -> Callable[[Optional[Principal]], Principal]:
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
if len(roles) < 1:
|
||||
raise ValueError("Must specify at least one role in roles_allowed.")
|
||||
def verify_roles(principal: Optional[Principal] = Depends(principal)) -> Principal:
|
||||
if principal is None:
|
||||
logger.info("Rejecting call due to missing principal.")
|
||||
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
for role in roles:
|
||||
if role in principal.roles:
|
||||
return principal
|
||||
logger.info("Rejecting call due to missing roles.")
|
||||
raise HTTPException(status_code=HTTP_403_FORBIDDEN)
|
||||
return verify_roles
|
||||
@@ -6,28 +6,13 @@ service.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Annotated, List, Optional
|
||||
from fastapi import FastAPI
|
||||
from fastapi import Depends
|
||||
from fastapi import Path
|
||||
from typing import Annotated, List
|
||||
from fastapi import Query
|
||||
from fastapi import Body
|
||||
from fastapi import Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_200_OK
|
||||
from sqlalchemy.orm import Session
|
||||
from inse.config import get_settings
|
||||
from fastapi import APIRouter
|
||||
|
||||
|
||||
from . import model
|
||||
from . import logic
|
||||
from . import schema
|
||||
from . import database
|
||||
from . import security
|
||||
from . import util
|
||||
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -42,126 +27,6 @@ router = APIRouter(
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
# @app.get("/", include_in_schema=False)
|
||||
# async def show_api():
|
||||
# return RedirectResponse("api")
|
||||
|
||||
|
||||
### items
|
||||
|
||||
|
||||
@router.get(
|
||||
"/items",
|
||||
operation_id="getItems",
|
||||
response_model=model.ItemPage,
|
||||
summary="Returns a page of items.",
|
||||
tags=["Items"],
|
||||
)
|
||||
def get_items(
|
||||
page_offset: Annotated[
|
||||
int, Query(alias="pageOffset", description="The page offset.", ge=0)
|
||||
] = 0,
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="The page size.", ge=0, le=1000)
|
||||
] = 100,
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return logic.get_page(db, schema.Item, model.Item, page_offset, page_size)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/items/{id}",
|
||||
operation_id="getItem",
|
||||
response_model=model.Item,
|
||||
summary="Returns the item with the id.",
|
||||
responses={HTTP_404_NOT_FOUND: {"model": None}},
|
||||
tags=["Items"],
|
||||
)
|
||||
def get_item(
|
||||
id: Annotated[int, Path(description="The item id.", ge=0)],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/items",
|
||||
operation_id="addItem",
|
||||
response_model=model.Item,
|
||||
summary="Adds a new item.",
|
||||
tags=["Items"],
|
||||
)
|
||||
def add_item(
|
||||
item: Annotated[model.ItemCreate, Body(description="The item to add.")],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
i = schema.Item()
|
||||
i.name = item.name
|
||||
i.description = item.description
|
||||
try:
|
||||
return logic.insert_element(db, i)
|
||||
finally:
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.put(
|
||||
"/items/{id}",
|
||||
operation_id="updateItem",
|
||||
response_model=model.Item,
|
||||
summary="Updates the item with the id.",
|
||||
responses={HTTP_404_NOT_FOUND: {"model": None}},
|
||||
tags=["Items"],
|
||||
)
|
||||
def update_item(
|
||||
id: Annotated[int, Path(description="The item id.", ge=0)],
|
||||
item: Annotated[model.ItemCreate, Body(description="The item data to update.")],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
i = util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
|
||||
i.name = item.name
|
||||
i.description = item.description
|
||||
db.flush()
|
||||
db.refresh(i)
|
||||
try:
|
||||
return i
|
||||
finally:
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/items/{id}",
|
||||
operation_id="deleteItem",
|
||||
summary="Deletes the item with the id.",
|
||||
response_model=None,
|
||||
responses={HTTP_404_NOT_FOUND: {"model": None}},
|
||||
tags=["Items"],
|
||||
)
|
||||
def delete_item(
|
||||
id: Annotated[int, Path(description="The item id.", ge=0)],
|
||||
db: Session = Depends(database.get),
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
util.raise_not_found_if_none(logic.get_element(db, schema.Item, id))
|
||||
try:
|
||||
logic.delete_element(db, schema.Item, id)
|
||||
return Response(status_code=HTTP_200_OK)
|
||||
finally:
|
||||
db.commit()
|
||||
|
||||
|
||||
### topics
|
||||
# hierarchy cache (temporaray => should be called by a scheduled job, with new openalex data indexing)
|
||||
@@ -209,6 +74,7 @@ def count_topic_hierarchy(
|
||||
):
|
||||
return logic.count_topic_hierarchy(topic_names)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topics/hierarchy",
|
||||
operation_id="getTopicHierarchy",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from enum import Enum
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class Tags(Enum):
|
||||
class Tags(StrEnum):
|
||||
PERSON = "Person"
|
||||
PERSON_NETWORK = "Person Network"
|
||||
INSTITUTIONS = "Institutions"
|
||||
@@ -9,3 +9,6 @@ class Tags(Enum):
|
||||
WORKS = "Works"
|
||||
NEWS = "News"
|
||||
PROJECTS = "Projects"
|
||||
AUTH = "Auth"
|
||||
ACCOUNT = "Account"
|
||||
ORGANIZATION = "Organization"
|
||||
|
||||
@@ -3,15 +3,19 @@
|
||||
"""
|
||||
Business logic for OpenAlex topics.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
ElasticsearchException,
|
||||
)
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
@@ -19,6 +23,7 @@ from inse.models.openalex.autocomplete_response_results_inner import (
|
||||
AutocompleteResponseResultsInner,
|
||||
)
|
||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||
from inse.model import ESCluster
|
||||
from .search_client import OpenAlexTopicsClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -38,10 +43,7 @@ async def list_topics(
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
) -> TopicsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
|
||||
@@ -66,12 +68,12 @@ async def list_topics(
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics request failed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
@@ -79,9 +81,9 @@ async def list_topics(
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex topics response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -156,7 +158,13 @@ def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
meta = normalized.get("meta")
|
||||
if isinstance(meta, dict):
|
||||
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
|
||||
for field in [
|
||||
"count",
|
||||
"db_response_time_ms",
|
||||
"page",
|
||||
"per_page",
|
||||
"groups_count",
|
||||
]:
|
||||
meta[field] = _int_or_none(meta.get(field))
|
||||
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
|
||||
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
|
||||
@@ -256,8 +264,11 @@ def _datetime_str_or_none(value: Any) -> str | None:
|
||||
return f"{text}T00:00:00Z"
|
||||
return text
|
||||
|
||||
|
||||
# Configuration for vector search similarity thresholds and boosts
|
||||
SIMILARITY_THRESHOLD = 0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||
SIMILARITY_THRESHOLD = (
|
||||
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||
)
|
||||
BOOST_LEXICAL = 1.0
|
||||
# higher values for semantic weights, because cosine similarity is between 0 and 1
|
||||
BOOST_DISPLAY_NAME_VECTOR = 30.0
|
||||
@@ -267,6 +278,79 @@ BOOST_KEYWORD_VECTORS = 25.0
|
||||
K = 500
|
||||
NUM_CANDIDATES = 500
|
||||
|
||||
|
||||
def _build_vector_search_body(
|
||||
*,
|
||||
query: str,
|
||||
query_vector: list[float],
|
||||
search_type: str = "hybrid",
|
||||
limit: int = 25,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Construct the Elasticsearch request body for topic vector/hybrid search.
|
||||
"""
|
||||
should_clauses = []
|
||||
|
||||
# Lexical multi_match search (only in hybrid mode)
|
||||
if search_type == "hybrid":
|
||||
should_clauses.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query,
|
||||
"fields": ["display_name^3", "keywords^2"],
|
||||
"boost": BOOST_LEXICAL,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Semantic KNN clauses
|
||||
should_clauses.extend(
|
||||
[
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"boost": BOOST_DISPLAY_NAME_VECTOR,
|
||||
"k": K,
|
||||
"num_candidates": NUM_CANDIDATES,
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"k": K,
|
||||
"num_candidates": NUM_CANDIDATES,
|
||||
}
|
||||
},
|
||||
"score_mode": "max",
|
||||
"boost": BOOST_KEYWORD_VECTORS,
|
||||
}
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
return {
|
||||
"query": {"bool": {"should": should_clauses}},
|
||||
"_source": {
|
||||
"excludes": [
|
||||
"display_name_vector",
|
||||
"keyword_vectors",
|
||||
"works_api_url",
|
||||
"updated_date",
|
||||
"created_date",
|
||||
"_index",
|
||||
] # remove unrequired fields
|
||||
},
|
||||
"size": limit,
|
||||
}
|
||||
|
||||
|
||||
async def vector_search_topics(
|
||||
*,
|
||||
query: str,
|
||||
@@ -282,10 +366,9 @@ async def vector_search_topics(
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to load elasticsearch integration: {exc}"
|
||||
)
|
||||
raise ElasticsearchException(
|
||||
f"Failed to load elasticsearch integration: {exc}"
|
||||
) from exc
|
||||
|
||||
# 1. Vectorize query
|
||||
try:
|
||||
@@ -293,81 +376,25 @@ async def vector_search_topics(
|
||||
query_vector = model.encode(query).tolist()
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode query text.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to encode query text: {exc}"
|
||||
)
|
||||
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
||||
|
||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||
should_clauses = []
|
||||
|
||||
# Lexical multi_match search (only in hybrid mode)
|
||||
if search_type == "hybrid":
|
||||
should_clauses.append({
|
||||
"multi_match": {
|
||||
"query": query,
|
||||
"fields": [
|
||||
"display_name^3",
|
||||
"keywords^2"
|
||||
],
|
||||
"boost": BOOST_LEXICAL
|
||||
}
|
||||
})
|
||||
|
||||
# Semantic KNN clauses
|
||||
should_clauses.extend([
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"boost": BOOST_DISPLAY_NAME_VECTOR,
|
||||
"k": K,
|
||||
"num_candidates": NUM_CANDIDATES
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"similarity": SIMILARITY_THRESHOLD,
|
||||
"k": K,
|
||||
"num_candidates": NUM_CANDIDATES
|
||||
}
|
||||
},
|
||||
"score_mode": "max",
|
||||
"boost": BOOST_KEYWORD_VECTORS
|
||||
}
|
||||
}
|
||||
])
|
||||
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": should_clauses
|
||||
}
|
||||
},
|
||||
"_source": {
|
||||
"excludes": ["display_name_vector", "keyword_vectors", "works_api_url", "updated_date", "created_date", "_index" ] # remove unrequired fields
|
||||
},
|
||||
"size": limit
|
||||
}
|
||||
body = _build_vector_search_body(
|
||||
query=query,
|
||||
query_vector=query_vector,
|
||||
search_type=search_type,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
try:
|
||||
raw_results = elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body=body,
|
||||
cluster="nes"
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch vector search failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Elasticsearch vector search failed: {exc}"
|
||||
)
|
||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||
raise ElasticsearchException(
|
||||
f"Unexpected vector search failure: {exc}"
|
||||
) from exc
|
||||
|
||||
# 3. Format result
|
||||
hits = raw_results.get("hits", {}).get("hits", [])
|
||||
@@ -375,22 +402,107 @@ async def vector_search_topics(
|
||||
total = len(hits)
|
||||
results = [hit.get("_source", {}) for hit in hits]
|
||||
|
||||
data = {
|
||||
"meta": {
|
||||
"count": total,
|
||||
"page": 1,
|
||||
"per_page": limit
|
||||
},
|
||||
"results": results
|
||||
}
|
||||
data = {"meta": {"count": total, "page": 1, "per_page": limit}, "results": results}
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("Vector search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Vector search response could not be parsed.",
|
||||
raise ElasticsearchException(
|
||||
f"Vector search response could not be parsed: {exc}"
|
||||
) from exc
|
||||
|
||||
|
||||
async def vector_search_topics_batch(
|
||||
*,
|
||||
keywords: list[str],
|
||||
search_type: str = "hybrid",
|
||||
) -> Any:
|
||||
"""
|
||||
Perform concurrent semantic/hybrid search for a list of keywords.
|
||||
"""
|
||||
from inse.topics.model import KeywordsTopicsResponse, KeywordTopicMatch
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
if not keywords:
|
||||
return KeywordsTopicsResponse(results=[])
|
||||
|
||||
try:
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.util import get_model
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise ElasticsearchException(
|
||||
f"Failed to load elasticsearch integration: {exc}"
|
||||
) from exc
|
||||
|
||||
# 1. Vectorize queries on CPU in batch
|
||||
try:
|
||||
model = get_model()
|
||||
vectors = model.encode(keywords)
|
||||
query_vectors = [v.tolist() for v in vectors]
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode batch queries.")
|
||||
raise ElasticsearchException(f"Failed to encode batch queries: {exc}") from exc
|
||||
|
||||
# 2. Construct search bodies and query Elasticsearch concurrently
|
||||
tasks = []
|
||||
for kw, qv in zip(keywords, query_vectors):
|
||||
body = _build_vector_search_body(
|
||||
query=kw,
|
||||
query_vector=qv,
|
||||
search_type=search_type,
|
||||
limit=1,
|
||||
)
|
||||
tasks.append(
|
||||
elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
raw_results_list = await asyncio.gather(*tasks)
|
||||
except Exception as exc:
|
||||
logger.exception("Batch Elasticsearch vector search failed with unexpected error.")
|
||||
raise ElasticsearchException(
|
||||
f"Unexpected batch vector search failure: {exc}"
|
||||
) from exc
|
||||
|
||||
# 3. Align and map raw results to KeywordTopicMatch objects
|
||||
results_by_index = [None] * len(keywords)
|
||||
keywords_with_topics = []
|
||||
topics_to_normalize = []
|
||||
index_mapping = []
|
||||
|
||||
for i, (keyword, raw_res) in enumerate(zip(keywords, raw_results_list)):
|
||||
hits = raw_res.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
topic_dict = hits[0].get("_source", {})
|
||||
keywords_with_topics.append(keyword)
|
||||
topics_to_normalize.append(topic_dict)
|
||||
index_mapping.append(i)
|
||||
else:
|
||||
results_by_index[i] = KeywordTopicMatch(keyword=keyword, topic=None)
|
||||
|
||||
if topics_to_normalize:
|
||||
data = {"results": topics_to_normalize}
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
normalized_topics = normalized_data.get("results", [])
|
||||
|
||||
for keyword, topic_dict, orig_idx in zip(keywords_with_topics, normalized_topics, index_mapping):
|
||||
try:
|
||||
topic = Topic.from_dict(topic_dict)
|
||||
except Exception as e:
|
||||
logger.exception(f"Failed to parse normalized topic dictionary for keyword '{keyword}': {e}")
|
||||
topic = None
|
||||
results_by_index[orig_idx] = KeywordTopicMatch(keyword=keyword, topic=topic)
|
||||
|
||||
# Fallback to fill any unfilled slots
|
||||
for i, res in enumerate(results_by_index):
|
||||
if res is None:
|
||||
results_by_index[i] = KeywordTopicMatch(keyword=keywords[i], topic=None)
|
||||
|
||||
return KeywordsTopicsResponse(results=results_by_index)
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
# Vector search for Keyword list
|
||||
class KeywordsTopicsRequest(BaseModel):
|
||||
keywords: List[str] = Field(..., description="List of keywords/sentences to query by similarity.")
|
||||
|
||||
|
||||
class KeywordTopicMatch(BaseModel):
|
||||
keyword: str
|
||||
topic: Optional[Topic] = Field(None, description="The top matching topic from OpenAlex, or None if no match is found.")
|
||||
|
||||
|
||||
class KeywordsTopicsResponse(BaseModel):
|
||||
results: List[KeywordTopicMatch] = Field(..., description="Top matching topics for each keyword in the requested list.")
|
||||
@@ -12,6 +12,7 @@ from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||
from inse.tags import Tags
|
||||
from . import logic
|
||||
from .model import KeywordsTopicsRequest, KeywordsTopicsResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS])
|
||||
@@ -140,3 +141,22 @@ async def vector_search_topics(
|
||||
search_type=search_type,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/vector-search/batch",
|
||||
operation_id="vectorSearchTopicsBatch",
|
||||
response_model=KeywordsTopicsResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Batch semantic / vector search for multiple keywords.",
|
||||
)
|
||||
async def vector_search_topics_batch(
|
||||
request_body: KeywordsTopicsRequest,
|
||||
search_type: Annotated[
|
||||
str,
|
||||
Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."),
|
||||
] = "hybrid",
|
||||
):
|
||||
return await logic.vector_search_topics_batch(
|
||||
keywords=request_body.keywords,
|
||||
search_type=search_type,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
@@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
|
||||
@@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran
|
||||
|
||||
|
||||
# Fetch top institutions for the topic by works_count
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=10,
|
||||
|
||||
@@ -8,15 +8,14 @@ from typing import Optional
|
||||
from typing import TypeVar
|
||||
from inse.models.openalex import Author
|
||||
from . import model
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from inse.exceptions import NotFoundException
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
def raise_not_found_if_none(value: Optional[T]) -> T:
|
||||
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
|
||||
if value == None:
|
||||
raise HTTPException(HTTP_404_NOT_FOUND)
|
||||
raise NotFoundException("Not found.")
|
||||
else:
|
||||
return value
|
||||
|
||||
|
||||
@@ -8,12 +8,8 @@ import logging
|
||||
from time import time
|
||||
from typing import Any, List
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse import config
|
||||
from inse.integrations import elasticsearch
|
||||
@@ -24,7 +20,7 @@ from inse.models.openalex.meta import Meta
|
||||
from inse.models.openalex.topic_count import TopicCount
|
||||
from inse.models.openalex.topics_by_year import TopicsByYear
|
||||
from inse.models.openalex.topics_by_time import TopicsByTime
|
||||
from .search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
from .search_client import OpenAlexWorksSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -122,10 +118,10 @@ async def get_primary_topic_counts(
|
||||
author_id: str,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> List[TopicCount]:
|
||||
topic_counts = _get_primary_topic_counts_from_es(author_id)
|
||||
topic_counts = await _get_primary_topic_counts_from_es(author_id)
|
||||
|
||||
topic_ids = [item["id"] for item in topic_counts if item["id"]]
|
||||
details = _get_topic_details(topic_ids)
|
||||
details = await _get_topic_details(topic_ids)
|
||||
|
||||
result = []
|
||||
|
||||
@@ -148,7 +144,7 @@ async def get_primary_topic_counts(
|
||||
return result
|
||||
|
||||
|
||||
def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
@@ -174,16 +170,13 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex primary topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
aggregations = response.get("aggregations", {})
|
||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||
@@ -212,18 +205,18 @@ async def get_work(
|
||||
return elements[0]
|
||||
|
||||
|
||||
def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
if not topic_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"terms": {"id": topic_ids}},
|
||||
source=TOPIC_DETAIL_SOURCE_FIELDS,
|
||||
size=len(topic_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic details from Elasticsearch.")
|
||||
return {}
|
||||
|
||||
@@ -242,7 +235,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
"domain": _extract_topic_hierarchy_item(source, "domain"),
|
||||
}
|
||||
|
||||
_enrich_topic_hierarchy_descriptions(details)
|
||||
await _enrich_topic_hierarchy_descriptions(details)
|
||||
|
||||
return details
|
||||
|
||||
@@ -260,7 +253,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non
|
||||
}
|
||||
|
||||
|
||||
def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
|
||||
hierarchy_ids = {
|
||||
item.get(hierarchy_key, {}).get("id")
|
||||
@@ -268,7 +261,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
if item.get(hierarchy_key, {}).get("id")
|
||||
}
|
||||
|
||||
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
|
||||
for item in details.values():
|
||||
hierarchy_item = item.get(hierarchy_key) or {}
|
||||
@@ -278,7 +271,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
hierarchy_item["description"] = descriptions[hierarchy_id]
|
||||
|
||||
|
||||
def _get_topic_hierarchy_descriptions(
|
||||
async def _get_topic_hierarchy_descriptions(
|
||||
index: str,
|
||||
hierarchy_ids: list[str],
|
||||
) -> dict[str, str | None]:
|
||||
@@ -286,13 +279,13 @@ def _get_topic_hierarchy_descriptions(
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
query={"terms": {"id": hierarchy_ids}},
|
||||
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
|
||||
size=len(hierarchy_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic hierarchy details from %s.", index)
|
||||
return {}
|
||||
|
||||
@@ -433,7 +426,7 @@ async def get_topics_by_time_by_author(
|
||||
client=client,
|
||||
)
|
||||
|
||||
return _get_topics_by_time_by_author_from_es(
|
||||
return await _get_topics_by_time_by_author_from_es(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
target_publications=target_publications,
|
||||
@@ -521,7 +514,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
if topic["id"]:
|
||||
topic_ids.add(topic["id"])
|
||||
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = []
|
||||
|
||||
@@ -580,13 +573,13 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
)
|
||||
|
||||
|
||||
def _get_topics_by_time_by_author_from_es(
|
||||
async def _get_topics_by_time_by_author_from_es(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
) -> TopicsByTime:
|
||||
year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
|
||||
year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id)
|
||||
selected_years, is_limited = _select_complete_timeline_years(
|
||||
year_buckets,
|
||||
target_publications=target_publications,
|
||||
@@ -602,13 +595,13 @@ def _get_topics_by_time_by_author_from_es(
|
||||
total_publications=total_publications,
|
||||
)
|
||||
|
||||
year_topic_buckets = _get_timeline_topic_counts_from_es(
|
||||
year_topic_buckets = await _get_timeline_topic_counts_from_es(
|
||||
author_id,
|
||||
years=selected_years,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets)
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = _build_timeline_elements_from_aggregations(
|
||||
year_topic_buckets,
|
||||
@@ -625,7 +618,7 @@ def _get_topics_by_time_by_author_from_es(
|
||||
)
|
||||
|
||||
|
||||
def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
body = {
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
@@ -642,21 +635,18 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex publication year aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
return _parse_year_count_buckets(response), _parse_total_hits(response)
|
||||
|
||||
|
||||
def _get_timeline_topic_counts_from_es(
|
||||
async def _get_timeline_topic_counts_from_es(
|
||||
author_id: str,
|
||||
years: list[int],
|
||||
max_topics_per_year: int,
|
||||
@@ -713,16 +703,13 @@ def _get_timeline_topic_counts_from_es(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex timeline topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
return response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
|
||||
|
||||
@@ -883,29 +870,16 @@ async def _search_author_works_data(
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> dict:
|
||||
try:
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
|
||||
def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
@@ -946,15 +920,15 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
elements.append(work)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex works search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex works search response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
return elements, total
|
||||
|
||||
|
||||
def get_publication_dois_of_author(
|
||||
async def get_publication_dois_of_author(
|
||||
raw_oa_author_id: str,
|
||||
) -> List[str]:
|
||||
query = {
|
||||
@@ -976,19 +950,16 @@ def get_publication_dois_of_author(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-works",
|
||||
source=["doi"],
|
||||
size=10000,
|
||||
query=query,
|
||||
cluster="nes",
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Request for publication DOIs of author failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Request for publication DOIs of author failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
dois = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
|
||||
@@ -6,13 +6,11 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import urllib
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,17 +18,11 @@ logger = logging.getLogger(__name__)
|
||||
class OpenAlexWorksSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
index: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
|
||||
self.index = index or config.settings.openalex_works_search_index
|
||||
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
|
||||
self.transport = transport
|
||||
|
||||
|
||||
def author_works_query(
|
||||
@@ -141,62 +133,49 @@ class OpenAlexWorksSearchClient:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=self.author_works_query(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
),
|
||||
)
|
||||
# logging.debug(f"Response: {response.text}")
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
body = self.author_works_query(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
||||
|
||||
async def search_work(self, identifier: str) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
decoded_id = urllib.parse.unquote(identifier)
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
decoded_id = urllib.parse.unquote(identifier)
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": decoded_id,
|
||||
"boost": 5
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": decoded_id,
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/" + decoded_id.lower(),
|
||||
"boost": 3
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/" + decoded_id.lower(),
|
||||
"boost": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
print(body)
|
||||
response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
return response
|
||||
}
|
||||
}
|
||||
response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1)
|
||||
return response
|
||||
|
||||
async def search_for_work_by_title(
|
||||
self,
|
||||
@@ -220,6 +199,6 @@ class OpenAlexWorksSearchClient:
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
}
|
||||
response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
|
||||
return response
|
||||
@@ -7,13 +7,11 @@ REST API for publication works.
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Depends
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
from .. import security
|
||||
from . import logic
|
||||
from inse.models.openalex.work_page import WorkPage
|
||||
from inse.models.openalex.work import Work
|
||||
@@ -56,9 +54,6 @@ async def get_author_works(
|
||||
list[str] | None,
|
||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||
] = None,
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return await logic.get_author_works(
|
||||
author_id,
|
||||
@@ -72,35 +67,47 @@ async def get_author_works(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{author_id}/all",
|
||||
operation_id="getAllAuthorWorks",
|
||||
response_model=WorksListResponse,
|
||||
summary="Returns all works for an author.")
|
||||
@router.get(
|
||||
"/{author_id}/all",
|
||||
operation_id="getAllAuthorWorks",
|
||||
response_model=WorksListResponse,
|
||||
summary="Returns all works for an author.",
|
||||
)
|
||||
async def get_all_author_works(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
author_id: Annotated[
|
||||
str, Path(description="The author id, for example A5023888391.")
|
||||
],
|
||||
):
|
||||
return await logic.get_all_author_works(author_id)
|
||||
|
||||
|
||||
@router.get("/{author_id}/primary-topic-counts",
|
||||
operation_id="getPrimaryTopicCountsByAuthor",
|
||||
response_model=list[TopicCount],
|
||||
summary="Returns work counts per primary topic for an author.")
|
||||
@router.get(
|
||||
"/{author_id}/primary-topic-counts",
|
||||
operation_id="getPrimaryTopicCountsByAuthor",
|
||||
response_model=list[TopicCount],
|
||||
summary="Returns work counts per primary topic for an author.",
|
||||
)
|
||||
async def get_primary_topic_counts(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
author_id: Annotated[
|
||||
str, Path(description="The author id, for example A5023888391.")
|
||||
],
|
||||
):
|
||||
return await logic.get_primary_topic_counts(author_id)
|
||||
|
||||
|
||||
@router.get("/{author_id}/topics-by-time",
|
||||
operation_id="getTopicsByTimeByAuthor",
|
||||
response_model=TopicsByTime,
|
||||
summary="Returns topics grouped by publication year for an author.")
|
||||
@router.get(
|
||||
"/{author_id}/topics-by-time",
|
||||
operation_id="getTopicsByTimeByAuthor",
|
||||
response_model=TopicsByTime,
|
||||
summary="Returns topics grouped by publication year for an author.",
|
||||
)
|
||||
async def get_topics_by_time_by_author(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
max_topics_per_year: Annotated[int, Query(description="The maximum number of topics per year.", ge=1, le=20)] = 3,
|
||||
author_id: Annotated[
|
||||
str, Path(description="The author id, for example A5023888391.")
|
||||
],
|
||||
max_topics_per_year: Annotated[
|
||||
int, Query(description="The maximum number of topics per year.", ge=1, le=20)
|
||||
] = 3,
|
||||
target_publications: Annotated[
|
||||
int,
|
||||
Query(
|
||||
@@ -112,7 +119,6 @@ async def get_topics_by_time_by_author(
|
||||
bool,
|
||||
Query(description="If true, all publications are used for the timeline."),
|
||||
] = False,
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
):
|
||||
return await logic.get_topics_by_time_by_author(
|
||||
author_id,
|
||||
@@ -130,13 +136,16 @@ async def get_topics_by_time_by_author(
|
||||
)
|
||||
async def get_work_by_identifier(
|
||||
identifier: Annotated[
|
||||
str, Path(description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication.")
|
||||
str,
|
||||
Path(
|
||||
description="The OpenAlex work id (e.g., W2741809807) or DOI number of the publication."
|
||||
),
|
||||
],
|
||||
title: Annotated[
|
||||
Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
|
||||
Optional[str],
|
||||
Query(
|
||||
description="Do we want to fallback to title search if ID and DOI dont work?"
|
||||
),
|
||||
] = "",
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return await logic.get_work(identifier,title=title)
|
||||
return await logic.get_work(identifier, title=title)
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.works.search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
@@ -152,37 +151,47 @@ def test_author_works_query_adds_topic_filter():
|
||||
]
|
||||
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_institution_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
|
||||
"authorships.institutions"
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions"
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == {
|
||||
"authorships.institutions.id": ["https://openalex.org/I205640436"],
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_topic_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body["query"]["bool"]["filter"] == [
|
||||
{
|
||||
"bool": {
|
||||
@@ -207,61 +216,55 @@ async def test_search_author_works_passes_topic_filter_to_query():
|
||||
},
|
||||
},
|
||||
]
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_calls_elasticsearch_index_with_api_key():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "POST"
|
||||
assert request.url.path == "/elastic/openalex-works/_search"
|
||||
assert request.headers["Authorization"] == "ApiKey test-key"
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}})
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
result = await client.search_author_works("A5023888391", page=1, size=20)
|
||||
|
||||
result = await client.search_author_works("A5023888391", page=1, size=20)
|
||||
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_work_filters_by_work_id():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body == {
|
||||
"size": 1,
|
||||
"query": {"term": {"id": "https://openalex.org/W2741809807"}},
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": "W2741809807",
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/w2741809807",
|
||||
"boost": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
Generated
+68
-68
@@ -2,8 +2,10 @@ version = 1
|
||||
revision = 3
|
||||
requires-python = ">=3.12"
|
||||
resolution-markers = [
|
||||
"sys_platform != 'darwin'",
|
||||
"sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -37,6 +39,49 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2-cffi"
|
||||
version = "25.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "argon2-cffi-bindings" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2-cffi-bindings"
|
||||
version = "25.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cffi" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/60/97/3c0a35f46e52108d4707c44b95cfe2afcafc50800b5450c197454569b776/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:3d3f05610594151994ca9ccb3c771115bdb4daef161976a266f0dd8aa9996b8f", size = 54393, upload-time = "2025-07-30T10:01:40.97Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/f4/98bbd6ee89febd4f212696f13c03ca302b8552e7dbf9c8efa11ea4a388c3/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8b8efee945193e667a396cbc7b4fb7d357297d6234d30a489905d96caabde56b", size = 29328, upload-time = "2025-07-30T10:01:41.916Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/24/90a01c0ef12ac91a6be05969f29944643bc1e5e461155ae6559befa8f00b/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3c6702abc36bf3ccba3f802b799505def420a1b7039862014a65db3205967f5a", size = 31269, upload-time = "2025-07-30T10:01:42.716Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/d3/942aa10782b2697eee7af5e12eeff5ebb325ccfb86dd8abda54174e377e4/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1c70058c6ab1e352304ac7e3b52554daadacd8d453c1752e547c76e9c99ac44", size = 86558, upload-time = "2025-07-30T10:01:43.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/82/b484f702fec5536e71836fc2dbc8c5267b3f6e78d2d539b4eaa6f0db8bf8/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2fd3bfbff3c5d74fef31a722f729bf93500910db650c925c2d6ef879a7e51cb", size = 92364, upload-time = "2025-07-30T10:01:44.887Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/c1/a606ff83b3f1735f3759ad0f2cd9e038a0ad11a3de3b6c673aa41c24bb7b/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c4f9665de60b1b0e99bcd6be4f17d90339698ce954cfd8d9cf4f91c995165a92", size = 85637, upload-time = "2025-07-30T10:01:46.225Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/b4/678503f12aceb0262f84fa201f6027ed77d71c5019ae03b399b97caa2f19/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ba92837e4a9aa6a508c8d2d7883ed5a8f6c308c89a4790e1e447a220deb79a85", size = 91934, upload-time = "2025-07-30T10:01:47.203Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/c7/f36bd08ef9bd9f0a9cff9428406651f5937ce27b6c5b07b92d41f91ae541/argon2_cffi_bindings-25.1.0-cp314-cp314t-win32.whl", hash = "sha256:84a461d4d84ae1295871329b346a97f68eade8c53b6ed9a7ca2d7467f3c8ff6f", size = 28158, upload-time = "2025-07-30T10:01:48.341Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/80/0106a7448abb24a2c467bf7d527fe5413b7fdfa4ad6d6a96a43a62ef3988/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b55aec3565b65f56455eebc9b9f34130440404f27fe21c3b375bf1ea4d8fbae6", size = 32597, upload-time = "2025-07-30T10:01:49.112Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/b8/d663c9caea07e9180b2cb662772865230715cbd573ba3b5e81793d580316/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87c33a52407e4c41f3b70a9c2d3f6056d88b10dad7695be708c5021673f55623", size = 28231, upload-time = "2025-07-30T10:01:49.92Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/57/96b8b9f93166147826da5f90376e784a10582dd39a393c99bb62cfcf52f0/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:aecba1723ae35330a008418a91ea6cfcedf6d31e5fbaa056a166462ff066d500", size = 54121, upload-time = "2025-07-30T10:01:50.815Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/08/a9bebdb2e0e602dde230bdde8021b29f71f7841bd54801bcfd514acb5dcf/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2630b6240b495dfab90aebe159ff784d08ea999aa4b0d17efa734055a07d2f44", size = 29177, upload-time = "2025-07-30T10:01:51.681Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/02/d297943bcacf05e4f2a94ab6f462831dc20158614e5d067c35d4e63b9acb/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:7aef0c91e2c0fbca6fc68e7555aa60ef7008a739cbe045541e438373bc54d2b0", size = 31090, upload-time = "2025-07-30T10:01:53.184Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/93/44365f3d75053e53893ec6d733e4a5e3147502663554b4d864587c7828a7/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e021e87faa76ae0d413b619fe2b65ab9a037f24c60a1e6cc43457ae20de6dc6", size = 81246, upload-time = "2025-07-30T10:01:54.145Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/52/94108adfdd6e2ddf58be64f959a0b9c7d4ef2fa71086c38356d22dc501ea/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3e924cfc503018a714f94a49a149fdc0b644eaead5d1f089330399134fa028a", size = 87126, upload-time = "2025-07-30T10:01:55.074Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/70/7a2993a12b0ffa2a9271259b79cc616e2389ed1a4d93842fac5a1f923ffd/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87b72589133f0346a1cb8d5ecca4b933e3c9b64656c9d175270a000e73b288d", size = 80343, upload-time = "2025-07-30T10:01:56.007Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/9a/4e5157d893ffc712b74dbd868c7f62365618266982b64accab26bab01edc/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1db89609c06afa1a214a69a462ea741cf735b29a57530478c06eb81dd403de99", size = 86777, upload-time = "2025-07-30T10:01:56.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/74/cd/15777dfde1c29d96de7f18edf4cc94c385646852e7c7b0320aa91ccca583/argon2_cffi_bindings-25.1.0-cp39-abi3-win32.whl", hash = "sha256:473bcb5f82924b1becbb637b63303ec8d10e84c8d241119419897a26116515d2", size = 27180, upload-time = "2025-07-30T10:01:57.759Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/c6/a759ece8f1829d1f162261226fbfd2c6832b3ff7657384045286d2afa384/argon2_cffi_bindings-25.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:a98cd7d17e9f7ce244c0803cad3c23a7d379c301ba618a5fa76a67d116618b98", size = 31715, upload-time = "2025-07-30T10:01:58.56Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/b9/f8d6fa329ab25128b7e98fd83a3cb34d9db5b059a9847eddb840a0af45dd/argon2_cffi_bindings-25.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:b0fdbcf513833809c882823f98dc2f931cf659d9a1429616ac3adebb49f5db94", size = 27149, upload-time = "2025-07-30T10:01:59.329Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2026.5.20"
|
||||
@@ -178,36 +223,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elastic-transport"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "certifi" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elasticsearch"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "elastic-transport" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastapi"
|
||||
version = "0.115.14"
|
||||
@@ -799,18 +814,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dateutil"
|
||||
version = "2.9.0.post0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "six" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.2"
|
||||
@@ -1125,9 +1128,9 @@ name = "service"
|
||||
version = "0.1.0"
|
||||
source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "argon2-cffi" },
|
||||
{ name = "cryptography" },
|
||||
{ name = "dotenv" },
|
||||
{ name = "elasticsearch" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
@@ -1138,7 +1141,7 @@ dependencies = [
|
||||
{ name = "python-multipart" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "sentence-transformers" },
|
||||
{ name = "sqlalchemy" },
|
||||
{ name = "sqlmodel" },
|
||||
{ name = "torch", version = "2.12.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform == 'darwin'" },
|
||||
{ name = "torch", version = "2.12.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'darwin'" },
|
||||
{ name = "uvicorn" },
|
||||
@@ -1146,9 +1149,9 @@ dependencies = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "argon2-cffi", specifier = "~=25.1.0" },
|
||||
{ name = "cryptography", specifier = "~=42.0.0" },
|
||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||
{ name = "elasticsearch", specifier = "~=9.4.0" },
|
||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||
{ name = "httpx", specifier = "~=0.27.0" },
|
||||
{ name = "openai", specifier = "~=2.41.0" },
|
||||
@@ -1159,7 +1162,7 @@ requires-dist = [
|
||||
{ name = "python-multipart", specifier = "~=0.0.19" },
|
||||
{ name = "pyyaml", specifier = "~=6.0.1" },
|
||||
{ name = "sentence-transformers", specifier = "~=5.5.1" },
|
||||
{ name = "sqlalchemy", specifier = "~=2.0.0" },
|
||||
{ name = "sqlmodel", specifier = "~=0.0.33" },
|
||||
{ name = "torch", index = "https://download.pytorch.org/whl/cpu" },
|
||||
{ name = "uvicorn", specifier = "~=0.29.0" },
|
||||
]
|
||||
@@ -1182,15 +1185,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "six"
|
||||
version = "1.17.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
@@ -1241,6 +1235,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d0/10/f7220e9b784d295d241c86ed99aeb537f92afcd469a64861f2717e9bb077/sqlalchemy-2.0.50-py3-none-any.whl", hash = "sha256:92064363517a3ff8212b5a93b8c62876579d8dfd1ca5b561335f30152d884fa9", size = 1943861, upload-time = "2026-05-24T19:59:01.119Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlmodel"
|
||||
version = "0.0.33"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "sqlalchemy" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c4/62/22c287122598e61d07d005eec0b4eb97e6bde9a1b051bcd66c2bca846ea8/sqlmodel-0.0.33.tar.gz", hash = "sha256:b473544ed5fc2097894d89033049e569e1f138363dd3ec2ed4b6932cc9f29f5f", size = 95578, upload-time = "2026-02-11T15:23:39.504Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/39/13891bae4658133b489a4d8b6a2f193d56110e392289560f312748e796dc/sqlmodel-0.0.33-py3-none-any.whl", hash = "sha256:9045bb4d97d2ba099c5a068ee9525af2d106972dda1ff8488e187ce50556bf73", size = 27444, upload-time = "2026-02-11T15:23:38.678Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "starlette"
|
||||
version = "0.46.2"
|
||||
@@ -1305,7 +1312,8 @@ name = "torch"
|
||||
version = "2.12.0"
|
||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||
resolution-markers = [
|
||||
"sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "filelock", marker = "sys_platform == 'darwin'" },
|
||||
@@ -1329,7 +1337,8 @@ name = "torch"
|
||||
version = "2.12.0+cpu"
|
||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||
resolution-markers = [
|
||||
"sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "filelock", marker = "sys_platform != 'darwin'" },
|
||||
@@ -1421,15 +1430,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "2.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uvicorn"
|
||||
version = "0.29.0"
|
||||
|
||||
Generated
-10
@@ -19,7 +19,6 @@
|
||||
"@angular/platform-browser-dynamic": "^21.2.14",
|
||||
"@angular/router": "^21.2.14",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-wordcloud": "^2.1.0",
|
||||
"ngx-echarts": "^21.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
@@ -6088,15 +6087,6 @@
|
||||
"zrender": "6.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/echarts-wordcloud": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/echarts-wordcloud/-/echarts-wordcloud-2.1.0.tgz",
|
||||
"integrity": "sha512-Kt1JmbcROgb+3IMI48KZECK2AP5lG6bSsOEs+AsuwaWJxQom31RTNd6NFYI01E/YaI1PFZeueaupjlmzSQasjQ==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"echarts": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/echarts/node_modules/tslib": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||
|
||||
+1
-2
@@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start": "ng serve --proxy-config src/proxy.conf.json",
|
||||
"build": "ng build",
|
||||
"generate:api": "openapi-generator-cli generate --generator-key inse-service",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
@@ -22,7 +22,6 @@
|
||||
"@angular/platform-browser-dynamic": "^21.2.14",
|
||||
"@angular/router": "^21.2.14",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-wordcloud": "^2.1.0",
|
||||
"ngx-echarts": "^21.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
|
||||
@@ -4,13 +4,14 @@ README.md
|
||||
api.base.service.ts
|
||||
api.module.ts
|
||||
api/api.ts
|
||||
api/auth.service.ts
|
||||
api/companyConnections.service.ts
|
||||
api/funding.service.ts
|
||||
api/iNSEAccountService.service.ts
|
||||
api/iNSEService.service.ts
|
||||
api/institutions.service.ts
|
||||
api/items.service.ts
|
||||
api/keywords.service.ts
|
||||
api/news.service.ts
|
||||
api/organization.service.ts
|
||||
api/patents.service.ts
|
||||
api/personNetwork.service.ts
|
||||
api/persons.service.ts
|
||||
@@ -21,10 +22,11 @@ configuration.ts
|
||||
encoder.ts
|
||||
git_push.sh
|
||||
index.ts
|
||||
model/accessGrant.ts
|
||||
model/accessResponse.ts
|
||||
model/accessToken.ts
|
||||
model/accountPage.ts
|
||||
model/accountProfile.ts
|
||||
model/allPatentsResponse.ts
|
||||
model/authAccount.ts
|
||||
model/authScope.ts
|
||||
model/author.ts
|
||||
model/authorAffiliationsInner.ts
|
||||
model/authorCountsByYearInner.ts
|
||||
@@ -40,7 +42,10 @@ model/autocompleteResponse.ts
|
||||
model/autocompleteResponseMeta.ts
|
||||
model/autocompleteResponseResultsInner.ts
|
||||
model/award.ts
|
||||
model/bodyCreateUser.ts
|
||||
model/bodyChangePassword.ts
|
||||
model/bodyGetAccessToken.ts
|
||||
model/bodyLogin.ts
|
||||
model/bodyRequestOtk.ts
|
||||
model/bundProject.ts
|
||||
model/bundProjectDetails.ts
|
||||
model/bundProjectPage.ts
|
||||
@@ -53,6 +58,8 @@ model/companyConnectionsResponse.ts
|
||||
model/cordisEuProject.ts
|
||||
model/cordisEuProjectPage.ts
|
||||
model/costUsd.ts
|
||||
model/createAccountRequest.ts
|
||||
model/createOrganizationRequest.ts
|
||||
model/customAuthor.ts
|
||||
model/customAuthorsListResponse.ts
|
||||
model/dehydratedAuthor.ts
|
||||
@@ -66,6 +73,9 @@ model/euCordisProjectResponse.ts
|
||||
model/euOrganizationProjectSummary.ts
|
||||
model/euOrganizationProjectSummaryPage.ts
|
||||
model/euProjectData.ts
|
||||
model/extractedKeywords.ts
|
||||
model/extractedKeywordsLLM.ts
|
||||
model/extractedKeywordsResponse.ts
|
||||
model/filterInformation.ts
|
||||
model/filterProperties.ts
|
||||
model/fp7EurosciVoc.ts
|
||||
@@ -103,7 +113,9 @@ model/hEUReportSummary.ts
|
||||
model/hEUTopic.ts
|
||||
model/hEUWebLink.ts
|
||||
model/hTTPValidationError.ts
|
||||
model/identityGrant.ts
|
||||
model/idToken.ts
|
||||
model/inseAccountManagementModelOrganizationProfile.ts
|
||||
model/inseOrganizationManagementModelOrganizationProfile.ts
|
||||
model/institution.ts
|
||||
model/institutionFunderSummary.ts
|
||||
model/institutionGeo.ts
|
||||
@@ -113,13 +125,18 @@ model/institutionNetworkNode.ts
|
||||
model/institutionPage.ts
|
||||
model/institutionsListResponse.ts
|
||||
model/ipcClassification.ts
|
||||
model/item.ts
|
||||
model/itemCreate.ts
|
||||
model/itemPage.ts
|
||||
model/keywordEntry.ts
|
||||
model/keywordEntryWithTopic.ts
|
||||
model/keywordTopicMatch.ts
|
||||
model/keywords.ts
|
||||
model/keywordsRequest.ts
|
||||
model/keywordsTopicsRequest.ts
|
||||
model/keywordsTopicsResponse.ts
|
||||
model/latitude.ts
|
||||
model/location.ts
|
||||
model/loginResponse.ts
|
||||
model/longitude.ts
|
||||
model/matchedAuthor.ts
|
||||
model/matchedOfficer.ts
|
||||
model/mentionedPerson.ts
|
||||
model/meta.ts
|
||||
@@ -129,8 +146,12 @@ model/newsArticle.ts
|
||||
model/newsArticleDetail.ts
|
||||
model/newsPage.ts
|
||||
model/openAccess.ts
|
||||
model/orgPatentEntry.ts
|
||||
model/orgPatentsResponse.ts
|
||||
model/organizationPage.ts
|
||||
model/patentEntry.ts
|
||||
model/patentsByAuthorResponse.ts
|
||||
model/patentsByInstitutionResponse.ts
|
||||
model/personBio.ts
|
||||
model/projectType.ts
|
||||
model/projectsFilteringProperties.ts
|
||||
@@ -139,8 +160,10 @@ model/publicationDetailByFunder.ts
|
||||
model/publicationIdsByAuthorPosition.ts
|
||||
model/publicationsByAuthorResponse.ts
|
||||
model/rankingResponse.ts
|
||||
model/refreshToken.ts
|
||||
model/score.ts
|
||||
model/sortDirection.ts
|
||||
model/tokenType.ts
|
||||
model/topic.ts
|
||||
model/topicCount.ts
|
||||
model/topicDomain.ts
|
||||
@@ -153,7 +176,9 @@ model/topicsByYear.ts
|
||||
model/topicsListResponse.ts
|
||||
model/universityRanking.ts
|
||||
model/universityTopicData.ts
|
||||
model/user.ts
|
||||
model/updateAccountRequest.ts
|
||||
model/updateOrganizationRequest.ts
|
||||
model/userRole.ts
|
||||
model/validationError.ts
|
||||
model/validationErrorLocInner.ts
|
||||
model/value.ts
|
||||
|
||||
@@ -46,10 +46,10 @@ npm link
|
||||
In your project:
|
||||
|
||||
```console
|
||||
npm link
|
||||
npm link
|
||||
```
|
||||
|
||||
**Note for Windows users:** The Angular CLI has troubles to use linked npm packages.
|
||||
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
|
||||
Please refer to this issue <https://github.com/angular/angular-cli/issues/8284> for a solution / workaround.
|
||||
Published packages are not effected by this issue.
|
||||
|
||||
@@ -58,22 +58,22 @@ Published packages are not effected by this issue.
|
||||
In your Angular project:
|
||||
|
||||
```typescript
|
||||
|
||||
import { ApplicationConfig } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi(),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi()
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
**NOTE**
|
||||
If you're still using `AppModule` and haven't [migrated](https://angular.dev/reference/migrations/standalone) yet, you can still import an Angular module:
|
||||
|
||||
```typescript
|
||||
import { ApiModule } from '';
|
||||
```
|
||||
@@ -86,11 +86,11 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi('http://localhost:9999'),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi('http://localhost:9999')
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -101,15 +101,15 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi({
|
||||
withCredentials: true,
|
||||
username: 'user',
|
||||
password: 'password',
|
||||
}),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi({
|
||||
withCredentials: true,
|
||||
username: 'user',
|
||||
password: 'password'
|
||||
})
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -120,22 +120,21 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi, Configuration } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
{
|
||||
provide: Configuration,
|
||||
useFactory: (authService: AuthService) =>
|
||||
new Configuration({
|
||||
basePath: 'http://localhost:9999',
|
||||
withCredentials: true,
|
||||
username: authService.getUsername(),
|
||||
password: authService.getPassword(),
|
||||
}),
|
||||
deps: [AuthService],
|
||||
multi: false,
|
||||
},
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
{
|
||||
provide: Configuration,
|
||||
useFactory: (authService: AuthService) => new Configuration({
|
||||
basePath: 'http://localhost:9999',
|
||||
withCredentials: true,
|
||||
username: authService.getUsername(),
|
||||
password: authService.getPassword(),
|
||||
}),
|
||||
deps: [AuthService],
|
||||
multi: false
|
||||
}
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -152,12 +151,12 @@ import { HttpClientModule } from '@angular/common/http';
|
||||
import { environment } from '../environments/environment';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideUserApi(environment.basePath),
|
||||
provideAdminApi(environment.basePath),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideUserApi(environment.basePath),
|
||||
provideAdminApi(environment.basePath),
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -177,8 +176,8 @@ Example value for use in your Configuration-Provider:
|
||||
|
||||
```typescript
|
||||
new Configuration({
|
||||
encodeParam: (param: Param) => myFancyParamEncoder(param),
|
||||
});
|
||||
encodeParam: (param: Param) => myFancyParamEncoder(param),
|
||||
})
|
||||
```
|
||||
|
||||
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
|
||||
|
||||
@@ -1,109 +1,83 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import {
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpParameterCodec,
|
||||
} from '@angular/common/http';
|
||||
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from './encoder';
|
||||
import { Configuration } from './configuration';
|
||||
|
||||
export class BaseService {
|
||||
protected basePath = 'http://localhost:8000';
|
||||
public defaultHeaders = new HttpHeaders();
|
||||
public configuration: Configuration;
|
||||
public encoder: HttpParameterCodec;
|
||||
protected basePath = 'http://localhost:8000';
|
||||
public defaultHeaders = new HttpHeaders();
|
||||
public configuration: Configuration;
|
||||
public encoder: HttpParameterCodec;
|
||||
|
||||
constructor(basePath?: string | string[], configuration?: Configuration) {
|
||||
this.configuration = configuration || new Configuration();
|
||||
if (typeof this.configuration.basePath !== 'string') {
|
||||
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
|
||||
if (firstBasePath != undefined) {
|
||||
basePath = firstBasePath;
|
||||
}
|
||||
constructor(basePath?: string|string[], configuration?: Configuration) {
|
||||
this.configuration = configuration || new Configuration();
|
||||
if (typeof this.configuration.basePath !== 'string') {
|
||||
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
|
||||
if (firstBasePath != undefined) {
|
||||
basePath = firstBasePath;
|
||||
}
|
||||
|
||||
if (typeof basePath !== 'string') {
|
||||
basePath = this.basePath;
|
||||
}
|
||||
this.configuration.basePath = basePath;
|
||||
}
|
||||
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
|
||||
}
|
||||
|
||||
protected canConsumeForm(consumes: string[]): boolean {
|
||||
return consumes.indexOf('multipart/form-data') !== -1;
|
||||
}
|
||||
|
||||
protected addToHttpParams(
|
||||
httpParams: HttpParams,
|
||||
value: any,
|
||||
key?: string,
|
||||
isDeep: boolean = false,
|
||||
): HttpParams {
|
||||
// If the value is an object (but not a Date), recursively add its keys.
|
||||
if (typeof value === 'object' && !(value instanceof Date)) {
|
||||
return this.addToHttpParamsRecursive(
|
||||
httpParams,
|
||||
value,
|
||||
isDeep ? key : undefined,
|
||||
isDeep,
|
||||
);
|
||||
}
|
||||
return this.addToHttpParamsRecursive(httpParams, value, key);
|
||||
}
|
||||
|
||||
protected addToHttpParamsRecursive(
|
||||
httpParams: HttpParams,
|
||||
value?: any,
|
||||
key?: string,
|
||||
isDeep: boolean = false,
|
||||
): HttpParams {
|
||||
if (value === null || value === undefined) {
|
||||
return httpParams;
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
// If JSON format is preferred, key must be provided.
|
||||
if (key != null) {
|
||||
return isDeep
|
||||
? Object.keys(value as Record<string, any>).reduce(
|
||||
(hp, k) => hp.append(`${key}[${k}]`, value[k]),
|
||||
httpParams,
|
||||
)
|
||||
: httpParams.append(key, JSON.stringify(value));
|
||||
}
|
||||
// Otherwise, if it's an array, add each element.
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(
|
||||
(elem) =>
|
||||
(httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)),
|
||||
);
|
||||
} else if (value instanceof Date) {
|
||||
if (key != null) {
|
||||
httpParams = httpParams.append(key, value.toISOString());
|
||||
} else {
|
||||
throw Error('key may not be null if value is Date');
|
||||
if (typeof basePath !== 'string') {
|
||||
basePath = this.basePath;
|
||||
}
|
||||
this.configuration.basePath = basePath;
|
||||
}
|
||||
} else {
|
||||
Object.keys(value).forEach((k) => {
|
||||
const paramKey = key ? `${key}.${k}` : k;
|
||||
httpParams = this.addToHttpParamsRecursive(
|
||||
httpParams,
|
||||
value[k],
|
||||
paramKey,
|
||||
);
|
||||
});
|
||||
}
|
||||
return httpParams;
|
||||
} else if (key != null) {
|
||||
return httpParams.append(key, value);
|
||||
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
|
||||
}
|
||||
|
||||
protected canConsumeForm(consumes: string[]): boolean {
|
||||
return consumes.indexOf('multipart/form-data') !== -1;
|
||||
}
|
||||
|
||||
protected addToHttpParams(httpParams: HttpParams, value: any, key?: string, isDeep: boolean = false): HttpParams {
|
||||
// If the value is an object (but not a Date), recursively add its keys.
|
||||
if (typeof value === 'object' && !(value instanceof Date)) {
|
||||
return this.addToHttpParamsRecursive(httpParams, value, isDeep ? key : undefined, isDeep);
|
||||
}
|
||||
return this.addToHttpParamsRecursive(httpParams, value, key);
|
||||
}
|
||||
|
||||
protected addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string, isDeep: boolean = false): HttpParams {
|
||||
if (value === null || value === undefined) {
|
||||
return httpParams;
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
// If JSON format is preferred, key must be provided.
|
||||
if (key != null) {
|
||||
return isDeep
|
||||
? Object.keys(value as Record<string, any>).reduce(
|
||||
(hp, k) => hp.append(`${key}[${k}]`, value[k]),
|
||||
httpParams,
|
||||
)
|
||||
: httpParams.append(key, JSON.stringify(value));
|
||||
}
|
||||
// Otherwise, if it's an array, add each element.
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
|
||||
} else if (value instanceof Date) {
|
||||
if (key != null) {
|
||||
httpParams = httpParams.append(key, value.toISOString());
|
||||
} else {
|
||||
throw Error("key may not be null if value is Date");
|
||||
}
|
||||
} else {
|
||||
Object.keys(value).forEach(k => {
|
||||
const paramKey = key ? `${key}.${k}` : k;
|
||||
httpParams = this.addToHttpParamsRecursive(httpParams, value[k], paramKey);
|
||||
});
|
||||
}
|
||||
return httpParams;
|
||||
} else if (key != null) {
|
||||
return httpParams.append(key, value);
|
||||
}
|
||||
throw Error("key may not be null if value is not object or array");
|
||||
}
|
||||
throw Error('key may not be null if value is not object or array');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,30 @@
|
||||
import {
|
||||
NgModule,
|
||||
ModuleWithProviders,
|
||||
SkipSelf,
|
||||
Optional,
|
||||
} from '@angular/core';
|
||||
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
|
||||
import { Configuration } from './configuration';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
|
||||
|
||||
@NgModule({
|
||||
imports: [],
|
||||
imports: [],
|
||||
declarations: [],
|
||||
exports: [],
|
||||
providers: [],
|
||||
exports: [],
|
||||
providers: []
|
||||
})
|
||||
export class ApiModule {
|
||||
public static forRoot(
|
||||
configurationFactory: () => Configuration,
|
||||
): ModuleWithProviders<ApiModule> {
|
||||
return {
|
||||
ngModule: ApiModule,
|
||||
providers: [{ provide: Configuration, useFactory: configurationFactory }],
|
||||
};
|
||||
}
|
||||
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
|
||||
return {
|
||||
ngModule: ApiModule,
|
||||
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
|
||||
};
|
||||
}
|
||||
|
||||
constructor(
|
||||
@Optional() @SkipSelf() parentModule: ApiModule,
|
||||
@Optional() http: HttpClient,
|
||||
) {
|
||||
if (parentModule) {
|
||||
throw new Error(
|
||||
'ApiModule is already loaded. Import in your base AppModule only.',
|
||||
);
|
||||
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
|
||||
@Optional() http: HttpClient) {
|
||||
if (parentModule) {
|
||||
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
|
||||
}
|
||||
if (!http) {
|
||||
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
|
||||
'See also https://github.com/angular/angular/issues/20575');
|
||||
}
|
||||
}
|
||||
if (!http) {
|
||||
throw new Error(
|
||||
'You need to import the HttpClientModule in your AppModule! \n' +
|
||||
'See also https://github.com/angular/angular/issues/20575',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
export * from './auth.service';
|
||||
import { AuthService } from './auth.service';
|
||||
export * from './companyConnections.service';
|
||||
import { CompanyConnectionsService } from './companyConnections.service';
|
||||
export * from './funding.service';
|
||||
import { FundingService } from './funding.service';
|
||||
export * from './iNSEAccountService.service';
|
||||
import { INSEAccountServiceService } from './iNSEAccountService.service';
|
||||
export * from './iNSEService.service';
|
||||
import { INSEServiceService } from './iNSEService.service';
|
||||
export * from './institutions.service';
|
||||
import { InstitutionsService } from './institutions.service';
|
||||
export * from './items.service';
|
||||
import { ItemsService } from './items.service';
|
||||
export * from './keywords.service';
|
||||
import { KeywordsService } from './keywords.service';
|
||||
export * from './news.service';
|
||||
import { NewsService } from './news.service';
|
||||
export * from './organization.service';
|
||||
import { OrganizationService } from './organization.service';
|
||||
export * from './patents.service';
|
||||
import { PatentsService } from './patents.service';
|
||||
export * from './personNetwork.service';
|
||||
@@ -25,13 +27,14 @@ import { TopicsService } from './topics.service';
|
||||
export * from './works.service';
|
||||
import { WorksService } from './works.service';
|
||||
export const APIS = [
|
||||
AuthService,
|
||||
CompanyConnectionsService,
|
||||
FundingService,
|
||||
INSEAccountServiceService,
|
||||
INSEServiceService,
|
||||
InstitutionsService,
|
||||
ItemsService,
|
||||
KeywordsService,
|
||||
NewsService,
|
||||
OrganizationService,
|
||||
PatentsService,
|
||||
PersonNetworkService,
|
||||
PersonsService,
|
||||
|
||||
@@ -0,0 +1,871 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AccessResponse } from '../model/accessResponse';
|
||||
// @ts-ignore
|
||||
import { AccessToken } from '../model/accessToken';
|
||||
// @ts-ignore
|
||||
import { AccountPage } from '../model/accountPage';
|
||||
// @ts-ignore
|
||||
import { AccountProfile } from '../model/accountProfile';
|
||||
// @ts-ignore
|
||||
import { BodyChangePassword } from '../model/bodyChangePassword';
|
||||
// @ts-ignore
|
||||
import { BodyGetAccessToken } from '../model/bodyGetAccessToken';
|
||||
// @ts-ignore
|
||||
import { BodyLogin } from '../model/bodyLogin';
|
||||
// @ts-ignore
|
||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||
// @ts-ignore
|
||||
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { InseAccountManagementModelOrganizationProfile } from '../model/inseAccountManagementModelOrganizationProfile';
|
||||
// @ts-ignore
|
||||
import { LoginResponse } from '../model/loginResponse';
|
||||
// @ts-ignore
|
||||
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change Password
|
||||
* Change the user\'s password and invalidate existing tokens.
|
||||
* @endpoint post /api/auth/v2/change-password
|
||||
* @param bodyChangePassword
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyChangePassword === null || bodyChangePassword === undefined) {
|
||||
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/change-password`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyChangePassword,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Account
|
||||
* @endpoint post /api/accounts
|
||||
* @param createAccountRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (createAccountRequest === null || createAccountRequest === undefined) {
|
||||
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountProfile>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: createAccountRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Account
|
||||
* @endpoint delete /api/accounts/{account_id}
|
||||
* @param accountId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (accountId === null || accountId === undefined) {
|
||||
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Access Token
|
||||
* Retrieve an access token for the authenticated user.
|
||||
* @endpoint post /api/auth/v2/access
|
||||
* @param bodyGetAccessToken
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
||||
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/access`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccessResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyGetAccessToken,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Current Account
|
||||
* @endpoint get /api/accounts/me
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/me`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountProfile>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Health Check
|
||||
* @endpoint get /api/auth/v2/health
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/health`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List Organizations
|
||||
* @endpoint get /api/accounts/organizations
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
|
||||
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<InseAccountManagementModelOrganizationProfile>>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List Accounts
|
||||
* @endpoint get /api/accounts
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param offset
|
||||
* @param search
|
||||
* @param organizationId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>offset, 'offset');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>search, 'search');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>organizationId, 'organization_id');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Login with One-Time Key
|
||||
* Login using a one-time key (OTK) sent to the user\'s email.
|
||||
* @endpoint post /api/auth/v2/login
|
||||
* @param bodyLogin
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<LoginResponse>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<LoginResponse>>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<LoginResponse>>;
|
||||
public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyLogin === null || bodyLogin === undefined) {
|
||||
throw new Error('Required parameter bodyLogin was null or undefined when calling login.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/login`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<LoginResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyLogin,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout
|
||||
* Logout the authenticated user.
|
||||
* @endpoint post /api/auth/v2/logout
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/logout`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Access Token
|
||||
* Refresh the access token using a valid refresh token.
|
||||
* @endpoint post /api/auth/v2/refresh
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
|
||||
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/refresh`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccessToken>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request One-Time Key
|
||||
* Request a one-time key (OTK) for authentication using email and password.
|
||||
* @endpoint post /api/auth/v2/request-otk
|
||||
* @param bodyRequestOtk
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/request-otk`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyRequestOtk,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Account
|
||||
* @endpoint put /api/accounts/{account_id}
|
||||
* @param accountId
|
||||
* @param updateAccountRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (accountId === null || accountId === undefined) {
|
||||
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
|
||||
}
|
||||
if (updateAccountRequest === null || updateAccountRequest === undefined) {
|
||||
throw new Error('Required parameter updateAccountRequest was null or undefined when calling updateAccount.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountProfile>('put', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: updateAccountRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse';
|
||||
@@ -28,121 +22,74 @@ import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CompanyConnectionsService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get possible company connections by OpenAlex author ID.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getCompanyConnectionsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<CompanyConnectionsResponse>;
|
||||
public getCompanyConnectionsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<CompanyConnectionsResponse>>;
|
||||
public getCompanyConnectionsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<CompanyConnectionsResponse>>;
|
||||
public getCompanyConnectionsByAuthor(
|
||||
authorId: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
/**
|
||||
* Get possible company connections by OpenAlex author ID.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CompanyConnectionsResponse>;
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CompanyConnectionsResponse>>;
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CompanyConnectionsResponse>>;
|
||||
public getCompanyConnectionsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<CompanyConnectionsResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<CompanyConnectionsResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse';
|
||||
@@ -30,246 +24,138 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class FundingService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get funding organizations by author.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/funders
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getFundersByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<FundersByAuthorResponse>;
|
||||
public getFundersByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<FundersByAuthorResponse>>;
|
||||
public getFundersByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<FundersByAuthorResponse>>;
|
||||
public getFundersByAuthor(
|
||||
authorId: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter authorId was null or undefined when calling getFundersByAuthor.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
/**
|
||||
* Get funding organizations by author.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/funders
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<FundersByAuthorResponse>;
|
||||
public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<FundersByAuthorResponse>>;
|
||||
public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<FundersByAuthorResponse>>;
|
||||
public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<FundersByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Get funded publications by author.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/publications
|
||||
* @param authorId
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PublicationsByAuthorResponse>;
|
||||
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PublicationsByAuthorResponse>>;
|
||||
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PublicationsByAuthorResponse>>;
|
||||
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PublicationsByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/funders`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<FundersByAuthorResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get funded publications by author.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/publications
|
||||
* @param authorId
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPublicationsByAuthor(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PublicationsByAuthorResponse>;
|
||||
public getPublicationsByAuthor(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PublicationsByAuthorResponse>>;
|
||||
public getPublicationsByAuthor(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PublicationsByAuthorResponse>>;
|
||||
public getPublicationsByAuthor(
|
||||
authorId: string,
|
||||
page?: number,
|
||||
pageSize?: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter authorId was null or undefined when calling getPublicationsByAuthor.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageSize,
|
||||
'page_size',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/publications`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PublicationsByAuthorResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,457 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AccessGrant } from '../model/accessGrant';
|
||||
// @ts-ignore
|
||||
import { BodyCreateUser } from '../model/bodyCreateUser';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { IdentityGrant } from '../model/identityGrant';
|
||||
// @ts-ignore
|
||||
import { User } from '../model/user';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class INSEAccountServiceService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create User
|
||||
* @endpoint post /inse-account/create
|
||||
* @param bodyCreateUser
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createUser(
|
||||
bodyCreateUser: BodyCreateUser,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<User>;
|
||||
public createUser(
|
||||
bodyCreateUser: BodyCreateUser,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<User>>;
|
||||
public createUser(
|
||||
bodyCreateUser: BodyCreateUser,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<User>>;
|
||||
public createUser(
|
||||
bodyCreateUser: BodyCreateUser,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (bodyCreateUser === null || bodyCreateUser === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter bodyCreateUser was null or undefined when calling createUser.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/inse-account/create`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<User>('post', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
body: bodyCreateUser,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Access Grant
|
||||
* @endpoint post /inse-account/auth/access
|
||||
* @param secret
|
||||
* @param account
|
||||
* @param organization
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAccessGrant(
|
||||
secret: string,
|
||||
account: number,
|
||||
organization: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<AccessGrant>;
|
||||
public getAccessGrant(
|
||||
secret: string,
|
||||
account: number,
|
||||
organization: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<AccessGrant>>;
|
||||
public getAccessGrant(
|
||||
secret: string,
|
||||
account: number,
|
||||
organization: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<AccessGrant>>;
|
||||
public getAccessGrant(
|
||||
secret: string,
|
||||
account: number,
|
||||
organization: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (secret === null || secret === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter secret was null or undefined when calling getAccessGrant.',
|
||||
);
|
||||
}
|
||||
if (account === null || account === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter account was null or undefined when calling getAccessGrant.',
|
||||
);
|
||||
}
|
||||
if (organization === null || organization === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter organization was null or undefined when calling getAccessGrant.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/x-www-form-urlencoded'];
|
||||
|
||||
const canConsumeForm = this.canConsumeForm(consumes);
|
||||
|
||||
let localVarFormParams: { append(param: string, value: any): any };
|
||||
let localVarUseForm = false;
|
||||
let localVarConvertFormParamsToString = false;
|
||||
if (localVarUseForm) {
|
||||
localVarFormParams = new FormData();
|
||||
} else {
|
||||
localVarFormParams = new HttpParams({ encoder: this.encoder });
|
||||
}
|
||||
|
||||
if (secret !== undefined) {
|
||||
localVarFormParams =
|
||||
(localVarFormParams.append('secret', <any>secret) as any) ||
|
||||
localVarFormParams;
|
||||
}
|
||||
if (account !== undefined) {
|
||||
localVarFormParams =
|
||||
(localVarFormParams.append('account', <any>account) as any) ||
|
||||
localVarFormParams;
|
||||
}
|
||||
if (organization !== undefined) {
|
||||
localVarFormParams =
|
||||
(localVarFormParams.append('organization', <any>organization) as any) ||
|
||||
localVarFormParams;
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/inse-account/auth/access`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccessGrant>(
|
||||
'post',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: localVarConvertFormParamsToString
|
||||
? localVarFormParams.toString()
|
||||
: localVarFormParams,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Identity Grant
|
||||
* @endpoint post /inse-account/auth/id
|
||||
* @param username
|
||||
* @param password
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getIdentityGrant(
|
||||
username: string,
|
||||
password: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<IdentityGrant>;
|
||||
public getIdentityGrant(
|
||||
username: string,
|
||||
password: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<IdentityGrant>>;
|
||||
public getIdentityGrant(
|
||||
username: string,
|
||||
password: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<IdentityGrant>>;
|
||||
public getIdentityGrant(
|
||||
username: string,
|
||||
password: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (username === null || username === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter username was null or undefined when calling getIdentityGrant.',
|
||||
);
|
||||
}
|
||||
if (password === null || password === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter password was null or undefined when calling getIdentityGrant.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/x-www-form-urlencoded'];
|
||||
|
||||
const canConsumeForm = this.canConsumeForm(consumes);
|
||||
|
||||
let localVarFormParams: { append(param: string, value: any): any };
|
||||
let localVarUseForm = false;
|
||||
let localVarConvertFormParamsToString = false;
|
||||
if (localVarUseForm) {
|
||||
localVarFormParams = new FormData();
|
||||
} else {
|
||||
localVarFormParams = new HttpParams({ encoder: this.encoder });
|
||||
}
|
||||
|
||||
if (username !== undefined) {
|
||||
localVarFormParams =
|
||||
(localVarFormParams.append('username', <any>username) as any) ||
|
||||
localVarFormParams;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
localVarFormParams =
|
||||
(localVarFormParams.append('password', <any>password) as any) ||
|
||||
localVarFormParams;
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/inse-account/auth/id`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<IdentityGrant>(
|
||||
'post',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: localVarConvertFormParamsToString
|
||||
? localVarFormParams.toString()
|
||||
: localVarFormParams,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,12 +24,6 @@ import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { Item } from '../model/item';
|
||||
// @ts-ignore
|
||||
import { ItemCreate } from '../model/itemCreate';
|
||||
// @ts-ignore
|
||||
import { ItemPage } from '../model/itemPage';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
@@ -48,124 +42,6 @@ export class INSEServiceService extends BaseService {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new item.
|
||||
* @endpoint post /api/inse-service/items
|
||||
* @param itemCreate
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Item>;
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Item>>;
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Item>>;
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter itemCreate was null or undefined when calling addItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('post', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the topic hierarchy cache.
|
||||
* @endpoint get /api/inse-service/topics/cache
|
||||
@@ -394,344 +270,6 @@ export class INSEServiceService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the item with the id.
|
||||
* @endpoint delete /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any>;
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<any>>;
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<any>>;
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling deleteItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>(
|
||||
'delete',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the item with the id.
|
||||
* @endpoint get /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getItem(
|
||||
id: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Item>;
|
||||
public getItem(
|
||||
id: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Item>>;
|
||||
public getItem(
|
||||
id: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Item>>;
|
||||
public getItem(
|
||||
id: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling getItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('get', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of items.
|
||||
* @endpoint get /api/inse-service/items
|
||||
* @param pageOffset The page offset.
|
||||
* @param pageSize The page size.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<ItemPage>;
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<ItemPage>>;
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<ItemPage>>;
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageOffset,
|
||||
'pageOffset',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageSize,
|
||||
'pageSize',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<ItemPage>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
|
||||
* @endpoint get /api/inse-service/topics/hierarchy
|
||||
@@ -822,132 +360,4 @@ export class INSEServiceService extends BaseService {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the item with the id.
|
||||
* @endpoint put /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param itemCreate
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Item>;
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Item>>;
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Item>>;
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling updateItem.',
|
||||
);
|
||||
}
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter itemCreate was null or undefined when calling updateItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('put', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,634 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { Item } from '../model/item';
|
||||
// @ts-ignore
|
||||
import { ItemCreate } from '../model/itemCreate';
|
||||
// @ts-ignore
|
||||
import { ItemPage } from '../model/itemPage';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class ItemsService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new item.
|
||||
* @endpoint post /api/inse-service/items
|
||||
* @param itemCreate
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Item>;
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Item>>;
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Item>>;
|
||||
public addItem(
|
||||
itemCreate: ItemCreate,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter itemCreate was null or undefined when calling addItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('post', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the item with the id.
|
||||
* @endpoint delete /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any>;
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<any>>;
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<any>>;
|
||||
public deleteItem(
|
||||
id: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling deleteItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>(
|
||||
'delete',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the item with the id.
|
||||
* @endpoint get /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getItem(
|
||||
id: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Item>;
|
||||
public getItem(
|
||||
id: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Item>>;
|
||||
public getItem(
|
||||
id: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Item>>;
|
||||
public getItem(
|
||||
id: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling getItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('get', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a page of items.
|
||||
* @endpoint get /api/inse-service/items
|
||||
* @param pageOffset The page offset.
|
||||
* @param pageSize The page size.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<ItemPage>;
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<ItemPage>>;
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<ItemPage>>;
|
||||
public getItems(
|
||||
pageOffset?: number,
|
||||
pageSize?: number,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageOffset,
|
||||
'pageOffset',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageSize,
|
||||
'pageSize',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<ItemPage>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the item with the id.
|
||||
* @endpoint put /api/inse-service/items/{id}
|
||||
* @param id The item id.
|
||||
* @param itemCreate
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Item>;
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Item>>;
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Item>>;
|
||||
public updateItem(
|
||||
id: number,
|
||||
itemCreate: ItemCreate,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling updateItem.',
|
||||
);
|
||||
}
|
||||
if (itemCreate === null || itemCreate === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter itemCreate was null or undefined when calling updateItem.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (bearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'bearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = ['application/json'];
|
||||
const httpContentTypeSelected: string | undefined =
|
||||
this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Content-Type',
|
||||
httpContentTypeSelected,
|
||||
);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/items/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Item>('put', `${basePath}${localVarPath}`, {
|
||||
context: localVarHttpContext,
|
||||
body: itemCreate,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { KeywordsRequest } from '../model/keywordsRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class KeywordsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts keywords from text.
|
||||
* @endpoint post /api/inse-service/keywords/extract
|
||||
* @param keywordsRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ExtractedKeywordsResponse>;
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ExtractedKeywordsResponse>>;
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ExtractedKeywordsResponse>>;
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (keywordsRequest === null || keywordsRequest === undefined) {
|
||||
throw new Error('Required parameter keywordsRequest was null or undefined when calling extractKeywords.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/keywords/extract`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<ExtractedKeywordsResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: keywordsRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+533
-1003
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,310 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { InseOrganizationManagementModelOrganizationProfile } from '../model/inseOrganizationManagementModelOrganizationProfile';
|
||||
// @ts-ignore
|
||||
import { OrganizationPage } from '../model/organizationPage';
|
||||
// @ts-ignore
|
||||
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class OrganizationService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Organization
|
||||
* @endpoint post /api/organizations
|
||||
* @param createOrganizationRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
|
||||
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: createOrganizationRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Organization
|
||||
* @endpoint delete /api/organizations/{organization_id}
|
||||
* @param organizationId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteOrganisation(organizationId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Organizations
|
||||
* @endpoint get /api/organizations
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param offset
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>offset, 'offset');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<OrganizationPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Organization
|
||||
* @endpoint put /api/organizations/{organization_id}
|
||||
* @param organizationId
|
||||
* @param updateOrganizationRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (organizationId === null || organizationId === undefined) {
|
||||
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
|
||||
}
|
||||
if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) {
|
||||
throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('put', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: updateOrganizationRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user