31 Commits

Author SHA1 Message Date
c2853af6b4 fix: update to new docker build 2024-02-17 17:11:34 +01:00
6b8e517e3c fix: migrate to alpine build 2024-02-17 17:10:02 +01:00
a4a868e899 feat: add docker build 2024-02-17 17:03:23 +01:00
d6a2f8ec15 feat: add loop support for container 2024-02-17 17:03:14 +01:00
7d3c449c16 fix: message title 2024-02-16 19:47:22 +01:00
7f468ba860 feat: add topic query from api 2024-02-16 19:15:04 +01:00
46260edfaa refactor: better method switching & ntfy support 2024-02-16 18:55:15 +01:00
9816036d90 wip: ntfy & smtp 2024-02-16 18:54:42 +01:00
c0561634f5 add: debug & smtp 2024-02-16 14:49:10 +01:00
8cb412c74b refacto: setup new dispatch 2024-02-16 13:57:16 +01:00
df93ee47ab wip: 2024-01-13 03:30:37 +01:00
294847d90a wip: 2024-01-06 14:37:28 +01:00
12d1096d8e fix: use correct prefix for jsonify 2023-08-12 14:12:26 +02:00
cedbf68130 fix: remove os.environ query for SQLITE location 2023-08-12 14:01:07 +02:00
0feb5a69fa feat: simple dispatch status query 2023-08-12 13:44:20 +02:00
5f5c75ada0 fix: fallback on empty owners/groups 2023-08-10 19:52:28 +02:00
f98ce6842f fix: manager pw var name 2023-08-10 19:37:53 +02:00
8ccc6416fd fix: set base_dn 2023-08-10 19:34:02 +02:00
e2ba8e20ee fix: show notification comment in message 2023-08-10 19:20:41 +02:00
1cc93f14b5 remove: obsolete info 2023-08-05 14:41:51 +02:00
2d9bc0b532 change: disable weblink in notification 2023-07-24 18:20:55 +02:00
881cf3134d fix: typo icingaweb_url 2023-07-24 17:59:20 +02:00
be733a05f5 fix: service state field name 2023-07-24 17:45:25 +02:00
6b8ff25de6 feat: icinga message parser 2023-07-24 16:54:57 +02:00
80874c7127 feat: add debug output for unsupported struct 2023-07-24 16:52:32 +02:00
4cf8f866b6 fix: encoding problems and optional contact info 2023-07-21 17:38:15 +02:00
d5901e9cb3 fix: use non-list var correctly 2023-07-21 17:16:37 +02:00
355385b4df fix: user correct attribute from reponse 2023-07-21 17:15:30 +02:00
40e289e20d fix: add phone number and email to reponse 2023-07-21 17:11:44 +02:00
1015991e71 feat: support authentication 2023-07-21 16:51:10 +02:00
6292e745a8 change: set signal cli bin via cmdline 2023-07-21 16:48:30 +02:00
14 changed files with 504 additions and 98 deletions

View File

@@ -29,10 +29,18 @@ jobs:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASS }}
-
name: Build and push signal-event-dispatcher
name: Build and push event-dispatcher
uses: docker/build-push-action@v3
with:
context: .
context: ./server/
platforms: linux/amd64
push: true
tags: "${{ secrets.REGISTRY }}/athq/event-dispatcher:latest"
-
name: Build and push event-dispatcher
uses: docker/build-push-action@v3
with:
context: ./client/
platforms: linux/amd64
push: true
tags: "${{ secrets.REGISTRY }}/athq/event-dispatcher-worker:latest"

2
.gitignore vendored
View File

@@ -1,4 +1,6 @@
*.swp
*.sqlite
sqlite.db
instance/
__pycache__/
signal_targets.txt

View File

@@ -1,25 +0,0 @@
FROM python:3.9-slim-buster
RUN apt update
RUN apt install python3-pip -y
RUN apt install libsasl2-dev python-dev libldap2-dev libssl-dev -y
RUN python3 -m pip install --upgrade pip
RUN apt install curl -y
RUN apt autoremove -y
RUN apt clean
WORKDIR /app
RUN python3 -m pip install waitress
COPY req.txt .
RUN python3 -m pip install --no-cache-dir -r req.txt
# precreate database directory for mount (will otherwise be created at before_first_request)
COPY ./ .
RUN mkdir /app/instance/
EXPOSE 5000/tcp
ENTRYPOINT ["waitress-serve"]
CMD ["--host", "0.0.0.0", "--port", "5000", "--call", "app:createApp" ]

