ソースを参照

Initial code transfer from local repo (no history, sorry)

Hal De 4 年 前
コミット
dda8d6728f
6 ファイル変更741 行追加0 行削除
  1. 78 0
      .env.dist
  2. 75 0
      README.md
  3. 14 0
      app.env.dist
  4. 420 0
      app/app.py
  5. 90 0
      app/utils.py
  6. 64 0
      docker-compose.yml

+ 78 - 0
.env.dist

@@ -0,0 +1,78 @@
+APP_FQDN=127.0.0.1
+MYSQL_ROOT_PASSWORD=secret
+MYSQL_PASSWORD=secret
+FREEPBX_CDRDBPASS=secret
+FREEPBX_AMPMGRPASS=secret
+
+SENDMAIL_TG=false
+TG_BOT_APIKEY=secret
+TG_BOT_CHATID=secret
+
+PERSISTENT_STORAGE_PATH=./data
+HTTPD_HTTPS_ENABLED=true
+HTTPD_REDIRECT_HTTP_TO_HTTPS=true
+LETSENCRYPT_ENABLED=false
+
+SMTP_MAIL_FROM=pbx@pbx.example.com
+ROOT_MAILTO=admin@example.com
+FAIL2BAN_DEFAULT_DESTEMAIL=security@example.com
+FAIL2BAN_DEFAULT_SENDER=fail2ban@example.com
+
+APP_DATA=/data
+APP_PORT_HTTP=80
+APP_PORT_HTTPS=443
+APP_PORT_IAX=4569
+APP_PORT_MYSQL=3306
+APP_PORT_PJSIP=5160
+APP_PORT_RTP_END=20000
+APP_PORT_RTP_START=10000
+APP_PORT_SIP=5060
+APP_API_PORT=8000
+
+CRON_ENABLED=true
+FAIL2BAN_ENABLED=true
+HTTPD_ENABLED=true
+POSTFIX_ENABLED=true
+RRTPBX_ENABLED=true
+
+FAIL2BAN_ASTERISK_ENABLED=true
+FAIL2BAN_DEFAULT_BANTIME=300
+FAIL2BAN_DEFAULT_FINDTIME=3600
+FAIL2BAN_DEFAULT_IGNOREIP=127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
+FAIL2BAN_DEFAULT_MAXRETRY=10
+FAIL2BAN_RECIDIVE_BANTIME=1814400
+FAIL2BAN_RECIDIVE_ENABLED=true
+FAIL2BAN_RECIDIVE_FINDTIME=15552000
+FAIL2BAN_RECIDIVE_MAXRETRY=10
+
+FREEPBX_AMPEXTENSIONS=deviceanduser
+FREEPBX_AS_DISPLAY_READONLY_SETTINGS=1
+FREEPBX_AS_OVERRIDE_READONLY=1
+FREEPBX_ASTSIPDRIVER=chan_pjsip
+#FREEPBX_BRAND_FREEPBX_ALT_FOOT=FreePBX®
+#FREEPBX_BRAND_FREEPBX_ALT_LEFT=FreePBX
+#FREEPBX_BRAND_IMAGE_FREEPBX_FOOT=images/freepbx_small.png
+#FREEPBX_BRAND_IMAGE_FREEPBX_LINK_FOOT=http://www.freepbx.org
+#FREEPBX_BRAND_IMAGE_FREEPBX_LINK_LEFT=http://www.freepbx.org
+#FREEPBX_BRAND_IMAGE_SPONSOR_FOOT=images/sangoma-horizontal_thumb.png
+#FREEPBX_BRAND_IMAGE_SPONSOR_LINK_FOOT=http://www.sangoma.com
+#FREEPBX_BRAND_IMAGE_TANGO_LEFT=images/tango.png
+#FREEPBX_BRAND_SPONSOR_ALT_FOOT=www.sangoma.com
+FREEPBX_CDRDBHOST=127.0.0.1
+FREEPBX_CDRDBNAME=asteriskcdrdb
+FREEPBX_CDRDBTABLENAME=cdr
+FREEPBX_CDRDBTYPE=mysql
+FREEPBX_CDRDBUSER=asterisk
+FREEPBX_DYNAMICHINTS=1
+FREEPBX_ENABLECW=0
+FREEPBX_FREEPBX_SYSTEM_IDENT=PBX
+#FREEPBX_MODULES_EXTRA=soundlang callrecording cdr conferences customappsreg featurecodeadmin infoservices logfiles music manager arimanager filestore recordings announcement asteriskinfo backup callforward callwaiting daynight calendar certman cidlookup contactmanager donotdisturb fax findmefollow iaxsettings miscapps miscdests ivr parking phonebook presencestate printextensions queues cel timeconditions pm2
+FREEPBX_PHPTIMEZONE=Europe/Moscow
+FREEPBX_SIGNATURECHECK=0
+FREEPBX_TONEZONE=ru
+FREEPBX_USEGOOGLEDNSFORENUM=1
+#HTTPD_ALLOW_FROM=127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
+
+MYSQL_DATABASE=asterisk
+MYSQL_SERVER=127.0.0.1
+MYSQL_USER=asterisk

