X-Git-Url: http://git.treefish.org/~alex/mtxbot.git/blobdiff_plain/6c4dbc2edd8bf5cac128c2fa48728d8abe52432e..732dbf2c4afa69b93f9e7e05d3d46d334059d00e:/src/mtxbot-post.py?ds=sidebyside diff --git a/src/mtxbot-post.py b/src/mtxbot-post.py index 3e97ef2..f7e5365 100755 --- a/src/mtxbot-post.py +++ b/src/mtxbot-post.py @@ -1,21 +1,47 @@ #!/usr/bin/env python3 +import argparse import base64 import errno +import markdown2 import os import posix +import random import stat +import string import sys import time assert sys.version_info >= (3, 5) -if len(sys.argv) != 2: - print("Usage: %s " % sys.argv[0]) - sys.exit(1) +FRAG_LEN = 1024 + +def send_line(line): + for i in range(0, 10): + fifo = -1 + try: + fifo = posix.open(fifo_path, posix.O_WRONLY | posix.O_NONBLOCK) + posix.write(fifo, line) + return + except OSError as e: + if e.errno == errno.ENXIO: + time.sleep(1.0) + finally: + if fifo != -1: + posix.close(fifo) + raise Exception("Error sending line!") + +parser = argparse.ArgumentParser(description='Post message using Matrix Bot.') +parser.add_argument('channel', type=str, help='channel to be used for posting') +parser.add_argument('--html', action='store_true', dest='is_html', + default=False, help='post html message') +parser.add_argument('--markdown', action='store_true', dest='is_markdown', + default=False, help='post markdown message') + +args = parser.parse_args() fifo_dir = os.getenv('MTXBOT_FIFO_DIR', '/run/mtxbot') -fifo_path = "%s/%s" % (fifo_dir, sys.argv[1]) +fifo_path = "%s/%s" % (fifo_dir, args.channel) if not os.path.isdir(fifo_dir): print("Fifo directory %s does not exist!" % fifo_dir, file=sys.stderr) @@ -23,24 +49,21 @@ if not os.path.isdir(fifo_dir): if not ( os.path.exists(fifo_path) and stat.S_ISFIFO(os.stat(fifo_path).st_mode) ): - print("Channel %s does not exist!" % sys.argv[1], file=sys.stderr) + print("Channel %s does not exist!" % args.channel, file=sys.stderr) sys.exit(3) -inBytes = sys.stdin.read().encode("UTF-8") -inB64 = base64.b64encode(inBytes) - -for i in range(0, 10): - fifo = -1 - try: - fifo = posix.open(fifo_path, posix.O_WRONLY | posix.O_NONBLOCK) - posix.write(fifo, inB64) - sys.exit(0) - except OSError as e: - if e.errno == errno.ENXIO: - time.sleep(1.0) - finally: - if fifo != -1: - posix.close(fifo) - -print("Error posting to channel %s!" % sys.argv[1], file=sys.stderr) -sys.exit(4) +in_raw = sys.stdin.read() + +if args.is_markdown: + in_raw = markdown2.markdown(in_raw) + +in_bytes = in_raw.encode("UTF-8") +in_b64 = base64.b64encode(in_bytes).decode("UTF-8") + +msg_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) +msg_fmt = 'HTML' if (args.is_html or args.is_markdown) else 'PLAIN' +msg_len = len(in_b64) // FRAG_LEN + (0 if len(in_b64) % FRAG_LEN == 0 else 1) + +send_line( ("%s %s %d\n" % (msg_id, msg_fmt, msg_len)).encode("UTF-8") ) +for i in range(0, len(in_b64), FRAG_LEN): + send_line( ("%s %d %s\n" % (msg_id, i//FRAG_LEN, in_b64[i:i+FRAG_LEN])).encode("UTF-8") )