├── idena ├── __init__.py ├── plugins │ ├── help │ │ ├── config │ │ │ └── help.json │ │ └── help.py │ ├── start │ │ ├── config │ │ │ └── start.json │ │ ├── resources │ │ │ ├── create_nodes.sql │ │ │ ├── create_users.sql │ │ │ └── intro.md │ │ └── start.py │ ├── list │ │ ├── resources │ │ │ ├── delete_node.sql │ │ │ └── select_nodes.sql │ │ ├── config │ │ │ └── list.json │ │ └── list.py │ ├── watch │ │ ├── resources │ │ │ ├── delete_node.sql │ │ │ ├── select_nodes.sql │ │ │ ├── insert_node.sql │ │ │ ├── node_exists.sql │ │ │ ├── watch.md │ │ │ └── select_notify.sql │ │ ├── config │ │ │ └── watch.json │ │ └── watch.py │ ├── notify │ │ ├── resources │ │ │ ├── update_discord.sql │ │ │ ├── update_email.sql │ │ │ └── update_telegram.sql │ │ ├── config │ │ │ └── notify.json │ │ └── notify.py │ ├── restart │ │ ├── config │ │ │ └── restart.json │ │ └── restart.py │ ├── shutdown │ │ ├── config │ │ │ └── shutdown.json │ │ └── shutdown.py │ ├── logfile │ │ ├── config │ │ │ └── logfile.json │ │ └── logfile.py │ ├── about │ │ ├── config │ │ │ └── about.json │ │ ├── resources │ │ │ └── info.md │ │ └── about.py │ └── backup │ │ ├── config │ │ └── backup.json │ │ ├── resources │ │ └── backup.md │ │ └── backup.py ├── __main__.py ├── constants.py ├── emoji.py ├── web.py ├── utils.py ├── config.py ├── start.py ├── tgbot.py └── plugin.py ├── run.sh ├── resources ├── select_user.sql ├── table_exists.sql ├── update_user.sql ├── insert_user.sql └── templates │ └── default.html ├── requirements.txt ├── Pipfile ├── config └── config.json ├── .gitignore ├── README.md └── LICENSE /idena/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | python3 -m idena -log 20 -------------------------------------------------------------------------------- /resources/select_user.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM users WHERE user_id = ? -------------------------------------------------------------------------------- /idena/plugins/help/config/help.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "help" 3 | } -------------------------------------------------------------------------------- /idena/plugins/start/config/start.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "start" 3 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | watchdog 3 | python-telegram-bot==11.1.0 4 | flask -------------------------------------------------------------------------------- /idena/plugins/list/resources/delete_node.sql: -------------------------------------------------------------------------------- 1 | DELETE 2 | FROM nodes 3 | WHERE rowid = ? -------------------------------------------------------------------------------- /idena/plugins/watch/resources/delete_node.sql: -------------------------------------------------------------------------------- 1 | DELETE 2 | FROM nodes 3 | WHERE address = ? -------------------------------------------------------------------------------- /idena/plugins/watch/resources/select_nodes.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT address 2 | FROM nodes -------------------------------------------------------------------------------- /idena/plugins/list/resources/select_nodes.sql: -------------------------------------------------------------------------------- 1 | SELECT rowid, * 2 | FROM nodes 3 | WHERE user_id = ? -------------------------------------------------------------------------------- /resources/table_exists.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM sqlite_master 3 | WHERE type = 'table' AND name = ? -------------------------------------------------------------------------------- /idena/__main__.py: -------------------------------------------------------------------------------- 1 | from idena.start import Idena 2 | 3 | # Entry point for bot 4 | Idena().start() 5 | -------------------------------------------------------------------------------- /idena/plugins/watch/resources/insert_node.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO nodes (user_id, address) 2 | VALUES (?, ?) -------------------------------------------------------------------------------- /idena/plugins/notify/resources/update_discord.sql: -------------------------------------------------------------------------------- 1 | UPDATE users 2 | SET ntfy_discord = ? 3 | WHERE user_id = ? -------------------------------------------------------------------------------- /idena/plugins/notify/resources/update_email.sql: -------------------------------------------------------------------------------- 1 | UPDATE users 2 | SET ntfy_email = ? 3 | WHERE user_id = ? -------------------------------------------------------------------------------- /idena/plugins/watch/resources/node_exists.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM nodes 3 | WHERE user_id = ? AND address = ? -------------------------------------------------------------------------------- /idena/plugins/notify/resources/update_telegram.sql: -------------------------------------------------------------------------------- 1 | UPDATE users 2 | SET ntfy_telegram = ? 3 | WHERE user_id = ? -------------------------------------------------------------------------------- /idena/plugins/restart/config/restart.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "restart", 3 | "description": "Restart the bot" 4 | } -------------------------------------------------------------------------------- /idena/plugins/shutdown/config/shutdown.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "shutdown", 3 | "description": "Shutdown the bot" 4 | } -------------------------------------------------------------------------------- /resources/update_user.sql: -------------------------------------------------------------------------------- 1 | UPDATE users 2 | SET first_name = ?, last_name = ?, username = ?, language = ? 3 | WHERE user_id = ? -------------------------------------------------------------------------------- /resources/insert_user.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO users (user_id, first_name, last_name, username, language, ntfy_telegram) 2 | VALUES (?, ?, ?, ?, ?, ?) -------------------------------------------------------------------------------- /idena/plugins/logfile/config/logfile.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "log", 3 | "description": "Download current logfile", 4 | "private": true 5 | } -------------------------------------------------------------------------------- /idena/plugins/about/config/about.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "about", 3 | "category": "Bot", 4 | "description": "Info about bot and creator" 5 | } -------------------------------------------------------------------------------- /idena/plugins/backup/config/backup.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "backup", 3 | "description": "Backup whole bot or a plugin", 4 | "private": true 5 | } -------------------------------------------------------------------------------- /idena/plugins/backup/resources/backup.md: -------------------------------------------------------------------------------- 1 | 2 | `/{{handle}}` 3 | Backup the whole bot 4 | 5 | `/{{handle}} ` 6 | Backup a specific plugin -------------------------------------------------------------------------------- /idena/plugins/watch/resources/watch.md: -------------------------------------------------------------------------------- 1 | 2 | `/{{handle}} ` 3 | 4 | Provide a IDENA wallet address to be able to watch the corresponding node -------------------------------------------------------------------------------- /idena/plugins/notify/config/notify.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "notify", 3 | "category": "Node Watching", 4 | "description": "Adjust your notification settings" 5 | } -------------------------------------------------------------------------------- /idena/plugins/watch/resources/select_notify.sql: -------------------------------------------------------------------------------- 1 | SELECT users.ntfy_telegram, users.ntfy_email, users.ntfy_discord 2 | FROM users 3 | LEFT JOIN nodes ON nodes.user_id = users.user_id 4 | WHERE nodes.address = ? -------------------------------------------------------------------------------- /idena/plugins/list/config/list.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "list", 3 | "category": "Node Watching", 4 | "description": "List all nodes that you watch", 5 | "identity_url": "https://scan.idena.io/identity?identity=" 6 | } -------------------------------------------------------------------------------- /idena/plugins/start/resources/create_nodes.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE nodes ( 2 | user_id TEXT NOT NULL, 3 | address TEXT NOT NULL, 4 | date_time DATETIME DEFAULT CURRENT_TIMESTAMP, 5 | PRIMARY KEY (user_id, address), 6 | FOREIGN KEY(user_id) REFERENCES users(user_id) 7 | ) -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | python-telegram-bot = "==11.1.0" 10 | watchdog = "==0.9.0" 11 | requests = "==2.21.0" 12 | 13 | [requires] 14 | python_version = "3.7" 15 | -------------------------------------------------------------------------------- /idena/plugins/start/resources/create_users.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users ( 2 | user_id TEXT NOT NULL, 3 | first_name TEXT NOT NULL, 4 | last_name TEXT, 5 | username TEXT, 6 | language TEXT, 7 | ntfy_telegram TEXT, 8 | ntfy_email TEXT, 9 | ntfy_discord TEXT, 10 | date_time DATETIME DEFAULT CURRENT_TIMESTAMP, 11 | PRIMARY KEY (user_id) 12 | ) -------------------------------------------------------------------------------- /idena/plugins/start/resources/intro.md: -------------------------------------------------------------------------------- 1 | ✨ *IDENA Node Manager Bot* ✨ 2 | 3 | Welcome {{firstname}}! I'm a bot and i can watch one or more IDENA nodes for you. Choose one of the following commands to get started: 4 | 5 | /watch - add a node to be watched 6 | /list - show or remove your watched nodes 7 | /notify - change notification settings 8 | 9 | Cheers 🍻👋 -------------------------------------------------------------------------------- /idena/plugins/about/resources/info.md: -------------------------------------------------------------------------------- 1 | ✨ *IDENA Node Watcher Bot* ✨ 2 | 3 | Please visit [idena.io](http://idena.io) to get detailed information about the IDENA project. 4 | 5 | This bot was coded in Python by user @endogen for the IDENA community. If you are interested in the source code then check out this [GitHub repository](https://github.com/Endogen/idena-node-watcher). -------------------------------------------------------------------------------- /idena/plugins/watch/config/watch.json: -------------------------------------------------------------------------------- 1 | { 2 | "handle": "watch", 3 | "category": "Node Watching", 4 | "description": "Add new node to be watched", 5 | "identity_url": "https://scan.idena.io/identity?identity=", 6 | "api_url": "https://api.idena.io/api/OnlineIdentity/", 7 | "api_timeout": 3, 8 | "check_time": 120, 9 | "time_delta": 900, 10 | "ls_threshold": 30 11 | } -------------------------------------------------------------------------------- /idena/plugins/about/about.py: -------------------------------------------------------------------------------- 1 | from telegram import ParseMode 2 | from idena.plugin import IdenaPlugin 3 | 4 | 5 | class About(IdenaPlugin): 6 | 7 | INFO_FILE = "info.md" 8 | 9 | @IdenaPlugin.threaded 10 | @IdenaPlugin.send_typing 11 | def execute(self, bot, update, args): 12 | update.message.reply_text( 13 | text=self.get_resource(self.INFO_FILE), 14 | parse_mode=ParseMode.MARKDOWN, 15 | disable_web_page_preview=True) 16 | -------------------------------------------------------------------------------- /idena/constants.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Project folders 4 | DIR_SRC = os.path.basename(os.path.dirname(__file__)) 5 | DIR_TEM = "templates" 6 | DIR_RES = "resources" 7 | DIR_PLG = "plugins" 8 | DIR_CFG = "config" 9 | DIR_LOG = "logs" 10 | DIR_DAT = "data" 11 | DIR_TMP = "temp" 12 | 13 | # Project files 14 | FILE_DAT = "global.db" 15 | FILE_CFG = "config.json" 16 | FILE_TKN = "token.json" 17 | FILE_LOG = f"{DIR_SRC}.log" 18 | 19 | # Max Telegram message length 20 | MAX_TG_MSG_LEN = 4096 21 | -------------------------------------------------------------------------------- /idena/emoji.py: -------------------------------------------------------------------------------- 1 | INFO = "ℹ" 2 | ERROR = "‼" 3 | WAIT = "⏳" 4 | GOODBYE = "👋" 5 | CHECK = "✅" 6 | HEART = "❤" 7 | ALERT = "🚨" 8 | SKULL = "💀" 9 | CANCEL = "❌" 10 | COFFIN = "⚰" 11 | DNA = "🧬" 12 | KEY = "🔐" 13 | BUST = "👤" 14 | NETWORK = "🦠" 15 | DONE = "☑" 16 | BELL = "🔔" 17 | QUESTION = "❓" 18 | MONEY = "💰" 19 | SPEAKING = "🗣" 20 | PICTURE = "🏞" 21 | GREEN = "🟢" 22 | RED = "🔴" 23 | EYE = "👁" 24 | IDENTITY = "🎫" 25 | CHAIN = "⛓" 26 | ORANGE = "🟧" 27 | BLUE = "🟦" 28 | PACKAGE = "📦" 29 | -------------------------------------------------------------------------------- /idena/plugins/shutdown/shutdown.py: -------------------------------------------------------------------------------- 1 | import os 2 | import signal 3 | import threading 4 | import idena.emoji as emo 5 | 6 | from idena.plugin import IdenaPlugin 7 | 8 | 9 | class Shutdown(IdenaPlugin): 10 | 11 | @IdenaPlugin.owner 12 | @IdenaPlugin.threaded 13 | @IdenaPlugin.send_typing 14 | def execute(self, bot, update, args): 15 | msg = f"{emo.GOODBYE} Shutting down..." 16 | update.message.reply_text(msg) 17 | 18 | threading.Thread(target=self._shutdown_thread).start() 19 | 20 | # TODO: Remove access to protected variable 21 | def _shutdown_thread(self): 22 | self._tgb.updater.stop() 23 | self._tgb.updater.is_idle = False 24 | os.kill(os.getpid(), signal.SIGINT) 25 | -------------------------------------------------------------------------------- /idena/plugins/start/start.py: -------------------------------------------------------------------------------- 1 | from telegram import ParseMode 2 | from idena.plugin import IdenaPlugin 3 | 4 | 5 | class Start(IdenaPlugin): 6 | 7 | INTRO_FILE = "intro.md" 8 | 9 | def __enter__(self): 10 | if not self.global_table_exists("users"): 11 | sql = self.get_resource("create_users.sql") 12 | self.execute_global_sql(sql) 13 | if not self.global_table_exists("nodes"): 14 | sql = self.get_resource("create_nodes.sql") 15 | self.execute_global_sql(sql) 16 | return self 17 | 18 | @IdenaPlugin.add_user 19 | @IdenaPlugin.threaded 20 | def execute(self, bot, update, args): 21 | user = update.effective_user 22 | 23 | intro = self.get_resource(self.INTRO_FILE) 24 | intro = intro.replace("{{firstname}}", user.first_name) 25 | 26 | update.message.reply_text(intro, parse_mode=ParseMode.MARKDOWN) 27 | -------------------------------------------------------------------------------- /config/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "admin": { 3 | "ids": [ 4 | 134166731 5 | ], 6 | "notify_on_error": true 7 | }, 8 | "telegram": { 9 | "read_timeout": 30, 10 | "connect_timeout": 30 11 | }, 12 | "webhook": { 13 | "use_webhook": false, 14 | "listen": "0.0.0.0", 15 | "port": 8443, 16 | "privkey_path": "/path/to/privkey.pem", 17 | "cert_path": "/path/to/cert.pem", 18 | "url": "https://somedomain.com" 19 | }, 20 | "notify": { 21 | "email": { 22 | "smtp": "smtp.gmail.com", 23 | "port": 465, 24 | "mail": "", 25 | "user": "", 26 | "pass": "", 27 | "subject": "IDENA Node OFFLINE", 28 | "message": "Node {{node}} is offline" 29 | } 30 | }, 31 | "web": { 32 | "use_web": false, 33 | "password": "" 34 | } 35 | } -------------------------------------------------------------------------------- /resources/templates/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 35 | 36 | 37 | 38 |
39 | 40 | 41 | -------------------------------------------------------------------------------- /idena/plugins/logfile/logfile.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import idena.emoji as emo 4 | import idena.constants as con 5 | 6 | from idena.plugin import IdenaPlugin 7 | 8 | 9 | class Logfile(IdenaPlugin): 10 | 11 | @IdenaPlugin.owner 12 | @IdenaPlugin.private 13 | @IdenaPlugin.threaded 14 | @IdenaPlugin.send_typing 15 | def execute(self, bot, update, args): 16 | base_dir = os.path.abspath(os.getcwd()) 17 | log_file = os.path.join(base_dir, con.DIR_LOG, con.FILE_LOG) 18 | 19 | if os.path.isfile(log_file): 20 | try: 21 | file = open(log_file, 'rb') 22 | except Exception as e: 23 | logging.error(e) 24 | self.notify(e) 25 | file = None 26 | else: 27 | file = None 28 | 29 | if file: 30 | update.message.reply_document( 31 | caption=f"{emo.CHECK} Current Logfile", 32 | document=file) 33 | else: 34 | update.message.reply_text( 35 | text=f"{emo.ERROR} Not possible to download logfile") 36 | -------------------------------------------------------------------------------- /idena/plugins/help/help.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | from telegram import ParseMode 4 | from idena.plugin import IdenaPlugin 5 | 6 | 7 | class Help(IdenaPlugin): 8 | 9 | @IdenaPlugin.threaded 10 | @IdenaPlugin.send_typing 11 | def execute(self, bot, update, args): 12 | categories = OrderedDict() 13 | 14 | for p in self.get_plugins(): 15 | if p.get_category() and p.get_description(): 16 | des = f"/{p.get_handle()} - {p.get_description()}" 17 | 18 | if p.get_category() not in categories: 19 | categories[p.get_category()] = [des] 20 | else: 21 | categories[p.get_category()].append(des) 22 | 23 | msg = "*Available commands*\n\n" 24 | 25 | for category in sorted(categories): 26 | msg += f"*{category}*\n" 27 | 28 | for cmd in sorted(categories[category]): 29 | msg += f"{cmd}\n" 30 | 31 | msg += "\n" 32 | 33 | update.message.reply_text( 34 | text=msg, 35 | parse_mode=ParseMode.MARKDOWN, 36 | disable_web_page_preview=True) 37 | -------------------------------------------------------------------------------- /idena/plugins/restart/restart.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | import logging 5 | import idena.emoji as emo 6 | 7 | from idena.plugin import IdenaPlugin 8 | 9 | 10 | # TODO: Remove access to protected variable 11 | class Restart(IdenaPlugin): 12 | 13 | def __enter__(self): 14 | chat_id = self.config.get("chat_id") 15 | mess_id = self.config.get("message_id") 16 | 17 | # If no data saved, don't do anything 18 | if not mess_id or not chat_id: 19 | return self 20 | 21 | try: 22 | self._tgb.updater.bot.edit_message_text( 23 | chat_id=chat_id, 24 | message_id=mess_id, 25 | text=f"{emo.CHECK} Restarting bot...") 26 | except Exception as e: 27 | logging.error(str(e)) 28 | finally: 29 | self.config.remove("chat_id") 30 | self.config.remove("message_id") 31 | 32 | return self 33 | 34 | @IdenaPlugin.owner 35 | @IdenaPlugin.threaded 36 | @IdenaPlugin.send_typing 37 | def execute(self, bot, update, args): 38 | msg = f"{emo.WAIT} Restarting bot..." 39 | message = update.message.reply_text(msg) 40 | 41 | chat_id = message.chat_id 42 | mess_id = message.message_id 43 | 44 | self.config.set(chat_id, "chat_id") 45 | self.config.set(mess_id, "message_id") 46 | 47 | m_name = __spec__.name 48 | m_name = m_name[:m_name.index(".")] 49 | 50 | time.sleep(1) 51 | os.execl(sys.executable, sys.executable, '-m', m_name, *sys.argv[1:]) 52 | -------------------------------------------------------------------------------- /idena/web.py: -------------------------------------------------------------------------------- 1 | import os 2 | import flask 3 | import inspect 4 | import idena.constants as con 5 | 6 | from flask import Flask, request, render_template 7 | 8 | 9 | class EndpointAction(object): 10 | 11 | def __init__(self, action, secret): 12 | self.action = action 13 | self.secret = secret 14 | 15 | def __call__(self): 16 | if self.secret: 17 | secret = request.args.get('secret') 18 | if not secret or secret != self.secret: 19 | return render_template("default.html") 20 | 21 | if self.action: 22 | param = str(inspect.signature(self.action))[1:-1] 23 | 24 | if param: 25 | param = request.args.get(param) 26 | 27 | if param: 28 | result = self.action(param) 29 | else: 30 | result = self.action(None) 31 | else: 32 | result = self.action() 33 | else: 34 | return render_template("default.html") 35 | 36 | # Create the answer (bundle it in a correctly formatted HTTP answer) 37 | if isinstance(result, str): 38 | # If it's a string, we bundle it has a HTML-like answer 39 | self.response = flask.Response(result, status=200, headers={}) 40 | else: 41 | # If it's something else (dict, ..) we jsonify and send it 42 | self.response = flask.jsonify(result) 43 | 44 | # Send it 45 | return self.response 46 | 47 | 48 | class FlaskAppWrapper(object): 49 | 50 | def __init__(self, name, port=None): 51 | self.port = port if port else 5000 52 | template_dir = os.path.join(os.pardir, con.DIR_RES, con.DIR_TEM) 53 | self.app = Flask(name, template_folder=template_dir) 54 | 55 | def run(self): 56 | self.app.run(host='0.0.0.0', port=self.port, debug=False) 57 | 58 | def add_endpoint(self, endpoint=None, endpoint_name=None, handler=None, secret=None): 59 | self.app.add_url_rule(endpoint, endpoint_name, EndpointAction(handler, secret)) 60 | -------------------------------------------------------------------------------- /idena/plugins/backup/backup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | import zipfile 4 | import time 5 | import idena.emoji as emo 6 | import idena.constants as con 7 | 8 | from idena.plugin import IdenaPlugin 9 | 10 | 11 | class Backup(IdenaPlugin): 12 | 13 | BCK_DIR = "backups" 14 | 15 | @IdenaPlugin.owner 16 | @IdenaPlugin.private 17 | @IdenaPlugin.threaded 18 | @IdenaPlugin.send_typing 19 | def execute(self, bot, update, args): 20 | command = "" 21 | 22 | if len(args) == 1: 23 | command = args[0].lower().strip() 24 | 25 | if not self.plugin_available(command): 26 | msg = f"{emo.ERROR} Plugin '{command}' not available" 27 | update.message.reply_text(msg) 28 | return 29 | 30 | # List of folders to exclude from backup 31 | exclude = [con.DIR_LOG, con.DIR_TMP, self.BCK_DIR, "__pycache__"] 32 | 33 | # Path to store backup files 34 | bck_path = os.path.join(con.DIR_SRC, con.DIR_PLG, self.get_name(), self.BCK_DIR) 35 | 36 | # Create folder to store backups 37 | os.makedirs(bck_path, exist_ok=True) 38 | 39 | filename = os.path.join(bck_path, f"{time.strftime('%Y%m%d%H%M%S')}{command}.zip") 40 | with zipfile.ZipFile(filename, "w", compression=zipfile.ZIP_DEFLATED) as zf: 41 | if command: 42 | base_dir = os.path.join(os.getcwd(), con.DIR_SRC, con.DIR_PLG, command) 43 | else: 44 | base_dir = os.getcwd() 45 | 46 | for root, dirs, files in os.walk(base_dir, topdown=True): 47 | dirs[:] = [d for d in dirs if d not in exclude and not d.startswith(".")] 48 | for name in dirs: 49 | path = os.path.normpath(os.path.join(root, name)) 50 | write_path = os.path.relpath(path, base_dir) 51 | zf.write(path, write_path) 52 | files[:] = [f for f in files if not f.startswith(".")] 53 | for name in files: 54 | path = os.path.normpath(os.path.join(root, name)) 55 | write_path = os.path.relpath(path, base_dir) 56 | zf.write(path, write_path) 57 | 58 | bot.send_document( 59 | chat_id=update.effective_user.id, 60 | caption=f"{emo.CHECK} Backup created", 61 | document=open(os.path.join(os.getcwd(), filename), 'rb')) 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | pip-wheel-metadata/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 97 | __pypackages__/ 98 | 99 | # Celery stuff 100 | celerybeat-schedule 101 | celerybeat.pid 102 | 103 | # SageMath parsed files 104 | *.sage.py 105 | 106 | # Environments 107 | .env 108 | .venv 109 | env/ 110 | venv/ 111 | ENV/ 112 | env.bak/ 113 | venv.bak/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | 133 | # Custom 134 | config.json 135 | token.json 136 | .idea 137 | logs/ 138 | data/ -------------------------------------------------------------------------------- /idena/utils.py: -------------------------------------------------------------------------------- 1 | def is_numeric(string): 2 | """ Also accepts '.' in the string. Function 'isnumeric()' doesn't """ 3 | try: 4 | float(string) 5 | return True 6 | except ValueError: 7 | pass 8 | 9 | try: 10 | import unicodedata 11 | unicodedata.numeric(string) 12 | return True 13 | except (TypeError, ValueError): 14 | pass 15 | 16 | return False 17 | 18 | 19 | def esc_md(text): 20 | import re 21 | 22 | rep = {"_": "\\_", "*": "\\*", "[": "\\[", "`": "\\`"} 23 | rep = dict((re.escape(k), v) for k, v in rep.items()) 24 | pattern = re.compile("|".join(rep.keys())) 25 | 26 | return pattern.sub(lambda m: rep[re.escape(m.group(0))], text) 27 | 28 | 29 | def build_menu(buttons, n_cols=1, header_buttons=None, footer_buttons=None): 30 | """ Build button-menu for Telegram """ 31 | menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] 32 | 33 | if header_buttons: 34 | menu.insert(0, header_buttons) 35 | if footer_buttons: 36 | menu.append(footer_buttons) 37 | 38 | return menu 39 | 40 | 41 | def is_bool(v): 42 | return v.lower() in ("yes", "true", "t", "1", "no", "false", "f", "0") 43 | 44 | 45 | def str2bool(v): 46 | return v.lower() in ("yes", "true", "t", "1") 47 | 48 | 49 | def split_msg(msg, max_len=None, split_char="\n", only_one=False): 50 | """ Restrict message length to max characters as defined by Telegram """ 51 | if not max_len: 52 | import trxbetbot.constants as con 53 | max_len = con.MAX_TG_MSG_LEN 54 | 55 | if only_one: 56 | return [msg[:max_len][:msg[:max_len].rfind(split_char)]] 57 | 58 | remaining = msg 59 | messages = list() 60 | while len(remaining) > max_len: 61 | split_at = remaining[:max_len].rfind(split_char) 62 | message = remaining[:max_len][:split_at] 63 | messages.append(message) 64 | remaining = remaining[len(message):] 65 | else: 66 | messages.append(remaining) 67 | 68 | return messages 69 | 70 | 71 | def encode_url(trxid): 72 | import urllib.parse as ul 73 | return ul.quote_plus(trxid) 74 | 75 | 76 | def unix2datetime(seconds, millies=False): 77 | from datetime import datetime 78 | 79 | try: 80 | seconds = int(seconds) 81 | except: 82 | return None 83 | 84 | if millies: 85 | seconds /= 1000 86 | 87 | return datetime.utcfromtimestamp(seconds).strftime('%Y-%m-%d %H:%M:%S') 88 | 89 | 90 | # Get list of keywords or value of keyword 91 | def get_kw(args, keyword=None, fallback=None): 92 | keywords = dict() 93 | 94 | if args: 95 | for arg in args: 96 | if "=" in arg: 97 | kv = arg.split("=") 98 | v = str2bool(kv[1]) if is_bool(kv[1]) else kv[1] 99 | keywords[kv[0]] = v 100 | 101 | if keyword: 102 | return keywords.get(keyword, fallback) 103 | 104 | return keywords 105 | 106 | 107 | def now(): 108 | from datetime import datetime 109 | return datetime.now().strftime("%d.%m.%Y %H:%M:%S") 110 | -------------------------------------------------------------------------------- /idena/plugins/list/list.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import idena.emoji as emo 3 | import idena.utils as utl 4 | 5 | from idena.plugin import IdenaPlugin 6 | from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton 7 | from telegram.ext import CallbackQueryHandler 8 | 9 | 10 | class List(IdenaPlugin): 11 | 12 | def __enter__(self): 13 | self.add_handler(CallbackQueryHandler(self._callback), group=0) 14 | return self 15 | 16 | @IdenaPlugin.threaded 17 | @IdenaPlugin.add_user 18 | @IdenaPlugin.send_typing 19 | def execute(self, bot, update, args): 20 | user_id = update.effective_user.id 21 | 22 | sql = self.get_resource("select_nodes.sql") 23 | res = self.execute_global_sql(sql, user_id) 24 | 25 | if not res["success"]: 26 | msg = f"{emo.ERROR} Not possible to retrieve watched nodes: {res['data']}" 27 | update.message.reply_text(msg) 28 | self.notify(msg) 29 | return 30 | 31 | if not res["data"]: 32 | msg = f"{emo.INFO} No watched nodes found" 33 | update.message.reply_text(msg) 34 | return 35 | 36 | for data in res["data"]: 37 | rowid = data[0] 38 | user_id = data[1] 39 | address = data[2] 40 | 41 | active = True if self.get_job(address) else False 42 | 43 | if not active: 44 | self.notify(f"Job for address {address} not active") 45 | 46 | identity_url = f"{self.config.get('identity_url')}{address}" 47 | state = f"ACTIVE" if active else "INACTIVE" 48 | msg = f"[{address[:12]}...{address[-12:]}]({identity_url})\n`Watcher-Job State: {state}`" 49 | 50 | try: 51 | bot.send_message( 52 | user_id, 53 | msg, 54 | reply_markup=self._remove_button(rowid), 55 | parse_mode=ParseMode.MARKDOWN, 56 | disable_web_page_preview=True) 57 | except Exception as e: 58 | msg = f"{emo.ERROR} Not possible to send watched node info for {address}: {e} - {res['data']}" 59 | update.message.reply_text(msg) 60 | logging.error(msg) 61 | self.notify(msg) 62 | 63 | def _remove_button(self, row_id): 64 | data = f"list_{row_id}" 65 | menu = utl.build_menu([InlineKeyboardButton("Remove from Watchlist", callback_data=data)]) 66 | return InlineKeyboardMarkup(menu, resize_keyboard=True) 67 | 68 | def _callback(self, bot, update): 69 | query = update.callback_query 70 | prefix = "list_" 71 | 72 | if not str(query.data).startswith(prefix): 73 | return 74 | 75 | # Remove node from database 76 | sql = self.get_resource("delete_node.sql") 77 | row_id = str(query.data)[len(prefix):] 78 | self.execute_global_sql(sql, row_id) 79 | 80 | # Edit message to show that node is not being watched anymore 81 | query.message.edit_text(f"{emo.CHECK} Node removed from watchlist") 82 | 83 | msg = f"{emo.INFO} Done" 84 | bot.answer_callback_query(query.id, msg) 85 | -------------------------------------------------------------------------------- /idena/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import logging 4 | import types 5 | import idena.constants as con 6 | 7 | from watchdog.observers import Observer 8 | from watchdog.events import FileSystemEventHandler 9 | 10 | 11 | class ConfigManager(FileSystemEventHandler): 12 | 13 | _cfg_file = con.FILE_CFG 14 | _cfg = dict() 15 | 16 | _callback = None 17 | _ignore = False 18 | _old = 0 19 | 20 | def __init__(self, config_file, callback=None): 21 | self._cfg_file = config_file 22 | self._callback = callback 23 | 24 | # Watch for config file changes 25 | observer = Observer() 26 | observer.schedule(self, os.path.dirname(self._cfg_file)) 27 | observer.start() 28 | 29 | def on_modified(self, event): 30 | """ Will be triggered if the config file has been changed manually. 31 | Will also execute the callback method if there is one """ 32 | 33 | if event.src_path == self._cfg_file: 34 | stat = os.stat(event.src_path) 35 | new = stat.st_mtime 36 | 37 | # Workaround for watchdog bug 38 | # https://github.com/gorakhargosh/watchdog/issues/93 39 | if (new - self._old) > 0.5: 40 | if self._ignore: 41 | self._ignore = False 42 | else: 43 | self._read_cfg() 44 | 45 | self._old = new 46 | 47 | if isinstance(self._callback, types.FunctionType): 48 | self._callback(self._cfg, None, None) 49 | 50 | def _read_cfg(self): 51 | """ Read the JSON content of a given configuration file """ 52 | try: 53 | if os.path.isfile(self._cfg_file): 54 | with open(self._cfg_file) as config_file: 55 | self._cfg = json.load(config_file) 56 | except Exception as e: 57 | err = f"Can't read '{self._cfg_file}'" 58 | logging.error(f"{repr(e)} - {err}") 59 | 60 | def _write_cfg(self): 61 | """ Write the JSON dictionary into the given configuration file """ 62 | try: 63 | if not os.path.exists(os.path.dirname(self._cfg_file)): 64 | os.makedirs(os.path.dirname(self._cfg_file)) 65 | with open(self._cfg_file, "w") as config_file: 66 | json.dump(self._cfg, config_file, indent=4) 67 | except Exception as e: 68 | err = f"Can't write '{self._cfg_file}'" 69 | logging.error(f"{repr(e)} - {err}") 70 | 71 | def get(self, *keys): 72 | """ Return the value of the given key(s) from a configuration file """ 73 | if not self._cfg: 74 | self._read_cfg() 75 | 76 | if not keys: 77 | return self._cfg 78 | 79 | value = self._cfg 80 | 81 | try: 82 | for key in keys: 83 | value = value[key] 84 | except Exception as e: 85 | err = f"Can't get '{keys}' from '{self._cfg_file}'" 86 | logging.debug(f"{repr(e)} - {err}") 87 | return None 88 | 89 | return value 90 | 91 | def set(self, value, *keys): 92 | """ Set a new value for the given key(s) in the configuration file. 93 | Will also execute the callback method if there is one """ 94 | if not self._cfg: 95 | self._read_cfg() 96 | 97 | if not keys: 98 | return 99 | 100 | tmp_cfg = self._cfg 101 | 102 | try: 103 | for key in keys[:-1]: 104 | tmp_cfg = tmp_cfg.setdefault(key, {}) 105 | tmp_cfg[keys[-1]] = value 106 | 107 | self._ignore = True 108 | self._write_cfg() 109 | 110 | if isinstance(self._callback, types.FunctionType): 111 | self._callback(self._cfg, value, *keys) 112 | except Exception as e: 113 | err = f"Can't set '{keys}' in '{self._cfg_file}'" 114 | logging.debug(f"{repr(e)} - {err}") 115 | 116 | def remove(self, *keys): 117 | """ Remove given key(s) from the configuration file. 118 | Will also execute the callback method if there is one """ 119 | if not self._cfg: 120 | self._read_cfg() 121 | 122 | if not keys: 123 | return 124 | 125 | tmp_cfg = self._cfg 126 | 127 | try: 128 | for key in keys[:-1]: 129 | tmp_cfg = tmp_cfg.setdefault(key, {}) 130 | del tmp_cfg[keys[-1]] 131 | 132 | self._ignore = True 133 | self._write_cfg() 134 | 135 | if isinstance(self._callback, types.FunctionType): 136 | self._callback(self._cfg, None, *keys) 137 | except KeyError as e: 138 | err = f"Can't remove key '{keys}' from '{self._cfg_file}'" 139 | logging.debug(f"{repr(e)} - {err}") 140 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # IDENA Node Watcher 2 | 3 | *IDENA Node Watcher* is a Telegram bot created by Telegram user @endogen for the IDENA community. The bot can monitor one or more IDENA nodes for you and notify you if one of them goes down. 4 | 5 | ## Overview 6 | 7 | The bot is build around the [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) module and is polling based. [Webhook mode](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks) is implemented but untested. 8 | 9 | ### General bot features 10 | 11 | - Every command is a plugin 12 | - Every plugin can be updated by sending the plugin file to the bot 13 | - Restart or shutdown the bot via command 14 | - Bot can be administered by more then one user 15 | - Commands to backup the bot or view latest logs are available 16 | 17 | ### IDENA specific features 18 | 19 | - Add one or more nodes to be watched by the bot 20 | - List all your watched node and verify that they are being watched 21 | - Remove nodes that you don't want to watch anymore 22 | - Change type of notification 23 | - Telegram 24 | - Email 25 | 26 | ## Configuration 27 | 28 | Before starting up the bot you have to take care of some settings and add a Telegram API token. The configuration file and token file are located in the `config` folder. 29 | 30 | ### config.json 31 | 32 | This file holds the configuration for the bot. You have to at least edit the value of __ids__. Everything else is optional. 33 | 34 | - __admin - ids__: This is a list of Telegram user IDs that will be able to control the bot. You can also add multiple users if you want. If you don't know your Telegram user ID, get in a conversation with Telegram bot [@userinfobot](https://t.me/userinfobot) and if you write him (anything) he will return you your user ID. 35 | - __admin - notify_on_error__: If set to `true` then all user IDs in the __admin - ids__ list will be notified if some error comes up. 36 | - __telegram - read_timeout__: Read timeout in seconds as integer. Usually this value doesn't have to be changed. 37 | - __telegram - connect_timeout__: Connect timeout in seconds as integer. Usually this value doesn't have to be changed. 38 | - __use_webhook__: If `true` then webhook settings will be applied. If `false` then polling will be used. 39 | - __webhook - listen__: Required only for webhook mode. IP to listen to. 40 | - __webhook - port__: Required only for webhook mode. Port to listen on. 41 | - __webhook - privkey_path__: Required only for webhook mode. Path to private key (.pem file). 42 | - __webhook - cert_path__: Required only for webhook mode. Path to certificate (.pem file). 43 | - __webhook - url__: Required only for webhook mode. URL under which the bot is hosted. 44 | 45 | ### token.json 46 | 47 | This file holds the Telegram bot token. You have to provide one and you will get it in a conversation with Telegram bot [@BotFather](https://t.me/BotFather) while registering your bot. 48 | 49 | If you don't want to provide the token in a file then you have two other options: 50 | 51 | - Provide it as a command line argument while starting your bot: `-tkn ` 52 | - Provide it as an command line input (**MOST SECURE**): `--input-tkn` 53 | 54 | ## Starting 55 | 56 | In order to run the bot you need to execute it with the Python interpreter. If you don't have any idea where to host the bot, take a look at [Where to host Telegram Bots](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Where-to-host-Telegram-Bots). Services like [Heroku](https://www.heroku.com) (free) will work fine. You can also run the script locally on your own computer for testing purposes. 57 | 58 | This guide is assuming that you want to run the bot on a Unix based system (Linux or macOS). 59 | 60 | ### Prerequisites 61 | 62 | You have to use at least __Python 3.7__ to execute the scripts. Everything else is not supported. 63 | 64 | ### Installation 65 | 66 | Install all needed Python modules 67 | 68 | ```shell 69 | pip3 install -r requirements.txt 70 | ``` 71 | 72 | ### Starting 73 | 74 | 1. First you have to make the script `run.sh` executable with 75 | 76 | 77 | ```shell 78 | chmod +x run.sh 79 | ``` 80 | 81 | 2. Then you need to start the script with 82 | 83 | ```shell 84 | ./run.sh & 85 | ``` 86 | 87 | ### Stopping 88 | 89 | The recommended way to stop the bot is by using the bot command `/shutdown`. If you don't want or can't use this, you can shut the bot down with: 90 | 91 | ```shell 92 | pkill python3.7 93 | ``` 94 | 95 | which will kill __every__ Python 3.7 process that is currently running. 96 | 97 | ## Usage 98 | 99 | ### Available commands 100 | 101 | ##### Bot 102 | 103 | ``` 104 | /about - Show info about the bot 105 | /backup - Backup whole bot folder 106 | /help - Show all available commands 107 | /log - Download current logfile 108 | /restart - Restart the bot 109 | /shutdown - Shutdown the bot 110 | ``` 111 | 112 | ##### Node Watcher 113 | 114 | ``` 115 | /watch - Add new node to watch 116 | /list - Show all your watched nodes 117 | /notify - Set or change notification settings 118 | ``` 119 | 120 | If you want to autocomplete available commands as you type in the chat with the bot, open a chat with Telegram bot [@BotFather](https://t.me/BotFather) and execute the command `/setcommands`. Then choose the bot you want to activate the autocomplete function for and after that send the list of commands with their descriptions. Something like this: 121 | 122 | ``` 123 | about - Show info about the bot 124 | backup - Backup whole bot folder 125 | help - Show all available commands 126 | log - Download current logfile 127 | restart - Restart the bot 128 | shutdown - Shutdown the bot 129 | watch - Add new node to watch 130 | list - Show all your watched nodes 131 | notify - Change notification settings 132 | ``` -------------------------------------------------------------------------------- /idena/start.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import sqlite3 4 | import logging 5 | import idena.constants as con 6 | 7 | from argparse import ArgumentParser 8 | from idena.tgbot import TelegramBot 9 | from idena.config import ConfigManager as Cfg 10 | from logging.handlers import TimedRotatingFileHandler 11 | from idena.web import FlaskAppWrapper 12 | 13 | 14 | class Idena: 15 | 16 | def __init__(self): 17 | # Parse command line arguments 18 | self.args = self._parse_args() 19 | 20 | # Set up logging 21 | self._init_logger() 22 | 23 | # Read global config file and create Telegram bot 24 | self.cfg = Cfg(os.path.join(con.DIR_CFG, con.FILE_CFG)) 25 | self.tgb = TelegramBot(self.cfg, self._get_bot_token()) 26 | 27 | def _parse_args(self): 28 | """ Parse command line arguments """ 29 | desc = "Telegram Tron Bot For Betting" 30 | parser = ArgumentParser(description=desc) 31 | 32 | # Save logfile 33 | parser.add_argument( 34 | "--no-log", 35 | dest="savelog", 36 | action="store_false", 37 | help="don't save log-files", 38 | required=False, 39 | default=True) 40 | 41 | # Log level 42 | parser.add_argument( 43 | "-log", 44 | dest="loglevel", 45 | type=int, 46 | choices=[0, 10, 20, 30, 40, 50], 47 | help="disabled, debug, info, warning, error, critical", 48 | default=30, 49 | required=False) 50 | 51 | # Module log level 52 | parser.add_argument( 53 | "-mlog", 54 | dest="mloglevel", 55 | help="set log level for a module", 56 | default=None, 57 | required=False) 58 | 59 | # Bot token 60 | parser.add_argument( 61 | "-tkn", 62 | dest="token", 63 | help="set Telegram bot token", 64 | required=False, 65 | default=None) 66 | 67 | # Bot token via input 68 | parser.add_argument( 69 | "--input-tkn", 70 | dest="input_token", 71 | action="store_true", 72 | help="set Telegram bot token", 73 | required=False, 74 | default=False) 75 | 76 | return parser.parse_args() 77 | 78 | # Configure logging 79 | def _init_logger(self): 80 | """ Initialize the console logger and file logger """ 81 | logger = logging.getLogger() 82 | logger.setLevel(self.args.loglevel) 83 | 84 | log_file = os.path.join(con.DIR_LOG, con.FILE_LOG) 85 | log_format = "[%(asctime)s %(levelname)s %(filename)s:%(lineno)s %(funcName)s()] %(message)s" 86 | 87 | # Log to console 88 | console_log = logging.StreamHandler() 89 | console_log.setFormatter(logging.Formatter(log_format)) 90 | console_log.setLevel(self.args.loglevel) 91 | 92 | logger.addHandler(console_log) 93 | 94 | # Save logs if enabled 95 | if self.args.savelog: 96 | # Create 'log' directory if not present 97 | log_path = os.path.dirname(log_file) 98 | if not os.path.exists(log_path): 99 | os.makedirs(log_path) 100 | 101 | file_log = TimedRotatingFileHandler( 102 | log_file, 103 | when="H", 104 | encoding="utf-8") 105 | 106 | file_log.setFormatter(logging.Formatter(log_format)) 107 | file_log.setLevel(self.args.loglevel) 108 | 109 | logger.addHandler(file_log) 110 | 111 | # Set log level for specified modules 112 | if self.args.mloglevel: 113 | for modlvl in self.args.mloglevel.split(","): 114 | module, loglvl = modlvl.split("=") 115 | logr = logging.getLogger(module) 116 | logr.setLevel(int(loglvl)) 117 | 118 | # Read bot token from file 119 | def _get_bot_token(self): 120 | """ Read Telegram bot token from config file or command line or input """ 121 | if self.args.input_token: 122 | return input("Enter Telegram Bot Token: ") 123 | if self.args.token: 124 | return self.args.token 125 | 126 | token_path = os.path.join(con.DIR_CFG, con.FILE_TKN) 127 | 128 | try: 129 | if os.path.isfile(token_path): 130 | with open(token_path, "r", encoding="utf8") as file: 131 | return json.load(file)["telegram"] 132 | else: 133 | exit(f"ERROR: No token file '{con.FILE_TKN}' found at '{token_path}'") 134 | except KeyError as e: 135 | cls_name = f"Class: {type(self).__name__}" 136 | logging.error(f"{repr(e)} - {cls_name}") 137 | exit("ERROR: Can't read bot token") 138 | 139 | def _get_nodes(self): 140 | path = os.path.join(os.getcwd(), con.DIR_DAT, con.FILE_DAT) 141 | 142 | if not os.path.isfile(path): 143 | return {"error": f"File doesn't exist: {path}"} 144 | 145 | connection = sqlite3.connect(path) 146 | cursor = connection.cursor() 147 | cursor.execute("SELECT * FROM nodes") 148 | connection.commit() 149 | data = cursor.fetchall() 150 | connection.close() 151 | 152 | return data 153 | 154 | def start(self): 155 | if self.cfg.get("webhook", "use_webhook"): 156 | self.tgb.bot_start_webhook() 157 | else: 158 | self.tgb.bot_start_polling() 159 | 160 | if self.cfg.get("web", "use_web"): 161 | secret = self.cfg.get("web", "password") 162 | 163 | port = self.cfg.get("web", "port") 164 | a = FlaskAppWrapper(__name__, port) 165 | 166 | a.add_endpoint( 167 | endpoint='/', 168 | endpoint_name='/') 169 | 170 | a.add_endpoint( 171 | endpoint='/nodes', 172 | endpoint_name='/nodes', 173 | handler=self._get_nodes, 174 | secret=secret) 175 | 176 | a.run() 177 | 178 | self.tgb.bot_idle() 179 | -------------------------------------------------------------------------------- /idena/plugins/notify/notify.py: -------------------------------------------------------------------------------- 1 | import idena.emoji as emo 2 | import idena.utils as utl 3 | import re 4 | 5 | from enum import auto 6 | from idena.plugin import IdenaPlugin 7 | from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ParseMode 8 | from telegram.ext import CallbackQueryHandler, RegexHandler, CommandHandler, \ 9 | ConversationHandler, MessageHandler, Filters 10 | 11 | 12 | class Notify(IdenaPlugin): 13 | 14 | ONOFF = auto() 15 | DATA = auto() 16 | FINAL = auto() 17 | 18 | TYPE_TG = "Telegram" 19 | TYPE_EM = "E-Mail" 20 | TYPE_DC = "Discord" 21 | 22 | ONOFF_Y = "Yes" 23 | ONOFF_N = "No" 24 | 25 | CANCEL = "Cancel" 26 | 27 | def __enter__(self): 28 | self.add_handler( 29 | ConversationHandler( 30 | entry_points=[CommandHandler('notify', self.cmd_notify)], 31 | states={ 32 | self.ONOFF: 33 | [CallbackQueryHandler(self.callback_onoff, pass_user_data=True)], 34 | self.DATA: 35 | [CallbackQueryHandler(self.callback_enable, pass_user_data=True)], 36 | self.FINAL: 37 | [RegexHandler(self.email_regex(), self.regex_email), 38 | RegexHandler(self.discord_regex(), self.regex_discord), 39 | CallbackQueryHandler(self.callback_cancel), 40 | MessageHandler(Filters.text, self.message_wrong, pass_user_data=True)] 41 | }, 42 | fallbacks=[CommandHandler('notify', self.cmd_notify)], 43 | allow_reentry=True), 44 | group=1) 45 | 46 | return self 47 | 48 | @IdenaPlugin.add_user 49 | @IdenaPlugin.send_typing 50 | def cmd_notify(self, bot, update): 51 | user_id = update.effective_user.id 52 | 53 | sql = self.get_global_resource("select_user.sql") 54 | res = self.execute_global_sql(sql, user_id) 55 | 56 | if not res["success"]: 57 | msg = f"{emo.ERROR} Not possible to retrieve user: {res['data']}" 58 | update.message.reply_text(msg) 59 | self.notify(msg) 60 | return 61 | 62 | if res["data"][0]: 63 | telegram = res["data"][0][5] 64 | email = res["data"][0][6] 65 | discord = res["data"][0][7] 66 | else: 67 | telegram = email = discord = str() 68 | 69 | msg = f"*Current notification settings*\n\n" \ 70 | f"`Telegram: {'Enabled' if telegram else 'Disabled'}`\n" \ 71 | f"`Discord : {'Enabled' if discord else 'Disabled'}`\n" \ 72 | f"`E-Mail : {'Enabled' if email else 'Disabled'}`\n\n" \ 73 | f"Choose which notification type to edit" 74 | 75 | buttons = [ 76 | InlineKeyboardButton(self.TYPE_TG, callback_data=self.TYPE_TG), 77 | InlineKeyboardButton(self.TYPE_EM, callback_data=self.TYPE_EM), 78 | InlineKeyboardButton(self.TYPE_DC, callback_data=self.TYPE_DC)] 79 | 80 | menu = utl.build_menu(buttons, n_cols=3) 81 | keyboard = InlineKeyboardMarkup(menu, resize_keyboard=True) 82 | 83 | update.message.reply_text(msg, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN) 84 | return self.ONOFF 85 | 86 | @IdenaPlugin.send_typing 87 | def callback_onoff(self, bot, update, user_data): 88 | query = update.callback_query 89 | 90 | if query.data not in [self.TYPE_DC, self.TYPE_EM, self.TYPE_TG]: 91 | return 92 | 93 | user_data["type"] = query.data 94 | 95 | buttons = [ 96 | InlineKeyboardButton(self.ONOFF_Y, callback_data=self.ONOFF_Y), 97 | InlineKeyboardButton(self.ONOFF_N, callback_data=self.ONOFF_N)] 98 | 99 | menu = utl.build_menu(buttons, n_cols=2) 100 | keyboard = InlineKeyboardMarkup(menu, resize_keyboard=True) 101 | 102 | bot.edit_message_text( 103 | chat_id=query.message.chat_id, 104 | message_id=query.message.message_id, 105 | text=f"Enable {user_data['type']} notifications?", 106 | reply_markup=keyboard) 107 | 108 | return self.DATA 109 | 110 | @IdenaPlugin.send_typing 111 | def callback_enable(self, bot, update, user_data): 112 | query = update.callback_query 113 | user_id = query.from_user.id 114 | 115 | if query.data not in [self.ONOFF_N, self.ONOFF_Y]: 116 | return 117 | 118 | user_data["enable"] = query.data 119 | 120 | if user_data["enable"] == self.ONOFF_N: 121 | 122 | sql = str() 123 | if user_data["type"] == self.TYPE_TG: 124 | sql = self.get_resource("update_telegram.sql") 125 | elif user_data["type"] == self.TYPE_EM: 126 | sql = self.get_resource("update_email.sql") 127 | elif user_data["type"] == self.TYPE_DC: 128 | sql = self.get_resource("update_discord.sql") 129 | 130 | if sql: 131 | self.execute_global_sql(sql, None, user_id) 132 | 133 | bot.edit_message_text( 134 | chat_id=query.message.chat_id, 135 | message_id=query.message.message_id, 136 | text=f"{emo.CANCEL} {user_data['type']} notifications disabled") 137 | 138 | return ConversationHandler.END 139 | 140 | user_data["enable"] = self.ONOFF_Y 141 | 142 | menu = utl.build_menu([InlineKeyboardButton(self.CANCEL, callback_data=self.CANCEL)]) 143 | keyboard = InlineKeyboardMarkup(menu, resize_keyboard=True) 144 | 145 | msg = str() 146 | if user_data["type"] == self.TYPE_TG: 147 | sql = self.get_resource("update_telegram.sql") 148 | self.execute_global_sql(sql, user_id, user_id) 149 | 150 | bot.edit_message_text( 151 | chat_id=query.message.chat_id, 152 | message_id=query.message.message_id, 153 | text=f"{emo.CHECK} {self.TYPE_TG} notifications enabled") 154 | return ConversationHandler.END 155 | 156 | elif user_data["type"] == self.TYPE_EM: 157 | msg = f"Please send me your {self.TYPE_EM} address or press {self.CANCEL}" 158 | 159 | elif user_data["type"] == self.TYPE_DC: 160 | #msg = f"Please send me your {self.TYPE_DC} ID or press {self.CANCEL}" 161 | 162 | # TODO: Remove this if Discord notifications are possible 163 | bot.edit_message_text( 164 | chat_id=query.message.chat_id, 165 | message_id=query.message.message_id, 166 | text=f"{emo.SKULL} {self.TYPE_DC} notifications not available yet") 167 | return ConversationHandler.END 168 | 169 | bot.edit_message_text( 170 | chat_id=query.message.chat_id, 171 | message_id=query.message.message_id, 172 | text=msg, 173 | reply_markup=keyboard) 174 | 175 | return self.FINAL 176 | 177 | @IdenaPlugin.send_typing 178 | def message_wrong(self, bot, update, user_data): 179 | msg = str() 180 | if user_data["type"] == self.TYPE_EM: 181 | msg = f"Not a valid email address. Send again" 182 | elif user_data["type"] == self.TYPE_DC: 183 | msg = f"Not a valid Discord ID. Send again" 184 | 185 | update.message.reply_text(msg) 186 | return self.FINAL 187 | 188 | def callback_cancel(self, bot, update): 189 | query = update.callback_query 190 | 191 | if not query.data == self.CANCEL: 192 | return 193 | 194 | bot.edit_message_text( 195 | chat_id=query.message.chat_id, 196 | message_id=query.message.message_id, 197 | text=f"{emo.INFO} Notifications not changed") 198 | 199 | return ConversationHandler.END 200 | 201 | @IdenaPlugin.send_typing 202 | def regex_email(self, bot, update): 203 | email = update.message.text 204 | user_id = update.effective_user.id 205 | 206 | sql = self.get_resource("update_email.sql") 207 | self.execute_global_sql(sql, email, user_id) 208 | 209 | update.message.reply_text(f"{emo.CHECK} {self.TYPE_EM} notifications enabled") 210 | return ConversationHandler.END 211 | 212 | @IdenaPlugin.send_typing 213 | def regex_discord(self, bot, update): 214 | discord = update.message.text 215 | user_id = update.effective_user.id 216 | 217 | sql = self.get_resource("update_discord.sql") 218 | self.execute_global_sql(sql, discord, user_id) 219 | 220 | update.message.reply_text(f"{emo.CHECK} {self.TYPE_DC} notifications enabled") 221 | return ConversationHandler.END 222 | 223 | # Returns pre compiled Regex pattern for EMail addresses 224 | def email_regex(self): 225 | pattern = "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" 226 | return re.compile(pattern, re.IGNORECASE) 227 | 228 | # Returns pre compiled Regex pattern for Discord tags 229 | def discord_regex(self): 230 | pattern = "(.*)#(\d{4})" 231 | return re.compile(pattern, re.IGNORECASE) 232 | 233 | @IdenaPlugin.threaded 234 | @IdenaPlugin.add_user 235 | @IdenaPlugin.send_typing 236 | def execute(self, bot, update, args): 237 | # Not used since we already defined a ConversationHandler 238 | pass 239 | -------------------------------------------------------------------------------- /idena/tgbot.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import importlib 4 | import shutil 5 | import idena.emoji as emo 6 | import idena.utils as utl 7 | import idena.constants as con 8 | 9 | from importlib import reload 10 | from zipfile import ZipFile 11 | from idena.config import ConfigManager 12 | from telegram import ParseMode, Chat 13 | from telegram.ext import Updater, MessageHandler, Filters, CommandHandler 14 | from telegram.error import InvalidToken 15 | 16 | 17 | class TelegramBot: 18 | 19 | plugins = list() 20 | 21 | def __init__(self, config: ConfigManager, token): 22 | self.config = config 23 | 24 | read_timeout = self.config.get("telegram", "read_timeout") 25 | connect_timeout = self.config.get("telegram", "connect_timeout") 26 | 27 | tgb_kwargs = dict() 28 | 29 | if read_timeout: 30 | tgb_kwargs["read_timeout"] = read_timeout 31 | if connect_timeout: 32 | tgb_kwargs["connect_timeout"] = connect_timeout 33 | 34 | try: 35 | self.updater = Updater(token, request_kwargs=tgb_kwargs) 36 | except InvalidToken as e: 37 | logging.error(e) 38 | exit("ERROR: Bot token not valid") 39 | 40 | self.job_queue = self.updater.job_queue 41 | self.dispatcher = self.updater.dispatcher 42 | 43 | # Load classes in folder 'plugins' 44 | self._load_plugins() 45 | 46 | # Handler for file downloads (plugin updates) 47 | mh = MessageHandler(Filters.document, self._update_plugin) 48 | self.dispatcher.add_handler(mh) 49 | 50 | # Handle all Telegram related errors 51 | self.dispatcher.add_error_handler(self._handle_tg_errors) 52 | 53 | # Send message to admin 54 | for admin in config.get("admin", "ids"): 55 | try: 56 | self.updater.bot.send_message(admin, f"{emo.DONE} Bot is up and running!") 57 | except Exception as e: 58 | logging.warning(f"Couldn't send startup message to ID {admin}: {e}") 59 | 60 | def bot_start_polling(self): 61 | """ Start the bot in polling mode """ 62 | self.updater.start_polling(clean=True) 63 | 64 | def bot_start_webhook(self): 65 | """ Start the bot in webhook mode """ 66 | self.updater.start_webhook( 67 | listen=self.config.get("webhook", "listen"), 68 | port=self.config.get("webhook", "port"), 69 | url_path=self.updater.bot.token, 70 | key=self.config.get("webhook", "privkey_path"), 71 | cert=self.config.get("webhook", "cert_path"), 72 | webhook_url=f"{self.config.get('webhook', 'url')}:" 73 | f"{self.config.get('webhook', 'port')}/" 74 | f"{self.updater.bot.token}") 75 | 76 | def bot_idle(self): 77 | """ Go in idle mode """ 78 | self.updater.idle() 79 | 80 | def add_plugin(self, module_name): 81 | """ Load a plugin so that it can be used """ 82 | for plugin in self.plugins: 83 | if plugin.get_name() == module_name.lower(): 84 | return {"success": False, "msg": "Plugin already active"} 85 | 86 | try: 87 | module_path = f"{con.DIR_SRC}.{con.DIR_PLG}.{module_name}.{module_name}" 88 | module = importlib.import_module(module_path) 89 | 90 | reload(module) 91 | 92 | with getattr(module, module_name.capitalize())(self) as plugin: 93 | self._add_handler(plugin) 94 | self.plugins.append(plugin) 95 | logging.info(f"Plugin '{plugin.get_name()}' added") 96 | return {"success": True, "msg": "Plugin added"} 97 | except Exception as ex: 98 | msg = f"Plugin '{module_name.capitalize()}' can't be added: {ex}" 99 | logging.warning(msg) 100 | raise ex 101 | 102 | def remove_plugin(self, module_name): 103 | """ Unload a plugin so that it can't be used """ 104 | for plugin in self.plugins: 105 | if plugin.get_name() == module_name.lower(): 106 | try: 107 | for handler in self.dispatcher.handlers[0]: 108 | if isinstance(handler, CommandHandler): 109 | if handler.command[0] == plugin.get_handle(): 110 | self.dispatcher.handlers[0].remove(handler) 111 | break 112 | 113 | self.plugins.remove(plugin) 114 | logging.info(f"Plugin '{plugin.get_name()}' removed") 115 | break 116 | except Exception as ex: 117 | msg = f"Plugin '{module_name.capitalize()}' can't be removed: {ex}" 118 | logging.warning(msg) 119 | raise ex 120 | return {"success": True, "msg": "Plugin removed"} 121 | 122 | def _load_plugins(self): 123 | """ Load all plugins from the 'plugins' folder """ 124 | try: 125 | for _, folders, _ in os.walk(os.path.join(con.DIR_SRC, con.DIR_PLG)): 126 | for folder in folders: 127 | if folder.startswith("_"): 128 | continue 129 | self._load_plugin(f"{folder}.py") 130 | break 131 | except Exception as e: 132 | logging.error(e) 133 | 134 | def _load_plugin(self, file): 135 | """ Load a single plugin """ 136 | try: 137 | module_name, extension = os.path.splitext(file) 138 | module_path = f"{con.DIR_SRC}.{con.DIR_PLG}.{module_name}.{module_name}" 139 | module = importlib.import_module(module_path) 140 | 141 | with getattr(module, module_name.capitalize())(self) as plugin: 142 | self._add_handler(plugin) 143 | self.plugins.append(plugin) 144 | logging.info(f"Plugin '{plugin.get_name()}' added") 145 | except Exception as e: 146 | logging.warning(f"File '{file}': {e}") 147 | 148 | def _add_handler(self, plugin): 149 | """ Add CommandHandler for given plugin """ 150 | handle = plugin.get_handle() 151 | 152 | if not isinstance(handle, str) or not plugin.get_handle(): 153 | raise Exception("Wrong command handler") 154 | 155 | self.dispatcher.add_handler( 156 | CommandHandler(handle, plugin.execute, pass_args=True)) 157 | 158 | def _update_plugin(self, bot, update): 159 | """ 160 | Update a plugin by uploading a file to the bot. 161 | 162 | If you provide a .ZIP file then the content will be extracted into 163 | the plugin with the same name as the file. For example the file 164 | 'about.zip' will be extracted into the 'about' plugin folder. 165 | 166 | It's also possible to provide a .PY file. In this case the file will 167 | replace the plugin implementation with the same name. For example the 168 | file 'about.py' will replace the same file in the 'about' plugin. 169 | 170 | All of this will only work in a private chat with the bot. 171 | """ 172 | 173 | # Check if in a private chat 174 | if bot.get_chat(update.message.chat_id).type != Chat.PRIVATE: 175 | return 176 | 177 | # Check if user that triggered the command is allowed to execute it 178 | if update.effective_user.id not in self.config.get("admin", "ids"): 179 | return 180 | 181 | name = update.message.effective_attachment.file_name.lower() 182 | zipped = False 183 | 184 | try: 185 | if name.endswith(".py"): 186 | plugin_name = name.replace(".py", "") 187 | elif name.endswith(".zip"): 188 | if len(name) == 18: 189 | msg = f"{emo.ERROR} Only backups of plugins are supported" 190 | update.message.reply_text(msg) 191 | return 192 | zipped = True 193 | if utl.is_numeric(name[:13]): 194 | plugin_name = name[14:].replace(".zip", "") 195 | else: 196 | plugin_name = name.replace(".zip", "") 197 | else: 198 | msg = f"{emo.ERROR} Wrong file format" 199 | update.message.reply_text(msg) 200 | return 201 | 202 | file = bot.getFile(update.message.document.file_id) 203 | 204 | if zipped: 205 | os.makedirs(con.DIR_TMP, exist_ok=True) 206 | zip_path = os.path.join(con.DIR_TMP, name) 207 | file.download(zip_path) 208 | 209 | with ZipFile(zip_path, 'r') as zip_file: 210 | plugin_path = os.path.join(con.DIR_SRC, con.DIR_PLG, plugin_name) 211 | zip_file.extractall(plugin_path) 212 | else: 213 | file.download(os.path.join(con.DIR_SRC, con.DIR_PLG, plugin_name, name)) 214 | 215 | self.remove_plugin(plugin_name) 216 | self.add_plugin(plugin_name) 217 | 218 | shutil.rmtree(con.DIR_TMP, ignore_errors=True) 219 | 220 | update.message.reply_text(f"{emo.CHECK} Plugin successfully loaded") 221 | except Exception as e: 222 | logging.error(e) 223 | msg = f"{emo.ERROR} {e}" 224 | update.message.reply_text(msg) 225 | 226 | def _handle_tg_errors(self, bot, update, error): 227 | """ Handle errors for module 'telegram' and 'telegram.ext' """ 228 | cls_name = f"Class: {type(self).__name__}" 229 | logging.error(f"{error} - {cls_name} - {update}") 230 | 231 | if not update: 232 | return 233 | 234 | error_msg = f"{emo.ERROR} *Telegram ERROR*: {error}" 235 | 236 | if update.message: 237 | update.message.reply_text( 238 | text=error_msg, 239 | parse_mode=ParseMode.MARKDOWN) 240 | elif update.callback_query: 241 | update.callback_query.message.reply_text( 242 | text=error_msg, 243 | parse_mode=ParseMode.MARKDOWN) 244 | -------------------------------------------------------------------------------- /idena/plugins/watch/watch.py: -------------------------------------------------------------------------------- 1 | import re 2 | import ssl 3 | import time 4 | import smtplib 5 | import logging 6 | import requests 7 | import idena.emoji as emo 8 | 9 | from random import randrange 10 | from datetime import datetime 11 | from telegram import ParseMode 12 | from idena.plugin import IdenaPlugin 13 | 14 | 15 | # TODO: Add possibility to remove node that is still offline after a week 16 | class Watch(IdenaPlugin): 17 | 18 | # At bot start, start jobs to watch all nodes 19 | def __enter__(self): 20 | # Get all node addresses 21 | sql = self.get_resource("select_nodes.sql") 22 | res = self.execute_global_sql(sql) 23 | 24 | if not res["success"]: 25 | msg = "Not possible to read nodes from database" 26 | self.notify(f"{emo.ERROR} {msg}") 27 | logging.error(msg) 28 | return self 29 | 30 | # Go through each node and create repeating job to check it 31 | for address in res["data"]: 32 | address = address[0] 33 | 34 | self.repeat_job( 35 | self.check_node, 36 | self.config.get("check_time"), 37 | first=randrange(0, self.config.get("check_time")), 38 | context={"address": address, "online": None, "ls_threshold": 0}, 39 | name=address) 40 | 41 | return self 42 | 43 | @IdenaPlugin.threaded 44 | @IdenaPlugin.add_user 45 | @IdenaPlugin.send_typing 46 | def execute(self, bot, update, args): 47 | user_id = update.effective_user.id 48 | 49 | if len(args) != 1: 50 | update.message.reply_text( 51 | self.get_usage(), 52 | parse_mode=ParseMode.MARKDOWN) 53 | return 54 | 55 | address = str(args[0]) 56 | 57 | # Check if provided wallet address is valid 58 | if not re.compile("^0x[a-fA-F0-9]{40}$").match(address): 59 | update.message.reply_text( 60 | f"{emo.ERROR} The provided address is not valid", 61 | parse_mode=ParseMode.MARKDOWN) 62 | return 63 | 64 | # Check if user is already watching this node 65 | sql = self.get_resource("node_exists.sql") 66 | res = self.execute_global_sql(sql, user_id, address) 67 | 68 | if res["data"]: 69 | update.message.reply_text( 70 | f"{emo.INFO} You are already watching this node", 71 | parse_mode=ParseMode.MARKDOWN) 72 | return 73 | 74 | # Save node in database 75 | sql = self.get_resource("insert_node.sql") 76 | res = self.execute_global_sql(sql, user_id, address) 77 | 78 | if not res["success"]: 79 | msg = f"{emo.ERROR} Not possible to add node: {res['data']}" 80 | update.message.reply_text(msg) 81 | self.notify(msg) 82 | return 83 | 84 | # Check if there is already a job to watch this node 85 | if not self.get_job(address): 86 | self.repeat_job( 87 | self.check_node, 88 | self.config.get("check_time"), 89 | context={"address": address, "online": None, "ls_threshold": 0}, 90 | name=address) 91 | 92 | update.message.reply_text(f"{emo.CHECK} Node is being watched") 93 | 94 | # Job logic to watch a node 95 | def check_node(self, bot, job): 96 | address = job.context["address"] 97 | 98 | api_url = self.config.get("api_url") 99 | api_url = f"{api_url}{address}" 100 | 101 | try: 102 | # Read IDENA explorer API to know when node was last seen 103 | response = requests.get(api_url, timeout=self.config.get("api_timeout")).json() 104 | except Exception as e: 105 | msg = f"{address} Could not reach API: {e}" 106 | logging.error(msg) 107 | return 108 | 109 | # If no last seen date-time, stop to watch node after some attempts 110 | if not response or not response["result"] or not response["result"]["lastActivity"]: 111 | job.context["ls_threshold"] += 1 112 | 113 | lst_context = job.context["ls_threshold"] 114 | lst_config = self.config.get("ls_threshold") 115 | 116 | msg = f"{address} Last-Seen-Threshold: {lst_context}/{lst_config}" 117 | logging.info(msg) 118 | 119 | if lst_context > lst_config: 120 | node = f"`{address[:12]}...{address[-12:]}`" 121 | msg = f"No 'Last Seen' date. Stopped watching node {node}" 122 | logging.info(f"{address} {msg}") 123 | job.schedule_removal() 124 | 125 | # Get all users that watch this node 126 | sql = self.get_resource("select_notify.sql") 127 | res = self.execute_global_sql(sql, address) 128 | 129 | if not res["success"]: 130 | msg = f"{address} No data found: {res['data']}" 131 | logging.error(msg) 132 | return 133 | 134 | # Send message to all users that watch this node 135 | for data in res["data"]: 136 | try: 137 | # Send message that watching this node is not possible 138 | bot.send_message(data[0], f"{emo.ERROR} {msg}", parse_mode=ParseMode.MARKDOWN) 139 | except Exception as e: 140 | msg = f"{address} Can't reply to user: {e}" 141 | logging.error(msg) 142 | 143 | # Remove node from database 144 | sql = self.get_resource("delete_node.sql") 145 | self.execute_global_sql(sql, address) 146 | 147 | return 148 | 149 | # Extract last seen date-time and convert it to seconds 150 | last_seen = response["result"]["lastActivity"].split(".")[0] 151 | last_seen_date = datetime.strptime(last_seen, "%Y-%m-%dT%H:%M:%S") 152 | last_seen_sec = (last_seen_date - datetime(1970, 1, 1)).total_seconds() 153 | 154 | # Load allowed time delta and calculate actual time delta 155 | allowed_delta = int(self.config.get("time_delta")) 156 | current_delta = int(time.time() - last_seen_sec) 157 | 158 | # Allowed time delta exceeded --> node is offline 159 | if current_delta > allowed_delta: 160 | if job.context['online']: 161 | job.context['online'] = False 162 | 163 | logging.info(f"{address} Node went offline " 164 | f"- {last_seen_date} " 165 | f"- {allowed_delta}/{current_delta}") 166 | 167 | # Create IDENA explorer link to identity 168 | identity_url = f"{self.config.get('identity_url')}{address}" 169 | 170 | msg = f"IDENA node is *OFFLINE*\n" \ 171 | f"[{address[:12]}...{address[-12:]}]({identity_url})" 172 | 173 | # Get all users that watch this node 174 | sql = self.get_resource("select_notify.sql") 175 | res = self.execute_global_sql(sql, address) 176 | 177 | if not res["success"]: 178 | msg = f"{address} No data found: {res['data']}" 179 | logging.error(msg) 180 | return 181 | 182 | # Notify user 183 | for data in res["data"]: 184 | # Telegram 185 | if data[0]: 186 | try: 187 | bot.send_message( 188 | data[0], 189 | f"{emo.ALERT} {msg}", 190 | parse_mode=ParseMode.MARKDOWN, 191 | disable_web_page_preview=True) 192 | logging.info(f"{address} Notification (Telegram) sent - {data}") 193 | except Exception as e: 194 | msg = f"{address} Can't notify user {data[0]} via Telegram: {e}" 195 | logging.error(msg) 196 | 197 | # Email 198 | if data[1]: 199 | try: 200 | smtp = self.global_config.get("notify", "email", "smtp") 201 | port = self.global_config.get("notify", "email", "port") 202 | mail = self.global_config.get("notify", "email", "mail") 203 | user = self.global_config.get("notify", "email", "user") 204 | pswd = self.global_config.get("notify", "email", "pass") 205 | subject = self.global_config.get("notify", "email", "subject") 206 | message = self.global_config.get("notify", "email", "message") 207 | message = str(message).replace("{{node}}", address) 208 | 209 | context = ssl.create_default_context() 210 | with smtplib.SMTP_SSL(smtp, port, context=context) as server: 211 | server.login(user, pswd) 212 | server.sendmail(mail, data[1], f"Subject: {subject}\n\n{message}") 213 | logging.info(f"{address} Notification (EMail) sent - {data}") 214 | except Exception as e: 215 | msg = f"{address} Can't notify user {data[0]} via EMail: {e}" 216 | logging.error(msg) 217 | 218 | # Discord 219 | if data[2]: 220 | # TODO: Not yet implemented 221 | pass 222 | else: 223 | logging.info(f"{address} Node is offline " 224 | f"- {last_seen_date} " 225 | f"- {current_delta}/{allowed_delta}") 226 | else: 227 | job.context['online'] = True 228 | logging.info(f"{address} Node is online " 229 | f"- {last_seen_date} " 230 | f"- {current_delta}/{allowed_delta}") 231 | -------------------------------------------------------------------------------- /idena/plugin.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sqlite3 3 | import logging 4 | import inspect 5 | import threading 6 | import idena.constants as c 7 | import idena.emoji as emo 8 | 9 | from pathlib import Path 10 | from telegram import ChatAction, Chat 11 | from idena.config import ConfigManager 12 | 13 | 14 | # TODO: Add properties where needed 15 | class IdenaPlugin: 16 | 17 | def __init__(self, tg_bot): 18 | self._tgb = tg_bot 19 | 20 | # Create access to global config 21 | self.global_config = self._tgb.config 22 | 23 | # Create access to plugin config 24 | cfg_path = os.path.join(self.get_cfg_path(), f"{self.get_name()}.json") 25 | self.config = ConfigManager(cfg_path) 26 | 27 | def __enter__(self): 28 | """ This method gets executed before the plugin gets loaded. 29 | Make sure to return 'self' if you override it """ 30 | return self 31 | 32 | def __exit__(self, exc_type, exc_value, traceback): 33 | """ This method gets executed after the plugin gets loaded """ 34 | pass 35 | 36 | def execute(self, bot, update, args): 37 | """ Override this to be executed after command gets triggered """ 38 | method = inspect.currentframe().f_code.co_name 39 | msg = f"Method '{method}' not implemented for plugin '{self.get_name()}'" 40 | logging.warning(msg) 41 | 42 | def get_usage(self): 43 | """ Return how to use the command """ 44 | usage = self.get_resource(f"{self.get_name()}.md") 45 | 46 | if usage: 47 | usage = usage.replace("{{handle}}", self.get_handle()) 48 | return usage 49 | 50 | return None 51 | 52 | def get_handle(self): 53 | """ Return the command string that triggers the plugin """ 54 | return self.config.get("handle") 55 | 56 | def get_category(self): 57 | """ Return the category of the plugin for the 'help' command """ 58 | return self.config.get("category") 59 | 60 | def get_description(self): 61 | """ Return the description of the plugin """ 62 | return self.config.get("description") 63 | 64 | def get_plugins(self): 65 | """ Return a list of all active plugins """ 66 | return self._tgb.plugins 67 | 68 | def get_jobs(self): 69 | """ Return a tuple with all currently active jobs """ 70 | return self._tgb.job_queue.jobs() 71 | 72 | def get_job(self, name=None): 73 | """ Return the periodic job with the given name or 74 | None if 'interval' is not set in plugin config """ 75 | 76 | name = self.get_name() if not name else name 77 | jobs = self._tgb.job_queue.get_jobs_by_name(name) 78 | 79 | if not jobs or len(jobs) < 1: 80 | return None 81 | 82 | return jobs[0] 83 | 84 | # TODO: Don't set default for name as plugin name. What if we have more than one? 85 | def repeat_job(self, callback, interval, first=0, context=None, name=None): 86 | """ Logic that gets executed periodically """ 87 | self._tgb.job_queue.run_repeating( 88 | callback, 89 | interval, 90 | first=first, 91 | name=name if name else self.get_usage(), 92 | context=context) 93 | 94 | def add_handler(self, handler, group=0): 95 | self._tgb.dispatcher.add_handler(handler, group=group) 96 | 97 | def add_plugin(self, module_name): 98 | """ Enable a plugin """ 99 | return self._tgb.add_plugin(module_name) 100 | 101 | def remove_plugin(self, module_name): 102 | """ Disable a plugin """ 103 | return self._tgb.remove_plugin(module_name) 104 | 105 | def get_global_resource(self, filename): 106 | """ Return the content of the given file 107 | from the global 'resource' directory """ 108 | 109 | path = os.path.join(os.getcwd(), c.DIR_RES, filename) 110 | 111 | try: 112 | with open(path, "r", encoding="utf8") as f: 113 | return f.read() 114 | except Exception as e: 115 | logging.error(e) 116 | self.notify(e) 117 | return None 118 | 119 | # TODO: Maybe give the option to only check filename without extension 120 | def get_resource(self, filename, plugin=""): 121 | """ Return the content of the given file from 122 | the 'resource' directory of the plugin """ 123 | path = os.path.join(self.get_res_path(plugin), filename) 124 | 125 | try: 126 | with open(path, "r", encoding="utf8") as f: 127 | return f.read() 128 | except Exception as e: 129 | logging.error(e) 130 | self.notify(e) 131 | return None 132 | 133 | def execute_global_sql(self, sql, *args): 134 | """ Execute raw SQL statement on the global 135 | database and return the result if there is one """ 136 | 137 | res = {"success": None, "data": None} 138 | 139 | db_path = os.path.join(os.getcwd(), c.DIR_DAT, c.FILE_DAT) 140 | 141 | try: 142 | # Create directory if it doesn't exist 143 | directory = os.path.dirname(db_path) 144 | os.makedirs(directory, exist_ok=True) 145 | except Exception as e: 146 | res["data"] = str(e) 147 | res["success"] = False 148 | logging.error(e) 149 | self.notify(e) 150 | 151 | con = None 152 | 153 | try: 154 | con = sqlite3.connect(db_path) 155 | cur = con.cursor() 156 | cur.execute(sql, args) 157 | con.commit() 158 | 159 | res["data"] = cur.fetchall() 160 | res["success"] = True 161 | except Exception as e: 162 | res["data"] = str(e) 163 | res["success"] = False 164 | logging.error(e) 165 | self.notify(e) 166 | finally: 167 | if con: 168 | con.close() 169 | 170 | return res 171 | 172 | # TODO: Describe how arguments can be used 173 | def execute_sql(self, sql, *args, plugin="", db_name=""): 174 | """ Execute raw SQL statement on database for given 175 | plugin and return the result if there is one """ 176 | 177 | res = {"success": None, "data": None} 178 | 179 | # Check if database usage is enabled 180 | if not self.global_config.get("database", "use_db"): 181 | res["data"] = "Database disabled" 182 | res["success"] = False 183 | return res 184 | 185 | if db_name: 186 | if not db_name.lower().endswith(".db"): 187 | db_name += ".db" 188 | else: 189 | if plugin: 190 | db_name = plugin + ".db" 191 | else: 192 | db_name = self.get_name() + ".db" 193 | 194 | if plugin: 195 | plugin = plugin.lower() 196 | data_path = self.get_dat_path(plugin=plugin) 197 | db_path = os.path.join(data_path, db_name) 198 | else: 199 | db_path = os.path.join(self.get_dat_path(), db_name) 200 | 201 | try: 202 | # Create directory if it doesn't exist 203 | directory = os.path.dirname(db_path) 204 | os.makedirs(directory, exist_ok=True) 205 | except Exception as e: 206 | res["data"] = str(e) 207 | res["success"] = False 208 | logging.error(e) 209 | self.notify(e) 210 | 211 | con = None 212 | 213 | try: 214 | con = sqlite3.connect(db_path) 215 | cur = con.cursor() 216 | cur.execute(sql, args) 217 | con.commit() 218 | 219 | res["data"] = cur.fetchall() 220 | res["success"] = True 221 | except Exception as e: 222 | res["data"] = str(e) 223 | res["success"] = False 224 | logging.error(e) 225 | self.notify(e) 226 | finally: 227 | if con: 228 | con.close() 229 | 230 | return res 231 | 232 | def global_table_exists(self, table_name): 233 | """ Return TRUE if given table exists in global database, otherwise FALSE """ 234 | db_path = os.path.join(os.getcwd(), c.DIR_DAT, c.FILE_DAT) 235 | 236 | if not Path(db_path).is_file(): 237 | return False 238 | 239 | con = sqlite3.connect(db_path) 240 | cur = con.cursor() 241 | exists = False 242 | 243 | statement = self.get_global_resource("table_exists.sql") 244 | 245 | try: 246 | if cur.execute(statement, [table_name]).fetchone(): 247 | exists = True 248 | except Exception as e: 249 | logging.error(e) 250 | self.notify(e) 251 | 252 | con.close() 253 | return exists 254 | 255 | def table_exists(self, table_name, plugin="", db_name=""): 256 | """ Return TRUE if given table exists, otherwise FALSE """ 257 | if db_name: 258 | if not db_name.lower().endswith(".db"): 259 | db_name += ".db" 260 | else: 261 | if plugin: 262 | db_name = plugin + ".db" 263 | else: 264 | db_name = self.get_name() + ".db" 265 | 266 | if plugin: 267 | db_path = os.path.join(self.get_dat_path(plugin=plugin), db_name) 268 | else: 269 | db_path = os.path.join(self.get_dat_path(), db_name) 270 | 271 | if not Path(db_path).is_file(): 272 | return False 273 | 274 | con = sqlite3.connect(db_path) 275 | cur = con.cursor() 276 | exists = False 277 | 278 | statement = self.get_global_resource("table_exists.sql") 279 | 280 | try: 281 | if cur.execute(statement, [table_name]).fetchone(): 282 | exists = True 283 | except Exception as e: 284 | logging.error(e) 285 | self.notify(e) 286 | 287 | con.close() 288 | return exists 289 | 290 | def get_name(self): 291 | """ Return the name of the current plugin """ 292 | return type(self).__name__.lower() 293 | 294 | def get_res_path(self, plugin=""): 295 | """ Return path of resource directory for this plugin """ 296 | if not plugin: 297 | plugin = self.get_name() 298 | return os.path.join(c.DIR_SRC, c.DIR_PLG, plugin, c.DIR_RES) 299 | 300 | def get_cfg_path(self, plugin=""): 301 | """ Return path of configuration directory for this plugin """ 302 | if not plugin: 303 | plugin = self.get_name() 304 | return os.path.join(c.DIR_SRC, c.DIR_PLG, plugin, c.DIR_CFG) 305 | 306 | def get_dat_path(self, plugin=""): 307 | """ Return path of data directory for this plugin """ 308 | if not plugin: 309 | plugin = self.get_name() 310 | return os.path.join(c.DIR_SRC, c.DIR_PLG, plugin, c.DIR_DAT) 311 | 312 | def get_plg_path(self, plugin=""): 313 | """ Return path of current plugin directory """ 314 | if not plugin: 315 | plugin = self.get_name() 316 | return os.path.join(c.DIR_SRC, c.DIR_PLG, plugin) 317 | 318 | def plugin_available(self, plugin_name): 319 | """ Return TRUE if the given plugin is enabled or FALSE otherwise """ 320 | for plugin in self.get_plugins(): 321 | if plugin.get_name() == plugin_name.lower(): 322 | return True 323 | return False 324 | 325 | def notify(self, some_input): 326 | """ All admins in global config will get a message with the given text. 327 | Primarily used for exceptions but can be used with other inputs too. """ 328 | 329 | if self.global_config.get("admin", "notify_on_error"): 330 | for admin in self.global_config.get("admin", "ids"): 331 | try: 332 | msg = f"{emo.ALERT} Admin Notification:\n{some_input}" 333 | self._tgb.updater.bot.send_message(admin, msg) 334 | except Exception as e: 335 | error = f"Not possible to notify admin id '{admin}'" 336 | logging.error(f"{error}: {e}") 337 | return some_input 338 | 339 | @staticmethod 340 | def threaded(fn): 341 | """ Decorator for methods that have to run in their own thread """ 342 | def _threaded(*args, **kwargs): 343 | thread = threading.Thread(target=fn, args=args, kwargs=kwargs) 344 | thread.start() 345 | 346 | return thread 347 | return _threaded 348 | 349 | @classmethod 350 | def private(cls, func): 351 | """ Decorator for methods that need to be run in a private chat with the bot """ 352 | def _private(self, bot, update, **kwargs): 353 | if self.config.get("private"): 354 | if bot.get_chat(update.message.chat_id).type == Chat.PRIVATE: 355 | return func(self, bot, update, **kwargs) 356 | 357 | return _private 358 | 359 | @classmethod 360 | def add_user(cls, func): 361 | """ Decorator for adding current Telegram user to database """ 362 | def _add_user(self, bot, update, **kwargs): 363 | user = update.effective_user 364 | 365 | sql = self.get_global_resource("select_user.sql") 366 | res = self.execute_global_sql(sql, user.id) 367 | 368 | if not res["success"]: 369 | msg = f"{emo.ERROR} Not possible to add user: {res['data']}" 370 | update.message.reply_text(msg) 371 | self.notify(msg) 372 | return 373 | 374 | same = True 375 | 376 | if res["data"]: 377 | data = res["data"][0] 378 | 379 | if data[1] != user.first_name: 380 | same = False 381 | elif data[2] != user.last_name: 382 | same = False 383 | elif data[3] != user.username: 384 | same = False 385 | elif data[4] != user.language_code: 386 | same = False 387 | 388 | if not same: 389 | sql = self.get_global_resource("update_user.sql") 390 | res = self.execute_global_sql( 391 | sql, 392 | user.first_name, 393 | user.last_name, 394 | user.username, 395 | user.language_code, 396 | user.id) 397 | 398 | if not res["success"]: 399 | msg = f"{emo.ERROR} Not possible to add user: {res['data']}" 400 | update.message.reply_text(msg) 401 | self.notify(msg) 402 | return 403 | else: 404 | sql = self.get_global_resource("insert_user.sql") 405 | res = self.execute_global_sql( 406 | sql, 407 | user.id, 408 | user.first_name, 409 | user.last_name, 410 | user.username, 411 | user.language_code, 412 | user.id) 413 | 414 | if not res["success"]: 415 | msg = f"{emo.ERROR} Not possible to add user: {res['data']}" 416 | update.message.reply_text(msg) 417 | self.notify(msg) 418 | return 419 | 420 | return func(self, bot, update, **kwargs) 421 | return _add_user 422 | 423 | @classmethod 424 | def send_typing(cls, func): 425 | """ Decorator for sending typing notification in the Telegram chat """ 426 | def _send_typing(self, bot, update, **kwargs): 427 | if update.message: 428 | user_id = update.message.chat_id 429 | elif update.callback_query: 430 | user_id = update.callback_query.message.chat_id 431 | else: 432 | return func(self, bot, update, **kwargs) 433 | 434 | try: 435 | bot.send_chat_action( 436 | chat_id=user_id, 437 | action=ChatAction.TYPING) 438 | except Exception as e: 439 | logging.error(f"{e} - {update}") 440 | 441 | return func(self, bot, update, **kwargs) 442 | return _send_typing 443 | 444 | @classmethod 445 | def owner(cls, func): 446 | """ 447 | Decorator that executes the method only if the user is an bot admin. 448 | 449 | The user ID that triggered the command has to be in the ["admin"]["ids"] 450 | list of the global config file 'config.json' or in the ["admins"] list 451 | of the currently used plugin config file. 452 | """ 453 | 454 | def _owner(self, bot, update, **kwargs): 455 | user_id = update.effective_user.id 456 | 457 | admins_global = self.global_config.get("admin", "ids") 458 | if admins_global and isinstance(admins_global, list): 459 | if user_id in admins_global: 460 | return func(self, bot, update, **kwargs) 461 | 462 | admins_plugin = self.config.get("admins") 463 | if admins_plugin and isinstance(admins_plugin, list): 464 | if user_id in admins_plugin: 465 | return func(self, bot, update, **kwargs) 466 | 467 | return _owner 468 | 469 | @classmethod 470 | def dependency(cls, func): 471 | """ Decorator that executes a method only if the mentioned 472 | plugins in the config file of the current plugin are enabled """ 473 | 474 | def _dependency(self, bot, update, **kwargs): 475 | dependencies = self.config.get("dependency") 476 | 477 | if dependencies and isinstance(dependencies, list): 478 | plugins = [p.get_name() for p in self.get_plugins()] 479 | 480 | for dependency in dependencies: 481 | if dependency.lower() not in plugins: 482 | return 483 | 484 | return func(self, bot, update, **kwargs) 485 | return _dependency 486 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------