Compare commits
9 Commits
remove-sub
...
cleanup-ci
| Author | SHA1 | Date | |
|---|---|---|---|
| e42e3b0bab | |||
| 5bfc3e5796 | |||
| cebdb24ed6 | |||
| 85f06aa445 | |||
| be15ac6899 | |||
| 047091367c | |||
|
|
8b7802a67a
|
||
| 4d2b3cb639 | |||
| f386625844 |
@@ -2,6 +2,8 @@ include:
|
||||
- local: 'ci_templates/.cic-template.yml'
|
||||
- local: 'apps/contract-migration/.gitlab-ci.yml'
|
||||
- local: 'apps/cic-eth/.gitlab-ci.yml'
|
||||
- local: 'apps/cic-ussd/.gitlab-ci.yml'
|
||||
- local: 'apps/cic-notify/.gitlab-ci.yml'
|
||||
|
||||
stages:
|
||||
- build
|
||||
|
||||
6
.gitmodules
vendored
6
.gitmodules
vendored
@@ -1,9 +1,3 @@
|
||||
[submodule "apps/cic-ussd"]
|
||||
path = apps/cic-ussd
|
||||
url = git@gitlab.com:grassrootseconomics/cic-ussd.git
|
||||
[submodule "apps/cic-notify"]
|
||||
path = apps/cic-notify
|
||||
url = git@gitlab.com:grassrootseconomics/cic-notify.git
|
||||
[submodule "apps/cic-cache"]
|
||||
path = apps/cic-cache
|
||||
url = git@gitlab.com:grassrootseconomics/cic-cache.git
|
||||
|
||||
@@ -17,10 +17,12 @@ COPY ./validator/bloxberg.json \
|
||||
./validator/validator.toml \
|
||||
/root/
|
||||
|
||||
COPY ./keys/ /root/keys/
|
||||
|
||||
# RUN chown -R parity:parity $HOME/ && \
|
||||
# chmod -R 775 $HOME/ && \
|
||||
# chmod g+s $HOME/
|
||||
# USER parity
|
||||
|
||||
ENTRYPOINT [ "parity" ]
|
||||
CMD [ "--config", "/root/validator.toml", "--keys-path", "/root/keys/" ]
|
||||
CMD [ "--config", "/root/validator.toml", "--keys-path", "/root/keys/" ]
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"maximumUncleCount": 0,
|
||||
"stepDuration": "5",
|
||||
"validators" : {
|
||||
"list": ["0x0ade5bd2065debbb250e816f614bc342a6ef71c1"]
|
||||
"list": ["0x6bd4e51b3730576ddc4049654ef60ed7f7436cb5"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ password = ["/root/validator.pwd"]
|
||||
|
||||
[mining]
|
||||
#CHANGE ENGINE SIGNER TO VALIDATOR ADDRESS
|
||||
engine_signer = "0x0ade5bd2065debbb250e816f614bc342a6ef71c1"
|
||||
engine_signer = "0x6bd4e51b3730576ddc4049654ef60ed7f7436cb5"
|
||||
reseal_on_txs = "none"
|
||||
force_sealing = true
|
||||
min_gas_price = 1000000
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
# FROM grassrootseconomics:cic
|
||||
|
||||
#FROM python:3.8.6-alpine
|
||||
FROM python:3.8.6-slim-buster
|
||||
|
||||
#COPY --from=0 /usr/local/share/cic/solidity/ /usr/local/share/cic/solidity/
|
||||
RUN apt-get update && \
|
||||
apt install -y gcc gnupg libpq-dev wget make g++ gnupg bash procps
|
||||
|
||||
WORKDIR /usr/src/cic-eth
|
||||
|
||||
ARG pip_extra_index_url_flag='--index https://pypi.org/simple --extra-index-url https://pip.grassrootseconomics.net:8433'
|
||||
ARG root_requirement_file='requirements.txt'
|
||||
|
||||
#RUN apk update && \
|
||||
# apk add gcc musl-dev gnupg libpq
|
||||
#RUN apk add postgresql-dev
|
||||
#RUN apk add linux-headers
|
||||
#RUN apk add libffi-dev
|
||||
RUN apt-get update && \
|
||||
apt install -y gcc gnupg libpq-dev wget make g++ gnupg bash procps
|
||||
|
||||
# Copy shared requirements from top of mono-repo
|
||||
RUN echo "copying root req file ${root_requirement_file}"
|
||||
COPY $root_requirement_file .
|
||||
|
||||
Submodule apps/cic-notify deleted from ba8e5989fa
4
apps/cic-notify/.config/africastalking.ini
Normal file
4
apps/cic-notify/.config/africastalking.ini
Normal file
@@ -0,0 +1,4 @@
|
||||
[AFRICASTALKING]
|
||||
api_username = foo
|
||||
api_key = bar
|
||||
api_sender_id = baz
|
||||
3
apps/cic-notify/.config/celery.ini
Normal file
3
apps/cic-notify/.config/celery.ini
Normal file
@@ -0,0 +1,3 @@
|
||||
[celery]
|
||||
broker_url = redis://
|
||||
result_url = redis://
|
||||
10
apps/cic-notify/.config/database.ini
Normal file
10
apps/cic-notify/.config/database.ini
Normal file
@@ -0,0 +1,10 @@
|
||||
[DATABASE]
|
||||
user = postgres
|
||||
password =
|
||||
host = localhost
|
||||
port = 5432
|
||||
name = /tmp/cic-notify.db
|
||||
#engine = postgresql
|
||||
#driver = psycopg2
|
||||
engine = sqlite
|
||||
driver = pysqlite
|
||||
4
apps/cic-notify/.config/tasks.ini
Normal file
4
apps/cic-notify/.config/tasks.ini
Normal file
@@ -0,0 +1,4 @@
|
||||
[TASKS]
|
||||
africastalking = cic_notify.tasks.sms.africastalking
|
||||
db = cic_notify.tasks.sms.db
|
||||
log = cic_notify.tasks.sms.log
|
||||
4
apps/cic-notify/.config/test/africastalking.ini
Normal file
4
apps/cic-notify/.config/test/africastalking.ini
Normal file
@@ -0,0 +1,4 @@
|
||||
[AFRICASTALKING]
|
||||
api_username = foo
|
||||
api_key = bar
|
||||
api_sender_id = baz
|
||||
3
apps/cic-notify/.config/test/celery.ini
Normal file
3
apps/cic-notify/.config/test/celery.ini
Normal file
@@ -0,0 +1,3 @@
|
||||
[celery]
|
||||
broker_url = filesystem://
|
||||
result_url = filesystem://
|
||||
10
apps/cic-notify/.config/test/database.ini
Normal file
10
apps/cic-notify/.config/test/database.ini
Normal file
@@ -0,0 +1,10 @@
|
||||
[DATABASE]
|
||||
user = postgres
|
||||
password =
|
||||
host = localhost
|
||||
port = 5432
|
||||
name = /tmp/cic-notify.db
|
||||
#engine = postgresql
|
||||
#driver = psycopg2
|
||||
engine = sqlite
|
||||
driver = pysqlite
|
||||
4
apps/cic-notify/.config/test/tasks.ini
Normal file
4
apps/cic-notify/.config/test/tasks.ini
Normal file
@@ -0,0 +1,4 @@
|
||||
[TASKS]
|
||||
africastalking = cic_notify.tasks.sms.africastalking
|
||||
db = cic_notify.tasks.sms.db
|
||||
log = cic_notify.tasks.sms.log
|
||||
4
apps/cic-notify/.gitignore
vendored
Normal file
4
apps/cic-notify/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
__pycache__
|
||||
*.pyc
|
||||
venv/
|
||||
.idea/
|
||||
23
apps/cic-notify/.gitlab-ci.yml
Normal file
23
apps/cic-notify/.gitlab-ci.yml
Normal file
@@ -0,0 +1,23 @@
|
||||
.cic_notify_variables:
|
||||
variables:
|
||||
APP_NAME: cic-notify
|
||||
DOCKERFILE_PATH: $APP_NAME/docker/Dockerfile
|
||||
|
||||
.this_changes_target:
|
||||
rules:
|
||||
- changes:
|
||||
- $CONTEXT/$APP_NAME/*
|
||||
|
||||
build-mr-cic-notify:
|
||||
extends:
|
||||
- .this_changes_target
|
||||
- .py_build_merge_request
|
||||
- .cic_notify_variables
|
||||
|
||||
build-push-cic-notify:
|
||||
extends:
|
||||
- .this_changes_target
|
||||
- .py_build_push
|
||||
- .cic_notify_variables
|
||||
|
||||
|
||||
24
apps/cic-notify/CHANGELOG
Normal file
24
apps/cic-notify/CHANGELOG
Normal file
@@ -0,0 +1,24 @@
|
||||
- 0.3.2
|
||||
* Relax dependencies to compatible
|
||||
- 0.3.1
|
||||
* Upgrade dependencies
|
||||
- 0.3.0
|
||||
* Rehabilitate africastalking script
|
||||
* Add queue identifiers
|
||||
- 0.2.0
|
||||
* Remove unnecessarily complicated code
|
||||
- 0.1.0
|
||||
* Simplify tasks
|
||||
- 0.0.4
|
||||
* Add python api
|
||||
* Add send sms tool
|
||||
* Add database to tasker script
|
||||
* Rename tasker script
|
||||
* Fix no-commit bug in db notification
|
||||
- 0.0.3
|
||||
* Add sms notify to db
|
||||
- 0.0.2
|
||||
* Re-introduce log sms notify handler
|
||||
- 0.0.1
|
||||
* Port code from cic-ussd
|
||||
* Make dynamic task module loader
|
||||
1
apps/cic-notify/cic_notify/__init__.py
Normal file
1
apps/cic-notify/cic_notify/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .api import *
|
||||
55
apps/cic-notify/cic_notify/api.py
Normal file
55
apps/cic-notify/cic_notify/api.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# standard imports
|
||||
import logging
|
||||
import re
|
||||
|
||||
# third-party imports
|
||||
import celery
|
||||
|
||||
# local imports
|
||||
from cic_notify.tasks import sms
|
||||
|
||||
app = celery.current_app
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logg = logging.getLogger()
|
||||
|
||||
sms_tasks_matcher = r"^(cic_notify.tasks.sms)(\.\w+)?"
|
||||
|
||||
|
||||
class Api:
|
||||
# TODO: Implement callback strategy
|
||||
def __init__(self, queue='cic-notify'):
|
||||
"""
|
||||
:param queue: The queue on which to execute notification tasks
|
||||
:type queue: str
|
||||
"""
|
||||
registered_tasks = app.tasks
|
||||
self.sms_tasks = []
|
||||
|
||||
for task in registered_tasks.keys():
|
||||
logg.debug(f'Found: {task} {registered_tasks[task]}')
|
||||
match = re.match(sms_tasks_matcher, task)
|
||||
if match:
|
||||
self.sms_tasks.append(task)
|
||||
|
||||
self.queue = queue
|
||||
logg.info(f'api using queue: {self.queue}')
|
||||
|
||||
def sms(self, message, recipient):
|
||||
"""This function chains all sms tasks in order to send a message, log and persist said data to disk
|
||||
:param message: The message to be sent to the recipient.
|
||||
:type message: str
|
||||
:param recipient: The phone number of the recipient.
|
||||
:type recipient: str
|
||||
:return: a celery Task
|
||||
:rtype: Celery.Task
|
||||
"""
|
||||
signatures = []
|
||||
for task in self.sms_tasks:
|
||||
signature = celery.signature(task)
|
||||
signatures.append(signature)
|
||||
signature_group = celery.group(signatures)
|
||||
result = signature_group.apply_async(
|
||||
args=[message, recipient],
|
||||
queue=self.queue
|
||||
)
|
||||
return result
|
||||
34
apps/cic-notify/cic_notify/db/__init__.py
Normal file
34
apps/cic-notify/cic_notify/db/__init__.py
Normal file
@@ -0,0 +1,34 @@
|
||||
# standard imports
|
||||
import os
|
||||
import logging
|
||||
|
||||
# local imports
|
||||
from cic_notify.db.models.base import SessionBase
|
||||
|
||||
logg = logging.getLogger()
|
||||
|
||||
|
||||
def dsn_from_config(config):
|
||||
scheme = config.get('DATABASE_ENGINE')
|
||||
if config.get('DATABASE_DRIVER') != None:
|
||||
scheme += '+{}'.format(config.get('DATABASE_DRIVER'))
|
||||
|
||||
dsn = ''
|
||||
if config.get('DATABASE_ENGINE') == 'sqlite':
|
||||
dsn = '{}:///{}'.format(
|
||||
scheme,
|
||||
config.get('DATABASE_NAME'),
|
||||
)
|
||||
|
||||
else:
|
||||
dsn = '{}://{}:{}@{}:{}/{}'.format(
|
||||
scheme,
|
||||
config.get('DATABASE_USER'),
|
||||
config.get('DATABASE_PASSWORD'),
|
||||
config.get('DATABASE_HOST'),
|
||||
config.get('DATABASE_PORT'),
|
||||
config.get('DATABASE_NAME'),
|
||||
)
|
||||
logg.debug('parsed dsn from config: {}'.format(dsn))
|
||||
return dsn
|
||||
|
||||
7
apps/cic-notify/cic_notify/db/enum.py
Normal file
7
apps/cic-notify/cic_notify/db/enum.py
Normal file
@@ -0,0 +1,7 @@
|
||||
import enum
|
||||
|
||||
class NotificationStatusEnum(enum.Enum):
|
||||
UNKNOWN = 'UNKNOWN'
|
||||
|
||||
class NotificationTransportEnum(enum.Enum):
|
||||
SMS = 'SMS'
|
||||
1
apps/cic-notify/cic_notify/db/migrations/default/README
Normal file
1
apps/cic-notify/cic_notify/db/migrations/default/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
85
apps/cic-notify/cic_notify/db/migrations/default/alembic.ini
Normal file
85
apps/cic-notify/cic_notify/db/migrations/default/alembic.ini
Normal file
@@ -0,0 +1,85 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# timezone to use when rendering the date
|
||||
# within the migration file as well as the filename.
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; this defaults
|
||||
# to migrations/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = postgres+psycopg2://postgres@localhost/cic-notify
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks=black
|
||||
# black.type=console_scripts
|
||||
# black.entrypoint=black
|
||||
# black.options=-l 79
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
77
apps/cic-notify/cic_notify/db/migrations/default/env.py
Normal file
77
apps/cic-notify/cic_notify/db/migrations/default/env.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = None
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Notify sms log
|
||||
|
||||
Revision ID: b2aedf79b0b2
|
||||
Revises:
|
||||
Create Date: 2020-10-11 15:59:02.765157
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b2aedf79b0b2'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
status_enum = sa.Enum(
|
||||
'UNKNOWN', # the state of the message is not known
|
||||
name='notification_status',
|
||||
)
|
||||
|
||||
transport_enum = sa.Enum(
|
||||
'SMS',
|
||||
name='notification_transport',
|
||||
)
|
||||
|
||||
def upgrade():
|
||||
op.create_table('notification',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('transport', transport_enum, nullable=False),
|
||||
sa.Column('status', status_enum, nullable=False),
|
||||
sa.Column('status_code', sa.String(), nullable=True),
|
||||
sa.Column('status_serial', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('recipient', sa.String(), nullable=False),
|
||||
sa.Column('created', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated', sa.DateTime(), nullable=False),
|
||||
sa.Column('message', sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('notification_recipient_transport_idx', 'notification', ['transport', 'recipient'], schema=None, unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('notification_recipient_transport_idx')
|
||||
op.drop_table('notification')
|
||||
status_enum.drop(op.get_bind(), checkfirst=False)
|
||||
transport_enum.drop(op.get_bind(), checkfirst=False)
|
||||
0
apps/cic-notify/cic_notify/db/models/__init__.py
Normal file
0
apps/cic-notify/cic_notify/db/models/__init__.py
Normal file
40
apps/cic-notify/cic_notify/db/models/base.py
Normal file
40
apps/cic-notify/cic_notify/db/models/base.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# third-party imports
|
||||
from sqlalchemy import Column, Integer
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
Model = declarative_base(name='Model')
|
||||
|
||||
|
||||
class SessionBase(Model):
|
||||
__abstract__ = True
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
|
||||
engine = None
|
||||
session = None
|
||||
query = None
|
||||
|
||||
|
||||
@staticmethod
|
||||
def create_session():
|
||||
session = sessionmaker(bind=SessionBase.engine)
|
||||
SessionBase.session = session()
|
||||
return SessionBase.session
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _set_engine(engine):
|
||||
SessionBase.engine = engine
|
||||
|
||||
|
||||
@staticmethod
|
||||
def build():
|
||||
Model.metadata.create_all(bind=SessionBase.engine)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def connect(dsn):
|
||||
e = create_engine(dsn)
|
||||
SessionBase._set_engine(e)
|
||||
27
apps/cic-notify/cic_notify/db/models/notification.py
Normal file
27
apps/cic-notify/cic_notify/db/models/notification.py
Normal file
@@ -0,0 +1,27 @@
|
||||
# standard imports
|
||||
import datetime
|
||||
|
||||
# third-party imports
|
||||
from sqlalchemy import Enum, Column, String, DateTime
|
||||
|
||||
# local imports
|
||||
from .base import SessionBase
|
||||
from ..enum import NotificationStatusEnum, NotificationTransportEnum
|
||||
|
||||
|
||||
class Notification(SessionBase):
|
||||
__tablename__ = 'notification'
|
||||
|
||||
transport = Column(Enum(NotificationTransportEnum))
|
||||
status = Column(Enum(NotificationStatusEnum))
|
||||
recipient = Column(String)
|
||||
message = Column(String)
|
||||
created = Column(DateTime, default=datetime.datetime.utcnow)
|
||||
updated = Column(DateTime, default=datetime.datetime.utcnow)
|
||||
|
||||
def __init__(self, transport, recipient, message, **kwargs):
|
||||
super(Notification, self).__init__(**kwargs)
|
||||
self.transport = transport
|
||||
self.recipient = recipient
|
||||
self.message = message
|
||||
self.status = NotificationStatusEnum.UNKNOWN
|
||||
11
apps/cic-notify/cic_notify/error.py
Normal file
11
apps/cic-notify/cic_notify/error.py
Normal file
@@ -0,0 +1,11 @@
|
||||
class NotInitializedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AlreadyInitializedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PleaseCommitFirstError(Exception):
|
||||
"""Raised when there exists uncommitted changes in the code while trying to build out the package."""
|
||||
pass
|
||||
110
apps/cic-notify/cic_notify/runnable/tasker.py
Normal file
110
apps/cic-notify/cic_notify/runnable/tasker.py
Normal file
@@ -0,0 +1,110 @@
|
||||
# standard imports
|
||||
import os
|
||||
import logging
|
||||
import importlib
|
||||
import argparse
|
||||
import tempfile
|
||||
|
||||
# third-party imports
|
||||
import celery
|
||||
import confini
|
||||
|
||||
# local imports
|
||||
from cic_notify.db.models.base import SessionBase
|
||||
from cic_notify.db import dsn_from_config
|
||||
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
logg = logging.getLogger()
|
||||
|
||||
config_dir = os.path.join('/usr/local/etc/cic-notify')
|
||||
|
||||
argparser = argparse.ArgumentParser()
|
||||
argparser.add_argument('-c', type=str, default=config_dir, help='config file')
|
||||
argparser.add_argument('-q', type=str, default='cic-notify', help='queue name for worker tasks')
|
||||
argparser.add_argument('-v', action='store_true', help='be verbose')
|
||||
argparser.add_argument('--env-prefix', default=os.environ.get('CONFINI_ENV_PREFIX'), dest='env_prefix', type=str, help='environment prefix for variables to overwrite configuration')
|
||||
argparser.add_argument('-vv', action='store_true', help='be more verbose')
|
||||
args = argparser.parse_args()
|
||||
|
||||
if args.vv:
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
elif args.v:
|
||||
logging.getLogger().setLevel(logging.INFO)
|
||||
|
||||
config = confini.Config(args.c, args.env_prefix)
|
||||
config.process()
|
||||
config.censor('PASSWORD', 'DATABASE')
|
||||
|
||||
# connect to database
|
||||
dsn = dsn_from_config(config)
|
||||
SessionBase.connect(dsn)
|
||||
|
||||
# verify database connection with minimal sanity query
|
||||
session = SessionBase.create_session()
|
||||
session.execute('select version_num from alembic_version')
|
||||
session.close()
|
||||
|
||||
# set up celery
|
||||
app = celery.Celery(__name__)
|
||||
|
||||
broker = config.get('CELERY_BROKER_URL')
|
||||
if broker[:4] == 'file':
|
||||
bq = tempfile.mkdtemp()
|
||||
bp = tempfile.mkdtemp()
|
||||
app.conf.update({
|
||||
'broker_url': broker,
|
||||
'broker_transport_options': {
|
||||
'data_folder_in': bq,
|
||||
'data_folder_out': bq,
|
||||
'data_folder_processed': bp,
|
||||
},
|
||||
},
|
||||
)
|
||||
logg.warning('celery broker dirs queue i/o {} processed {}, will NOT be deleted on shutdown'.format(bq, bp))
|
||||
else:
|
||||
app.conf.update({
|
||||
'broker_url': broker,
|
||||
})
|
||||
|
||||
result = config.get('CELERY_RESULT_URL')
|
||||
if result[:4] == 'file':
|
||||
rq = tempfile.mkdtemp()
|
||||
app.conf.update({
|
||||
'result_backend': 'file://{}'.format(rq),
|
||||
})
|
||||
logg.warning('celery backend store dir {} created, will NOT be deleted on shutdown'.format(rq))
|
||||
else:
|
||||
app.conf.update({
|
||||
'result_backend': result,
|
||||
})
|
||||
|
||||
|
||||
for key in config.store.keys():
|
||||
if key[:5] == 'TASKS':
|
||||
logg.info(f'adding sms task from {key}')
|
||||
module = importlib.import_module(config.store[key])
|
||||
if key == 'TASKS_AFRICASTALKING':
|
||||
africastalking_notifier = module.AfricasTalkingNotifier
|
||||
africastalking_notifier.initialize(
|
||||
config.get('AFRICASTALKING_API_USERNAME'),
|
||||
config.get('AFRICASTALKING_API_KEY'),
|
||||
config.get('AFRICASTALKING_API_SENDER_ID')
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
argv = ['worker']
|
||||
if args.vv:
|
||||
argv.append('--loglevel=DEBUG')
|
||||
elif args.v:
|
||||
argv.append('--loglevel=INFO')
|
||||
argv.append('-Q')
|
||||
argv.append(args.q)
|
||||
argv.append('-n')
|
||||
argv.append(args.q)
|
||||
|
||||
app.worker_main(argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
1
apps/cic-notify/cic_notify/tasks/__init__.py
Normal file
1
apps/cic-notify/cic_notify/tasks/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from . import sms
|
||||
12
apps/cic-notify/cic_notify/tasks/sms/__init__.py
Normal file
12
apps/cic-notify/cic_notify/tasks/sms/__init__.py
Normal file
@@ -0,0 +1,12 @@
|
||||
# standard imports
|
||||
|
||||
# third-party imports
|
||||
|
||||
# local imports
|
||||
import celery
|
||||
|
||||
celery_app = celery.current_app
|
||||
|
||||
from .africastalking import send
|
||||
from .db import persist_notification
|
||||
from .log import log
|
||||
69
apps/cic-notify/cic_notify/tasks/sms/africastalking.py
Normal file
69
apps/cic-notify/cic_notify/tasks/sms/africastalking.py
Normal file
@@ -0,0 +1,69 @@
|
||||
# standard imports
|
||||
import logging
|
||||
|
||||
# third party imports
|
||||
import celery
|
||||
import africastalking
|
||||
|
||||
# local imports
|
||||
from cic_notify.error import NotInitializedError, AlreadyInitializedError
|
||||
|
||||
logg = logging.getLogger()
|
||||
celery_app = celery.current_app
|
||||
|
||||
|
||||
class AfricasTalkingNotifier:
|
||||
initiated = None
|
||||
sender_id = None
|
||||
|
||||
def __init__(self):
|
||||
if not self.initiated:
|
||||
raise NotInitializedError()
|
||||
self.api_client = africastalking.SMS
|
||||
|
||||
@staticmethod
|
||||
def initialize(api_username, api_key, sender_id=None):
|
||||
"""
|
||||
:param api_username:
|
||||
:type api_username:
|
||||
:param api_key:
|
||||
:type api_key:
|
||||
:param sender_id:
|
||||
:type sender_id:
|
||||
"""
|
||||
if AfricasTalkingNotifier.initiated:
|
||||
raise AlreadyInitializedError()
|
||||
africastalking.initialize(username=api_username, api_key=api_key)
|
||||
|
||||
AfricasTalkingNotifier.sender_id = sender_id
|
||||
AfricasTalkingNotifier.initiated = True
|
||||
|
||||
def send(self, message, recipient):
|
||||
"""
|
||||
:param message:
|
||||
:type message:
|
||||
:param recipient:
|
||||
:type recipient:
|
||||
:return:
|
||||
:rtype:
|
||||
"""
|
||||
if self.sender_id:
|
||||
response = self.api_client.send(message=message, recipients=[recipient], sender_id=self.sender_id)
|
||||
logg.debug(f'Africastalking response sender-id {response}')
|
||||
else:
|
||||
response = self.api_client.send(message=message, recipients=[recipient])
|
||||
logg.debug(f'africastalking response no-sender-id {response}')
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def send(message, recipient):
|
||||
"""
|
||||
:param message:
|
||||
:type message:
|
||||
:param recipient:
|
||||
:type recipient:
|
||||
:return:
|
||||
:rtype:
|
||||
"""
|
||||
africastalking_notifier = AfricasTalkingNotifier()
|
||||
africastalking_notifier.send(message=message, recipient=recipient)
|
||||
26
apps/cic-notify/cic_notify/tasks/sms/db.py
Normal file
26
apps/cic-notify/cic_notify/tasks/sms/db.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# standard imports
|
||||
|
||||
# third-party imports
|
||||
import celery
|
||||
|
||||
# local imports
|
||||
from cic_notify.db.models.notification import Notification
|
||||
from cic_notify.db.enum import NotificationTransportEnum
|
||||
|
||||
celery_app = celery.current_app
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def persist_notification(recipient, message):
|
||||
"""
|
||||
:param recipient:
|
||||
:type recipient:
|
||||
:param message:
|
||||
:type message:
|
||||
:return:
|
||||
:rtype:
|
||||
"""
|
||||
Notification.create_session()
|
||||
notification = Notification(transport=NotificationTransportEnum.SMS, recipient=recipient, message=message)
|
||||
Notification.session.add(notification)
|
||||
Notification.session.commit()
|
||||
26
apps/cic-notify/cic_notify/tasks/sms/log.py
Normal file
26
apps/cic-notify/cic_notify/tasks/sms/log.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# standard imports
|
||||
import logging
|
||||
import time
|
||||
|
||||
# third-party imports
|
||||
import celery
|
||||
|
||||
celery_app = celery.current_app
|
||||
logg = celery_app.log.get_default_logger()
|
||||
local_logg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def log(recipient, message):
|
||||
"""
|
||||
:param recipient:
|
||||
:type recipient:
|
||||
:param message:
|
||||
:type message:
|
||||
:return:
|
||||
:rtype:
|
||||
"""
|
||||
timestamp = time.time()
|
||||
log_string = f'[{timestamp}] {__name__} message to {recipient}: {message}'
|
||||
logg.info(log_string)
|
||||
local_logg.info(log_string)
|
||||
47
apps/cic-notify/cic_notify/version.py
Normal file
47
apps/cic-notify/cic_notify/version.py
Normal file
@@ -0,0 +1,47 @@
|
||||
# standard imports
|
||||
import logging
|
||||
import time
|
||||
|
||||
# third-party imports
|
||||
import semver
|
||||
|
||||
# local imports
|
||||
from cic_notify.error import PleaseCommitFirstError
|
||||
|
||||
logg = logging.getLogger()
|
||||
|
||||
version = (0, 4, 0, 'alpha.2')
|
||||
|
||||
version_object = semver.VersionInfo(
|
||||
major=version[0],
|
||||
minor=version[1],
|
||||
patch=version[2],
|
||||
prerelease=version[3],
|
||||
)
|
||||
|
||||
version_string = str(version_object)
|
||||
|
||||
|
||||
def git_hash():
|
||||
import subprocess
|
||||
git_diff = subprocess.run(['git', 'diff'], capture_output=True)
|
||||
if len(git_diff.stdout) > 0:
|
||||
raise PleaseCommitFirstError()
|
||||
|
||||
git_hash = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True)
|
||||
git_hash_brief = git_hash.stdout.decode('utf-8')[:8]
|
||||
return git_hash_brief
|
||||
|
||||
|
||||
try:
|
||||
version_git = git_hash()
|
||||
version_string += '.build.{}'.format(version_git)
|
||||
except FileNotFoundError:
|
||||
time_string_pair = str(time.time()).split('.')
|
||||
version_string += '+build.{}{:<09d}'.format(
|
||||
time_string_pair[0],
|
||||
int(time_string_pair[1]),
|
||||
)
|
||||
logg.info(f'Final version string will be {version_string}')
|
||||
|
||||
__version_string__ = version_string
|
||||
5
apps/cic-notify/doc/texinfo/Makefile
Normal file
5
apps/cic-notify/doc/texinfo/Makefile
Normal file
@@ -0,0 +1,5 @@
|
||||
all: html
|
||||
|
||||
.PHONY: html
|
||||
html:
|
||||
makeinfo --html --output html index.texi
|
||||
14
apps/cic-notify/doc/texinfo/api.texi
Normal file
14
apps/cic-notify/doc/texinfo/api.texi
Normal file
@@ -0,0 +1,14 @@
|
||||
@node API
|
||||
@chapter API
|
||||
|
||||
A setuptools file is provided to install @code{cic-notify} as a normal python package.
|
||||
|
||||
A single Python API method is provided so far:
|
||||
|
||||
@itemize @code
|
||||
@item sms(recipient, content)
|
||||
@end itemize
|
||||
|
||||
@code{recipient} is a string with phone number in @code{msisdn} format with a @code{+} prefix.
|
||||
|
||||
@code{content} is a UTF-8 string containing the message to be sent.
|
||||
61
apps/cic-notify/doc/texinfo/html/API.html
Normal file
61
apps/cic-notify/doc/texinfo/html/API.html
Normal file
@@ -0,0 +1,61 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<!-- Released 2020 under GPL3 -->
|
||||
<!-- Created by GNU Texinfo 6.7, http://www.gnu.org/software/texinfo/ -->
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>API (Grassroots Economics CIC notify 0.2.0)</title>
|
||||
|
||||
<meta name="description" content="API (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="keywords" content="API (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="resource-type" content="document">
|
||||
<meta name="distribution" content="global">
|
||||
<meta name="Generator" content="makeinfo">
|
||||
<link href="index.html" rel="start" title="Top">
|
||||
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
|
||||
<link href="index.html" rel="up" title="Top">
|
||||
<link href="Run.html" rel="prev" title="Run">
|
||||
<style type="text/css">
|
||||
<!--
|
||||
a.summary-letter {text-decoration: none}
|
||||
blockquote.indentedblock {margin-right: 0em}
|
||||
div.display {margin-left: 3.2em}
|
||||
div.example {margin-left: 3.2em}
|
||||
div.lisp {margin-left: 3.2em}
|
||||
kbd {font-style: oblique}
|
||||
pre.display {font-family: inherit}
|
||||
pre.format {font-family: inherit}
|
||||
pre.menu-comment {font-family: serif}
|
||||
pre.menu-preformatted {font-family: serif}
|
||||
span.nolinebreak {white-space: nowrap}
|
||||
span.roman {font-family: initial; font-weight: normal}
|
||||
span.sansserif {font-family: sans-serif; font-weight: normal}
|
||||
ul.no-bullet {list-style: none}
|
||||
-->
|
||||
</style>
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body lang="en">
|
||||
<span id="API"></span><div class="header">
|
||||
<p>
|
||||
Previous: <a href="Run.html" accesskey="p" rel="prev">Run</a>, Up: <a href="index.html" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>]</p>
|
||||
</div>
|
||||
<hr>
|
||||
<span id="API-1"></span><h2 class="chapter">4 API</h2>
|
||||
|
||||
<p>A single Python API method is provided so far:
|
||||
</p>
|
||||
<ul class="no-bullet">
|
||||
<li> sms(recipient, content)
|
||||
</li></ul>
|
||||
|
||||
<p><code>recipient</code> is a string with phone number in <code>msisdn</code> format with a <code>+</code> prefix.
|
||||
</p>
|
||||
<p><code>content</code> is a UTF-8 string containing the message to be sent.
|
||||
</p>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
72
apps/cic-notify/doc/texinfo/html/Overview.html
Normal file
72
apps/cic-notify/doc/texinfo/html/Overview.html
Normal file
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<!-- Released 2020 under GPL3 -->
|
||||
<!-- Created by GNU Texinfo 6.7, http://www.gnu.org/software/texinfo/ -->
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Overview (Grassroots Economics CIC notify 0.2.0)</title>
|
||||
|
||||
<meta name="description" content="Overview (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="keywords" content="Overview (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="resource-type" content="document">
|
||||
<meta name="distribution" content="global">
|
||||
<meta name="Generator" content="makeinfo">
|
||||
<link href="index.html" rel="start" title="Top">
|
||||
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
|
||||
<link href="index.html" rel="up" title="Top">
|
||||
<link href="Setup.html" rel="next" title="Setup">
|
||||
<link href="index.html" rel="prev" title="Top">
|
||||
<style type="text/css">
|
||||
<!--
|
||||
a.summary-letter {text-decoration: none}
|
||||
blockquote.indentedblock {margin-right: 0em}
|
||||
div.display {margin-left: 3.2em}
|
||||
div.example {margin-left: 3.2em}
|
||||
div.lisp {margin-left: 3.2em}
|
||||
kbd {font-style: oblique}
|
||||
pre.display {font-family: inherit}
|
||||
pre.format {font-family: inherit}
|
||||
pre.menu-comment {font-family: serif}
|
||||
pre.menu-preformatted {font-family: serif}
|
||||
span.nolinebreak {white-space: nowrap}
|
||||
span.roman {font-family: initial; font-weight: normal}
|
||||
span.sansserif {font-family: sans-serif; font-weight: normal}
|
||||
ul.no-bullet {list-style: none}
|
||||
-->
|
||||
</style>
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body lang="en">
|
||||
<span id="Overview"></span><div class="header">
|
||||
<p>
|
||||
Next: <a href="Setup.html" accesskey="n" rel="next">Setup</a>, Up: <a href="index.html" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>]</p>
|
||||
</div>
|
||||
<hr>
|
||||
<span id="Overview-1"></span><h2 class="chapter">1 Overview</h2>
|
||||
|
||||
<p>This system is in early stages of development. It is intended to be a flexible notification broker where additional notification targets easily can be plugged in.
|
||||
</p>
|
||||
<p>The framework is designed to asynchronously execute all tasks belonging to a specific context, based on the name of the task.
|
||||
</p>
|
||||
<p>Currently, only handlers for <strong>sms</strong> notifications are implemented. Any task with a <code>notify.sms.</code> prefix registered in the celery task worker pool will be executed upon the high-level "send sms" task.
|
||||
</p>
|
||||
<p>Similary, any other notification category can be implemented. e.g. <code>notify.email.</code>, <code>notify.telegram.</code>, <code>notify.mattermost.</code> etc.
|
||||
</p>
|
||||
<span id="Contents"></span><h3 class="section">1.1 Contents</h3>
|
||||
|
||||
<p>The only implementations so far are three <code>sms</code> notification tasks:
|
||||
</p>
|
||||
<ul>
|
||||
<li> log (as in python logger, thus more or less noop)
|
||||
</li><li> db (postgres)
|
||||
</li><li> Africas Talking API
|
||||
</li></ul>
|
||||
|
||||
<p><strong>NOTE</strong>: The Africas Talking API will be removed from the suite, and provided as an add-on package down the road. It will illustrate how to include arbitrary tasks to a asynchronous group of notification targets.
|
||||
</p>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
54
apps/cic-notify/doc/texinfo/html/Run.html
Normal file
54
apps/cic-notify/doc/texinfo/html/Run.html
Normal file
@@ -0,0 +1,54 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<!-- Released 2020 under GPL3 -->
|
||||
<!-- Created by GNU Texinfo 6.7, http://www.gnu.org/software/texinfo/ -->
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Run (Grassroots Economics CIC notify 0.2.0)</title>
|
||||
|
||||
<meta name="description" content="Run (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="keywords" content="Run (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="resource-type" content="document">
|
||||
<meta name="distribution" content="global">
|
||||
<meta name="Generator" content="makeinfo">
|
||||
<link href="index.html" rel="start" title="Top">
|
||||
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
|
||||
<link href="index.html" rel="up" title="Top">
|
||||
<link href="API.html" rel="next" title="API">
|
||||
<link href="Setup.html" rel="prev" title="Setup">
|
||||
<style type="text/css">
|
||||
<!--
|
||||
a.summary-letter {text-decoration: none}
|
||||
blockquote.indentedblock {margin-right: 0em}
|
||||
div.display {margin-left: 3.2em}
|
||||
div.example {margin-left: 3.2em}
|
||||
div.lisp {margin-left: 3.2em}
|
||||
kbd {font-style: oblique}
|
||||
pre.display {font-family: inherit}
|
||||
pre.format {font-family: inherit}
|
||||
pre.menu-comment {font-family: serif}
|
||||
pre.menu-preformatted {font-family: serif}
|
||||
span.nolinebreak {white-space: nowrap}
|
||||
span.roman {font-family: initial; font-weight: normal}
|
||||
span.sansserif {font-family: sans-serif; font-weight: normal}
|
||||
ul.no-bullet {list-style: none}
|
||||
-->
|
||||
</style>
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body lang="en">
|
||||
<span id="Run"></span><div class="header">
|
||||
<p>
|
||||
Next: <a href="API.html" accesskey="n" rel="next">API</a>, Previous: <a href="Setup.html" accesskey="p" rel="prev">Setup</a>, Up: <a href="index.html" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>]</p>
|
||||
</div>
|
||||
<hr>
|
||||
<span id="Running-the-Application"></span><h2 class="chapter">3 Running the Application</h2>
|
||||
|
||||
<p>A convenience task runner is provided in <samp>scripts/cic-notify-tasker.py</samp>.
|
||||
</p>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
64
apps/cic-notify/doc/texinfo/html/Setup.html
Normal file
64
apps/cic-notify/doc/texinfo/html/Setup.html
Normal file
@@ -0,0 +1,64 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<!-- Released 2020 under GPL3 -->
|
||||
<!-- Created by GNU Texinfo 6.7, http://www.gnu.org/software/texinfo/ -->
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Setup (Grassroots Economics CIC notify 0.2.0)</title>
|
||||
|
||||
<meta name="description" content="Setup (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="keywords" content="Setup (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="resource-type" content="document">
|
||||
<meta name="distribution" content="global">
|
||||
<meta name="Generator" content="makeinfo">
|
||||
<link href="index.html" rel="start" title="Top">
|
||||
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
|
||||
<link href="index.html" rel="up" title="Top">
|
||||
<link href="Run.html" rel="next" title="Run">
|
||||
<link href="Overview.html" rel="prev" title="Overview">
|
||||
<style type="text/css">
|
||||
<!--
|
||||
a.summary-letter {text-decoration: none}
|
||||
blockquote.indentedblock {margin-right: 0em}
|
||||
div.display {margin-left: 3.2em}
|
||||
div.example {margin-left: 3.2em}
|
||||
div.lisp {margin-left: 3.2em}
|
||||
kbd {font-style: oblique}
|
||||
pre.display {font-family: inherit}
|
||||
pre.format {font-family: inherit}
|
||||
pre.menu-comment {font-family: serif}
|
||||
pre.menu-preformatted {font-family: serif}
|
||||
span.nolinebreak {white-space: nowrap}
|
||||
span.roman {font-family: initial; font-weight: normal}
|
||||
span.sansserif {font-family: sans-serif; font-weight: normal}
|
||||
ul.no-bullet {list-style: none}
|
||||
-->
|
||||
</style>
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body lang="en">
|
||||
<span id="Setup"></span><div class="header">
|
||||
<p>
|
||||
Next: <a href="Run.html" accesskey="n" rel="next">Run</a>, Previous: <a href="Overview.html" accesskey="p" rel="prev">Overview</a>, Up: <a href="index.html" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>]</p>
|
||||
</div>
|
||||
<hr>
|
||||
<span id="Setup-1"></span><h2 class="chapter">2 Setup</h2>
|
||||
|
||||
|
||||
<span id="Handlers"></span><h3 class="section">2.1 Handlers</h3>
|
||||
|
||||
<p>Notification tasks in this package are intended to be loaded dynamically, making no assumptions on which handlers that should be connected to the different tasks. The tasks provided are:
|
||||
</p>
|
||||
<ul>
|
||||
<li> <strong>notify.sms.log</strong>: (none)
|
||||
</li><li> <strong>notify.sms.db</strong>: Postgresql, along with python packages alembic, SQLAlchemy and psycopg2.
|
||||
</li><li> <strong>notify.sms.africastalking</strong>: africastalking python package.
|
||||
</li></ul>
|
||||
|
||||
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
94
apps/cic-notify/doc/texinfo/html/index.html
Normal file
94
apps/cic-notify/doc/texinfo/html/index.html
Normal file
@@ -0,0 +1,94 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<!-- Released 2020 under GPL3 -->
|
||||
<!-- Created by GNU Texinfo 6.7, http://www.gnu.org/software/texinfo/ -->
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Top (Grassroots Economics CIC notify 0.2.0)</title>
|
||||
|
||||
<meta name="description" content="Top (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="keywords" content="Top (Grassroots Economics CIC notify 0.2.0)">
|
||||
<meta name="resource-type" content="document">
|
||||
<meta name="distribution" content="global">
|
||||
<meta name="Generator" content="makeinfo">
|
||||
<link href="#Top" rel="start" title="Top">
|
||||
<link href="#SEC_Contents" rel="contents" title="Table of Contents">
|
||||
<link href="Overview.html" rel="next" title="Overview">
|
||||
<style type="text/css">
|
||||
<!--
|
||||
a.summary-letter {text-decoration: none}
|
||||
blockquote.indentedblock {margin-right: 0em}
|
||||
div.display {margin-left: 3.2em}
|
||||
div.example {margin-left: 3.2em}
|
||||
div.lisp {margin-left: 3.2em}
|
||||
kbd {font-style: oblique}
|
||||
pre.display {font-family: inherit}
|
||||
pre.format {font-family: inherit}
|
||||
pre.menu-comment {font-family: serif}
|
||||
pre.menu-preformatted {font-family: serif}
|
||||
span.nolinebreak {white-space: nowrap}
|
||||
span.roman {font-family: initial; font-weight: normal}
|
||||
span.sansserif {font-family: sans-serif; font-weight: normal}
|
||||
ul.no-bullet {list-style: none}
|
||||
-->
|
||||
</style>
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body lang="en">
|
||||
<h1 class="settitle" align="center">Grassroots Economics CIC notify 0.2.0</h1>
|
||||
|
||||
|
||||
|
||||
<span id="SEC_Contents"></span>
|
||||
<h2 class="contents-heading">Table of Contents</h2>
|
||||
|
||||
<div class="contents">
|
||||
|
||||
<ul class="no-bullet">
|
||||
<li><a id="toc-Overview-1" href="Overview.html#Overview">1 Overview</a>
|
||||
<ul class="no-bullet">
|
||||
<li><a id="toc-Contents" href="Overview.html#Contents">1.1 Contents</a></li>
|
||||
</ul></li>
|
||||
<li><a id="toc-Setup-1" href="Setup.html#Setup">2 Setup</a>
|
||||
<ul class="no-bullet">
|
||||
<li><a id="toc-Handlers" href="Setup.html#Handlers">2.1 Handlers</a></li>
|
||||
</ul></li>
|
||||
<li><a id="toc-Running-the-Application" href="Run.html#Run">3 Running the Application</a></li>
|
||||
<li><a id="toc-API-1" href="API.html#API">4 API</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
|
||||
<span id="Top"></span><div class="header">
|
||||
<p>
|
||||
[<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>]</p>
|
||||
</div>
|
||||
<hr>
|
||||
<span id="Grassroots-Economics-CIC-ETH"></span><h1 class="top">Grassroots Economics CIC ETH</h1>
|
||||
|
||||
<p>This document describes microservices that broker external notifications from the CIC network
|
||||
</p>
|
||||
|
||||
<table class="menu" border="0" cellspacing="0">
|
||||
<tr><td align="left" valign="top">• <a href="Overview.html" accesskey="1">Overview</a></td><td> </td><td align="left" valign="top">
|
||||
</td></tr>
|
||||
<tr><td align="left" valign="top">• <a href="Setup.html" accesskey="2">Setup</a></td><td> </td><td align="left" valign="top">
|
||||
</td></tr>
|
||||
<tr><td align="left" valign="top">• <a href="Run.html" accesskey="3">Running the Application</a></td><td> </td><td align="left" valign="top">
|
||||
</td></tr>
|
||||
<tr><td align="left" valign="top">• <a href="API.html" accesskey="4">API</a></td><td> </td><td align="left" valign="top">
|
||||
</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
<div class="header">
|
||||
<p>
|
||||
[<a href="#SEC_Contents" title="Table of contents" rel="contents">Contents</a>]</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
28
apps/cic-notify/doc/texinfo/index.texi
Normal file
28
apps/cic-notify/doc/texinfo/index.texi
Normal file
@@ -0,0 +1,28 @@
|
||||
\input texinfo
|
||||
@settitle Grassroots Economics CIC notify 0.2.0
|
||||
|
||||
@copying
|
||||
Released 2020 under GPL3
|
||||
@end copying
|
||||
|
||||
@titlepage
|
||||
@title Community Inclusion Currency Network
|
||||
@author Louis Holbrook
|
||||
|
||||
@end titlepage
|
||||
|
||||
@c
|
||||
@contents
|
||||
|
||||
@ifnottex
|
||||
@node Top
|
||||
@top Grassroots Economics CIC ETH
|
||||
|
||||
This document describes microservices that broker external notifications from the CIC network
|
||||
@end ifnottex
|
||||
|
||||
|
||||
@include overview.texi
|
||||
@include setup.texi
|
||||
@include run.texi
|
||||
@include api.texi
|
||||
22
apps/cic-notify/doc/texinfo/overview.texi
Normal file
22
apps/cic-notify/doc/texinfo/overview.texi
Normal file
@@ -0,0 +1,22 @@
|
||||
@node Overview
|
||||
@chapter Overview
|
||||
|
||||
This system is in early stages of development. It is intended to be a flexible notification broker where additional notification targets easily can be plugged in.
|
||||
|
||||
The framework is designed to asynchronously execute all tasks belonging to a specific context, based on the name of the task.
|
||||
|
||||
Currently, only handlers for @strong{sms} notifications are implemented. Any task with a @code{notify.sms.} prefix registered in the celery task worker pool will be executed upon the high-level "send sms" task.
|
||||
|
||||
Similary, any other notification category can be implemented. e.g. @code{notify.email.}, @code{notify.telegram.}, @code{notify.mattermost.} etc.
|
||||
|
||||
@section Contents
|
||||
|
||||
The only implementations so far are three @code{sms} notification tasks:
|
||||
|
||||
@itemize
|
||||
@item log (as in python logger, thus more or less noop)
|
||||
@item db (postgres)
|
||||
@item Africas Talking API
|
||||
@end itemize
|
||||
|
||||
@strong{NOTE}: The Africas Talking API will be removed from the suite, and provided as an add-on package down the road. It will illustrate how to include arbitrary tasks to a asynchronous group of notification targets.
|
||||
4
apps/cic-notify/doc/texinfo/run.texi
Normal file
4
apps/cic-notify/doc/texinfo/run.texi
Normal file
@@ -0,0 +1,4 @@
|
||||
@node Run
|
||||
@chapter Running the Application
|
||||
|
||||
A convenience task runner is provided in @file{scripts/cic-notify-tasker.py}.
|
||||
17
apps/cic-notify/doc/texinfo/setup.texi
Normal file
17
apps/cic-notify/doc/texinfo/setup.texi
Normal file
@@ -0,0 +1,17 @@
|
||||
@node Setup
|
||||
@chapter Setup
|
||||
|
||||
|
||||
@section Handlers
|
||||
|
||||
Notification tasks in this package are intended to be loaded dynamically, making no assumptions on which handlers that should be connected to the different tasks. The tasks provided are:
|
||||
|
||||
@itemize
|
||||
@item
|
||||
@strong{notify.sms.log}: (none)
|
||||
@item
|
||||
@strong{notify.sms.db}: Postgresql, along with python packages alembic, SQLAlchemy and psycopg2.
|
||||
@item
|
||||
@strong{notify.sms.africastalking}: africastalking python package.
|
||||
@end itemize
|
||||
|
||||
39
apps/cic-notify/docker/Dockerfile
Normal file
39
apps/cic-notify/docker/Dockerfile
Normal file
@@ -0,0 +1,39 @@
|
||||
FROM python:3.8.6
|
||||
|
||||
RUN apt-get update && \
|
||||
apt install -y gcc gnupg libpq-dev wget make g++ gnupg bash procps
|
||||
|
||||
WORKDIR /usr/src/cic-notify
|
||||
|
||||
ARG pip_extra_index_url_flag='--index https://pypi.org/simple --extra-index-url https://pip.grassrootseconomics.net:8433'
|
||||
ARG root_requirement_file='requirements.txt'
|
||||
RUN echo "copying root req file ${root_requirement_file}"
|
||||
COPY $root_requirement_file .
|
||||
RUN pip install -r $root_requirement_file $pip_extra_index_url_flag
|
||||
|
||||
COPY cic-notify/setup.cfg \
|
||||
cic-notify/setup.py \
|
||||
./
|
||||
COPY cic-notify/cic_notify/ ./cic_notify/
|
||||
COPY cic-notify/requirements.txt \
|
||||
cic-notify/test_requirements.txt \
|
||||
./
|
||||
|
||||
COPY cic-notify/scripts/ scripts/
|
||||
RUN pip install $pip_extra_index_url_flag .[africastalking,notifylog]
|
||||
|
||||
COPY cic-notify/tests/ tests/
|
||||
COPY cic-notify/docker/db.sh \
|
||||
cic-notify/docker/start_tasker.sh \
|
||||
/root/
|
||||
|
||||
#RUN apk add postgresql-client
|
||||
#RUN apk add bash
|
||||
|
||||
# ini files in config directory defines the configurable parameters for the application
|
||||
# they can all be overridden by environment variables
|
||||
# to generate a list of environment variables from configuration, use: confini-dump -z <dir> (executable provided by confini package)
|
||||
COPY cic-notify/.config/ /usr/local/etc/cic-notify/
|
||||
COPY cic-notify/cic_notify/db/migrations/ /usr/local/share/cic-notify/alembic/
|
||||
|
||||
WORKDIR /root
|
||||
13
apps/cic-notify/docker/Dockerfile.service
Normal file
13
apps/cic-notify/docker/Dockerfile.service
Normal file
@@ -0,0 +1,13 @@
|
||||
FROM grassrootseconomics:cic-notify
|
||||
|
||||
#FROM python:3.8.6-alpine
|
||||
|
||||
#RUN apk update && \
|
||||
# apk add gnupg libpq
|
||||
|
||||
#COPY --from=0 /usr/local/ /usr/local/
|
||||
#COPY --from=0 /root/ /root/
|
||||
|
||||
#RUN apk add bash
|
||||
|
||||
WORKDIR /root
|
||||
3
apps/cic-notify/docker/db.sh
Normal file
3
apps/cic-notify/docker/db.sh
Normal file
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
|
||||
migrate.py -c /usr/local/etc/cic-notify --migrations-dir /usr/local/share/cic-notify/alembic -vv
|
||||
5
apps/cic-notify/docker/start_tasker.sh
Executable file
5
apps/cic-notify/docker/start_tasker.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
. ./db.sh
|
||||
|
||||
/usr/local/bin/cic-notify-tasker -vv $@
|
||||
5
apps/cic-notify/requirements.txt
Normal file
5
apps/cic-notify/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
celery~=4.4.7
|
||||
confini~=0.3.6a1
|
||||
alembic~=1.4.2
|
||||
redis~=3.5.3
|
||||
semver==2.13.0
|
||||
57
apps/cic-notify/scripts/migrate.py
Normal file
57
apps/cic-notify/scripts/migrate.py
Normal file
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python
|
||||
# standard imports
|
||||
import argparse
|
||||
import os
|
||||
import logging
|
||||
|
||||
# third party imports
|
||||
import alembic
|
||||
from alembic.config import Config as AlembicConfig
|
||||
import confini
|
||||
|
||||
from cic_notify.db import dsn_from_config
|
||||
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
logg = logging.getLogger()
|
||||
|
||||
rootdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
dbdir = os.path.join(rootdir, 'cic_notify', 'db')
|
||||
migrationsdir = os.path.join(dbdir, 'migrations')
|
||||
|
||||
config_dir = os.path.join('/usr/local/etc/cic-notify')
|
||||
|
||||
argparser = argparse.ArgumentParser()
|
||||
argparser.add_argument('-c', type=str, default=config_dir, help='config file')
|
||||
argparser.add_argument('--env-prefix', default=os.environ.get('CONFINI_ENV_PREFIX'), dest='env_prefix', type=str, help='environment prefix for variables to overwrite configuration')
|
||||
argparser.add_argument('--migrations-dir', dest='migrations_dir', default=migrationsdir, type=str, help='path to alembic migrations directory')
|
||||
argparser.add_argument('-v', action='store_true', help='be verbose')
|
||||
argparser.add_argument('-vv', action='store_true', help='be more verbose')
|
||||
args = argparser.parse_args()
|
||||
|
||||
if args.vv:
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
elif args.v:
|
||||
logging.getLogger().setLevel(logging.INFO)
|
||||
|
||||
config = confini.Config(args.c, args.env_prefix)
|
||||
config.process()
|
||||
config.censor('PASSWORD', 'DATABASE')
|
||||
#config.censor('PASSWORD', 'SSL')
|
||||
logg.debug('config:\n{}'.format(config))
|
||||
|
||||
migrations_dir = os.path.join(args.migrations_dir, config.get('DATABASE_ENGINE'))
|
||||
if not os.path.isdir(migrations_dir):
|
||||
logg.debug('migrations dir for engine {} not found, reverting to default'.format(config.get('DATABASE_ENGINE')))
|
||||
migrations_dir = os.path.join(args.migrations_dir, 'default')
|
||||
|
||||
# connect to database
|
||||
dsn = dsn_from_config(config)
|
||||
|
||||
|
||||
logg.info('using migrations dir {}'.format(migrations_dir))
|
||||
logg.info('using db {}'.format(dsn))
|
||||
ac = AlembicConfig(os.path.join(migrations_dir, 'alembic.ini'))
|
||||
ac.set_main_option('sqlalchemy.url', dsn)
|
||||
ac.set_main_option('script_location', migrations_dir)
|
||||
|
||||
alembic.command.upgrade(ac, 'head')
|
||||
12
apps/cic-notify/scripts/send_sms.py
Normal file
12
apps/cic-notify/scripts/send_sms.py
Normal file
@@ -0,0 +1,12 @@
|
||||
# local imports
|
||||
import cic_notify
|
||||
|
||||
# third-part imports
|
||||
import celery
|
||||
|
||||
|
||||
# TODO: Add configurable backend
|
||||
celery_app = celery.Celery(broker='redis:///', backend='redis:///')
|
||||
|
||||
api = cic_notify.Api('cic-notify')
|
||||
print(api.sms('+25412121212', 'foo'))
|
||||
47
apps/cic-notify/setup.cfg
Normal file
47
apps/cic-notify/setup.cfg
Normal file
@@ -0,0 +1,47 @@
|
||||
[metadata]
|
||||
name = cic-notify
|
||||
version= attr: cic_notify.version.__version_string__
|
||||
description = CIC notifications service
|
||||
author = Louis Holbrook
|
||||
author_email = dev@holbrook.no
|
||||
url = https://gitlab.com/grassrootseconomics/cic-eth
|
||||
keywords =
|
||||
cic
|
||||
cryptocurrency
|
||||
ethereum
|
||||
sms
|
||||
classifiers =
|
||||
Programming Language :: Python :: 3
|
||||
Operating System :: OS Independent
|
||||
Development Status :: 3 - Alpha
|
||||
Environment :: No Input/Output (Daemon)
|
||||
Intended Audience :: Developers
|
||||
License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
|
||||
Topic :: Internet
|
||||
Topic :: Blockchain :: EVM
|
||||
license = GPL3
|
||||
licence_files =
|
||||
LICENSE.txt
|
||||
|
||||
[options]
|
||||
python_requires = >= 3.6
|
||||
packages =
|
||||
cic_notify
|
||||
cic_notify.db
|
||||
cic_notify.db.models
|
||||
cic_notify.tasks.sms
|
||||
cic_notify.runnable
|
||||
scripts =
|
||||
scripts/migrate.py
|
||||
[options.extras_require]
|
||||
africastalking = africastalking==1.2.3
|
||||
notifylog = psycopg2==2.8.6
|
||||
testing =
|
||||
pytest==6.0.1
|
||||
pytest-celery==0.0.0a1
|
||||
pytest-mock==3.3.1
|
||||
pysqlite3==0.4.3
|
||||
|
||||
[options.entry_points]
|
||||
console_scripts =
|
||||
cic-notify-tasker = cic_notify.runnable.tasker:main
|
||||
30
apps/cic-notify/setup.py
Normal file
30
apps/cic-notify/setup.py
Normal file
@@ -0,0 +1,30 @@
|
||||
# standard imports
|
||||
from setuptools import setup
|
||||
|
||||
# third-party imports
|
||||
|
||||
# local imports
|
||||
|
||||
|
||||
requirements = []
|
||||
requirements_file = open('requirements.txt', 'r')
|
||||
while True:
|
||||
requirement = requirements_file.readline()
|
||||
if requirement == '':
|
||||
break
|
||||
requirements.append(requirement.rstrip())
|
||||
requirements_file.close()
|
||||
|
||||
test_requirements = []
|
||||
test_requirements_file = open('test_requirements.txt', 'r')
|
||||
while True:
|
||||
test_requirement = test_requirements_file.readline()
|
||||
if test_requirement == '':
|
||||
break
|
||||
test_requirements.append(test_requirement.rstrip())
|
||||
test_requirements_file.close()
|
||||
|
||||
setup(
|
||||
install_requires=requirements,
|
||||
tests_require=test_requirements,
|
||||
)
|
||||
5
apps/cic-notify/test_requirements.txt
Normal file
5
apps/cic-notify/test_requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
pytest~=6.0.1
|
||||
pytest-celery~=0.0.0a1
|
||||
pytest-mock~=3.3.1
|
||||
pysqlite3~=0.4.3
|
||||
|
||||
31
apps/cic-notify/tests/conftest.py
Normal file
31
apps/cic-notify/tests/conftest.py
Normal file
@@ -0,0 +1,31 @@
|
||||
# standard imports
|
||||
import sys
|
||||
import os
|
||||
import pytest
|
||||
import logging
|
||||
|
||||
# third party imports
|
||||
import confini
|
||||
|
||||
script_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
root_dir = os.path.dirname(script_dir)
|
||||
sys.path.insert(0, root_dir)
|
||||
|
||||
# local imports
|
||||
from cic_notify.db.models.base import SessionBase
|
||||
#from transport.notification import AfricastalkingNotification
|
||||
|
||||
# fixtures
|
||||
from tests.fixtures_config import *
|
||||
from tests.fixtures_celery import *
|
||||
from tests.fixtures_database import *
|
||||
|
||||
logg = logging.getLogger()
|
||||
|
||||
|
||||
#@pytest.fixture(scope='session')
|
||||
#def africastalking_notification(
|
||||
# load_config,
|
||||
# ):
|
||||
# return AfricastalkingNotificationTransport(load_config)
|
||||
#
|
||||
48
apps/cic-notify/tests/fixtures_celery.py
Normal file
48
apps/cic-notify/tests/fixtures_celery.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# third-party imports
|
||||
import pytest
|
||||
import tempfile
|
||||
import logging
|
||||
import shutil
|
||||
|
||||
logg = logging.getLogger(__file__)
|
||||
|
||||
|
||||
# celery fixtures
|
||||
@pytest.fixture(scope='session')
|
||||
def celery_includes():
|
||||
return [
|
||||
'cic_notify.tasks.sms',
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def celery_config():
|
||||
bq = tempfile.mkdtemp()
|
||||
bp = tempfile.mkdtemp()
|
||||
rq = tempfile.mkdtemp()
|
||||
logg.debug('celery broker queue {} processed {}'.format(bq, bp))
|
||||
logg.debug('celery backend store {}'.format(rq))
|
||||
yield {
|
||||
'broker_url': 'filesystem://',
|
||||
'broker_transport_options': {
|
||||
'data_folder_in': bq,
|
||||
'data_folder_out': bq,
|
||||
'data_folder_processed': bp,
|
||||
},
|
||||
'result_backend': 'file://{}'.format(rq),
|
||||
}
|
||||
logg.debug('cleaning up celery filesystem backend files {} {} {}'.format(bq, bp, rq))
|
||||
shutil.rmtree(bq)
|
||||
shutil.rmtree(bp)
|
||||
shutil.rmtree(rq)
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def celery_worker_parameters():
|
||||
return {
|
||||
# 'queues': ('cic-notify'),
|
||||
}
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def celery_enable_logging():
|
||||
return True
|
||||
20
apps/cic-notify/tests/fixtures_config.py
Normal file
20
apps/cic-notify/tests/fixtures_config.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# standard imports
|
||||
import os
|
||||
import logging
|
||||
|
||||
# third-party imports
|
||||
import pytest
|
||||
import confini
|
||||
|
||||
script_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
root_dir = os.path.dirname(script_dir)
|
||||
logg = logging.getLogger(__file__)
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def load_config():
|
||||
config_dir = os.path.join(root_dir, '.config/test')
|
||||
conf = confini.Config(config_dir, 'CICTEST')
|
||||
conf.process()
|
||||
logg.debug('config {}'.format(conf))
|
||||
return conf
|
||||
48
apps/cic-notify/tests/fixtures_database.py
Normal file
48
apps/cic-notify/tests/fixtures_database.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# standard imports
|
||||
import os
|
||||
|
||||
# third-party imports
|
||||
import pytest
|
||||
import alembic
|
||||
from alembic.config import Config as AlembicConfig
|
||||
|
||||
# local imports
|
||||
from cic_notify.db import SessionBase
|
||||
from cic_notify.db import dsn_from_config
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def database_engine(
|
||||
load_config,
|
||||
):
|
||||
dsn = dsn_from_config(load_config)
|
||||
SessionBase.connect(dsn)
|
||||
return dsn
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def init_database(
|
||||
load_config,
|
||||
database_engine,
|
||||
):
|
||||
|
||||
rootdir = os.path.dirname(os.path.dirname(__file__))
|
||||
dbdir = os.path.join(rootdir, 'cic_notify', 'db')
|
||||
migrationsdir = os.path.join(dbdir, 'migrations', load_config.get('DATABASE_ENGINE'))
|
||||
if not os.path.isdir(migrationsdir):
|
||||
migrationsdir = os.path.join(dbdir, 'migrations', 'default')
|
||||
|
||||
session = SessionBase.create_session()
|
||||
|
||||
ac = AlembicConfig(os.path.join(migrationsdir, 'alembic.ini'))
|
||||
ac.set_main_option('sqlalchemy.url', database_engine)
|
||||
ac.set_main_option('script_location', migrationsdir)
|
||||
|
||||
alembic.command.downgrade(ac, 'base')
|
||||
alembic.command.upgrade(ac, 'head')
|
||||
|
||||
yield session
|
||||
session.commit()
|
||||
session.close()
|
||||
|
||||
|
||||
34
apps/cic-notify/tests/test_sms.py
Normal file
34
apps/cic-notify/tests/test_sms.py
Normal file
@@ -0,0 +1,34 @@
|
||||
# standard imports
|
||||
import json
|
||||
|
||||
# third party imports
|
||||
import pytest
|
||||
import celery
|
||||
|
||||
# local imports
|
||||
from cic_notify.tasks.sms import db
|
||||
from cic_notify.tasks.sms import log
|
||||
|
||||
def test_log_notification(
|
||||
celery_session_worker,
|
||||
):
|
||||
|
||||
recipient = '+25412121212'
|
||||
content = 'bar'
|
||||
s_log = celery.signature('cic_notify.tasks.sms.log.log')
|
||||
t = s_log.apply_async(args=[recipient, content])
|
||||
|
||||
r = t.get()
|
||||
|
||||
|
||||
def test_db_notification(
|
||||
init_database,
|
||||
celery_session_worker,
|
||||
):
|
||||
|
||||
recipient = '+25412121213'
|
||||
content = 'foo'
|
||||
s_db = celery.signature('cic_notify.tasks.sms.db.persist_notification')
|
||||
t = s_db.apply_async(args=[recipient, content])
|
||||
|
||||
r = t.get()
|
||||
Submodule apps/cic-ussd deleted from c5ffcc19c5
16
apps/cic-ussd/.config/app.ini
Normal file
16
apps/cic-ussd/.config/app.ini
Normal file
@@ -0,0 +1,16 @@
|
||||
[app]
|
||||
ALLOWED_IP=127.0.0.1
|
||||
LOCALE_FALLBACK=en
|
||||
LOCALE_PATH=var/lib/locale/
|
||||
MAX_BODY_LENGTH=1024
|
||||
PASSWORD_PEPPER=QYbzKff6NhiQzY3ygl2BkiKOpER8RE/Upqs/5aZWW+I=
|
||||
SERVICE_CODE=*483*46#
|
||||
|
||||
[ussd]
|
||||
MENU_FILE=/usr/local/lib/python3.8/site-packages/cic_ussd/db/ussd_menu.json
|
||||
|
||||
[statemachine]
|
||||
STATES=/usr/src/cic-ussd/states/
|
||||
TRANSITIONS=/usr/src/cic-ussd/transitions/
|
||||
|
||||
|
||||
2
apps/cic-ussd/.config/cic.ini
Normal file
2
apps/cic-ussd/.config/cic.ini
Normal file
@@ -0,0 +1,2 @@
|
||||
[cic]
|
||||
chain_spec = Bloxberg:8995
|
||||
8
apps/cic-ussd/.config/database.ini
Normal file
8
apps/cic-ussd/.config/database.ini
Normal file
@@ -0,0 +1,8 @@
|
||||
[database]
|
||||
NAME=cic_ussd
|
||||
USER=postgres
|
||||
PASSWORD=password
|
||||
HOST=localhost
|
||||
PORT=5432
|
||||
ENGINE=postgresql
|
||||
DRIVER=psycopg2
|
||||
5
apps/cic-ussd/.config/pip.ini
Normal file
5
apps/cic-ussd/.config/pip.ini
Normal file
@@ -0,0 +1,5 @@
|
||||
[PIP]
|
||||
extra_index_host = pip.grassrootseconomics.net
|
||||
extra_index_port = 8433
|
||||
extra_index_path = /
|
||||
extra_index_proto = https
|
||||
9
apps/cic-ussd/.config/redis.ini
Normal file
9
apps/cic-ussd/.config/redis.ini
Normal file
@@ -0,0 +1,9 @@
|
||||
[celery]
|
||||
BROKER_URL=redis://
|
||||
RESULT_URL=redis://
|
||||
|
||||
[redis]
|
||||
HOSTNAME=localhost
|
||||
PASSWORD=
|
||||
PORT=6379
|
||||
DATABASE=0
|
||||
14
apps/cic-ussd/.config/test/app.ini
Normal file
14
apps/cic-ussd/.config/test/app.ini
Normal file
@@ -0,0 +1,14 @@
|
||||
[app]
|
||||
ALLOWED_IP=127.0.0.1
|
||||
LOCALE_FALLBACK=en
|
||||
LOCALE_PATH=var/lib/locale/
|
||||
MAX_BODY_LENGTH=1024
|
||||
PASSWORD_PEPPER=QYbzKff6NhiQzY3ygl2BkiKOpER8RE/Upqs/5aZWW+I=
|
||||
SERVICE_CODE=*483*46#
|
||||
|
||||
[ussd]
|
||||
MENU_FILE=cic_ussd/db/ussd_menu.json
|
||||
|
||||
[statemachine]
|
||||
STATES=states/
|
||||
TRANSITIONS=transitions/
|
||||
2
apps/cic-ussd/.config/test/cic.ini
Normal file
2
apps/cic-ussd/.config/test/cic.ini
Normal file
@@ -0,0 +1,2 @@
|
||||
[cic]
|
||||
chain_spec = Bloxberg:8995
|
||||
8
apps/cic-ussd/.config/test/database.ini
Normal file
8
apps/cic-ussd/.config/test/database.ini
Normal file
@@ -0,0 +1,8 @@
|
||||
[database]
|
||||
NAME=cic_ussd_test
|
||||
USER=postgres
|
||||
PASSWORD=
|
||||
HOST=localhost
|
||||
PORT=5432
|
||||
ENGINE=sqlite
|
||||
DRIVER=pysqlite
|
||||
5
apps/cic-ussd/.config/test/pip.ini
Normal file
5
apps/cic-ussd/.config/test/pip.ini
Normal file
@@ -0,0 +1,5 @@
|
||||
[PIP]
|
||||
extra_index_host = pip.grassrootseconomics.net
|
||||
extra_index_port = 8433
|
||||
extra_index_path = /
|
||||
extra_index_proto = https
|
||||
9
apps/cic-ussd/.config/test/redis.ini
Normal file
9
apps/cic-ussd/.config/test/redis.ini
Normal file
@@ -0,0 +1,9 @@
|
||||
[celery]
|
||||
BROKER_URL = filesystem://
|
||||
RESULT_URL = filesystem://
|
||||
|
||||
[redis]
|
||||
HOSTNAME=localhost
|
||||
PASSWORD=
|
||||
PORT=6379
|
||||
DATABASE=0
|
||||
6
apps/cic-ussd/.coveragerc
Normal file
6
apps/cic-ussd/.coveragerc
Normal file
@@ -0,0 +1,6 @@
|
||||
[report]
|
||||
omit =
|
||||
venv/*
|
||||
scripts/*
|
||||
cic_ussd/db/migrations/*
|
||||
cic_ussd/runnable/*
|
||||
5
apps/cic-ussd/.gitignore
vendored
Normal file
5
apps/cic-ussd/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
__pycache__
|
||||
.idea
|
||||
venv
|
||||
node_modules
|
||||
.coverage
|
||||
23
apps/cic-ussd/.gitlab-ci.yml
Normal file
23
apps/cic-ussd/.gitlab-ci.yml
Normal file
@@ -0,0 +1,23 @@
|
||||
.cic_ussd_variables:
|
||||
variables:
|
||||
APP_NAME: cic-ussd
|
||||
DOCKERFILE_PATH: $APP_NAME/docker/Dockerfile
|
||||
|
||||
.this_changes_target:
|
||||
rules:
|
||||
- changes:
|
||||
- $CONTEXT/$APP_NAME/*
|
||||
|
||||
build-mr-cic-ussd:
|
||||
extends:
|
||||
- .this_changes_target
|
||||
- .py_build_merge_request
|
||||
- .cic_ussd_variables
|
||||
|
||||
build-push-cic-ussd:
|
||||
extends:
|
||||
- .this_changes_target
|
||||
- .py_build_push
|
||||
- .cic_ussd_variables
|
||||
|
||||
|
||||
674
apps/cic-ussd/LICENSE.md
Normal file
674
apps/cic-ussd/LICENSE.md
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
0
apps/cic-ussd/cic_ussd/__init__.py
Normal file
0
apps/cic-ussd/cic_ussd/__init__.py
Normal file
39
apps/cic-ussd/cic_ussd/accounts.py
Normal file
39
apps/cic-ussd/cic_ussd/accounts.py
Normal file
@@ -0,0 +1,39 @@
|
||||
# standard imports
|
||||
import logging
|
||||
from collections import deque
|
||||
|
||||
# third-party imports
|
||||
from cic_eth.api import Api
|
||||
|
||||
# local imports
|
||||
from cic_ussd.transactions import from_wei
|
||||
|
||||
logg = logging.getLogger()
|
||||
|
||||
|
||||
class BalanceManager:
|
||||
|
||||
def __init__(self, address: str, chain_str: str, token_symbol: str):
|
||||
"""
|
||||
:param address: Ethereum address of account whose balance is being queried
|
||||
:type address: str, 0x-hex
|
||||
:param chain_str: The chain name and network id.
|
||||
:type chain_str: str
|
||||
:param token_symbol: ERC20 token symbol of whose balance is being queried
|
||||
:type token_symbol: str
|
||||
"""
|
||||
self.address = address
|
||||
self.chain_str = chain_str
|
||||
self.token_symbol = token_symbol
|
||||
|
||||
def get_operational_balance(self) -> float:
|
||||
"""This question queries cic-eth for an account's balance
|
||||
:return: The current balance of the account as reflected on the blockchain.
|
||||
:rtype: int
|
||||
"""
|
||||
cic_eth_api = Api(chain_str=self.chain_str, callback_task=None)
|
||||
balance_request_task = cic_eth_api.balance(address=self.address, token_symbol=self.token_symbol)
|
||||
balance_request_task_results = balance_request_task.collect()
|
||||
balance_result = deque(balance_request_task_results, maxlen=1).pop()
|
||||
balance = from_wei(value=balance_result[-1])
|
||||
return balance
|
||||
36
apps/cic-ussd/cic_ussd/db/__init__.py
Normal file
36
apps/cic-ussd/cic_ussd/db/__init__.py
Normal file
@@ -0,0 +1,36 @@
|
||||
# standard imports
|
||||
import logging
|
||||
|
||||
# third party imports
|
||||
from confini import Config
|
||||
|
||||
logg = logging.getLogger()
|
||||
|
||||
|
||||
def dsn_from_config(config):
|
||||
"""
|
||||
This function builds a data source name mapping to a database from values defined in the config object.
|
||||
:param config: A config object.
|
||||
:type config: Config
|
||||
:return: A database URI.
|
||||
:rtype: str
|
||||
"""
|
||||
scheme = config.get('DATABASE_ENGINE')
|
||||
if config.get('DATABASE_DRIVER') is not None:
|
||||
scheme += '+{}'.format(config.get('DATABASE_DRIVER'))
|
||||
|
||||
dsn = ''
|
||||
if config.get('DATABASE_ENGINE') == 'sqlite':
|
||||
dsn = f'{scheme}:///{config.get("DATABASE_NAME")}'
|
||||
|
||||
else:
|
||||
dsn = '{}://{}:{}@{}:{}/{}'.format(
|
||||
scheme,
|
||||
config.get('DATABASE_USER'),
|
||||
config.get('DATABASE_PASSWORD'),
|
||||
config.get('DATABASE_HOST'),
|
||||
config.get('DATABASE_PORT'),
|
||||
config.get('DATABASE_NAME'),
|
||||
)
|
||||
logg.debug('parsed dsn from config: {}'.format(dsn))
|
||||
return dsn
|
||||
1
apps/cic-ussd/cic_ussd/db/migrations/default/README
Normal file
1
apps/cic-ussd/cic_ussd/db/migrations/default/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
74
apps/cic-ussd/cic_ussd/db/migrations/default/alembic.ini
Normal file
74
apps/cic-ussd/cic_ussd/db/migrations/default/alembic.ini
Normal file
@@ -0,0 +1,74 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = .
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# timezone to use when rendering the date
|
||||
# within the migration file as well as the filename.
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; this defaults
|
||||
# to ./versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat ./versions
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
80
apps/cic-ussd/cic_ussd/db/migrations/default/env.py
Normal file
80
apps/cic-ussd/cic_ussd/db/migrations/default/env.py
Normal file
@@ -0,0 +1,80 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name, disable_existing_loggers=True)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = None
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = context.config.attributes.get("connection", None)
|
||||
|
||||
if connectable is None:
|
||||
connectable = engine_from_config(
|
||||
context.config.get_section(context.config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
24
apps/cic-ussd/cic_ussd/db/migrations/default/script.py.mako
Normal file
24
apps/cic-ussd/cic_ussd/db/migrations/default/script.py.mako
Normal file
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Create ussd session table
|
||||
|
||||
Revision ID: 2a329190a9af
|
||||
Revises: b5ab9371c0b8
|
||||
Create Date: 2020-10-06 00:06:54.354168
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2a329190a9af'
|
||||
down_revision = 'f289e8510444'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('ussd_session',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('created', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated', sa.DateTime(), nullable=True),
|
||||
sa.Column('external_session_id', sa.String(), nullable=False),
|
||||
sa.Column('service_code', sa.String(), nullable=False),
|
||||
sa.Column('msisdn', sa.String(), nullable=False),
|
||||
sa.Column('user_input', sa.String(), nullable=True),
|
||||
sa.Column('state', sa.String(), nullable=False),
|
||||
sa.Column('session_data', postgresql.JSON(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_ussd_session_external_session_id'), 'ussd_session', ['external_session_id'], unique=True)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_ussd_session_external_session_id'), table_name='ussd_session')
|
||||
op.drop_table('ussd_session')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Create task tracker table
|
||||
|
||||
Revision ID: a571d0aee6f8
|
||||
Revises: 2a329190a9af
|
||||
Create Date: 2021-01-04 18:28:00.462228
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a571d0aee6f8'
|
||||
down_revision = '2a329190a9af'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('task_tracker',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('created', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated', sa.DateTime(), nullable=True),
|
||||
sa.Column('task_uuid', sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('task_tracker')
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Create user table
|
||||
|
||||
Revision ID: f289e8510444
|
||||
Revises:
|
||||
Create Date: 2020-07-14 21:37:13.014200
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f289e8510444'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('user',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('blockchain_address', sa.String(), nullable=False),
|
||||
sa.Column('phone_number', sa.String(), nullable=False),
|
||||
sa.Column('preferred_language', sa.String(), nullable=True),
|
||||
sa.Column('password_hash', sa.String(), nullable=True),
|
||||
sa.Column('failed_pin_attempts', sa.Integer(), nullable=False),
|
||||
sa.Column('account_status', sa.Integer(), nullable=False),
|
||||
sa.Column('created', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_user_phone_number'), 'user', ['phone_number'], unique=True)
|
||||
op.create_index(op.f('ix_user_blockchain_address'), 'user', ['blockchain_address'], unique=True)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_user_blockchain_address'), table_name='user')
|
||||
op.drop_index(op.f('ix_user_phone_number'), table_name='user')
|
||||
op.drop_table('user')
|
||||
47
apps/cic-ussd/cic_ussd/db/models/base.py
Normal file
47
apps/cic-ussd/cic_ussd/db/models/base.py
Normal file
@@ -0,0 +1,47 @@
|
||||
# standard imports
|
||||
import datetime
|
||||
|
||||
# third-party imports
|
||||
from sqlalchemy import Column, Integer, DateTime
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
Model = declarative_base(name='Model')
|
||||
|
||||
|
||||
class SessionBase(Model):
|
||||
__abstract__ = True
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
created = Column(DateTime, default=datetime.datetime.utcnow)
|
||||
updated = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
|
||||
|
||||
engine = None
|
||||
session = None
|
||||
query = None
|
||||
|
||||
@staticmethod
|
||||
def create_session():
|
||||
session = sessionmaker(bind=SessionBase.engine)
|
||||
return session()
|
||||
|
||||
@staticmethod
|
||||
def _set_engine(engine):
|
||||
SessionBase.engine = engine
|
||||
|
||||
@staticmethod
|
||||
def build():
|
||||
Model.metadata.create_all(bind=SessionBase.engine)
|
||||
|
||||
@staticmethod
|
||||
# https://docs.sqlalchemy.org/en/13/core/pooling.html#pool-disconnects
|
||||
def connect(data_source_name):
|
||||
engine = create_engine(data_source_name, pool_pre_ping=True)
|
||||
SessionBase._set_engine(engine)
|
||||
|
||||
@staticmethod
|
||||
def disconnect():
|
||||
SessionBase.engine.dispose()
|
||||
SessionBase.engine = None
|
||||
|
||||
19
apps/cic-ussd/cic_ussd/db/models/task_tracker.py
Normal file
19
apps/cic-ussd/cic_ussd/db/models/task_tracker.py
Normal file
@@ -0,0 +1,19 @@
|
||||
# standard imports
|
||||
import logging
|
||||
|
||||
# third-party imports
|
||||
from sqlalchemy import Column, String
|
||||
|
||||
# local imports
|
||||
from cic_ussd.db.models.base import SessionBase
|
||||
|
||||
logg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TaskTracker(SessionBase):
|
||||
__tablename__ = 'task_tracker'
|
||||
|
||||
def __init__(self, task_uuid):
|
||||
self.task_uuid = task_uuid
|
||||
|
||||
task_uuid = Column(String, nullable=False)
|
||||
90
apps/cic-ussd/cic_ussd/db/models/user.py
Normal file
90
apps/cic-ussd/cic_ussd/db/models/user.py
Normal file
@@ -0,0 +1,90 @@
|
||||
# standard imports
|
||||
from enum import IntEnum
|
||||
|
||||
# third party imports
|
||||
from sqlalchemy import Column, Integer, String
|
||||
|
||||
# local imports
|
||||
from cic_ussd.db.models.base import SessionBase
|
||||
from cic_ussd.encoder import check_password_hash, create_password_hash
|
||||
|
||||
|
||||
class AccountStatus(IntEnum):
|
||||
PENDING = 1
|
||||
ACTIVE = 2
|
||||
LOCKED = 3
|
||||
RESET = 4
|
||||
|
||||
|
||||
class User(SessionBase):
|
||||
"""
|
||||
This class defines a user record along with functions responsible for hashing the user's corresponding password and
|
||||
subsequently verifying a password's validity given an input to compare against the persisted hash.
|
||||
"""
|
||||
__tablename__ = 'user'
|
||||
|
||||
blockchain_address = Column(String)
|
||||
phone_number = Column(String)
|
||||
password_hash = Column(String)
|
||||
failed_pin_attempts = Column(Integer)
|
||||
account_status = Column(Integer)
|
||||
preferred_language = Column(String)
|
||||
|
||||
def __init__(self, blockchain_address, phone_number):
|
||||
self.blockchain_address = blockchain_address
|
||||
self.phone_number = phone_number
|
||||
self.password_hash = None
|
||||
self.failed_pin_attempts = 0
|
||||
self.account_status = AccountStatus.PENDING.value
|
||||
|
||||
def __repr__(self):
|
||||
return f'<User: {self.blockchain_address}>'
|
||||
|
||||
def create_password(self, password):
|
||||
"""This method takes a password value and hashes the value before assigning it to the corresponding
|
||||
`hashed_password` attribute in the user record.
|
||||
:param password: A password value
|
||||
:type password: str
|
||||
"""
|
||||
self.password_hash = create_password_hash(password)
|
||||
|
||||
def verify_password(self, password):
|
||||
"""This method takes a password value and compares it to the user's corresponding `hashed_password` value to
|
||||
establish password validity.
|
||||
:param password: A password value
|
||||
:type password: str
|
||||
:return: Pin validity
|
||||
:rtype: boolean
|
||||
"""
|
||||
return check_password_hash(password, self.password_hash)
|
||||
|
||||
def reset_account_pin(self):
|
||||
"""This method is used to unlock a user's account."""
|
||||
self.failed_pin_attempts = 0
|
||||
self.account_status = AccountStatus.RESET.value
|
||||
|
||||
def get_account_status(self):
|
||||
"""This method checks whether the account is past the allowed number of failed pin attempts.
|
||||
If so, it changes the accounts status to Locked.
|
||||
:return: The account status for a user object
|
||||
:rtype: str
|
||||
"""
|
||||
if self.failed_pin_attempts > 2:
|
||||
self.account_status = AccountStatus.LOCKED.value
|
||||
return AccountStatus(self.account_status).name
|
||||
|
||||
def activate_account(self):
|
||||
"""This method is used to reset failed pin attempts and change account status to Active."""
|
||||
self.failed_pin_attempts = 0
|
||||
self.account_status = AccountStatus.ACTIVE.value
|
||||
|
||||
def has_valid_pin(self):
|
||||
"""This method checks whether the user's account status and if a pin hash is present which implies
|
||||
pin validity.
|
||||
:return: The presence of a valid pin and status of the account being active.
|
||||
:rtype: bool
|
||||
"""
|
||||
valid_pin = None
|
||||
if self.get_account_status() == 'ACTIVE' and self.password_hash is not None:
|
||||
valid_pin = True
|
||||
return valid_pin
|
||||
71
apps/cic-ussd/cic_ussd/db/models/ussd_session.py
Normal file
71
apps/cic-ussd/cic_ussd/db/models/ussd_session.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# standard imports
|
||||
import logging
|
||||
|
||||
# third-party imports
|
||||
from sqlalchemy import Column, String, Integer
|
||||
from sqlalchemy.dialects.postgresql import JSON
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
# local imports
|
||||
from cic_ussd.db.models.base import SessionBase
|
||||
from cic_ussd.error import VersionTooLowError
|
||||
|
||||
logg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UssdSession(SessionBase):
|
||||
__tablename__ = 'ussd_session'
|
||||
|
||||
external_session_id = Column(String, nullable=False, index=True, unique=True)
|
||||
service_code = Column(String, nullable=False)
|
||||
msisdn = Column(String, nullable=False)
|
||||
user_input = Column(String)
|
||||
state = Column(String, nullable=False)
|
||||
session_data = Column(JSON)
|
||||
version = Column(Integer, nullable=False)
|
||||
|
||||
def set_data(self, key, session, value):
|
||||
if self.session_data is None:
|
||||
self.session_data = {}
|
||||
self.session_data[key] = value
|
||||
|
||||
# https://stackoverflow.com/questions/42559434/updates-to-json-field-dont-persist-to-db
|
||||
flag_modified(self, "session_data")
|
||||
session.add(self)
|
||||
|
||||
def get_data(self, key):
|
||||
if self.session_data is not None:
|
||||
return self.session_data.get(key)
|
||||
else:
|
||||
return None
|
||||
|
||||
def check_version(self, new_version):
|
||||
if new_version <= self.version:
|
||||
raise VersionTooLowError('New session version number is not greater than last saved version!')
|
||||
|
||||
def update(self, user_input, state, version, session):
|
||||
self.check_version(version)
|
||||
self.user_input = user_input
|
||||
self.state = state
|
||||
self.version = version
|
||||
session.add(self)
|
||||
|
||||
@staticmethod
|
||||
def have_session_for_phone(phone):
|
||||
r = UssdSession.session.query(UssdSession).filter_by(msisdn=phone).first()
|
||||
return r is not None
|
||||
|
||||
def to_json(self):
|
||||
""" This function serializes the in db ussd session object to a JSON object
|
||||
:return: A JSON object of a ussd session in db
|
||||
:rtype: dict
|
||||
"""
|
||||
return {
|
||||
"external_session_id": self.external_session_id,
|
||||
"service_code": self.service_code,
|
||||
"msisdn": self.msisdn,
|
||||
"user_input": self.user_input,
|
||||
"state": self.state,
|
||||
"session_data": self.session_data,
|
||||
"version": self.version
|
||||
}
|
||||
214
apps/cic-ussd/cic_ussd/db/ussd_menu.json
Normal file
214
apps/cic-ussd/cic_ussd/db/ussd_menu.json
Normal file
@@ -0,0 +1,214 @@
|
||||
{
|
||||
"ussd_menu": {
|
||||
"1": {
|
||||
"description": "The self signup process has been initiated and the account is being created",
|
||||
"display_key": "ussd.kenya.account_creation_prompt",
|
||||
"name": "account_creation_prompt",
|
||||
"parent": null
|
||||
},
|
||||
"2": {
|
||||
"description": "Start menu. This is the entry point for users to select their preferred language",
|
||||
"display_key": "ussd.kenya.initial_language_selection",
|
||||
"name": "initial_language_selection",
|
||||
"parent": null
|
||||
},
|
||||
"3": {
|
||||
"description": "PIN setup entry menu",
|
||||
"display_key": "ussd.kenya.initial_pin_entry",
|
||||
"name": "initial_pin_entry",
|
||||
"parent": "initial_language_selection"
|
||||
},
|
||||
"4": {
|
||||
"description": "Confirm new PIN menu",
|
||||
"display_key": "ussd.kenya.initial_pin_confirmation",
|
||||
"name": "initial_pin_confirmation",
|
||||
"parent": "initial_pin_entry"
|
||||
},
|
||||
"5": {
|
||||
"description": "Start menu. This is the entry point for activated users",
|
||||
"display_key": "ussd.kenya.start",
|
||||
"name": "start",
|
||||
"parent": null
|
||||
},
|
||||
"6": {
|
||||
"description": "Send Token recipient entry",
|
||||
"display_key": "ussd.kenya.enter_transaction_recipient",
|
||||
"name": "enter_transaction_recipient",
|
||||
"parent": "start"
|
||||
},
|
||||
"7": {
|
||||
"description": "Send Token amount prompt menu",
|
||||
"display_key": "ussd.kenya.enter_transaction_amount",
|
||||
"name": "enter_transaction_amount",
|
||||
"parent": "start"
|
||||
},
|
||||
"8": {
|
||||
"description": "PIN entry for authorization to send token",
|
||||
"display_key": "ussd.kenya.transaction_pin_authorization",
|
||||
"name": "transaction_pin_authorization",
|
||||
"parent": "start"
|
||||
},
|
||||
"9": {
|
||||
"description": "Terminal of a menu flow where an SMS is expected after.",
|
||||
"display_key": "ussd.kenya.complete",
|
||||
"name": "complete",
|
||||
"parent": null
|
||||
},
|
||||
"10": {
|
||||
"description": "Help menu",
|
||||
"display_key": "ussd.kenya.help",
|
||||
"name": "help",
|
||||
"parent": "start"
|
||||
},
|
||||
"11": {
|
||||
"description": "Manage account menu",
|
||||
"display_key": "ussd.kenya.profile_management",
|
||||
"name": "profile_management",
|
||||
"parent": "start"
|
||||
},
|
||||
"12": {
|
||||
"description": "Manage business directory info",
|
||||
"display_key": "ussd.kenya.select_preferred_language",
|
||||
"name": "select_preferred_language",
|
||||
"parent": "account_management"
|
||||
},
|
||||
"13": {
|
||||
"description": "About business directory info",
|
||||
"display_key": "ussd.kenya.mini_statement_pin_authorization",
|
||||
"name": "mini_statement_pin_authorization",
|
||||
"parent": "account_management"
|
||||
},
|
||||
"14": {
|
||||
"description": "Change business directory info",
|
||||
"display_key": "ussd.kenya.enter_current_pin",
|
||||
"name": "enter_current_pin",
|
||||
"parent": "account_management"
|
||||
},
|
||||
"15": {
|
||||
"description": "New PIN entry menu",
|
||||
"display_key": "ussd.kenya.enter_new_pin",
|
||||
"name": "enter_new_pin",
|
||||
"parent": "account_management"
|
||||
},
|
||||
"16": {
|
||||
"description": "First name entry menu",
|
||||
"display_key": "ussd.kenya.enter_first_name",
|
||||
"name": "enter_first_name",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"17": {
|
||||
"description": "Last name entry menu",
|
||||
"display_key": "ussd.kenya.enter_last_name",
|
||||
"name": "enter_last_name",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"18": {
|
||||
"description": "Gender entry menu",
|
||||
"display_key": "ussd.kenya.enter_gender",
|
||||
"name": "enter_gender",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"19": {
|
||||
"description": "Location entry menu",
|
||||
"display_key": "ussd.kenya.enter_location",
|
||||
"name": "enter_location",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"20": {
|
||||
"description": "Business profile entry menu",
|
||||
"display_key": "ussd.kenya.enter_business_profile",
|
||||
"name": "enter_business_profile",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"21": {
|
||||
"description": "Menu to display a user's entire profile",
|
||||
"display_key": "ussd.kenya.display_user_profile_data",
|
||||
"name": "display_user_profile_data",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"22": {
|
||||
"description": "Pin authorization to change name",
|
||||
"display_key": "ussd.kenya.name_management_pin_authorization",
|
||||
"name": "name_management_pin_authorization",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"23": {
|
||||
"description": "Pin authorization to change gender",
|
||||
"display_key": "ussd.kenya.gender_management_pin_authorization",
|
||||
"name": "gender_management_pin_authorization",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"24": {
|
||||
"description": "Pin authorization to change location",
|
||||
"display_key": "ussd.kenya.location_management_pin_authorization",
|
||||
"name": "location_management_pin_authorization",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"26": {
|
||||
"description": "Pin authorization to display user's profile",
|
||||
"display_key": "ussd.kenya.view_profile_pin_authorization",
|
||||
"name": "view_profile_pin_authorization",
|
||||
"parent": "profile_management"
|
||||
},
|
||||
"27": {
|
||||
"description": "Exit menu",
|
||||
"display_key": "ussd.kenya.exit",
|
||||
"name": "exit",
|
||||
"parent": null
|
||||
},
|
||||
"28": {
|
||||
"description": "Invalid menu option",
|
||||
"display_key": "ussd.kenya.exit_invalid_menu_option",
|
||||
"name": "exit_invalid_menu_option",
|
||||
"parent": null
|
||||
},
|
||||
"29": {
|
||||
"description": "PIN policy violation",
|
||||
"display_key": "ussd.kenya.exit_invalid_pin",
|
||||
"name": "exit_invalid_pin",
|
||||
"parent": null
|
||||
},
|
||||
"30": {
|
||||
"description": "PIN mismatch. New PIN and the new PIN confirmation do not match",
|
||||
"display_key": "ussd.kenya.exit_pin_mismatch",
|
||||
"name": "exit_pin_mismatch",
|
||||
"parent": null
|
||||
},
|
||||
"31": {
|
||||
"description": "Ussd PIN Blocked Menu",
|
||||
"display_key": "ussd.kenya.exit_pin_blocked",
|
||||
"name": "exit_pin_blocked",
|
||||
"parent": null
|
||||
},
|
||||
"32": {
|
||||
"description": "Key params missing in request",
|
||||
"display_key": "ussd.kenya.exit_invalid_request",
|
||||
"name": "exit_invalid_request",
|
||||
"parent": null
|
||||
},
|
||||
"33": {
|
||||
"description": "The user did not select a choice",
|
||||
"display_key": "ussd.kenya.exit_invalid_input",
|
||||
"name": "exit_invalid_input",
|
||||
"parent": null
|
||||
},
|
||||
"34": {
|
||||
"description": "Exit following a successful transaction.",
|
||||
"display_key": "ussd.kenya.exit_successful_transaction",
|
||||
"name": "exit_successful_transaction",
|
||||
"parent": null
|
||||
},
|
||||
"35": {
|
||||
"description": "Manage account menu",
|
||||
"display_key": "ussd.kenya.account_management",
|
||||
"name": "account_management",
|
||||
"parent": "start"
|
||||
},
|
||||
"36": {
|
||||
"description": "Exit following insufficient balance to perform a transaction.",
|
||||
"display_key": "ussd.kenya.exit_insufficient_balance",
|
||||
"name": "exit_insufficient_balance",
|
||||
"parent": null
|
||||
}
|
||||
}
|
||||
}
|
||||
69
apps/cic-ussd/cic_ussd/encoder.py
Normal file
69
apps/cic-ussd/cic_ussd/encoder.py
Normal file
@@ -0,0 +1,69 @@
|
||||
# third party imports
|
||||
import bcrypt
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
|
||||
class PasswordEncoder(Fernet):
|
||||
"""This class is responsible for defining the encryption function for password encoding in the application and the
|
||||
provision of a class method that can be used to define the static key attribute at the application's entry point.
|
||||
|
||||
:cvar key: a URL-safe base64-encoded 32-byte
|
||||
:type key: bytes
|
||||
"""
|
||||
|
||||
key = None
|
||||
|
||||
@classmethod
|
||||
def set_key(cls, key: bytes):
|
||||
"""This method sets the value of the static key attribute to make it accessible to all subsequent instances of
|
||||
the class once defined.
|
||||
:param key: key: a URL-safe base64-encoded 32-byte
|
||||
:type key: bytes
|
||||
"""
|
||||
cls.key = key
|
||||
|
||||
def encrypt(self, ciphertext: bytes):
|
||||
"""This overloads the encrypt function of the Fernet class
|
||||
:param ciphertext: The data to be encrypted.
|
||||
:type ciphertext: bytes
|
||||
:return: A fernet token (A set of bytes representing the hashed value succeeding the encryption)
|
||||
:rtype: bytes
|
||||
"""
|
||||
return super(PasswordEncoder, self).encrypt(ciphertext)
|
||||
|
||||
|
||||
def create_password_hash(password):
|
||||
"""This method encrypts a password value using a pre-set pepper and an appended salt. Documentation is brief since
|
||||
symmetric encryption using a unique key (pepper) and salted passwords before hashing is well documented.
|
||||
N/B: Fernet encryption requires the unique key to be a URL-safe base64-encoded 32-byte key.
|
||||
https://cryptography.io/en/latest/fernet/
|
||||
:param password: A password value
|
||||
:type password: str
|
||||
|
||||
:raises ValueError: if a key whose length length is less than 32 bytes.
|
||||
:raises binascii.Error: if base64 key is invalid or corrupted.
|
||||
|
||||
:return: A fernet token (A set of bytes representing the hashed value succeeding the encryption)
|
||||
:rtype: str
|
||||
"""
|
||||
fernet = PasswordEncoder(PasswordEncoder.key)
|
||||
return fernet.encrypt(bcrypt.hashpw(password.encode(), bcrypt.gensalt())).decode()
|
||||
|
||||
|
||||
def check_password_hash(password, hashed_password):
|
||||
"""This method ascertains a password's validity by hashing the provided password value using the original pepper and
|
||||
compares the resultant fernet signature to the one persisted in the db for a given user.
|
||||
:param password: A password value
|
||||
:type password: str
|
||||
:param hashed_password: A hash for a user's password value
|
||||
:type hashed_password: str
|
||||
|
||||
:raises ValueError: if a key whose length length is less than 32 bytes.
|
||||
:raises binascii.Error: if base64 key is invalid or corrupted.
|
||||
|
||||
:return: Password validity
|
||||
:rtype: boolean
|
||||
"""
|
||||
fernet = PasswordEncoder(PasswordEncoder.key)
|
||||
hashed_password = fernet.decrypt(hashed_password.encode())
|
||||
return bcrypt.checkpw(password.encode(), hashed_password)
|
||||
19
apps/cic-ussd/cic_ussd/error.py
Normal file
19
apps/cic-ussd/cic_ussd/error.py
Normal file
@@ -0,0 +1,19 @@
|
||||
class VersionTooLowError(Exception):
|
||||
"""Raised when the session version doesn't match latest version."""
|
||||
pass
|
||||
|
||||
|
||||
class SessionNotFoundError(Exception):
|
||||
"""Raised when queried session is not found in memory."""
|
||||
pass
|
||||
|
||||
|
||||
class InvalidFileFormatError(OSError):
|
||||
"""Raised when the file format is invalid."""
|
||||
pass
|
||||
|
||||
|
||||
class ActionDataNotFoundError(OSError):
|
||||
"""Raised when action data matching a specific task uuid is not found in the redis cache"""
|
||||
pass
|
||||
|
||||
0
apps/cic-ussd/cic_ussd/files/__init__.py
Normal file
0
apps/cic-ussd/cic_ussd/files/__init__.py
Normal file
50
apps/cic-ussd/cic_ussd/files/local_files.py
Normal file
50
apps/cic-ussd/cic_ussd/files/local_files.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# standard imports
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
# third party imports
|
||||
from tinydb import TinyDB
|
||||
|
||||
logg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_local_file_data_stores(file_location: str, table_name: str):
|
||||
"""
|
||||
This methods creates a file where data can be stored in memory.
|
||||
:param file_location: Path to file to create tiny db in-memory data store.
|
||||
:type file_location: str
|
||||
:param table_name: The name of the tiny db table structure to store the data.
|
||||
:type table_name: str
|
||||
:return: A tinyDB table
|
||||
"""
|
||||
store = TinyDB(file_location, sort_keys=True, indent=4, separators=(',', ': '))
|
||||
return store.table(table_name, cache_size=30)
|
||||
|
||||
|
||||
def json_file_parser(filepath: str) -> list:
|
||||
"""This function takes an entry name for a group of transitions or states, it then reads the
|
||||
successive file and returns a list of the corresponding elements representing a set of transitions or states.
|
||||
|
||||
:param filepath: A path to the JSON file containing data.
|
||||
:type filepath: str
|
||||
:return: A list of objects to add to the state machine's transitions.
|
||||
:rtype: list
|
||||
"""
|
||||
data = []
|
||||
for json_data_file_path in os.listdir(filepath):
|
||||
# get path of data files
|
||||
data_file_path = os.path.join(filepath, json_data_file_path)
|
||||
|
||||
# open data file
|
||||
data_file = open(data_file_path)
|
||||
|
||||
# load json data
|
||||
json_data = json.load(data_file)
|
||||
logg.debug(f'Loading data from: {json_data_file_path}')
|
||||
|
||||
# get all data in one list
|
||||
data += json_data
|
||||
data_file.close()
|
||||
|
||||
return data
|
||||
0
apps/cic-ussd/cic_ussd/menu/__init__.py
Normal file
0
apps/cic-ussd/cic_ussd/menu/__init__.py
Normal file
104
apps/cic-ussd/cic_ussd/menu/ussd_menu.py
Normal file
104
apps/cic-ussd/cic_ussd/menu/ussd_menu.py
Normal file
@@ -0,0 +1,104 @@
|
||||
# standard imports
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
# third party imports
|
||||
from tinydb import Query
|
||||
from tinydb.table import Document, Table
|
||||
|
||||
# define logger.
|
||||
logg = logging.getLogger()
|
||||
|
||||
|
||||
class UssdMenu:
|
||||
"""
|
||||
This class defines the USSD menu object that is called whenever a user makes transitions in the menu.
|
||||
:cvar ussd_menu_db: The tinydb database object.
|
||||
:type ussd_menu_db: Table
|
||||
"""
|
||||
ussd_menu_db = None
|
||||
Menu = Query()
|
||||
|
||||
def __init__(self,
|
||||
name: str,
|
||||
description: str,
|
||||
parent: Optional[str],
|
||||
country: Optional[str] = 'Kenya',
|
||||
gateway: Optional[str] = 'USSD'):
|
||||
"""
|
||||
This function is called whenever a USSD menu object is created and saves the instance to a JSON DB.
|
||||
:param name: The name of the menu and is used as it's unique identifier.
|
||||
:type name: str.
|
||||
:param description: A brief explanation of what the menu does.
|
||||
:type description: str.
|
||||
:param parent: The menu from which the current menu is called. Transitions move from parent to child menus.
|
||||
:type parent: str.
|
||||
:param country: The country from which the menu is created for and being used. Defaults to Kenya.
|
||||
:type country: str
|
||||
:param gateway: The gateway through which the menu is used. Defaults to USSD.
|
||||
:type gateway: str.
|
||||
:raises ValueError: If menu already exists.
|
||||
"""
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.parent = parent
|
||||
self.display_key = f'{gateway.lower()}.{country.lower()}.{name}'
|
||||
|
||||
menu = self.ussd_menu_db.get(UssdMenu.Menu.name == name)
|
||||
if menu:
|
||||
raise ValueError('Menu already exists!')
|
||||
self.ussd_menu_db.insert({
|
||||
'name': self.name,
|
||||
'description': self.description,
|
||||
'parent': self.parent,
|
||||
'display_key': self.display_key
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def find_by_name(name: str) -> Document:
|
||||
"""
|
||||
This function attempts to fetch a menu from the JSON DB using the unique name.
|
||||
:param name: The name of the menu that is being searched for.
|
||||
:type name: str.
|
||||
:return: The function returns the queried menu in JSON format if found,
|
||||
else it returns the menu item for invalid requests.
|
||||
:rtype: Document.
|
||||
"""
|
||||
menu = UssdMenu.ussd_menu_db.get(UssdMenu.Menu.name == name)
|
||||
if not menu:
|
||||
logg.error("No USSD Menu with name {}".format(name))
|
||||
return UssdMenu.ussd_menu_db.get(UssdMenu.Menu.name == 'exit_invalid_request')
|
||||
else:
|
||||
return menu
|
||||
|
||||
@staticmethod
|
||||
def set_description(name: str, description: str):
|
||||
"""
|
||||
This function updates the description for a specific menu in the JSON DB.
|
||||
:param name: The name of the menu whose description should be updated.
|
||||
:type name: str.
|
||||
:param description: The new menu description. On success it should overwrite the menu's previous description.
|
||||
:type description: str.
|
||||
"""
|
||||
menu = UssdMenu.find_by_name(name=name)
|
||||
UssdMenu.ussd_menu_db.update({'description': description}, UssdMenu.Menu.name == menu['name'])
|
||||
|
||||
@staticmethod
|
||||
def parent_menu(menu_name: str) -> Document:
|
||||
"""
|
||||
This function fetches the parent menu of the menu instance it has been called on.
|
||||
:param menu_name: The name of the menu whose parent is to be returned.
|
||||
:type menu_name: str
|
||||
:return: This function returns the menu's parent menu in JSON format.
|
||||
:rtype: Document.
|
||||
"""
|
||||
ussd_menu = UssdMenu.find_by_name(name=menu_name)
|
||||
return UssdMenu.find_by_name(ussd_menu.get('parent'))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""
|
||||
This method return the object representation of the menu.
|
||||
:return: This function returns a string containing the object representation of the menu.
|
||||
:rtype: str.
|
||||
"""
|
||||
return f"<UssdMenu {self.name} - {self.description}>"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user