commit 7be5ebcdaad84b42f422e01276fae2e583cb9cc8 Author: Jiang Yio Date: Sat Mar 2 00:34:29 2024 -0500 First diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7f98dee --- /dev/null +++ b/.gitignore @@ -0,0 +1,166 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Application-specific +*.ini +*.db* + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5b8d8f9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023 jyio + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..287a7d0 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# vistassh-py + +Python-based web interface for VistA roll-and-scroll terminal \ No newline at end of file diff --git a/XWBSSOi.py b/XWBSSOi.py new file mode 100644 index 0000000..0cfe53e --- /dev/null +++ b/XWBSSOi.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 + +import ctypes +import ctypes.wintypes +import winreg +import socket +import contextlib +from typing import Any, Optional, Generator + +DEFAULT_USER_AGENT = 'Borland SOAP 1.2' +DEFAULT_ISSUER = 'https://ssoi.sts.va.gov/Issuer/smtoken/SAML2' + +HCERTSTORE = ctypes.c_void_p +PCERT_INFO = ctypes.c_void_p +HCRYPTPROV_LEGACY = ctypes.c_void_p + +CERT_STORE_PROV_MEMORY = b'Memory' +X509_ASN_ENCODING = 0x00000001 +PKCS_7_ASN_ENCODING = 0x00010000 +CERT_COMPARE_ANY = 0 +CERT_COMPARE_SHIFT = 16 +CERT_FIND_ANY = CERT_COMPARE_ANY< Generator[HCERTSTORE, None, None]: + res = CertOpenStore(lpszStoreProvider, dwEncodingType, hCryptProv, dwFlags, pvPara) + try: + yield res + finally: + CertCloseStore(res, 0) + +@contextlib.contextmanager +def ManagedCertOpenSystemStore(hProv: HCRYPTPROV_LEGACY, szSubsystemProtocol: ctypes.wintypes.LPCWSTR) -> Generator[HCERTSTORE, None, None]: + res = CertOpenSystemStoreW(hProv, szSubsystemProtocol) + try: + yield res + finally: + CertCloseStore(res, 0) + +def get_vista_certificate(show_cert_dialog: bool=True, hwnd: Optional[int]=0) -> PCCERT_CONTEXT: + with ManagedCertOpenSystemStore(0, 'MY') as store_system, ManagedCertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None) as store_memory: + cert_selection = cert_iter = None + while cert_iter := CertEnumCertificatesInStore(store_system, cert_iter): + if cert_valid := CertFindCertificateInStore(store_system, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, None, None): + name_bufsz = CertGetNameStringW(cert_iter, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, None, None, 0) + buf = ctypes.create_unicode_buffer(name_bufsz) + CertGetNameStringW(cert_iter, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, None, buf, name_bufsz) + name_string = buf.value + key_usage_bits = ctypes.wintypes.BYTE() + CertGetIntendedKeyUsage(X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, cert_iter.contents.pCertInfo, ctypes.byref(key_usage_bits), ctypes.sizeof(key_usage_bits)) + valid_date = CertVerifyTimeValidity(None, cert_iter.contents.pCertInfo) + if ((key_usage_bits.value&CERT_DIGITAL_SIGNATURE_KEY_USAGE) == CERT_DIGITAL_SIGNATURE_KEY_USAGE) and (valid_date == 0) and ('Card Authentication' not in name_string) and ('0,' not in name_string) and ('Signature' not in name_string): + CertAddCertificateContextToStore(store_memory, cert_iter, CERT_STORE_ADD_ALWAYS, ctypes.byref(cert_valid)) + cert_selection = cert_valid + return CryptUIDlgSelectCertificateFromStore(store_memory, hwnd if hwnd is not None else GetConsoleWindow(), 'VistA Logon - Certificate Selection', 'Select a certificate for VistA authentication', 0, 0, None) if show_cert_dialog else cert_selection + +def get_certificate_thumbprint(certificate: PCCERT_CONTEXT) -> str: + bufsz = ctypes.wintypes.DWORD() + CertGetCertificateContextProperty(certificate, CERT_HASH_PROP_ID, None, ctypes.byref(bufsz)) + buffer = ctypes.create_string_buffer(bufsz.value) + CertGetCertificateContextProperty(certificate, CERT_HASH_PROP_ID, buffer, ctypes.byref(bufsz)) + return buffer.value + +def get_certificate_friendly_display_name(certificate: PCCERT_CONTEXT) -> str: + name_bufsz = CertGetNameStringW(certificate, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, None, None, 0) + buffer = ctypes.create_unicode_buffer(name_bufsz) + CertGetNameStringW(certificate, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, None, buffer, name_bufsz) + return buffer.value + +get_registry_iam = lambda: get_registry_value(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Vista\\Common\\IAM', default='https://services.eauth.va.gov:9301/STS/RequestSecurityToken') +get_registry_iam_ad = lambda: get_registry_value(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Vista\\Common\\IAM_AD', default='https://services.eauth.va.gov:9201/STS/RequestSecurityToken') +get_registry_rioserver = lambda: get_registry_value(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Vista\\Common\\RIOSERVER', default='SecurityTokenService') +get_registry_rioport = lambda: get_registry_value(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Vista\\Common\\RIOPORT', default='RequestSecurityToken') +def get_registry_value(hkey: int, subkey: str, value: Optional[str]=None, default: Any=None) -> Any: + try: + with winreg.OpenKey(hkey, subkey) as key: + return winreg.QueryValueEx(key, value)[0] + except FileNotFoundError: + return default + +# issuer: https://ssoi.sts.va.gov/Issuer/smtoken/SAML2 +# application: https://{computer_name}/Delphi_RPC_Broker/{app_name} +# app_name: CPRSChart.exe +def get_iam_request(application: str, issuer: str) -> str: + return f''' + + + + + + + + + + {application} + + + + {issuer} + + http://schemas.xmlsoap.org/ws/2005/02/trust/Validate + + +''' + +get_local_hostname = lambda: socket.getfqdn() + +def get_sso_token(application: Optional[str]=None, hostname: Optional[str]=None, issuer: Optional[str]=None, iam: Optional[str]=None, ua: Optional[str]=None, certificate: Optional[str]=None) -> str: + import sys, subprocess + if certificate is None: + certificate = get_certificate_thumbprint(get_vista_certificate()).hex() + res = subprocess.run(['curl', '-fsSL', '-X', 'POST', iam or get_registry_iam(), '--ca-native', '--cert', 'CurrentUser\\MY\\' + certificate, '-A', ua or DEFAULT_USER_AGENT, '-H', 'Content-Type: application/xml', '-H', 'Accept: application/xml', '-d', get_iam_request(f"https://{hostname or get_local_hostname()}/Delphi_RPC_Broker/{application or 'CPRSChart.exe'}", issuer or DEFAULT_ISSUER)], capture_output=True) + print(res.stderr.decode('utf8'), end='', file=sys.stderr) + return res.stdout.decode('utf8') + +async def get_sso_token_async(application: Optional[str]=None, hostname: Optional[str]=None, issuer: Optional[str]=None, iam: Optional[str]=None, ua: Optional[str]=None, certificate: Optional[str]=None) -> str: + import sys, asyncio + if certificate is None: + certificate = get_certificate_thumbprint(get_vista_certificate()).hex() + res = await (await asyncio.create_subprocess_exec('curl', '-fsSL', '-X', 'POST', iam or get_registry_iam(), '--ca-native', '--cert', 'CurrentUser\\MY\\' + certificate, '-A', ua or DEFAULT_USER_AGENT, '-H', 'Content-Type: application/xml', '-H', 'Accept: application/xml', '-d', get_iam_request(f"https://{hostname or get_local_hostname()}/Delphi_RPC_Broker/{application or 'CPRSChart.exe'}", issuer or DEFAULT_ISSUER), stdin=None, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)).communicate() + print(res[1].decode('utf8'), end='', file=sys.stderr) + return res[0].decode('utf8') + +if __name__ == '__main__': + try: + print(get_sso_token()) + except OSError: + exit(1) diff --git a/autoproc.py b/autoproc.py new file mode 100644 index 0000000..3d6f3af --- /dev/null +++ b/autoproc.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 + +import sys +import getpass +import re +import codecs +import asyncio +import contextlib +import logging +from collections import namedtuple + +from typing import Optional, Union, Sequence, NamedTuple, Callable + +logger = logging.getLogger(__name__) + +ExpectMatch = namedtuple('PatternMatch', ('batch', 'index', 'pattern', 'match', 'groups', 'groupdict', 'before')) +ExpectMatch.__new__.__defaults__ = (None,)*len(ExpectMatch._fields) +class ExpectQ(object): + """Provide an expect-like interface over an asyncio queue""" + def __init__(self, pipequeue: asyncio.Queue, timeout_settle: float=1): + self.pipequeue = pipequeue + self.buffer = '' + self.timeout_settle = timeout_settle + def set_timeout(self, timeout_settle: float=1): + """Set default timeout""" + self.timeout_settle = timeout_settle + def reset(self, buffer: str=''): + """Clear or restore buffer""" + self.buffer = buffer + clear = reset + async def prompts(self, endl: str='\r\n', timeout_settle: Optional[float]=None, throw: bool=False): + len_endl = len(endl) + while True: + if (pos := self.buffer.rfind(endl)) >= 0: + buffer = self.buffer + self.buffer = '' + yield buffer, pos + len_endl + while True: + try: + self.buffer += await asyncio.wait_for(self.pipequeue.get(), timeout=(timeout_settle or self.timeout_settle)) + break + except asyncio.TimeoutError: # no more data + if throw: + raise + yield None, None + async def promptmatches(self, *mappings: Union[str, re.Pattern, tuple, list], endl: str='\r\n', timeout_settle: Optional[float]=None, throw: bool=False): + for i, mapping in enumerate(mappings): + try: + match mapping: + case (str() as pattern, response) if response is None or isinstance(response, str) or callable(response): + async for buffer, pos in self.prompts(endl=endl, timeout_settle=timeout_settle, throw=True): + if pattern == buffer[pos:]: + yield (m := self.ExactMatch(batch=i, index=0, pattern=mapping, match=mapping, groups=None, groupdict=None, before=buffer[:pos])), (response(m) if callable(response) else response) + break + else: + self.reset(buffer) + case (re.Pattern() as pattern, response) if response is None or isinstance(response, str) or callable(response): + async for buffer, pos in self.prompts(endl=endl, timeout_settle=timeout_settle, throw=True): + if match := pattern.search(buffer[pos:]): + yield (m := self.PatternMatch(batch=i, index=0, pattern=pattern, match=match, groups=match.groups(), groupdict=match.groupdict(), before=buffer[:pos])), (response(m) if callable(response) else response) + break + else: + self.reset(buffer) + case (*_,) as components: + exact = {} + expr = {} + for j, component in enumerate(components): + match component: + case (str() as pattern, response, *rest) if response is None or isinstance(response, str) or callable(response): + exact[pattern] = (j, response, None if len(rest) < 1 else rest[0]) + case (re.Pattern() as pattern, response, *rest) if response is None or isinstance(response, str) or callable(response): + expr[pattern] = (j, response, None if len(rest) < 1 else rest[0]) + async for buffer, pos in self.prompts(endl=endl, timeout_settle=timeout_settle, throw=True): + if buffer is not None: + prompt = buffer[pos:] + if prompt in exact: + j, response, end = exact[prompt] + interrupt = yield (m := self.ExactMatch(batch=i, index=j, pattern=prompt, match=prompt, groups=None, groupdict=None, before=buffer[:pos])), (response(m) if callable(response) else response) + else: + for pattern in expr: + if match := pattern.search(prompt): + j, response, end = expr[pattern] + interrupt = yield (m := self.PatternMatch(batch=i, index=j, pattern=pattern, match=match, groups=match.groups(), groupdict=match.groupdict(), before=buffer[:pos])), (response(m) if callable(response) else response) + break + else: + self.reset(buffer) + continue + if interrupt: + yield + break + elif end: + break + except asyncio.TimeoutError as ex: # no more data + if throw: + raise asyncio.TimeoutError(*(ex.args + (i, mapping))) + yield None, None + async def earliest(self, *patterns: Union[str, re.Pattern], timeout_settle: Optional[float]=None, throw: bool=False) -> Optional[NamedTuple]: + """Wait for any string or regular expression pattern match, specified in *patterns, and optionally raise exception upon timeout""" + try: + while True: + for i, pattern in enumerate(patterns): # try every option + if isinstance(pattern, str): + if (pos := self.buffer.find(pattern)) >= 0: # found it + res = self.ExactMatch(index=i, pattern=pattern, match=pattern, groups=None, groupdict=None, before=self.buffer[:pos]) + self.buffer = self.buffer[pos + len(pattern):] + return res + else: + if match := pattern.search(self.buffer): # found it + res = self.PatternMatch(index=i, pattern=pattern, match=match, groups=match.groups(), groupdict=match.groupdict(), before=self.buffer[:match.start()]) + self.buffer = self.buffer[match.end():] + return res + else: # fetch more data + self.buffer += await asyncio.wait_for(self.pipequeue.get(), timeout=(timeout_settle or self.timeout_settle)) + except asyncio.TimeoutError: # no more data + if throw: + raise + return None + async def startswith(self, *patterns: Union[str, re.Pattern], timeout_settle: Optional[float]=None, throw: bool=False) -> Optional[NamedTuple]: + """Wait for any string or regular expression pattern match, specified in *patterns, at the start of the stream and optionally raise exception upon timeout""" + try: + while True: + for i, pattern in enumerate(patterns): # try every option + if isinstance(pattern, str): + if self.buffer.startswith(pattern): # found it + res = self.ExactMatch(index=i, pattern=pattern, match=pattern, groups=None, groupdict=None, before='') + self.buffer = self.buffer[len(pattern):] + return res + else: + if match := pattern.match(self.buffer): # found it + res = self.PatternMatch(index=i, pattern=pattern, match=match, groups=match.groups(), groupdict=match.groupdict(), before=self.buffer[:match.start()]) + self.buffer = self.buffer[match.end():] + return res + else: # fetch more data + self.buffer += await asyncio.wait_for(self.pipequeue.get(), timeout=(timeout_settle or self.timeout_settle)) + except asyncio.TimeoutError: # no more data + if throw: + raise + return None + async def endswith(self, *patterns: Union[str, re.Pattern], timeout_settle: Optional[float]=None, throw: bool=False) -> Optional[NamedTuple]: + """Wait for any string or regular expression pattern match, specified in *patterns, at the end of the stream and optionally raise exception upon timeout""" + try: + while True: + for i, pattern in enumerate(patterns): # try every option + if isinstance(pattern, str): + if self.buffer.endswith(pattern): # found it + res = self.ExactMatch(index=i, pattern=pattern, match=pattern, groups=None, groupdict=None, before=self.buffer[:-len(pattern)]) + self.buffer = '' + return res + else: + if match := pattern.search(self.buffer): # found it + res = self.PatternMatch(index=i, pattern=pattern, match=match, groups=match.groups(), groupdict=match.groupdict(), before=self.buffer[:match.start()]) + self.buffer = self.buffer[match.end():] + return res + else: # fetch more data + self.buffer += await asyncio.wait_for(self.pipequeue.get(), timeout=(timeout_settle or self.timeout_settle)) + except asyncio.TimeoutError: # no more data + if throw: + raise + return None + __call__ = earliest + ExactMatch = type('ExactMatch', (ExpectMatch,), {}) + PatternMatch = type('PatternMatch', (ExpectMatch,), {}) + +class LockableCallable(object): + def __init__(self, func: Callable, lock: asyncio.Lock=None): + if lock is None: + lock = asyncio.Lock() + self.lock = lock + self.locked = lock.locked + self.acquire = lock.acquire + self.release = lock.release + self.func = func + self.__name__ = func.__name__ + self.__doc__ = func.__doc__ + def __call__(self, *args, **kw): + return self.func(*args, **kw) + async def __aenter__(self): + await self.lock.acquire() + async def __aexit__(self, exc_type, exc, tb): + self.lock.release() + async def withlock(self, *args, **kw): + async with self.lock: + return self.func(*args, **kw) + +async def create_instrumented_subprocess_exec(*args: str, stdin_endl=b'\n', **kw) -> asyncio.subprocess.Process: + """Create asyncio subprocess, coupled to host stdio, with ability to attach tasks that could inspect its stdout and inject into its stdin""" + process = await asyncio.create_subprocess_exec(*args, **kw) + tasks = set() + queues = set() + def create_task(*args, **kw): + tasks.add(item := asyncio.create_task(*args, **kw)) + item.add_done_callback(tasks.remove) + return item + process.create_task = create_task + def subscribe(pipequeue=None): + queues.add(pipequeue := pipequeue or asyncio.Queue()) + pipequeue.unsubscribe = lambda: queues.remove(pipequeue) + return pipequeue + process.subscribe = subscribe + def sendline(data=None, endl=None): + if data is not None: + process.stdin.write(data.encode('utf-8') + (endl or stdin_endl)) + else: + process.stdin.write(endl or stdin_endl) + process.sendline = LockableCallable(sendline) + create_task(stdout_writer(process.stdout, queues), name='@task:stdout-writer') # stdout + process_wait = process.wait + async def wait_wrapper(): # clean up tasks at the end + await process_wait() + proc_id = id(process) + logger.debug('SHUTDOWN [proc#%d]: cleaning up'%proc_id) + for item in set(tasks): # copy set to avoid RuntimeError: Set changed size during iteration + if not item.done(): + item.cancel() + try: + logger.debug('SHUTDOWN [proc#%d]: stopping [task#%d] %r'%(proc_id, id(item), item)) + await item + except asyncio.CancelledError: + pass + logger.debug('SHUTDOWN [proc#%d]: stopped [task#%d]'%(proc_id, id(item))) + logger.debug('SHUTDOWN [proc#%d]: done'%proc_id) + process.wait = wait_wrapper + return process + +async def stdout_writer(pipe: asyncio.StreamWriter, subscribers: Sequence[asyncio.Task], chunksize: int=4096, echo: bool=True): + """Read data from pipe, decode into Unicode strings, and send to subscribers""" + try: + decoder = codecs.getincrementaldecoder('utf-8')(errors='replace') + while True: + try: + chunk = await pipe.read(chunksize) # fetch a bunch of bytes + if not chunk: # EOF + break + text = decoder.decode(chunk) + except asyncio.TimeoutError: + continue + except UnicodeDecodeError: # should not encounter errors with errors='replace' + logger.exception('stdout_writer') + break # bail on error + else: + if echo: # echo to stdout + sys.stdout.write(text) + sys.stdout.flush() + for item in subscribers: # distribute to subscribers + await item.put(text) + except KeyboardInterrupt: + logger.info('KeyboardInterrupt: stdout_writer') + +@contextlib.contextmanager +def subscribe(proc): + queue = proc.subscribe() + queue.sendline = proc.sendline + try: + yield queue + finally: + queue.unsubscribe() + +@contextlib.asynccontextmanager +async def subscribe_async(proc): + queue = proc.subscribe() + queue.sendline = proc.sendline + try: + yield queue + finally: + queue.unsubscribe() + +@contextlib.contextmanager +def expect(proc): + queue = proc.subscribe() + expect = ExpectQ(queue) + expect.sendline = proc.sendline + try: + yield expect + finally: + queue.unsubscribe() + +@contextlib.asynccontextmanager +async def expect_async(proc): + queue = proc.subscribe() + expect = ExpectQ(queue) + expect.sendline = proc.sendline + try: + yield expect + finally: + queue.unsubscribe() diff --git a/ext_discovery.py b/ext_discovery.py new file mode 100644 index 0000000..c78fede --- /dev/null +++ b/ext_discovery.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +import re +import autoproc + +async def cmd_listclinics(proc): + """Fetch list of clinics""" + async with proc.sendline, autoproc.expect_async(proc) as expect: + proc.sendline('^Appointment List') + assert await expect.endswith('\r\nSelect division: ALL// ') + proc.sendline() # default ALL + assert await expect.endswith('\r\nCount, Non Count, or Both: C//') + proc.sendline('Both') + assert await expect.endswith('\r\nSelect clinic: ALL// ') + proc.sendline('??') + assert await expect.earliest('\r\n Choose from:') + while m_delimiter := await expect.endswith('\r\n Type to continue or \'^\' to exit: ', '\r\nSelect clinic: ALL// '): + for line in m_delimiter.before.splitlines(): + line = line.strip() + if len(line) > 0: + assert (m := re.match(r'^(\d+)\s{2,}(.*?)(?:\s{2,}(.*?))?$', line)) + yield { 'uid': int(m.group(1)), 'name': m.group(2).upper(), 'provider': m.group(3).upper() if m.group(3) else None } + if m_delimiter.index == 0: + proc.sendline() + else: + proc.sendline('^') + break + proc.sendline('^Patient information AND OE/RR') + assert await expect.endswith('\r\nSelect Patient Information and OE/RR Option: ', '\r\nSelect Patient Information and OE/RR Option: ') + expect.clear() diff --git a/ext_lab.py b/ext_lab.py new file mode 100644 index 0000000..16246c9 --- /dev/null +++ b/ext_lab.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 + +import re +import datetime +import util +import autoproc + +import logging +logger = logging.getLogger(__name__) + +local_tzinfo = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo +def parse(text): + data = { 'body': text.rstrip() } + if match := re.search(r'\bProvider: \b(?P.*?)\r\n', text): + data.update(match.groupdict()) + if match := re.search(r'\bSpecimen: \b(?P.*?)\r\n', text): + data.update(match.groupdict()) + if match := re.search(r'\bAccession \[UID\]: \b(?P.*?) \[(?P.*?)\]\r\n', text): + data.update(match.groupdict()) + if match := re.search(r'\bReport Released: \b(?P.*?)\r\n', text): + value = match.group(1) + data['time_released'] = datetime.datetime.strptime(value, '%b %d, %Y@%H:%M').replace(tzinfo=local_tzinfo) if '@' in value else datetime.datetime.strptime(value, '%b %d, %Y').replace(tzinfo=local_tzinfo) + if match := re.search(r'\bSpecimen Collection Date: \b(?P.*?)\r\n', text): + value = match.group(1) + data['time_collected'] = datetime.datetime.strptime(value, '%b %d, %Y@%H:%M').replace(tzinfo=local_tzinfo) if '@' in value else datetime.datetime.strptime(value, '%b %d, %Y').replace(tzinfo=local_tzinfo) + if match := re.match(r'\s+----(.*?)----\s+page \d+\r\n', text): + data['title'] = match.group(1) + if match := re.search(r'\bAccession \[UID\]: (?P.*?) \[(?P.*?)\]\s+Received: (?P.*?)\r\n', text): + data.update(match.groupdict()) + data['time_received'] = datetime.datetime.strptime(data['time_received'], '%b %d, %Y@%H:%M').replace(tzinfo=local_tzinfo) if '@' in data['time_received'] else datetime.datetime.strptime(data['time_received'], '%b %d, %Y').replace(tzinfo=local_tzinfo) + if match := re.search(r'\bReport Completed: \b(?P.*?)\r\n', text): + value = match.group(1) + data['time_completed'] = datetime.datetime.strptime(value, '%b %d, %Y@%H:%M').replace(tzinfo=local_tzinfo) if '@' in value else datetime.datetime.strptime(value, '%b %d, %Y').replace(tzinfo=local_tzinfo) + if match := re.search(r'\bCollection sample: (?P.*?)\s+Collection date: (?P.*?)\r\n', text): + data.update(match.groupdict()) + data['time_collected'] = datetime.datetime.strptime(data['time_collected'], '%b %d, %Y %H:%M').replace(tzinfo=local_tzinfo) if ':' in data['time_collected'] else datetime.datetime.strptime(data['time_collected'], '%b %d, %Y').replace(tzinfo=local_tzinfo) + return data + +async def cmd_reports(proc, mrn, alpha, omega): + """Fetch lab reports""" + async with proc.sendline, autoproc.expect_async(proc) as expect: + proc.sendline('^Laboratory Menu') + async for prompt, response in expect.promptmatches( + ('Select HOSPITAL LOCATION NAME: ', None), + ('Select Laboratory Menu Option: ', '13'), # Interim report + ('Select Patient Name: ', mrn), + ( + ('Do you wish to continue with this patient [Yes/No]? ', 'Yes'), + ('Date to START with: TODAY//', util.vista_strftime(omega), True), + ), + ('Date to END with: T-7//', util.vista_strftime(alpha)), + ('Print address page? NO// ', None), # default NO + ( + ('Do you want to start each note on a new page? NO// ', None), # default NO + ('DEVICE: HOME// ', 'HOME;90;1023', True), + ), + throw=True): + proc.sendline(response) + assert await expect.earliest(' HOME(CRT)\r\n') + pages = [] + async for prompt, response in expect.promptmatches(( + (re.compile(r' PRESS \'\^\' TO STOP $'), None), + (re.compile(r' \'\^\' TO STOP$'), None), + ('Select Patient Name: ', None), + ('Select Laboratory Menu Option: ', None, True), + ), throw=True): + proc.sendline(response) + match prompt: + case autoproc.ExpectMatch(index=(0|1), before=before): + if left := re.match(r'(?:\x1b\[H\x1b\[J\x1b\[2J\x1b\[H\r\n\r\n.+?[ ]{2,}Report date: .+?\r\n Pat ID: \d{3}-\d{2}-\d{4}[ ]{2,}SEX: \w[ ]{2,}DOB: .+?[ ]{2,}LOC: .+?\r\n)|(?:\r\n\x1b\[H\x1b\[J\x1b\[2J\x1b\[H\r\n.+?[ ]{2,}\d{3}-\d{2}-\d{4}[ ]{2,}AGE: \d+[^\r\n]*?\r\n)|(?:\r[ ]+\r\r\n.+?[ ]{2,}\d{3}-\d{2}-\d{4}[ ]{2,}AGE: \d+[ ]{2,}.+?\r\n)', before): + pages.append(before[len(left.group(0)):]) + elif re.match(r'(?:\r\n)+.+?[ ]{2,}\d{3}-\d{2}-\d{4}[ ]{2,}.+?[ ]+$', before) or re.match(r'^(?:\r\n)+$', before): + pass + else: + print(repr(before)) + assert False + assert await expect.endswith('\r\nSelect Patient Information and OE/RR Option: ', '\r\nSelect Patient Information and OE/RR Option: ') + expect.clear() + text = re.sub(r'\r\n\s+>> CONTINUATION OF .+? <<(?:(?:\r\n)|(?:\s+page \d+))', '', '\r\n'.join(pages)) + positions = [m.start() for m in re.finditer(r'(?:(?:[ ]+----MICROBIOLOGY----[ ]+page \d+\r\n\r\n)|(?:[ ]+))Reporting Lab:', text)] + positions.append(len(text)) + for i in range(len(positions) - 1): + yield parse(text[positions[i]:positions[i + 1]]) diff --git a/ext_measurement.py b/ext_measurement.py new file mode 100644 index 0000000..90daba6 --- /dev/null +++ b/ext_measurement.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +import re +import datetime +import util +import autoproc + +units = { + 'P': 'bpm', + 'R': 'bpm', + 'B/P': 'mmHg', + 'Body Mass Index': 'kg/m²' +} + +local_tzinfo = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo +async def cmd_entries(proc, mrn, alpha, omega): + """Fetch measurements""" + async with proc.sendline, autoproc.expect_async(proc) as expect: + proc.sendline('^Results Reporting Menu') + async for prompt, response in expect.promptmatches( + ( + (' Press return to continue ', None), + ('Select Patient(s): ', mrn, True), + ('Select Patient: ', mrn, True), + ), + ('Select Item(s): ', '7'), # Vitals Cumulative Report + ('Start Date [Time]: T// ', util.vista_strftime(alpha)), + (re.compile(r'^Ending Date \[Time\] \(inclusive\): (.*?)// $'), util.vista_strftime(omega)), + ('DEVICE: HOME// ', 'HOME;;1023'), + timeout_settle=2, throw=True): + proc.sendline(response) + assert await expect.earliest(' HOME(CRT)\r\n') + pages = [] + async for prompt, response in expect.promptmatches(( + ('Press return to continue "^" to escape ', None), + ('Press RETURN to continue or \'^\' to exit: ', None), + ('Select Clinician Menu Option: ', None, True), + ), throw=True): + proc.sendline(response) + if prompt.index == 0 or prompt.index == 1: + pages.append(re.sub(r'^\x1b\[H\x1b\[J\x1b\[2J\x1b\[H\r\n[^\r\n]+? Cumulative Vitals\/Measurements Report[ ]+Page \d+\r\n\r\n-{10,}\r\n(?:\d{2}\/\d{2}\/\d{2} \(continued\)\r\n\r\n)?|\r\n\r\n\*\*\*[^\r\n]+\r\n\r\n[^\r\n]+?VAF 10-7987j\r\nUnit:[^\r\n]+\r\nDivision:[^\r\n]+(?:\r\n)?$', '', prompt.before)) + assert await expect.endswith('\r\nSelect Patient Information and OE/RR Option: ', '\r\nSelect Patient Information and OE/RR Option: ') + expect.clear() + for m_date in re.finditer(r'^(?P\d{2}\/\d{2}\/\d{2})\r\n(?P.*?\r\n)(?:(?=\d{2}\/)|\r\n|$)', '\r\n'.join(pages), re.DOTALL|re.MULTILINE): + g_date = m_date.group('date') + for m_time in re.finditer(r'^(?P