Commit 2e17488e by Oleksandr Barabash

mars hook update

parent 70935e07
......@@ -26,6 +26,7 @@ from bots.exceptions import ConversationNotFound, DataParsingError
from config import AppConfig, COSMOS_CLIENT, TeamsAppConfig, TOKEN_HELPER, \
CosmosDBConfig
from entities.json.admin_user import AdminUser
from entities.json.mars_report import MarsReport
from entities.json.notification import Notification
from entities.json.pa_message import PAMessage
from utils.cosmos_client import ItemNotFound
......@@ -323,6 +324,24 @@ async def v1_pa_authorize(request: Request) -> Response:
return make_response(400, "Bad Request")
async def v1_mars_report(request: Request) -> Response:
""" Finishes the Attachment upload """
# noinspection PyBroadException
try:
channel_id = request.query.get("channelId", "")
if not channel_id:
raise AttributeError("ChannelID is required")
request_json = await request.json()
report = MarsReport.load(request_json, unknown=EXCLUDE)
response = await BOT.handle_mars_report(channel_id, report)
Log.d(TAG, f"v1_mars_report::notification: '{response}'")
return make_response(200, "OK")
except Exception:
Log.e(TAG, "v1_mars_report::error", exc_info=sys.exc_info())
return make_response(400, "Bad Request")
async def init_db_containers():
""" To speed up the process we have to create containers first """
await COSMOS_CLIENT.create_db(CosmosDBConfig.Conversations.DATABASE)
......@@ -375,6 +394,9 @@ async def app_factory(bot):
bot.add_web_app(app)
bot.add_cosmos_client(COSMOS_CLIENT)
# MARSv2
app.router.add_post("/api/mars/v1/hook", v1_mars_report)
return app
......
......@@ -22,16 +22,18 @@ from marshmallow import EXCLUDE
from bots.exceptions import ConversationNotFound
from config import TaskModuleConfig, AppConfig, CLEANER_CLIENT
from entities.json.mars_report import MarsReport
from entities.json.medx import MedX, MXTypes
from entities.json.notification import NotificationCosmos
from entities.json.pa_message import PAMessage
from utils.card_helper import CardHelper
from utils.cosmos_client import CosmosClient, ItemNotFound
from utils.functions import get_i18n
from utils.functions import get_i18n, quote_b64encode_str_safe
from utils.log import Log
log = logging.getLogger()
log = logging.getLogger(__name__)
logger = log
TAG = __name__
......@@ -99,6 +101,14 @@ class TeamsMessagingExtensionsActionPreviewBot(TeamsActivityHandler):
return True
return False
async def handle_mars_report(self, channel_id: str, report: MarsReport) \
-> Future[ResourceResponse]:
""" Handle Mars report """
# 1. Get channel recipients
# 2. Add permissions for the recipients
# 3. Send info into the flow
logger.info("handle_mars_report")
def send_message(self, pa_message: PAMessage) -> Future[ResourceResponse]:
""" Send message as a bot """
io_loop = asyncio.get_event_loop()
......@@ -220,6 +230,15 @@ class TeamsMessagingExtensionsActionPreviewBot(TeamsActivityHandler):
return future
@staticmethod
def generate_url_kwargs(url: str, **kwargs) -> str:
""" Generate URL for the task module """
parsed_url = urlparse(url)
params = dict(parse_qsl(parsed_url.query))
params.update(kwargs)
# noinspection PyProtectedMember
return parsed_url._replace(query=urlencode(params)).geturl()
@staticmethod
def generate_url(url: str, channel_id: str) -> str:
""" Generate URL for the task module """
parsed_url = urlparse(url)
......@@ -393,8 +412,13 @@ class TeamsMessagingExtensionsActionPreviewBot(TeamsActivityHandler):
if message_lower in [cmd_mars.lower(), cmd_upload.lower()]:
header = i18n.t("text_upload_header")
title = i18n.t("text_upload_title")
url = self.generate_url(f"https://{AppConfig.MARS_FQDN}/",
turn_context.activity.conversation.id)
report_url = quote_b64encode_str_safe(self.generate_url(
f"{AppConfig.WEB_APP_NAME}.azurewebsites.net"
f"/api/mars/v1/hook",
turn_context.activity.conversation.id
))
url = self.generate_url_kwargs(f"https://{AppConfig.MARS_FQDN}/",
reportUrl=report_url)
card = CardHelper.load_assets_card("task_card", context=dict(
title=title, header=header, task_type=MXTypes.Task.LINK,
task_url=url
......
......@@ -2,6 +2,7 @@
import uuid
from datetime import datetime
from time import time
from typing import Dict, Any
import marshmallow_dataclass
from marshmallow import pre_load, post_dump, EXCLUDE
......@@ -39,3 +40,9 @@ class CamelCaseMixin:
def get_schema(cls, *args, **kwargs):
""" Get schema """
return marshmallow_dataclass.class_schema(cls)(*args, **kwargs)
@classmethod
def load(cls, data: Dict[str, Any], *args, **kwargs) -> "CamelCaseMixin":
""" load data into the object """
schema = cls.get_schema(*args, **kwargs)
return schema.load(data)
""" PA message to send to Teams """
from dataclasses import dataclass, field
from typing import List
from entities.json.camel_case_mixin import CamelCaseMixin
@dataclass
class MarsReportFile(CamelCaseMixin):
""" Mars Report File Metadata """
file_name: str
content_type: str
size: int
url: str
@dataclass
class MarsReport(CamelCaseMixin):
""" ClientUploadSession Form """
files: List[MarsReportFile] = field(default_factory=list)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment