70 lines
1.7 KiB
Python
70 lines
1.7 KiB
Python
from flask import Flask, jsonify, request
|
|
import re
|
|
|
|
|
|
|
|
HOSTS_PATH = "/app/hosts.d/izbi"
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
hosts = {}
|
|
|
|
|
|
|
|
def update_hosts(path: str, hosts: dict = {}): bool
|
|
try:
|
|
hosts_str = ""
|
|
for domain, ip in hosts.items():
|
|
hosts_str += f"{ip}\t{domain}\n"
|
|
with open(path, "w") as f:
|
|
f.write(hosts_str)
|
|
print(f"ddns - updated {path}")
|
|
return True
|
|
except Exception as e:
|
|
print(e)
|
|
return False
|
|
|
|
|
|
|
|
def validate_ip(ip: str): bool
|
|
exp = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
|
|
return re.search(exp, ip)
|
|
|
|
|
|
|
|
@app.route('/', methods=["GET"])
|
|
def health():
|
|
return jsonify({"status": "healthy", "comment": ""})
|
|
|
|
|
|
|
|
@app.route('/update', methods=["GET"])
|
|
def update_addr():
|
|
if 'domain' not in request.args:
|
|
return jsonify({"status": "400", "code": "domain-error", "comment": "Missing or invalid domain"}), 400
|
|
domain = request.args['domain']
|
|
|
|
if 'ip' not in request.args:
|
|
ip = request.remote_addr
|
|
elif not validate_ip(request.args['ip']):
|
|
return jsonify({"status": "400", "code": "ip-error", "comment": "Invalid IP"}), 400
|
|
else:
|
|
ip = request.args['ip']
|
|
|
|
print(f"ddns - update request of [{domain}, {ip}] from {request.remote_addr}")
|
|
|
|
hosts[domain] = ip
|
|
success = update_hosts(HOSTS_PATH, hosts)
|
|
|
|
if not success:
|
|
return jsonify({"status": "500", "code": "internal-server-error", "An error occurred while processing request"}), 500
|
|
|
|
return jsonify({"status": "200", "code": "ok", "comment": "Updated successfully"})
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host="0.0.0.0", port=8080, debug=True)
|