+ 75 - 0
README.md

@@ -0,0 +1,75 @@
+# Quick Start:
+```sh
+git clone https://gogs.halsbox.ru/RRT/pbx.git
+cd pbx
+cp .env.dist .env
+cp app.env.dist app.env
+```
+
+Edit `.env` and `app.env` with your preffered editor.
+Adjust environment variables for your needs.
+The most important variables to set are:
+| Variable | Description |
+| -------- | ----------- |
+| PERSISTENT_STORAGE_PATH | Host path for persistent data storage |
+| APP_FQDN | Domain name of the app |
+| APP_AMI_HOST | IP address of host (by default Asterisk runs in host network mode) |
+| APP_AMI_USERNAME | AMI username for the app |
+| APP_AMI_SECRET | AMI password for the app |
+| APP_AUTH_HEADER | HTTP header to use for the app auth |
+| APP_AUTH_SECRET | Secret string to authorize access to the app |
+| MYSQL_ROOT_PASSWORD | Set this to some secure password |
+| MYSQL_PASSWORD | Set this to some secure password |
+| FREEPBX_AMPMGRPASS | Password for Freepbx builtin AMI admin user, set it to some secure password |
+| FREEPBX_CDRDBPASS | Set it to same value as MYSQL_PASSWORD |
+| SENDMAIL_TG | Change to "true" if your want all mail from PBX to be forwarded to Telegram |
+| TG_BOT_APIKEY | Create Telegram bot using BotFather and put your new bot API key here |
+| TG_BOT_CHATID | Set destination Telegram User Id or Chat Id |
+| HTTPD_HTTPS_ENABLED | Set to "true" to enable HTTPS for Freepbx |
+| HTTPD_REDIRECT_HTTP_TO_HTTPS | Set to "true" to redirect HTTP requests to HTTPS |
+| LETSENCRYPT_ENABLED | Set to "true" to automatically request and maintain LetsEncrypt cert for HTTPS |
+| | Change following variables to desired values. Not required if SENDMAIL_TG=true. |
+| SMTP_MAIL_FROM |
+| ROOT_MAILTO |
+| FAIL2BAN_DEFAULT_DESTEMAIL |
+| FAIL2BAN_DEFAULT_SENDER |
+
+Run:
+
+```sh
+
+docker-compose build
+```
+Wait paitently until you see:
+`Successfully tagged halsbox/docker-freepbx:latest`
+If running for first time it can take long to build everything.
+
+Run:
+
+```
+
+docker-compose up -d
+```
+
+Run:
+
+```
+
+docker-compose logs -f pbx
+```
+Watch pbx container initialization for errors and wait for:
+` fail2ban entered RUNNING state, process has stayed up for > than 5 seconds`
+Close container log output with `Ctrl+C` keys.
+
+Restart container with `docker restart pbx` if you set `LETSENCRYPT_ENABLED` to `true`.
+
+Open the address you set for APP_FQDN in browser and configure Freepbx superadmin username and password. Proceed to voice language configuration. Finally press "Apply Config" button.
+
+Run:
+
+```
+
+docker-compose logs -f app
+```
+Open `http://APP_FQDN:8000/ui`
+Test the API with youre configured `APP_AUTH_SECRET`

+ 14 - 0
app.env.dist

