JANINE/janine/utils.py

85 lines
2.1 KiB
Python
Raw Normal View History

2020-09-17 16:19:57 +00:00
'''
This file is part of JANINE.
JANINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
JANINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JANINE. If not, see <https://www.gnu.org/licenses/>.
'''
import datetime
import aioxmpp
2020-09-17 17:42:39 +00:00
def make_msg(to, body):
2020-09-17 16:19:57 +00:00
'''
Wrapper for creating a message object to enqueue or send.
'''
msg = aioxmpp.Message(
type_=aioxmpp.MessageType.CHAT,
to=to)
msg.body[None] = body
return msg
2020-09-17 17:42:39 +00:00
def format_time(time_str):
2020-09-17 16:19:57 +00:00
'''
Reformat ISO style time data to a more
readable format.
'''
try:
date = datetime.datetime.fromisoformat(time_str)
except ValueError:
return time_str
return f'{date.day}.{date.month}.{date.year} {date.hour}:{date.minute}'
2020-09-17 18:10:50 +00:00
def format_warning(warning):
2020-09-17 16:19:57 +00:00
'''
Send a warning to all the recipients
'''
# Reformat the message a bit
effective_time = format_time(warning.effective_from)
expiry_time = format_time(warning.expires)
body = f'''*{warning.headline}*
({effective_time} bis {expiry_time})
{warning.description}'''
if warning.instruction:
body = f'''{body}
{warning.instruction}'''
2020-09-17 16:19:57 +00:00
# Smells like script injection, but okay
body = body.replace('<br>', '\n')
body = body.replace('<br/>', '\n')
return body
2020-08-22 13:09:59 +00:00
def find_one(func, array):
'''
Utility function
Return the first element in array for which func returns True.
'''
for e in array:
if func(e):
return e
return None
def find_all(func, array):
'''
Utility function
Return all elements in array for which func returns True.
'''
return [e for e in array if func(e)]