#!/usr/bin/env python3
"""LineVaults answering machine detection: Asterisk EAGI client.

Streams the answered call's audio to the LineVaults service and sets two channel variables:

  AMDSTATUS = HUMAN | MACHINE | FALLBACK
  AMDCAUSE  = HUMAN | MACHINE | SCREENING | SILENCE | TONE | BUSY | UNKNOWN      (HUMAN / MACHINE)
              AUTH | SUSPENDED | QUOTA | CONCURRENCY | CPS | NOSERVER            (FALLBACK)

FALLBACK means the service cannot judge this call (bad or disabled key, plan limit reached, or the
service cannot be reached). It is decided before the call's audio is used, so the dialplan can run
Asterisk's own AMD() instead. Any error after streaming started, or a timeout, gives MACHINE / UNKNOWN:
only a confirmed HUMAN is passed to an agent.

Dialplan:
  exten => 8370,n,EAGI(linevaults.agi.py,wss://amd.linevaults.com/,YOUR_KEY,4500)
  exten => 8370,n,GotoIf($["${AMDSTATUS}" = "FALLBACK"]?native)

Arguments: WebSocket URL (wss:// or ws://), API key, overall timeout in ms (default 4500; it must cover
the service's longest listening window, 3.2 s, plus network time).

Install: copy to /var/lib/asterisk/agi-bin/ and chmod +x. Python 3.6 or newer, standard library only.
Test without Asterisk:  linevaults.agi.py --test URL KEY [file.wav]   (8 kHz mono 16-bit WAV, default: silence)
"""
import base64, json, os, select, socket, ssl, struct, sys, time

AUDIO_FD = 3                 # EAGI: the call's audio, slin16 8 kHz mono
FRAME_BYTES = 1600           # 100 ms
MAX_STREAM_BYTES = 96000     # 6 s: the service decides well before this
HANDSHAKE_S = 1.0            # connect + TLS + WebSocket handshake budget: past it, FALLBACK while AMD() still can
VERSION = "1.0.0"


class NoServer(Exception):
    """Could not reach a working service before streaming: the dialplan should run AMD()."""


def agi(cmd):
    sys.stdout.write(cmd + "\n")
    sys.stdout.flush()
    sys.stdin.readline()


def parse_url(url):
    if url.startswith("wss://"):
        tls, rest, port = True, url[6:], 443
    elif url.startswith("ws://"):
        tls, rest, port = False, url[5:], 80
    else:
        raise NoServer("URL must start with wss:// or ws://")
    hostport, _, path = rest.partition("/")
    host = hostport
    if ":" in hostport and not hostport.endswith("]"):
        host, p = hostport.rsplit(":", 1)
        port = int(p)
    return tls, host, port, "/" + path, hostport


class WS:
    """Just enough RFC 6455 for one call: masked client frames, small unmasked server text frames."""

    def __init__(self, url, key, deadline):
        tls, host, port, path, hostport = parse_url(url)
        left = max(0.05, deadline - time.monotonic())
        try:
            raw = socket.create_connection((host, port), timeout=left)
            raw.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            if tls:
                ctx = ssl.create_default_context()
                raw = ctx.wrap_socket(raw, server_hostname=host)
            self.sock = raw
            nonce = base64.b64encode(os.urandom(16)).decode()
            req = ("GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
                   "Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\nAuthorization: Bearer %s\r\n"
                   "User-Agent: linevaults-agi/%s\r\n\r\n" % (path, hostport, nonce, key, VERSION))
            self.sock.settimeout(max(0.05, deadline - time.monotonic()))
            self.sock.sendall(req.encode())
            head = b""
            while b"\r\n\r\n" not in head:  # byte at a time: never read past the headers
                if time.monotonic() > deadline:
                    raise NoServer("handshake timeout")
                b = self.sock.recv(1)
                if not b:
                    raise NoServer("closed during handshake")
                head += b
                if len(head) > 8192:
                    raise NoServer("bad handshake")
            if b" 101" not in head.split(b"\r\n", 1)[0]:
                raise NoServer("handshake refused: " + head.split(b"\r\n", 1)[0].decode("latin-1"))
        except NoServer:
            raise
        except (OSError, ssl.SSLError, ValueError) as e:
            raise NoServer(str(e))
        self.sock.setblocking(False)
        self.inbuf = b""

    def send(self, opcode, data):
        n = len(data)
        if n < 126:
            hdr = struct.pack("!BB", 0x80 | opcode, 0x80 | n)
        elif n < 65536:
            hdr = struct.pack("!BBH", 0x80 | opcode, 0x80 | 126, n)
        else:
            hdr = struct.pack("!BBQ", 0x80 | opcode, 0x80 | 127, n)
        mask = os.urandom(4)
        body = bytes(b ^ mask[i & 3] for i, b in enumerate(data))
        out = hdr + mask + body
        self.sock.setblocking(True)
        self.sock.settimeout(1.0)
        try:
            self.sock.sendall(out)
        finally:
            self.sock.setblocking(False)

    def read_text(self):
        """Returns a complete text frame if one has arrived, None if not yet; raises EOFError on close."""
        try:
            chunk = self.sock.recv(4096)
            if not chunk:
                raise EOFError()
            self.inbuf += chunk
        except (BlockingIOError, ssl.SSLWantReadError):
            pass
        while len(self.inbuf) >= 2:
            op, n = self.inbuf[0] & 0x0F, self.inbuf[1] & 0x7F
            off = 2
            if n == 126:
                if len(self.inbuf) < 4:
                    return None
                n, off = struct.unpack("!H", self.inbuf[2:4])[0], 4
            elif n == 127:
                if len(self.inbuf) < 10:
                    return None
                n, off = struct.unpack("!Q", self.inbuf[2:10])[0], 10
            if len(self.inbuf) < off + n:
                return None
            payload, self.inbuf = self.inbuf[off:off + n], self.inbuf[off + n:]
            if op == 0x1:
                return payload.decode("utf-8", "replace")
            if op == 0x8:
                raise EOFError()
        return None

    def pending(self):
        return isinstance(self.sock, ssl.SSLSocket) and self.sock.pending() > 0

    def close(self):
        try:
            self.send(0x8, b"\x03\xe8")
        except Exception:
            pass
        try:
            self.sock.close()
        except Exception:
            pass