@@ -0,0 +1,14 @@
+APP_TITLE="PBX API"
+APP_SCHEME=http
+APP_BODY_TIMEOUT=60
+APP_DEBUG=False
+APP_MAX_CONTENT_LENGTH=16777216
+APP_AMI_HOST=127.0.0.1
+APP_AMI_PORT=5038
+APP_AMI_USERNAME=app
+APP_AMI_SECRET=secret
+APP_AMI_PING_DELAY=10
+APP_AMI_PING_INTERVAL=10
+APP_AMI_TIMEOUT=5
+APP_AUTH_HEADER=APP-auth-token
+APP_AUTH_SECRET=secret

+ 420 - 0
app/app.py

@@ -0,0 +1,420 @@
+#!/usr/bin/env python3
+import asyncio
+import logging
+import os
+import re
+import json
+import base64
+from quart import jsonify, request, render_template_string
+from quart_openapi import Pint, Resource
+from http import HTTPStatus
+from panoramisk import Manager, Message
+from utils import *
+from logging.config import dictConfig
+
+# One asyncio event loop is used for AMI communication and HTTP requests routing with Quart
+main_loop = asyncio.get_event_loop()
+
+app = Pint(__name__, title=os.getenv('APP_TITLE', 'PBX API'), no_openapi=True)
+
+app.config.update({
+  'TITLE':                  os.getenv('APP_TITLE', 'PBX API'),
+  'APPLICATION_ROOT':       os.getenv('APP_APPLICATION_ROOT', None),
+  'SCHEME':                 os.getenv('APP_SCHEME', 'http'),
+  'FQDN':                   os.getenv('APP_FQDN', '127.0.0.1'),
+  'PORT':               int(os.getenv('APP_API_PORT', 8000)),
+  'BODY_TIMEOUT':       int(os.getenv('APP_BODY_TIMEOUT', 60)),
+  'DEBUG':                  os.getenv('APP_DEBUG', 'False').lower() in TRUEs,
+  'MAX_CONTENT_LENGTH': int(os.getenv('APP_MAX_CONTENT_LENGTH', 16777216)),
+  'AMI_HOST':               os.getenv('APP_AMI_HOST', '127.0.0.1'),
+  'AMI_PORT':           int(os.getenv('APP_AMI_PORT', 5038)),
+  'AMI_USERNAME':           os.getenv('APP_AMI_USERNAME', 'app'),
+  'AMI_SECRET':             os.getenv('APP_AMI_SECRET', 'secret'),
+  'AMI_PING_DELAY':     int(os.getenv('APP_AMI_PING_DELAY', 10)),
+  'AMI_PING_INTERVAL':  int(os.getenv('APP_AMI_PING_INTERVAL', 10)),
+  'AMI_TIMEOUT':        int(os.getenv('APP_AMI_TIMEOUT', 5)),
+  'AUTH_HEADER':            os.getenv('APP_AUTH_HEADER', 'APP-auth-token'),
+  'AUTH_SECRET':            os.getenv('APP_AUTH_SECRET', '3bfbeaabf363dd64fe263bd36830a6b6'),
+  'SWAGGER_JS_URL':         os.getenv('APP_SWAGGER_JS_URL', SWAGGER_JS_URL),
+  'SWAGGER_CSS_URL':        os.getenv('APP_SWAGGER_CSS_URL', SWAGGER_CSS_URL)})
+
+manager = Manager(
+  loop=main_loop,
+  host=app.config['AMI_HOST'],
+  port=app.config['AMI_PORT'],
+  username=app.config['AMI_USERNAME'],
+  secret=app.config['AMI_SECRET'],
+  ping_delay=app.config['AMI_PING_DELAY'],
+  ping_interval=app.config['AMI_PING_INTERVAL'],
+  reconnect_timeout=app.config['AMI_TIMEOUT'],
+)
+
+class AuthMiddleware:
+  '''ASGI process middleware that rejects requests missing
+  the correct authentication header'''
+
+  def __init__(self, app):
+    self.app = app
+  async def __call__(self, scope, receive, send):
+    if 'headers' not in scope:
+      return await self.app(scope, receive, send)
+    for header, value in scope['headers']:
+      if ((header == bytes(app.config['AUTH_HEADER'].lower(), 'utf-8')) and
+          (value == bytes(app.config['AUTH_SECRET'], 'utf-8'))):
+        return await self.app(scope, receive, send)
+    # Paths "/openapi.json" and "/ui" do not require auth
+    if (('path' in scope) and
+        (scope['path'] in NO_AUTH_ROUTES)):
+      return await self.app(scope, receive, send)
+    return await self.error_response(receive, send)
+  async def error_response(self, receive, send):
+    await send({'type': 'http.response.start',
+                'status': 401,
+                'headers': [(b'content-length', b'21')]})
+    await send({'type': 'http.response.body',
+                'body': b'Authorization requred',
+                'more_body': False})
+
+app.asgi_app = AuthMiddleware(app.asgi_app)
+
+#@manager.register_event('*')
+#async def ami_callback(mngr: Manager, msg: Message):
+#  print("GOT MSG:", msg)
+
+@app.route('/openapi.json')
+async def openapi():
+  '''Generates JSON that conforms OpenAPI Specification
+  '''
+  schema = app.__schema__
+  schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
+                                                  app.config['FQDN'],
+                                                  app.config['PORT'])}]
+  schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
+                                                       'name': app.config['AUTH_HEADER'],
+                                                       'in': 'header'}}}
+  schema['security'] = [{'ApiKey':[]}]
+  return jsonify(schema)
+
+@app.route('/ui')
+async def ui():
+  '''Swagger UI
+  '''
+  return await render_template_string(SWAGGER_TEMPLATE,
+                                      title=app.config['TITLE'],
+                                      js_url=app.config['SWAGGER_JS_URL'],
+                                      css_url=app.config['SWAGGER_CSS_URL'])
+
+@app.route('/ami/action', methods=['POST'])
+async def action():
+  _payload = await request.get_data()
+  reply = await manager.send_action(json.loads(_payload))
+  return reply.getdict()
+
+@app.route('/ami/getvar/<string:variable>')
+async def amiGetVar(variable):
+  '''AMI GetVar
+  Returns value of requested variable using AMI action GetVar in background.
+
+  Parameters:
+    variable (string): Variable to query for
+
+  Returns:
+    string: Variable value or empty string if variable not found
+  '''
+  reply = await manager.send_action({'Action': 'GetVar',
+                                     'Variable': variable})
+  app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
+  return reply.value
+
+async def amiSetVar(variable, value):
+  '''AMI SetVar
+  Sets variable using AMI action SetVar to value in background.
+
+  Parameters:
+    variable (string): Variable to set
+    value (string): Value to set for variable
+
+  Returns:
+    boolean: True if DBPut action was successfull, False overwise
+  '''
+  reply = await manager.send_action({'Action': 'SetVar',
+                                     'Variable': variable,
+                                     'Value': value})
+  app.logger.warning('SetVar({}, {})'.format(variable, value))
+  if (isinstance(reply, Message) and reply.success):
+    return True
+  return False
+
+async def amiDBGet(family, key):
+  '''AMI DBGet
+  Returns value of requested astdb key using AMI action DBGet in background.
+
+  Parameters:
+    family (string): astdb key family to query for
+    key (string): astdb key to query for
+
+  Returns:
+    string: Value or empty string if variable not found
+  '''
+  reply = await manager.send_action({'Action': 'DBGet',
+                                     'Family': family,
+                                     'Key': key})
+  if (isinstance(reply, list) and
+      (len(reply) > 1)):
+    for message in reply:
+      if (message.event == 'DBGetResponse'):
+        app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
+        return message.val
+  app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
+  return None
+
+async def amiDBPut(family, key, value):
+  '''AMI DBPut
+  Writes value to astdb by family and key using AMI action DBPut in background.
+
+  Parameters:
+    family (string): astdb key family to write to
+    key (string): astdb key to write to
+    value (string): value to write
+
+  Returns:
+    boolean: True if DBPut action was successfull, False overwise
+  '''
+  reply = await manager.send_action({'Action': 'DBPut',
+                                     'Family': family,
+                                     'Key': key,
+                                     'Val': value})
+  app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
+  if (isinstance(reply, Message) and reply.success):
+    return True
+  return False
+
+async def amiDBDel(family, key):
+  '''AMI DBDel
+  Deletes key from family in astdb using AMI action DBDel in background.
+
+  Parameters:
+    family (string): astdb key family
+    key (string): astdb key to delete
+
+  Returns:
+    boolean: True if DBDel action was successfull, False overwise
+  '''
+  reply = await manager.send_action({'Action': 'DBDel',
+                                     'Family': family,
+                                     'Key': key})
+  app.logger.warning('DBDel(/{}/{})'.format(family, key))
+  if (isinstance(reply, Message) and reply.success):
+    return True
+  return False
+
+async def amiSetHint(context, user, hint):
+  '''AMI SetHint
+  Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
+
+  Parameters:
+    context (string): dialplan context
+    user (string): user
+    hint (string): hint for user
+
+  Returns:
+    boolean: True if DialplanUserAdd action was successfull, False overwise
+  '''
+  reply = await manager.send_action({'Action': 'DialplanUserAdd',
+                                     'Context': context,
+                                     'User': user,
+                                     'Priority': 'hint',
+                                     'Application': hint,
+                                     'Replace': 'yes'})
+  app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
+  if (isinstance(reply, Message) and reply.success):
+    return True
+  return False
+
+async def amiCommand(command):
+  '''AMI Command
+  Runs specified command using AMI action Command in background.
+
+  Parameters:
+    command (string): command to run
+
+  Returns:
+    boolean, list: tuple representing the boolean result of request and list of lines of command output
+  '''
+  reply = await manager.send_action({'Action': 'Command',
+                                     'Command': command})
+  result = []
+  if (isinstance(reply, Message) and reply.success):
+    if isinstance(reply.output, list):
+      result = reply.output
+    else:
+      result = reply.output.split('\n')
+    app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
+    return True, result
+  app.logger.warning('Command({})->Error!'.format(command))
+  return False, result
+
+async def amiReload(module='core'):
+  '''AMI Reload
+  Reload specified asterisk module using AMI action reload in background.
+
+  Parameters:
+    module (string): module to reload, defaults to core
+
+  Returns:
+    boolean: True if Reload action was successfull, False overwise
+  '''
+  reply = await manager.send_action({'Action': 'Reload',
+                                     'Module': module})
+  app.logger.warning('Reload({})'.format(module))
+  if (isinstance(reply, Message) and reply.success):
+    return True
+  return False
+
+async def getGlobalVars():
+  globalVars = GlobalVars()
+  for _var in globalVars.d():
+    setattr(globalVars, _var, await amiGetVar(_var))
+  return globalVars
+
+async def setUserHint(user, dial, ast):
+  if dial in NONEs:
+    hint = 'CustomPresence:{}'.format(user)
+  else:
+    _dial= [dial]
+    if (ast.DNDDEVSTATE == 'TRUE'):
+      _dial.append('Custom:DND{}'.format(user))
+    hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
+  return await amiSetHint('ext-local', user, hint)
+
+async def amiQueues():
+  queues = {}
+  reply = await manager.send_action({'Action':'QueueStatus'})
+  if len(reply) >= 2:
+    for message in reply:
+      if message.event == 'QueueMember':
+        _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
+        queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
+  return queues
+
+async def setQueueStates(queues, user, device, state):
+  for queue in [_q for _q, _ma in queues.items() for _m in _ma if _m.user == user]:
+    await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
+
+async def getDeviceUser(device):
+  return await amiDBGet('DEVICE', '{}/user'.format(device))
+
+async def getDeviceDial(device):
+  return await amiDBGet('DEVICE', '{}/dial'.format(device))
+
+async def getUserCID(user):
+  return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
+
+async def setDeviceUser(device, user):
+  return await amiDBPut('DEVICE', '{}/user'.format(device), user)
+
+async def setUserDevice(user, device):
+  if device is None:
+    return await amiDBDel('AMPUSER', '{}/device'.format(user))
+  else:
+    return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
+
+async def unbindOtherDevices(user, newDevice, queues, ast):
+  '''Unbinds user from all devices except newDevice and sets
+  all required device states.
+  '''
+  devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
+  if devices not in NONEs:
+    for _device in sorted(set(previousDevices.split('&')), key=int):
+      if _device != newDevice:
+        if ast.FMDEVSTATE == 'TRUE':
+          await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
+        if ast.QUEDEVSTATE == 'TRUE':
+          await setQueueStates(queues, user, _device, 'NOT_INUSE')
+        if ast.DNDDEVSTATE:
+          await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
+        if ast.CFDEVSTATE:
+          await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
+        await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
+
+async def setUserDeviceStates(user, device, queues, ast):
+  if ast.FMDEVSTATE == 'TRUE':
+    _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
+    if _followMe is not None:
+      await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
+  if ast.QUEDEVSTATE == 'TRUE':
+    await setQueueStates(queues, user, device, 'INUSE')
+  if ast.DNDDEVSTATE:
+    _dnd = await amiDBGet('DND', user)
+    await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
+  if ast.CFDEVSTATE:
+    _cf = await amiDBGet('CF', user)
+    await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
+
+@app.route('/device/<device>/<user>/on')
+@app.route('/user/<user>/<device>/on')
+class UserDeviceBind(Resource):
+  @app.param('device', 'Device number to bind to', 'path')
+  @app.param('user', 'User user to bind', 'path')
+  @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
+  @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
+  async def get(self, device, user):
+    '''Binds user to device.
+    Both user and device numbers are checked for existance.
+    Any device user was previously bound to, is unbound.
+    Any user previously bound to device is unbound also.
+    '''
+    cidnum = await getUserCID(user) # Check if user exists in astdb
+    if cidnum is None:
+      return noUser(user)
+    dial = await getDeviceDial(device) # Check if device exists in astdb
+    if dial is None:
+      return noDevice(device)
+    currentUser = await getDeviceUser(device) # Check if any user is already bound to device
+    if currentUser == user:
+      return beenBound(user, device)
+    ast = await getGlobalVars()
+    queues = await amiQueues()
+    if currentUser not in NONEs: # If any other user is bound to device, unbind him,
+      await setUserDevice(currentUser, None)
+      if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
+        await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
+      await setUserHint(currentUser, None, ast) # set hints for previous user
+    await setDeviceUser(device, user) # Bind user to device
+    # If user is bound to some other devices, unbind him and set
+    # device states for those devices
+    await unbindOtherDevices(user, device, queues, ast)
+    if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
+      return hintError(user, device)
+    await setUserDeviceStates(user, device, queues, ast) # Set device states for users new device
+    if not (await setUserDevice(user, device)): # Bind device to user
+      return bindError(user, device)
+    return beenBound(user, device)
+
+@app.route('/device/<device>/off')
+class DeviceUnBind(Resource):
+  @app.param('device', 'Device number to unbind', 'path')
+  @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
+  @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
+  async def get(self, device):
+    '''Unbinds any user from device.
+    Device is checked for existance.
+    '''
+    dial = await getDeviceDial(device) # Check if device exists in astdb
+    if dial is None:
+      return noDevice(device)
+    currentUser = await getDeviceUser(device) # Check if any user is bound to device
+    if currentUser in NONEs:
+      return noUserBound(device)
+    else:
+      ast = await getGlobalVars()
+      queues = await amiQueues()
+      await setUserDevice(currentUser, None) # Unbind device from current user
+      if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
+        await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
+      await setUserHint(currentUser, None, ast) # set hints for current user
+    await setDeviceUser(device, 'none') # Unbind user from device
+    return beenUnbound(currentUser, device)
+
+manager.connect()
+app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])

