-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
214 lines (179 loc) · 6.07 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# Copyright 2024 Artem Shurshilov
# Apache License Version 2.0
import asyncio
import logging
import sys
from logging.handlers import RotatingFileHandler
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.staticfiles import StaticFiles
from starlette.status import (
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED,
HTTP_422_UNPROCESSABLE_ENTITY,
HTTP_500_INTERNAL_SERVER_ERROR,
)
from const import VERSION
from dependencies.db import get_db_connector
from exceptions.exceptions import AuthError, BusinessError
from routers.checkup import router as checkup
from routers.history_calls import router as history_calls
from routers.history_events import router as history_events
from routers.numbers import router as numbers
from routers.recordings import router as recordings
from schemas.config_schema import Config
from services.ami import Ami
# from services.ami_new import Ami as AmiNew
from services.ari import Ari
from services.websocket import WebsocketEvents
log_file_handler = RotatingFileHandler(
filename="asterisk_agent.log",
mode="a",
maxBytes=5 * 1024 * 1024,
backupCount=2,
encoding=None,
)
logging.basicConfig(
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
level="DEBUG",
handlers=[log_file_handler, logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger("asterisk_agent")
app = FastAPI(
title="Asterisk Agent",
description="Light web server for calls history and webhook features",
version=VERSION,
docs_url=None,
redoc_url=None,
responses={
HTTP_400_BAD_REQUEST: {
"description": "Business Logic Error",
},
HTTP_401_UNAUTHORIZED: {
"description": "Unauthorized",
},
HTTP_422_UNPROCESSABLE_ENTITY: {"description": "Validation Error"},
HTTP_500_INTERNAL_SERVER_ERROR: {
"description": "Internal Server Error",
},
},
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/docs", include_in_schema=False)
async def swagger_ui_html():
"""Swagger ui docs from static (local) files not CDN
Returns:
HTML swagger ui
"""
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
"""Redoc ui docs from static (local) files not CDN
Returns:
HTML redoc ui
"""
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="/static/redoc.standalone.js",
)
# статичная папка для картинок документации
app.mount(
"/static",
StaticFiles(directory="static"),
name="static",
)
app.include_router(checkup)
app.include_router(recordings)
app.include_router(history_events)
app.include_router(history_calls)
app.include_router(numbers)
@app.exception_handler(BusinessError)
async def catch_exception_buisness(req: Request, exc: BusinessError):
log.info("Business error %s", exc)
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail=exc.detail,
)
@app.exception_handler(AuthError)
async def catch_exception_auth(req: Request, exc: AuthError):
log.info("Auth error %s", exc)
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail=exc.detail,
)
@app.exception_handler(Exception)
async def catch_exception_internal(req: Request, exc: Exception):
log.exception("Internal server error %s", exc)
raise HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
async def producer_webhook(config: Config, timeout: int = 30) -> None:
"""Producer send events to cusomer webhook from config file"""
while True:
try:
if not getattr(app.state, "websocket_client", None):
websocket_client = WebsocketEvents(
ari_config=config.ari_config,
api_key=config.api_key,
api_key_base64=config.api_key_base64,
webhook_url=f"{config.webhook_url}",
timeout=timeout,
)
app.state.websocket_client = websocket_client
await websocket_client.start_consumer()
except asyncio.CancelledError:
break
except Exception as exc:
log.exception("Unknown producer_webhook error: %s", exc)
finally:
await asyncio.sleep(timeout)
@app.on_event("startup")
async def start() -> None:
"""Create backgrond task and init app"""
# read and validate config file
config = Config() # type: ignore
ari = Ari(api_key=config.api_key, ari_url=str(config.ari_url))
# ami = AmiNew(
# ami_config=config.ami_config,
# api_key_base64=config.api_key_base64,
# webhook_url=str(config.webhook_url),
# )
ami = Ami(
ami_config=config.ami_config,
api_key_base64=config.api_key_base64,
webhook_url=str(config.webhook_url),
)
app.state.background_tasks = []
app.state.config = config
app.state.ari = ari
app.state.ami = ami
app.state.connector_database = get_db_connector(config)
if config.db_check_cdr_enable:
log.info("start check cdr version...")
try:
await app.state.connector_database.check_cdr_old()
except Exception as exc:
log.exception("Unknown check_cdr_old error: %s", exc)
log.info("end check cdr version")
if config.ami_enable:
asyncio.gather(ami.start_catch_events())
if config.ari_enable:
app.state.background_tasks = [
asyncio.create_task(producer_webhook(config)),
]
@app.on_event("shutdown")
async def shutdown():
for task in app.state.background_tasks:
task.cancel()