[feat] Remove Filesystem based watcher

This commit is contained in:
Alex 2021-05-07 12:12:08 +02:00
parent 0ffb69de30
commit fb8c22a535
2 changed files with 29 additions and 82 deletions

107
mms2mail
View file

@ -25,8 +25,6 @@ if sys.version_info[0] == 3 and sys.version_info[1] > 8:
import argparse import argparse
import configparser import configparser
import re
import time
import getpass import getpass
import socket import socket
import mimetypes import mimetypes
@ -38,8 +36,6 @@ from marrow.mailer import Mailer, Message
from gi.repository import GLib from gi.repository import GLib
import dbus import dbus
import dbus.mainloop.glib import dbus.mainloop.glib
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MMS2Mail: class MMS2Mail:
@ -214,74 +210,21 @@ class MMS2Mail:
self.mailer.stop() self.mailer.stop()
class FSWatcher:
"""
Use OS filesystem notification to watch for new MMS (DEPRECATED).
Events are send to the FSHandler class
"""
# Path to modemmanager storage
mms_folder = f"{Path.home()}/.mms/modemmanager"
def __init__(self):
"""Construct an instance."""
self.observer = Observer()
self.patternold = re.compile('[0-9A-F]{40}$')
self.pattern = re.compile('[0-9a-f]{36}$')
def is_mmsd_mms_file(self, path):
"""
Test if the provided file seems to be a mms file created by mmsd.
:param path: the mms filesystem path
:type path: str
:rtype boolean
:return: the test result
"""
if self.pattern.search(path) or self.patternold.search(path):
return True
else:
return False
def run(self):
"""Run the watcher mainloop."""
event_handler = FSHandler()
self.observer.schedule(event_handler, self.mms_folder, recursive=False)
self.observer.start()
try:
while True:
time.sleep(5)
finally:
self.observer.stop()
self.observer.join()
class FSHandler(FileSystemEventHandler):
"""Handle the FSWatcher event."""
@staticmethod
def on_any_event(event):
"""Trigger conversion on event by the FSWatcher."""
if event.is_directory:
return None
elif event.event_type == 'created' or event.event_type == 'modified':
if w.is_mmsd_mms_file(event.src_path):
print(f"New MMS found : {event.src_path}.", file=sys.stderr)
m.convert(event.src_path)
elif event.event_type == 'moved':
if w.is_mmsd_mms_file(event.dest_path):
print(f"New MMS found : {event.dest_path}.", file=sys.stderr)
m.convert(event.dest_path)
class DbusWatcher(): class DbusWatcher():
"""Use DBus Signal notification to watch for new MMS.""" """Use DBus Signal notification to watch for new MMS."""
def __init__(self, mms2mail):
"""
Return a DBusWatcher instance.
:param mms2mail: An mms2mail instance to convert new mms
:type mms2mail: mms2mail()
"""
self.mms2mail = mms2mail
def run(self): def run(self):
"""Run the watcher mainloop.""" """Run the watcher mainloop."""
bus = m.get_bus() bus = self.mms2mail.get_bus()
bus.add_signal_receiver(self.message_added, bus.add_signal_receiver(self.message_added,
bus_name="org.ofono.mms", bus_name="org.ofono.mms",
signal_name="MessageAdded", signal_name="MessageAdded",
@ -289,25 +232,29 @@ class DbusWatcher():
path_keyword="path", path_keyword="path",
interface_keyword="interface") interface_keyword="interface")
mainloop = GLib.MainLoop() mainloop = GLib.MainLoop()
print("Starting DBus watcher mainloop")
try:
mainloop.run() mainloop.run()
except KeyboardInterrupt:
print("Stopping DBus watcher mainloop")
mainloop.quit()
def message_added(self, name, value, member, path, interface): def message_added(self, name, value, member, path, interface):
"""Trigger conversion on MessageAdded signal.""" """Trigger conversion on MessageAdded signal."""
if value['Status'] == 'downloaded' or value['Status'] == 'received': if value['Status'] == 'downloaded' or value['Status'] == 'received':
print(f"New incoming MMS found ({name.split('/')[-1]})") print(f"New incoming MMS found ({name.split('/')[-1]})")
m.convert(value['Attachments'][0][2], name) self.mms2mail.convert(value['Attachments'][0][2], name)
else: else:
print(f"New outgoing MMS found ({name.split('/')[-1]})") print(f"New outgoing MMS found ({name.split('/')[-1]})")
if __name__ == '__main__': def main():
"""Run the different functions handling mms and mail."""
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
mode = parser.add_mutually_exclusive_group() mode = parser.add_mutually_exclusive_group()
mode.add_argument("-d", "--daemon", mode.add_argument("-d", "--daemon",
help="Use dbus signal from mmsd by default but can also \ help="Use dbus signal from mmsd to trigger conversion",
watch mmsd storage folder (useful for mmsd < 1.0)", action='store_true', dest='watcher')
nargs="?", default="dbus",
choices=['dbus', 'filesystem'], dest='watcher')
mode.add_argument("-f", "--file", nargs='+', mode.add_argument("-f", "--file", nargs='+',
help="Parse specified mms files and quit", dest='files') help="Parse specified mms files and quit", dest='files')
parser.add_argument('--delete', action='store_true', dest='delete', parser.add_argument('--delete', action='store_true', dest='delete',
@ -322,13 +269,13 @@ if __name__ == '__main__':
if args.files: if args.files:
for mms_file in args.files: for mms_file in args.files:
m.convert(mms_file) m.convert(mms_file)
elif args.watcher == 'dbus': elif args.watcher:
print("Starting mms2mail in daemon mode with dbus watcher") print("Starting mms2mail in daemon mode")
w = DbusWatcher() w = DbusWatcher(m)
w.run()
elif args.watcher == 'filesystem':
print("Starting mms2mail in daemon mode with filesystem watcher")
w = FSWatcher()
w.run() w.run()
else: else:
parser.print_help() parser.print_help()
if __name__ == '__main__':
main()

View file

@ -3,7 +3,7 @@ Description=Multimedia Messaging Service to Mail converter Daemon
After=mmsd.service After=mmsd.service
[Service] [Service]
ExecStart=python3 %h/.local/bin/mms2mail -d dbus ExecStart=python3 %h/.local/bin/mms2mail -d
Restart=on-failure Restart=on-failure
RestartSec=10s RestartSec=10s