+ 90 - 0
app/utils.py

@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+from dataclasses import dataclass, asdict
+from panoramisk import Message
+
+TRUEs = ('true', '1', 'y', 'yes')
+NONEs = (None,'none','')
+NO_AUTH_ROUTES = ('/ui','/openapi.json','/favicon.ico')
+SWAGGER_JS_URL = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.37.2/swagger-ui-bundle.js"
+SWAGGER_CSS_URL = "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.37.2/swagger-ui.min.css"
+SWAGGER_TEMPLATE = '''
+  <head>
+    <link type="text/css" rel="stylesheet" href="{{ css_url }}">
+    <title>{{ title }}</title>
+  </head>
+  <body>
+    <div id="swagger-ui"></div>
+    <script src="{{ js_url }}"></script>
+    <script>
+      const ui = SwaggerUIBundle({
+        deepLinking: true,
+        dom_id: "#swagger-ui",
+        layout: "BaseLayout",
+        presets: [
+          SwaggerUIBundle.presets.apis,
+          SwaggerUIBundle.SwaggerUIStandalonePreset
+        ],
+        showExtensions: true,
+        showCommonExtensions: true,
+        url: "/openapi.json"
+      });
+    </script>
+  </body>'''
+
+def followMe2DevState(followMeState):
+  if followMeState == 'DIRECT':
+    return 'INUSE'
+  if followMeState == 'EXTENSION':
+    return 'NOT_INUSE'
+  return 'INVALID'
+
+@dataclass
+class QueueMember:
+  user: str
+  name: str = ''
+  location: str = ''
+  membership: str = ''
+  stateinterface: str = ''
+  status: str = ''
+  def fromMessage(self, _m: Message):
+    for key in asdict(self):
+      if key in _m.getdict():
+        setattr(self, key, _m[key])
+    return self
+
+@dataclass
+class GlobalVars:
+  FMDEVSTATE: str = ''
+  QUEDEVSTATE: str = ''
+  QUEUETOGGLE: str = ''
+  QUEUEPAUSETOGGLE: str = ''
+  INTERCOMCODE: str = ''
+  CAMPONTOGGLE: str = ''
+  DNDDEVSTATE: str = ''
+  CFDEVSTATE: str = ''
+  def d(self):
+    return asdict(self)
+
+def jsonAPIReply(success, result):
+  return {'success':success, 'result': result}
+
+def noUser(user):
+  return jsonAPIReply(False, 'user {} does not exist'.format(user))
+
+def noDevice(device):
+  return jsonAPIReply(False, 'device {} does not exist'.format(device))
+
+def beenBound(user, device):
+  return jsonAPIReply(True, '{} is bound to {}'.format(user, device))
+
+def bindError(user, device):
+  return jsonAPIReply(False, 'Failed binding {} to {}'.format(user, device))
+
+def hintError(user, device):
+  return jsonAPIReply(False, 'Failed setting hint for {}@{}'.format(user, device))
+
+def noUserBound(device):
+  return jsonAPIReply(False, 'no user is bound to {}'.format(device))
+
+def beenUnbound(user, device):
+  return jsonAPIReply(True, '{} unbound from {}'.format(user, device))

