You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.6 KiB
Python

#!/bin/env python
from __future__ import print_function
import os
import tempfile
from datetime import datetime
import argparse
import yaml
from matrix_client.client import MatrixClient
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
class MatrixImageSender(object):
def __init__(self, login):
self.client = MatrixClient(login["homeserver"], valid_cert_check=False)
self.client.api.validate_cert = False
self.client.login_with_password(username=login["username"], password=login["password"])
def send_image(self, room_id, img_to_send, text=datetime.now().strftime("%c")):
self.room = self.client.join_room(room_id)
self.room.send_image(text, img_to_send)
class RaspiImageFetcher(object):
def __init__(self, argstring):
self.exe_path = which("raspistill")
self.argstring = argstring
if not self.exe_path:
raise Exception("No raspistill found!")
def take_photo(self):
self.path = "/var/lib/camtrix/images"
if not os.path.exists(self.path):
os.makedirs(self.path)
self.filepath = "%s/%s.jpg" % (str(self.path),
datetime.strftime(datetime.now(), "%Y%m%d_%H%M%S"))
self.args = "%s %s" % (
"-o %s" % self.filepath,
self.argstring
)
command = "%s %s" % (self.exe_path, self.args)
os.system(command)
if os.path.isfile(self.filepath):
return self.filepath
return None
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Send an Image to a Matrix room")
parser.add_argument('--room', type=str, help="Matrix room ID to send the image to")
parser.add_argument('--login', type=str, help="Path to a YAML with a single username and single password key.")
args = parser.parse_args()
image_sender = MatrixImageSender(yaml.safe_load(open(args.login)))
image_fetcher = RaspiImageFetcher(os.environ["RASPISTILL_OPTS"])
image_fetcher.take_photo()
for path in os.listdir(image_fetcher.path):
with open(os.path.join(image_fetcher.path, path)) as f:
image_sender.send_image(args.room, f, path)
os.remove(os.path.join(image_fetcher.path, path))