2020-07-05 21:35:56 +00:00
|
|
|
# Copyright (C) 2020 by Maike <maike@systemli.org>
|
2020-07-15 21:50:24 +00:00
|
|
|
# Copyright (C) 2020 by Cathy Hu <cathy.hu@fau.de>
|
|
|
|
# Copyright (C) 2020 by Thomas Lindner <tom@dl6tom.de>
|
2020-09-28 22:39:32 +00:00
|
|
|
# Copyright (C) 2020 by Martin Rey <martin.rey@mailbox.org>
|
2020-07-05 21:35:56 +00:00
|
|
|
#
|
|
|
|
# SPDX-License-Identifier: 0BSD
|
|
|
|
|
2020-10-13 08:35:20 +00:00
|
|
|
from logging import getLogger
|
|
|
|
from os import urandom
|
|
|
|
from smtplib import SMTPException
|
|
|
|
from sqlite3 import IntegrityError
|
|
|
|
|
2020-07-15 21:50:24 +00:00
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
2020-10-13 08:35:20 +00:00
|
|
|
from nacl import exceptions
|
|
|
|
from ormantic.exceptions import NoMatch
|
|
|
|
from pydantic import BaseModel, validator
|
|
|
|
|
2020-07-16 12:29:57 +00:00
|
|
|
from kibicara import email
|
2020-10-13 08:35:20 +00:00
|
|
|
from kibicara.config import config
|
|
|
|
from kibicara.platformapi import Message
|
2020-07-05 21:35:56 +00:00
|
|
|
from kibicara.platforms.email.bot import spawner
|
2020-07-06 18:51:07 +00:00
|
|
|
from kibicara.platforms.email.model import Email, EmailSubscribers
|
2020-07-15 21:50:24 +00:00
|
|
|
from kibicara.webapi.admin import from_token, to_token
|
2020-07-09 01:10:37 +00:00
|
|
|
from kibicara.webapi.hoods import get_hood, get_hood_unauthorized
|
2020-07-07 13:08:18 +00:00
|
|
|
|
|
|
|
logger = getLogger(__name__)
|
2020-07-05 21:35:56 +00:00
|
|
|
|
|
|
|
|
2020-07-15 21:50:24 +00:00
|
|
|
class BodyEmail(BaseModel):
|
|
|
|
name: str
|
|
|
|
|
2020-07-18 11:53:11 +00:00
|
|
|
@validator('name')
|
|
|
|
def valid_prefix(cls, value):
|
|
|
|
if not value.startswith('kibicara-'):
|
|
|
|
raise ValueError('Recipient address didn\'t start with kibicara-')
|
|
|
|
return value
|
|
|
|
|
2020-07-15 21:50:24 +00:00
|
|
|
|
2020-09-03 15:37:03 +00:00
|
|
|
class BodyEmailPublic(BaseModel):
|
|
|
|
name: str
|
|
|
|
|
|
|
|
|
2020-07-05 21:35:56 +00:00
|
|
|
class BodyMessage(BaseModel):
|
2020-10-13 09:38:33 +00:00
|
|
|
"""This model shows which values are supplied by the MDA listener script."""
|
2020-07-06 19:26:32 +00:00
|
|
|
|
2020-07-05 21:35:56 +00:00
|
|
|
text: str
|
|
|
|
secret: str
|
|
|
|
|
|
|
|
|
2020-07-15 21:50:24 +00:00
|
|
|
class BodySubscriber(BaseModel):
|
2020-10-13 09:38:33 +00:00
|
|
|
"""This model holds the email address of a fresh subscriber."""
|
2020-07-06 19:26:32 +00:00
|
|
|
|
2020-07-06 14:33:07 +00:00
|
|
|
email: str
|
|
|
|
|
|
|
|
|
2020-07-15 21:50:24 +00:00
|
|
|
async def get_email(email_id: int, hood=Depends(get_hood)):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Get Email row by hood.
|
2020-10-13 09:38:33 +00:00
|
|
|
|
2020-07-11 03:12:29 +00:00
|
|
|
You can specify an email_id to nail it down, but it works without as well.
|
|
|
|
|
|
|
|
:param hood: Hood the Email bot belongs to.
|
|
|
|
:return: Email row of the found email bot.
|
|
|
|
"""
|
2020-07-07 13:08:18 +00:00
|
|
|
try:
|
2020-07-15 21:50:24 +00:00
|
|
|
return await Email.objects.get(id=email_id, hood=hood)
|
|
|
|
except NoMatch:
|
|
|
|
return HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
|
|
|
|
|
|
|
|
|
|
|
async def get_subscriber(subscriber_id: int, hood=Depends(get_hood)):
|
|
|
|
try:
|
2020-07-17 17:59:25 +00:00
|
|
|
return await EmailSubscribers.objects.get(id=subscriber_id, hood=hood)
|
2020-07-07 13:08:18 +00:00
|
|
|
except NoMatch:
|
2020-07-07 13:28:51 +00:00
|
|
|
return HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
2020-07-07 13:08:18 +00:00
|
|
|
|
|
|
|
|
2020-07-11 03:12:29 +00:00
|
|
|
# registers the routes, gets imported in /kibicara/webapi/__init__.py
|
2020-07-06 19:53:48 +00:00
|
|
|
router = APIRouter()
|
2020-07-05 21:35:56 +00:00
|
|
|
|
|
|
|
|
2020-09-03 15:37:03 +00:00
|
|
|
@router.get(
|
|
|
|
'/public',
|
|
|
|
# TODO response_model
|
|
|
|
operation_id='get_emails_public',
|
|
|
|
)
|
|
|
|
async def email_read_all_public(hood=Depends(get_hood_unauthorized)):
|
|
|
|
if hood.email_enabled:
|
|
|
|
emails = await Email.objects.filter(hood=hood).all()
|
|
|
|
return [BodyEmailPublic(name=email.name) for email in emails]
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.get(
|
|
|
|
'/',
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='get_emails',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def email_read_all(hood=Depends(get_hood)):
|
2020-09-06 17:11:18 +00:00
|
|
|
return await Email.objects.filter(hood=hood).select_related('hood').all()
|
2020-07-15 21:50:24 +00:00
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.post(
|
|
|
|
'/',
|
|
|
|
status_code=status.HTTP_201_CREATED,
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='create_email',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def email_create(values: BodyEmail, response: Response, hood=Depends(get_hood)):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Create an Email bot. Call this when creating a hood.
|
2020-07-06 18:51:07 +00:00
|
|
|
|
2020-07-11 03:12:29 +00:00
|
|
|
:param hood: Hood row of the hood the Email bot is supposed to belong to.
|
2020-07-06 18:51:07 +00:00
|
|
|
:return: Email row of the new email bot.
|
|
|
|
"""
|
2020-07-05 21:35:56 +00:00
|
|
|
try:
|
2020-07-15 21:50:24 +00:00
|
|
|
email = await Email.objects.create(
|
|
|
|
hood=hood, secret=urandom(32).hex(), **values.__dict__
|
|
|
|
)
|
2020-09-28 22:39:32 +00:00
|
|
|
response.headers['Location'] = str(hood.id)
|
2020-07-15 21:50:24 +00:00
|
|
|
return email
|
2020-07-05 21:35:56 +00:00
|
|
|
except IntegrityError:
|
|
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
|
2020-07-06 15:57:24 +00:00
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.get(
|
|
|
|
'/status',
|
|
|
|
status_code=status.HTTP_200_OK,
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='status_email',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-18 11:53:11 +00:00
|
|
|
async def email_status(hood=Depends(get_hood)):
|
|
|
|
return {'status': spawner.get(hood).status.name}
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.post(
|
|
|
|
'/start',
|
|
|
|
status_code=status.HTTP_200_OK,
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='start_email',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-18 11:53:11 +00:00
|
|
|
async def email_start(hood=Depends(get_hood)):
|
|
|
|
await hood.update(email_enabled=True)
|
|
|
|
spawner.get(hood).start()
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.post(
|
|
|
|
'/stop',
|
|
|
|
status_code=status.HTTP_200_OK,
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='stop_email',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-18 11:53:11 +00:00
|
|
|
async def email_stop(hood=Depends(get_hood)):
|
|
|
|
await hood.update(email_enabled=False)
|
|
|
|
spawner.get(hood).stop()
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.get(
|
|
|
|
'/{email_id}',
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='get_email',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def email_read(email=Depends(get_email)):
|
|
|
|
return email
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.delete(
|
2020-07-25 19:46:39 +00:00
|
|
|
'/{email_id}', status_code=status.HTTP_204_NO_CONTENT, operation_id='delete_email'
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def email_delete(email=Depends(get_email)):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Delete an Email bot.
|
2020-10-13 09:38:33 +00:00
|
|
|
|
2020-07-15 21:50:24 +00:00
|
|
|
Stops and deletes the Email bot.
|
2020-07-06 18:51:07 +00:00
|
|
|
|
|
|
|
:param hood: Hood the Email bot belongs to.
|
|
|
|
"""
|
2020-07-15 21:50:24 +00:00
|
|
|
await email.delete()
|
2020-09-11 00:58:39 +00:00
|
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
2020-07-05 21:35:56 +00:00
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.post(
|
|
|
|
'/subscribe/',
|
|
|
|
status_code=status.HTTP_202_ACCEPTED,
|
|
|
|
operation_id='subscribe',
|
|
|
|
response_model=BaseModel,
|
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def email_subscribe(
|
|
|
|
subscriber: BodySubscriber, hood=Depends(get_hood_unauthorized)
|
|
|
|
):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Send a confirmation mail to subscribe to messages via email.
|
2020-07-06 18:51:07 +00:00
|
|
|
|
|
|
|
:param subscriber: Subscriber object, holds the email address.
|
|
|
|
:param hood: Hood the Email bot belongs to.
|
|
|
|
:return: Returns status code 200 after sending confirmation email.
|
|
|
|
"""
|
2020-07-15 21:50:24 +00:00
|
|
|
token = to_token(hood=hood.id, email=subscriber.email)
|
2020-09-28 22:39:32 +00:00
|
|
|
confirm_link = '{0}/hoods/{1}/email-confirm?token={2}'.format(
|
2020-09-06 21:06:52 +00:00
|
|
|
config['frontend_url'],
|
2020-07-15 21:50:24 +00:00
|
|
|
hood.id,
|
|
|
|
token,
|
2020-07-06 17:14:12 +00:00
|
|
|
)
|
2020-07-07 13:28:51 +00:00
|
|
|
try:
|
2020-09-11 16:40:35 +00:00
|
|
|
subs = await EmailSubscribers.objects.filter(email=subscriber.email).all()
|
|
|
|
if subs:
|
|
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
|
2020-07-16 12:29:57 +00:00
|
|
|
email.send_email(
|
2020-07-07 13:28:51 +00:00
|
|
|
subscriber.email,
|
2020-10-13 08:12:35 +00:00
|
|
|
'Subscribe to Kibicara {0}'.format(hood.name),
|
|
|
|
body='To confirm your subscription, follow this link: {0}'.format(
|
|
|
|
confirm_link
|
|
|
|
),
|
2020-07-07 13:28:51 +00:00
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
return {}
|
2020-07-09 01:10:37 +00:00
|
|
|
except ConnectionRefusedError:
|
|
|
|
logger.info(token)
|
2020-10-13 08:12:35 +00:00
|
|
|
logger.error('Sending subscription confirmation email failed.', exc_info=True)
|
2020-07-09 01:10:37 +00:00
|
|
|
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY)
|
|
|
|
except SMTPException:
|
|
|
|
logger.info(token)
|
2020-10-13 08:12:35 +00:00
|
|
|
logger.error('Sending subscription confirmation email failed.', exc_info=True)
|
2020-07-07 13:28:51 +00:00
|
|
|
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY)
|
2020-07-06 14:33:07 +00:00
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.post(
|
|
|
|
'/subscribe/confirm/{token}',
|
|
|
|
status_code=status.HTTP_201_CREATED,
|
|
|
|
operation_id='confirm_subscriber',
|
|
|
|
response_model=BaseModel,
|
|
|
|
)
|
2020-07-09 01:10:37 +00:00
|
|
|
async def email_subscribe_confirm(token, hood=Depends(get_hood_unauthorized)):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Confirm a new subscriber and add them to the database.
|
2020-07-06 18:51:07 +00:00
|
|
|
|
|
|
|
:param token: encrypted JSON token, holds the email of the subscriber.
|
|
|
|
:param hood: Hood the Email bot belongs to.
|
|
|
|
:return: Returns status code 200 after adding the subscriber to the database.
|
|
|
|
"""
|
2020-07-07 13:08:18 +00:00
|
|
|
payload = from_token(token)
|
2020-07-15 21:50:24 +00:00
|
|
|
# If token.hood and url.hood are different, raise an error:
|
|
|
|
if hood.id is not payload['hood']:
|
|
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
|
2020-07-06 14:33:07 +00:00
|
|
|
try:
|
2020-07-07 13:08:18 +00:00
|
|
|
await EmailSubscribers.objects.create(hood=hood.id, email=payload['email'])
|
2020-07-15 21:50:24 +00:00
|
|
|
return {}
|
2020-07-06 14:33:07 +00:00
|
|
|
except IntegrityError:
|
|
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.delete(
|
|
|
|
'/unsubscribe/{token}',
|
|
|
|
status_code=status.HTTP_204_NO_CONTENT,
|
|
|
|
operation_id='unsubscribe',
|
|
|
|
)
|
2020-07-09 01:10:37 +00:00
|
|
|
async def email_unsubscribe(token, hood=Depends(get_hood_unauthorized)):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Remove a subscriber from the database when they click on an unsubscribe link.
|
2020-07-06 18:51:07 +00:00
|
|
|
|
|
|
|
:param token: encrypted JSON token, holds subscriber email + hood.id.
|
|
|
|
:param hood: Hood the Email bot belongs to.
|
|
|
|
"""
|
2020-09-06 21:06:52 +00:00
|
|
|
try:
|
2020-10-13 08:12:35 +00:00
|
|
|
logger.warning('token is: {0}'.format(token))
|
2020-09-06 21:06:52 +00:00
|
|
|
payload = from_token(token)
|
|
|
|
# If token.hood and url.hood are different, raise an error:
|
|
|
|
if hood.id is not payload['hood']:
|
|
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
|
|
|
|
subscriber = await EmailSubscribers.objects.filter(
|
|
|
|
hood=payload['hood'], email=payload['email']
|
|
|
|
).get()
|
|
|
|
await subscriber.delete()
|
2020-09-11 00:58:39 +00:00
|
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
2020-09-06 21:06:52 +00:00
|
|
|
except NoMatch:
|
2020-09-11 21:33:37 +00:00
|
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
2020-09-06 21:06:52 +00:00
|
|
|
except exceptions.CryptoError:
|
2020-09-11 21:33:37 +00:00
|
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
|
2020-07-15 21:50:24 +00:00
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.get(
|
|
|
|
'/subscribers/',
|
|
|
|
# TODO response_model
|
|
|
|
operation_id='get_subscribers',
|
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def subscribers_read_all(hood=Depends(get_hood)):
|
|
|
|
return await EmailSubscribers.objects.filter(hood=hood).all()
|
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.get(
|
|
|
|
'/subscribers/{subscriber_id}',
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='get_subscriber',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-15 21:50:24 +00:00
|
|
|
async def subscribers_read(subscriber=Depends(get_subscriber)):
|
|
|
|
return subscriber
|
2020-07-05 21:35:56 +00:00
|
|
|
|
|
|
|
|
2020-07-25 11:38:10 +00:00
|
|
|
@router.post(
|
|
|
|
'/messages/',
|
|
|
|
status_code=status.HTTP_201_CREATED,
|
|
|
|
# TODO response_model
|
2020-07-25 19:46:39 +00:00
|
|
|
operation_id='send_message',
|
2020-07-25 11:38:10 +00:00
|
|
|
)
|
2020-07-09 01:10:37 +00:00
|
|
|
async def email_message_create(
|
2020-07-13 01:21:11 +00:00
|
|
|
message: BodyMessage, hood=Depends(get_hood_unauthorized)
|
2020-07-09 01:10:37 +00:00
|
|
|
):
|
2020-09-04 23:39:24 +00:00
|
|
|
"""Receive a message from the MDA and pass it to the censor.
|
2020-07-06 18:51:07 +00:00
|
|
|
|
|
|
|
:param message: BodyMessage object, holds the message.
|
2020-07-06 19:53:48 +00:00
|
|
|
:param hood: Hood the Email bot belongs to.
|
2020-07-06 18:51:07 +00:00
|
|
|
:return: returns status code 201 if the message is accepted by the censor.
|
|
|
|
"""
|
2020-07-17 17:59:25 +00:00
|
|
|
for receiver in await Email.objects.filter(hood=hood).all():
|
|
|
|
if message.secret == receiver.secret:
|
2020-07-15 21:50:24 +00:00
|
|
|
# pass message.text to bot.py
|
|
|
|
if await spawner.get(hood).publish(Message(message.text)):
|
2020-10-13 08:12:35 +00:00
|
|
|
logger.warning('Message was accepted: {0}'.format(message.text))
|
2020-07-15 21:50:24 +00:00
|
|
|
return {}
|
|
|
|
else:
|
2020-10-13 08:13:06 +00:00
|
|
|
logger.warning('Message wasn\'t accepted: {0}'.format(message.text))
|
2020-07-15 21:50:24 +00:00
|
|
|
raise HTTPException(
|
|
|
|
status_code=status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
|
|
|
|
)
|
|
|
|
logger.warning(
|
2020-10-13 08:12:35 +00:00
|
|
|
'Someone is trying to submit an email without the correct API secret'
|
2020-07-15 21:50:24 +00:00
|
|
|
)
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
|