+ 64 - 0
docker-compose.yml

@@ -0,0 +1,64 @@
+version: '3'
+
+services:
+  pbx:
+    container_name: pbx
+    hostname: ${APP_FQDN}
+    build: https://gogs.halsbox.ru/hal/docker-freepbx.git
+    image: halsbox/docker-freepbx:latest
+    restart: always
+    depends_on:
+    - db
+    env_file:
+    - .env
+    - app.env
+    volumes:
+    - /etc/localtime:/etc/localtime:ro
+    - ${PERSISTENT_STORAGE_PATH}/pbx:/data
+    cap_add:
+    - NET_ADMIN
+    privileged: true
+    network_mode: host
+  db:
+    container_name: db
+    image: mariadb:10.5.8
+    command: --sql-mode=ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
+    restart: always
+    env_file:
+    - .env
+    ports:
+    - ${APP_PORT_MYSQL}:3306
+    volumes:
+    - /etc/localtime:/etc/localtime:ro
+    - ${PERSISTENT_STORAGE_PATH}/db:/var/lib/mysql
+    environment:
+    - MYSQL_ROOT_PASSWORD
+    - MYSQL_DATABASE
+    - MYSQL_USER
+    - MYSQL_PASSWORD
+  app:
+    container_name: app
+    hostname: ${APP_FQDN}
+    image: jfloff/alpine-python:latest-slim
+    restart: always
+    depends_on:
+    - pbx
+    env_file:
+    - app.env
+    ports:
+    - ${APP_API_PORT}:${APP_API_PORT}
+    volumes:
+      - /etc/localtime:/etc/localtime:ro
+      - ./app:/app
+    command:
+      - -p requests
+      - -p quart
+      - -p quart-openapi
+      - -p hypercorn
+      - -p git+https://github.com/gawel/panoramisk.git@master
+      - --
+      - python
+      - /app/app.py
+    environment:
+    - APP_FQDN
+    - APP_API_PORT