ansible/roles/asterisk/files/voicemail_api.py
2024-11-27 00:08:07 -05:00

52 lines
1.5 KiB
Python

"""Simple Asterisk voicemail HTTP API"""
import configparser
import os
import pathlib
import fastapi
VM_ROOT = pathlib.Path("/var/spool/asterisk/voicemail")
app = fastapi.FastAPI()
@app.get("/contexts")
def list_contexts():
return os.listdir(VM_ROOT)
@app.get("/mailboxes/{context}")
def list_context_mailboxes(context: str):
context = VM_ROOT / context
if not (context.exists() and context.is_dir()):
raise fastapi.HTTPException(404)
return os.listdir(context)
@app.get("/mailboxes/{context}/{mailbox}")
def list_mailbox_folders(context: str, mailbox: str):
mailbox = VM_ROOT / context / mailbox
if not (mailbox.exists() and mailbox.is_dir()):
raise fastapi.HTTPException(404)
folders = sorted(node.name for node in mailbox.iterdir() if node.is_dir())
return folders
@app.get("/mailboxes/{context}/{mailbox}/{folder}")
def list_messages(context: str, mailbox: str, folder: str):
folder = VM_ROOT / context / mailbox / folder
if not (folder.exists() and folder.is_dir()):
raise fastapi.HTTPException(404)
messages = []
for info_path in sorted(folder.glob("*.txt")):
files = [
filename.name
for filename in folder.glob(f"{info_path.stem}.*")
if filename != info_path
]
with info_path.open("r") as info:
parser = configparser.ConfigParser()
parser.read_file(info)
messages.append({"info": parser["message"], "files": files})
return messages