#!/usr/bin/python3.7 import smtplib import os from datetime import datetime, timedelta import requests import json print("Content-Type: text/html\n\n") HTML_FILE = "streamer.html" LOG_FILE = "stream-key.log" smtp_username = "rad.smtp@gmail.com" smtp_password = os.environ["SMTP_PASSWORD"] def get_location(ip_addr): url = "https://freegeoip.app/json/" + ip_addr headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("GET", url, headers=headers) return json.loads(response.text) def send_mail(title, content): # The mail addresses and password sender_address = smtp_username sender_pass = smtp_password receiver_address = 'reezuan@gmail.com' message = """Subject: Check-in Alert [%s] %s """ % (title, content) with smtplib.SMTP('smtp.gmail.com', 587) as session: session.starttls() # enable security session.login(sender_address, sender_pass) session.sendmail(sender_address, receiver_address, message) def write_log(text): log_items = [] # open log file for reading if os.path.exists(LOG_FILE): with open(LOG_FILE, "r") as f: log_items = f.readlines() if len(log_items) == 1000: log_items.pop(0) log_items.append(text) # reopen the file for appending with open(LOG_FILE, "w") as f: f.writelines(log_items) try: # update log file remote_addr = os.environ["REMOTE_ADDR"] geo_info = get_location(remote_addr) d = datetime.utcnow() d = d + timedelta(hours=8) log_text = "Request detected from %s (%s, %s, %s) at %s.\n" % (remote_addr, geo_info["city"], geo_info["region_name"], geo_info["country_name"], d.strftime("%c")) send_mail(geo_info["country_code"], log_text) log_text = "Request detected from %s at %s.\n" % (remote_addr, d.strftime("%c")) write_log(log_text) with open(HTML_FILE, "r") as f: html_text = f.read() print(html_text) except Exception as ex: print("Error:", ex)