def verdict_vars(text):
    """AMDSTATUS / AMDCAUSE from the service's verdict, with the HUMAN rule enforced."""
    try:
        v = json.loads(text)
    except ValueError:
        return "MACHINE", "UNKNOWN"
    status, cause = str(v.get("amdstatus", "")), str(v.get("amdcause", ""))
    if status == "FALLBACK":
        return "FALLBACK", cause or "NOSERVER"
    if status not in ("HUMAN", "MACHINE"):
        return "MACHINE", "UNKNOWN"
    if (status == "HUMAN") != (cause == "HUMAN"):
        return "MACHINE", cause if cause != "HUMAN" else "UNKNOWN"
    return status, cause


def run(url, key, timeout_ms, call_id, audio_fd):
    t0 = time.monotonic()
    deadline = t0 + timeout_ms / 1000.0
    try:
        ws = WS(url, key, min(deadline, t0 + HANDSHAKE_S))
        ws.send(0x1, json.dumps({"type": "start", "call_id": call_id}).encode())
    except NoServer:
        return "FALLBACK", "NOSERVER"
    except OSError:
        return "FALLBACK", "NOSERVER"

    status, cause = "MACHINE", "UNKNOWN"
    have, sent, audio_open = b"", 0, audio_fd is not None
    try:
        while True:
            left = deadline - time.monotonic()
            if left <= 0:
                break
            rlist = [ws.sock] + ([audio_fd] if audio_open and sent < MAX_STREAM_BYTES else [])
            ready = [ws.sock] if ws.pending() else select.select(rlist, [], [], left)[0]
            if not ready:
                break
            if audio_fd in ready:
                try:
                    chunk = os.read(audio_fd, FRAME_BYTES - len(have))
                except OSError:
                    chunk = b""
                if not chunk:  # call ended: let the service decide with what it has
                    audio_open = False
                    try:
                        if have:
                            ws.send(0x2, have)
                        ws.send(0x1, b'{"type":"close"}')
                    except OSError:
                        pass
                else:
                    have += chunk
                    if len(have) >= FRAME_BYTES:
                        try:
                            ws.send(0x2, have)
                            sent += len(have)
                        except OSError:
                            audio_open = False  # it may have decided already: keep reading for the verdict
                        have = b""
            if ws.sock in ready:
                text = ws.read_text()
                if text is not None:
                    status, cause = verdict_vars(text)
                    break
    except (EOFError, OSError, ssl.SSLError):
        pass
    ws.close()
    return status, cause


def main():
    args = sys.argv[1:]
    if args and args[0] == "--test":
        return test(args[1:])
    env = {}
    for line in iter(sys.stdin.readline, ""):  # AGI environment, up to a blank line
        line = line.strip()
        if not line:
            break
        k, _, v = line.partition(":")
        env[k.strip()] = v.strip()
    if len(args) < 2:
        status, cause = "FALLBACK", "NOSERVER"
    else:
        timeout = int(args[2]) if len(args) > 2 and args[2].isdigit() else 4500
        status, cause = run(args[0], args[1], timeout, env.get("agi_uniqueid", ""), AUDIO_FD)
    agi('SET VARIABLE AMDSTATUS "%s"' % status)
    agi('SET VARIABLE AMDCAUSE "%s"' % cause)
    agi('VERBOSE "linevaults.agi: %s %s" 3' % (status, cause))


def test(args):
    """linevaults.agi.py --test URL KEY [file.wav]: stream a file through a pipe, print the result."""
    import threading, wave
    if len(args) < 2:
        sys.exit("usage: linevaults.agi.py --test URL KEY [file.wav]")
    if len(args) > 2:
        w = wave.open(args[2], "rb")
        if w.getframerate() != 8000 or w.getnchannels() != 1 or w.getsampwidth() != 2:
            sys.exit("need an 8 kHz mono 16-bit WAV")
        pcm = w.readframes(w.getnframes())
    else:
        pcm = b"\x00\x00" * 8000 * 3
    r, wfd = os.pipe()

    def feed():  # at call speed, like Asterisk
        for i in range(0, len(pcm), FRAME_BYTES):
            try:
                os.write(wfd, pcm[i:i + FRAME_BYTES])
            except OSError:
                break
            time.sleep(0.1)
        os.close(wfd)
    threading.Thread(target=feed, daemon=True).start()
    t = time.monotonic()
    status, cause = run(args[0], args[1], 4500, "linevaults_agi_test", r)
    print("AMDSTATUS=%s AMDCAUSE=%s (%d ms)" % (status, cause, (time.monotonic() - t) * 1000))


if __name__ == "__main__":
    main()
