X-Git-Url: http://git.treefish.org/~alex/mtxbot.git/blobdiff_plain/c4b302f9d8c02035bc4f45458a33bb9e9ba26935..94f38bb41b8a779a1a9345998603fe6b536511c3:/src/mtxbot-post.py?ds=sidebyside diff --git a/src/mtxbot-post.py b/src/mtxbot-post.py index 3673eda..d1f713f 100755 --- a/src/mtxbot-post.py +++ b/src/mtxbot-post.py @@ -1,41 +1,69 @@ #!/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 or e.errno == errno.EAGAIN: + 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) sys.exit(2) -if not stat.S_ISFIFO( os.stat(fifo_path).st_mode ): - print("Channel %s does not exist!" % sys.argv[1], file=sys.stderr) +if not ( os.path.exists(fifo_path) and + stat.S_ISFIFO(os.stat(fifo_path).st_mode) ): + print("Channel %s does not exist!" % args.channel, file=sys.stderr) sys.exit(3) -for i in range(0, 10): - fifo = -1 - try: - fifo = posix.open(fifo_path, posix.O_WRONLY | posix.O_NONBLOCK) - posix.write(fifo, sys.stdin.read().encode()) - 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") )