9
client/Dockerfile Normal file
View File

@@ -0,0 +1,9 @@
FROM alpine
WORKDIR /app/
RUN apk --update --no-cache add python3 py3-requests
COPY ./*.py ./
ENTRYPOINT ["python"]
CMD ["dispatch-query.py"]

202
client/dispatch-query.py Executable file
View File

@@ -0,0 +1,202 @@
#!/usr/bin/python3
import sys
import time
import argparse
import subprocess
import os
import requests
import smtphelper
import json
HTTP_NOT_FOUND = 404
DISPATCH_SERVER = None
AUTH = None
def debug_send(uuid, data, fail_it=False):
'''Dummy function to print and ack a dispatch for debugging'''
print(json.dumps(data, indent=2))
if fail_it:
report_failed_dispatch(uuid, "Dummy Error for Debugging")
else:
confirm_dispatch(uuid)
def email_send(dispatch_uuid, email_address, message, smtp_target, smtp_user, smtp_pass):
'''Send message via email'''
subject = "Atlantis Dispatch"
smtphelper.smtp_send(smtp_target, smtp_user, smtp_pass, email_address, subject, message)
report_failed_dispatch(uuid, "Email dispatch not yet implemented")
def ntfy_api_get_topic(ntfy_api_server, ntfy_api_token, username):
'''Get the topic of the user'''
params = {
"user" : username,
"token" : ntfy_api_token,
}
r = requests.get(ntfy_api_server + "/topic", params=params)
if r.status_code != 200:
print(r.text)
return None
else:
print(r.text)
return r.json().get("topic")
def ntfy_send(dispatch_uuid, user_topic, title, message, ntfy_push_target, ntfy_user, ntfy_pass):
'''Send message via NTFY topic'''
if not user_topic:
report_failed_dispatch(dispatch_uuid, "No user topic")
return
try:
# build message #
payload = {
"topic" : user_topic,
"message" : message,
"title" : title or "Atlantis Notify",
#"tags" : [],
"priority" : 4,
#"attach" : None,
"click" : "https://vid.pr0gramm.com/2022/11/06/ed66c8c5a9cd1a3b.mp4",
#"actions" : []
}
# send #
r = requests.post(ntfy_push_target, auth=(ntfy_user, ntfy_pass), json=payload)
print(r.status_code, r.text, payload)
r.raise_for_status()
# talk to dispatch #
confirm_dispatch(dispatch_uuid)
except requests.exceptions.HTTPError as e:
report_failed_dispatch(dispatch_uuid, str(e))
except requests.exceptions.ConnectionError as e:
report_failed_dispatch(dispatch_uuid, str(e))
def report_failed_dispatch(uuid, error):
'''Inform the server that the dispatch has failed'''
payload = [{ "uuid" : uuid, "error" : error }]
response = requests.post(DISPATCH_SERVER + "/report-dispatch-failed", json=payload, auth=AUTH)
if response.status_code not in [200, 204]:
print("Failed to report back failed dispatch for {} ({})".format(
uuid, response.text), file=sys.stderr)
def confirm_dispatch(uuid):
'''Confirm to server that message has been dispatched and can be removed'''
payload = [{ "uuid" : uuid }]
response = requests.post(DISPATCH_SERVER + "/confirm-dispatch", json=payload, auth=AUTH)
if response.status_code not in [200, 204]:
print("Failed to confirm dispatch with server for {} ({})".format(
uuid, response.text), file=sys.stderr)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Query Atlantis Dispatch for Signal',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dispatch-server')
parser.add_argument('--dispatch-user')
parser.add_argument('--dispatch-password')
parser.add_argument('--ntfy-api-server')
parser.add_argument('--ntfy-api-token')
parser.add_argument('--ntfy-push-target')
parser.add_argument('--ntfy-user')
parser.add_argument('--ntfy-pass')
parser.add_argument('--smtp-target')
parser.add_argument('--smtp-user')
parser.add_argument('--smtp-pass')
parser.add_argument('--loop', default=True, action=argparse.BooleanOptionalAction)
args = parser.parse_args()
# set dispatch server & authentication #
DISPATCH_SERVER = args.dispatch_server
AUTH = (args.dispatch_user, args.dispatch_password)
dispatch_server = args.dispatch_server or os.environ.get("DISPATCH_SERVER")
dispatch_user = args.dispatch_user or os.environ.get("DISPATCH_USER")
dispatch_password = args.dispatch_password or os.environ.get("DISPATCH_PASSWORD")
ntfy_api_server = args.ntfy_api_server or os.environ.get("NTFY_API_SERVER")
ntfy_api_token = args.ntfy_api_token or os.environ.get("NTFY_API_TOKEN")
ntfy_push_target = args.ntfy_push_target or os.environ.get("NTFY_PUSH_TARGET")
ntfy_user = args.ntfy_user or os.environ.get("NTFY_USER")
ntfy_pass = args.ntfy_pass or os.environ.get("NTFY_PASS")
smtp_target = args.smtp_target or os.environ.get("SMTP_TARGET")
smtp_user = args.smtp_user or os.environ.get("SMTP_USER")
smtp_pass = args.smtp_pass or os.environ.get("SMTP_PASS")
first_run = True
while args.loop or first_run:
# request dispatches #
response = requests.get(args.dispatch_server + "/get-dispatch?method=all&timeout=0", auth=AUTH)
# check status #
if response.status_code == HTTP_NOT_FOUND:
sys.exit(0)
# fallback check for status #
response.raise_for_status()
# track dispatches that were confirmed to avoid duplicate confirmation #
dispatch_confirmed = []
# track failed dispatches #
errors = dict()
# iterate over dispatch requests #
for entry in response.json():
user = entry["username"]
dispatch_uuid = entry["uuid"]
method = entry["method"]
message = entry["message"]
title = entry.get("title")
# method dependent fields #
phone = entry.get("phone")
email_address = entry.get("email")
# send message #
if method == "signal":
pass
elif method == "ntfy":
user_topic = ntfy_api_get_topic(ntfy_api_server, ntfy_api_token, user)
ntfy_send(dispatch_uuid, user_topic, title, message,
ntfy_push_target, ntfy_user, ntfy_pass)
elif method == "email":
email_send(dispatch_uuid, email_address, message, smtp_target, smtp_user, smtp_pass)
elif method == "debug":
debug_send(dispatch_uuid, entry)
elif method == "debug-fail":
debug_send(dispatch_uuid, entry, fail_it=True)
else:
print("Unsupported dispatch method {}".format(entry["method"]), sys=sys.stderr)
continue
# wait a moment #
if args.loop:
time.sleep(5)
# handle non-loop runs #
first_run = False

37
client/smtphelper.py Normal file
View File

@@ -0,0 +1,37 @@
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def smtp_send(server, user, password, recipient, subject, body):
# Email and password for authentication
sender_email = f'{user}@{server}'
sender_password = password
# Recipient email address
recipient_email = recipient
# SMTP server details
smtp_server = server
smtp_port = 587 # Default port for TLS connection
# Create a message
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
# Add body to email
body = body
message.attach(MIMEText(body, 'plain'))
# Establish a connection to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Secure the connection
server.login(sender_email, sender_password)
# Send the email
server.sendmail(sender_email, recipient_email, message.as_string())
# Close the connection
server.quit()

View File

@@ -1,26 +0,0 @@
class UnsupportedStruct(Exception):
def __init__(self, struct):
self.message = "{} is invalid struct and not a message".format(str(struct))
super().__init__(self.message)
def make_icinga_message(struct):
pass
def make_generic_message(struct):
pass
def load_struct(struct):
if type(struct) == str:
return struct
elif not struct.get("type"):
raise UnsupportedStruct(struct)
if struct.get("type") == "icinga":
return make_icinga_message(struct)
elif struct.get("type") == "generic":
return make_generic_message(struct)
else:
raise UnsupportedStruct(struct)

22
server/Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM alpine
RUN apk add --update --no-cache python3 py3-pip py3-ldap
WORKDIR /app
RUN python3 -m pip install --no-cache-dir --break-system-packages waitress
COPY req.txt .
# remove python-ldap (installed via apk) #
RUN sed -i '/^python-ldap.*$/d' req.txt
RUN python3 -m pip install --no-cache-dir --break-system-packages -r req.txt
# precreate database directory for mount (will otherwise be created at before_first_request)
COPY ./ .
RUN mkdir /app/instance/
EXPOSE 5000/tcp
ENTRYPOINT ["waitress-serve"]
CMD ["--host", "0.0.0.0", "--port", "5000", "--call", "app:createApp" ]

View File

@@ -33,9 +33,45 @@ class DispatchObject(db.Model):
timestamp = Column(Integer, primary_key=True)
phone = Column(String)
email = Column(String)
title = Column(String)
message = Column(String, primary_key=True)
method = Column(String)
dispatch_secret = Column(String)
dispatch_error = Column(String)
def serialize(self):
ret = {
"person" : self.username, # legacy field TODO remove at some point
"username" : self.username,
"timestamp" : self.timestamp,
"phone" : self.phone,
"email" : self.email,
"title" : self.title,
"message" : self.message,
"uuid" : self.dispatch_secret,
"method" : self.method,
"error" : self.dispatch_error,
}
# fix bytes => string from LDAP #
for key, value in ret.items():
if type(value) == bytes:
ret[key] = value.decode("utf-8")
return ret
@app.route('/get-dispatch-status')
def get_dispatch_status():
'''Retrive the status of a specific dispatch by it's secret'''
secret = flask.request.args.get("secret")
do = db.session.query(DispatchObject).filter(DispatchObject.dispatch_secret == secret).first()
if not do:
return ("Not in Queue", 200)
else:
return ("Waiting for dispatch", 200)
@app.route('/get-dispatch')
@@ -43,33 +79,79 @@ def get_dispatch():
'''Retrive consolidated list of dispatched objects'''
method = flask.request.args.get("method")
timeout = flask.request.args.get("timeout") or 5 # timeout in seconds
timeout = int(timeout)
if not method:
return (500, "Missing Dispatch Target (signal|email|phone)")
return (500, "Missing Dispatch Target (signal|email|phone|ntfy|all)")
# prevent message floods #
timeout_cutoff = datetime.datetime.now() - datetime.timedelta(seconds=5)
timeout_cutoff = datetime.datetime.now() - datetime.timedelta(seconds=timeout)
timeout_cutoff_timestamp = timeout_cutoff.timestamp()
lines_unfiltered = db.session.query(DispatchObject)
lines_timeout = lines_unfiltered.filter(DispatchObject.timestamp < timeout_cutoff_timestamp)
dispatch_objects = lines_timeout.filter(DispatchObject.method == method).all()
# accumulate messages by person #
dispatch_by_person = dict()
dispatch_secrets = []
for dobj in dispatch_objects:
if dobj.username not in dispatch_by_person:
dispatch_by_person.update({ dobj.username : dobj.message })
dispatch_secrets.append(dobj.dispatch_secret)
else:
dispatch_by_person[dobj.username] += "\n{}".format(dobj.message)
dispatch_secrets.append(dobj.dispatch_secret)
if method != "all":
dispatch_objects = lines_timeout.filter(DispatchObject.method == method).all()
else:
dispatch_objects = lines_timeout.all()
response = [ { "person" : str(tupel[0]), "message" : tupel[1], "method" : method, "uids" : dispatch_secrets }
for tupel in dispatch_by_person.items() ]
# TODO THIS IS THE NEW MASTER PART
if method and method != "signal":
print([ d.serialize() for d in dispatch_objects])
return flask.jsonify([ d.serialize() for d in dispatch_objects])
else:
# TODO THIS PART WILL BE REMOVED ##
# accumulate messages by person #
dispatch_by_person = dict()
dispatch_secrets = []
for dobj in dispatch_objects:
if dobj.username not in dispatch_by_person:
dispatch_by_person.update({ dobj.username : dobj.message })
dispatch_secrets.append(dobj.dispatch_secret)
else:
dispatch_by_person[dobj.username] += "\n{}".format(dobj.message)
dispatch_secrets.append(dobj.dispatch_secret)
return flask.jsonify(response)
response = [ { "person" : tupel[0].decode("utf-8"),
"message" : tupel[1],
"method" : method,
"uids" : dispatch_secrets
} for tupel in dispatch_by_person.items() ]
# add phone numbers and emails #
for obj in response:
for person in dispatch_objects:
if obj["person"] == person.username.decode("utf-8"):
if person.email:
obj.update({ "email" : person.email.decode("utf-8") })
if person.phone:
obj.update({ "phone" : person.phone.decode("utf-8") })
return flask.jsonify(response)
@app.route('/report-dispatch-failed', methods=["POST"])
def reject_dispatch():
'''Inform the server that a dispatch has failed'''
rejects = flask.request.json
for r in rejects:
uuid = r["uuid"]
error = r["error"]
dpo = db.session.query(DispatchObject).filter(
DispatchObject.dispatch_secret == uuid).first()
if not dpo:
return ("No pending dispatch for this UID/Secret", 404)
dpo.dispatch_error = error
db.session.merge(dpo)
db.session.commit()
return ("", 204)
@app.route('/confirm-dispatch', methods=["POST"])
def confirm_dispatch():
@@ -79,8 +161,9 @@ def confirm_dispatch():
for c in confirms:
uid = c["uid"]
dpo = db.session.query(DispatchObject).filter(DispatchObject.dispatch_secret == uid).first()
uuid = c["uuid"]
dpo = db.session.query(DispatchObject).filter(
DispatchObject.dispatch_secret == uuid).first()
if not dpo:
return ("No pending dispatch for this UID/Secret", 404)
@@ -109,22 +192,35 @@ def smart_send_to_clients():
users = instructions.get("users")
groups = instructions.get("groups")
message = instructions.get("msg")
title = instructions.get("title")
method = instructions.get("method")
# allow single use string instead of array #
if type(users) == str:
users = [users]
struct = instructions.get("data")
if struct:
try:
message = messagetools.load_struct(struct)
except messagetools.UnsupportedStruct as e:
print(str(e), file=sys.stderr)
return (e.response(), 408)
if method in ["debug", "debug-fail"]:
persons = [ldaptools.Person(cn="none", username=users[0], name="Mr. Debug",
email="invalid@nope.notld", phone="0")]
else:
persons = ldaptools.select_targets(users, groups, app.config["LDAP_ARGS"])
persons = ldaptools.select_targets(users, groups, app.config["LDAP_ARGS"])
save_in_dispatch_queue(persons, message)
return ("OK", 200)
dispatch_secrets = save_in_dispatch_queue(persons, title, message, method)
return flask.jsonify(dispatch_secrets)
def save_in_dispatch_queue(persons, message):
def save_in_dispatch_queue(persons, title, message, method):
dispatch_secrets = []
for p in persons:
if not p:
@@ -133,16 +229,25 @@ def save_in_dispatch_queue(persons, message):
# this secret will be needed to confirm the message as dispatched #
dispatch_secret = secrets.token_urlsafe(32)
# TODO fix this
master_method = "signal"
obj = DispatchObject(username=p.username,
phone=p.phone,
email=p.email,
method="signal",
method=method or master_method,
timestamp=datetime.datetime.now().timestamp(),
dispatch_secret=dispatch_secret,
title=title,
message=message)
db.session.merge(obj)
db.session.commit()
dispatch_secrets.append(dispatch_secret)
return dispatch_secrets
def create_app():
db.create_all()

View File

@@ -1,12 +1,6 @@
import ldap
import sys
# LDAP server details
ldap_server = "ldap://localhost:5005"
base_dn = "ou=People,dc=atlantishq,dc=de"
manager_dn = "cn=Manager,dc=atlantishq,dc=de"
manager_password = "flanigan"
class Person:
def __init__(self, cn, username, name, email, phone):
@@ -36,7 +30,7 @@ def ldap_query(search_filter, ldap_args, alt_base_dn=None):
# estabilish connection
conn = ldap.initialize(ldap_server)
conn.simple_bind_s(manager_dn, manager_password)
conn.simple_bind_s(manager_dn, manager_pw)
# search in scope #
search_scope = ldap.SCOPE_SUBTREE
@@ -83,6 +77,7 @@ def get_members_of_group(group, ldap_args):
search_filter = "(&(objectClass=groupOfNames)(cn={group_name}))".format(group_name=group)
# TODO wtf is this btw??
base_dn = ldap_args["LDAP_BASE_DN"]
groups_dn = ",".join([ s.replace("People","groups") for s in base_dn.split(",")])
results = ldap_query(search_filter, ldap_args, alt_base_dn=groups_dn)
@@ -110,10 +105,11 @@ def select_targets(users, groups, ldap_args, admin_group="pki"):
'''Returns a list of persons to send notifications to'''
persons = []
if users:
# FIXME better handling of empty owner/groups
if users and not any([ not s for s in users]):
for username in users:
persons.append(get_user_by_uid(username, ldap_args))
elif groups:
elif groups and not any([ not s for s in groups ]):
for group in groups:
persons += get_members_of_group(group, ldap_args)
else:

47
server/messagetools.py Normal file
View File

@@ -0,0 +1,47 @@
class UnsupportedStruct(Exception):
def __init__(self, struct):
self.message = "{} is invalid struct and not a message".format(str(struct))
super().__init__(self.message)
def make_icinga_message(struct):
first_line = "{state} - {service} ({host})".format(state=struct.get("service_state"),
service=struct.get("service_name"), host=struct.get("service_host"))
second_line = struct.get("service_output") or ""
#third_line = "Direkt-Link: {link}".format(link=struct.get("icingaweb_url"))
if not struct.get("owners") and not struct.get("owner-groups"):
fourth_line = "Notification to: admins (default)"
else:
owners = struct.get("owners") or []
groups = struct.get("owner-groups") or []
groups_strings = [ g + "-group" for g in groups ]
fourth_line = "Notification to: " + ", ".join(owners) + " " + ", ".join(groups_strings)
if struct.get("comment"):
fith_line = "Extra Comment: \n{}".format(struct.get("comment"))
return "\n".join([first_line, second_line, fourth_line, fith_line])
else:
return "\n".join([first_line, second_line, fourth_line])
def make_generic_message(struct):
msg = struct.get("message") or struct.get("msg")
return msg
def load_struct(struct):
if type(struct) == str:
return struct
elif not struct.get("type"):
raise UnsupportedStruct(struct)
if struct.get("type") == "icinga":
return make_icinga_message(struct)
elif struct.get("type") == "generic":
return make_generic_message(struct)
else:
raise UnsupportedStruct(struct)

View File

@@ -10,61 +10,90 @@ from functools import wraps
HTTP_NOT_FOUND = 404
def signal_send(user, message):
def signal_send(phone, message):
'''Send message via signal'''
cmd = [signal_cli_bin, "send", "-m", message, user]
cmd = [signal_cli_bin, "send", "-m", "'{}'".format(message.replace("'","")), phone]
p = subprocess.run(cmd)
# TODO check return code #
def report_dispatch_error(target, uid, error):
'''Report an error for a give dispatch'''
pass # TODO
def confirm_dispatch(target, uid):
'''Confirm to server that message has been dispatched and can be removed'''
response = requests.post(target + "/confirm-dispatch", json=[{ "uid" : uid }])
response = requests.post(target + "/confirm-dispatch", json=[{ "uid" : uid }],
auth=(args.user, args.password))
if response.status_code not in [200, 204]:
print("Failed to confirm disptach with server for {} ({})".format(uid, response.text), file=sys.stderr)
print("Failed to confirm disptach with server for {} ({})".format(
uid, response.text), file=sys.stderr)
if __name__ == "__main__":
# set signal cli from env #
signal_cli_bin = os.environ["SIGNAL_CLI_BIN"]
parser = argparse.ArgumentParser(description='Query Atlantis Dispatch for Signal',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--target', required=True)
parser.add_argument('--method', default="signal")
parser.add_argument('--no-confirm', action="store_true")
parser.add_argument('--signal-cli-bin')
parser.add_argument('--user')
parser.add_argument('--password')
args = parser.parse_args()
if args.signal_cli_bin:
signal_cli_bin = args.signal_cli_bin
response = requests.get(args.target + "/get-dispatch?method={}".format(args.method))
# request dispatches #
response = requests.get(args.target + "/get-dispatch?method={}".format(args.method),
auth=(args.user, args.password))
# check status #
if response.status_code == HTTP_NOT_FOUND:
sys.exit(0)
# fallback check for status #
response.raise_for_status()
# track dispatches that were confirmed to avoid duplicate confirmation #
dispatch_confirmed = []
# track failed dispatches #
errors = dict()
# iterate over dispatch requests #
for entry in response.json():
user = entry["person"]
phone = entry["phone"]
message = entry["message"]
uid_list = entry["uids"]
# send message #
if entry["method"] == "signal":
signal_send(user, message)
uid, error = signal_send(phone, message)
else:
print("Unsupported dispatch method {}".format(entry["method"]), sys=sys.stderr)
print("Unsupported dispatch method {}".format(entry["method"]),
sys=sys.stderr)
# confirm dispatch
if not args.no_confirm:
for uid in uid_list:
if uid not in dispatch_confirmed:
confirm_dispatch(args.target, uid)
dispatch_confirmed.append(uid)
# confirm or report fail #
if errors[uid]:
report_dispatch_error(args.target, uid, errors[uid])
else:
confirm_dispatch(args.target, uid)
dispatch_confirmed.append(uid)
else:
continue