-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptopaper-2.py
203 lines (171 loc) · 7.29 KB
/
cryptopaper-2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
## (c) 2024 Kerry Fraser-Robinson
from flask import Flask, request, jsonify, send_from_directory, render_template
from flask_cors import CORS
import requests
import os, sys, time, string, re
from werkzeug.utils import secure_filename
from bs4 import BeautifulSoup # For BBC News scraping proxy
import socket # For confirming ip address
import qrcode
PORT = 5000
DEFAULT_LOCALE = 'Toronto'
locale = DEFAULT_LOCALE
TITLE, VERSION = 'Cryptopaper', '2.0.5'
LIBDIR = 'lib/'
T_START = int(time.time())
OPTIONS_FILE = 'options.txt'
KEYWORDS_FILE = 'watch-words.txt'
QR_FILENAME = 'qr.png'
USE_SSL = False
app = Flask(__name__, template_folder=LIBDIR)
CORS(app) # Enable CORS for all routes
def read_locale():
global locale
try:
with open(os.path.join(LIBDIR, OPTIONS_FILE), 'r') as file:
locale = file.read().lstrip().rstrip()
print_log(f"Using locale: `{locale}`")
except:
locale = DEFAULT_LOCALE
print_log(f"Using DEFAULT locale (`{locale}`)")
def print_log(log_string = '',log_to_file=True, noStdOut = False):
LOG_FILENAME = sys.argv[0].split('.')[0] + '.log'
timestamp = time.strftime("%m/%d/%y %H:%M:%S", time.localtime(time.time()))
if not noStdOut: print(f"[ {timestamp} ] {log_string}")
if(log_to_file):
with open(LOG_FILENAME, "a") as file:
file.write(f"[ {timestamp} ] {log_string}\n")
def ip_address():
try:
ip = ((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(
("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["(No IP)"])[0])
except:
ip = "(IP Timeout)"
return ip
def generateQR(url='http://127.0.0.1:5000/', save_path='qrcode.png', transparentBackground=True, fgColor=(0, 0, 0)):
# Create a QR Code object
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data to the QR Code
qr.add_data(url)
qr.make(fit=True)
# Create an image from the QR Code instance
img = qr.make_image(fill_color=fgColor, back_color="white").convert('RGBA')
if transparentBackground:
# Make the background transparent
data = img.getdata()
new_data = []
for item in data:
# Change all white pixels to transparent
if item[:3] == (255, 255, 255):
new_data.append((255, 255, 255, 0))
else:
new_data.append(item)
img.putdata(new_data)
img.save(save_path)
print_log(f"QR code file ({save_path}) updated with URL = '{url}'")
def sanitize_watch_words(watch_words: str):
lines = watch_words.split('\n')
# Remove non-alphanumeric characters and empty lines
sanitized_lines = [re.sub(r'\W+', '', line) for line in lines if line.strip() != '']
return '\n'.join(sorted(sanitized_lines, key=str.lower))
def sanitize_locale(locale: str):
return ''.join(ch for ch in locale if ch.isprintable())
@app.route('/', methods=['GET', 'POST'])
def index():
global locale
if request.method == 'POST' and 'locale' in request.form:
locale = sanitize_locale(request.form['locale'])
try:
with open(os.path.join(LIBDIR, OPTIONS_FILE), 'w') as file:
file.write(locale)
print_log(f'{OPTIONS_FILE} (locale) updated.')
except:
print_log('Locale not updated.')
return send_from_directory(LIBDIR, 'index.html')
@app.route('/words', methods=['GET'])
def words():
watchWords = []
# Load watch words. Ignore any words containing non-printable characters
try:
watchWords = [line.strip() for line in open(os.path.join(LIBDIR, KEYWORDS_FILE)) if all(char in string.printable for char in line)]
print_log("Watch list loaded: '" + ", ".join(watchWords) + "'")
except:
# Defaults :
watchWords = ['alert', 'biolog', 'bitcoin', 'bomb', 'breaking', 'budanov', 'casualt', 'chemical', 'Crimea', 'crypto', 'cyber', 'dead', 'detected', 'explod', 'explos', 'hypers', 'infect', 'jet', 'Kerch', 'killed', 'Kremlin', 'Kyiv', 'launch', 'military', 'missile', 'Moscow', 'NAFO', 'NATO', 'nuclear', 'outbreak', 'posture', 'Putin', 'radioac', 'readiness', 'rocket', 'shell', 'shot', 'siren', 'spreads', 'submarine', 'troop', 'ukraine', 'zelensky']
return jsonify(watchWords)
@app.route('/status', methods=['GET'])
def status():
statusData = {
'title': TITLE,
'version': VERSION,
'start_time': T_START,
'ip_addr': ip_address(),
'locale': locale
}
return jsonify(statusData)
@app.route('/options')
def options():
system_name = os.uname().nodename
server_time = time.strftime("%m/%d/%y %H:%M:%S", time.localtime(time.time()))
return render_template('options.html', status = f'{system_name} :: {server_time}', locale = locale)
@app.route('/save_watch_words', methods=['POST'])
def save_watch_words():
text = sanitize_watch_words(request.form['text'])
try:
with open(os.path.join(LIBDIR, KEYWORDS_FILE), 'w') as file:
file.write(text)
return {'message': 'File saved successfully.'}
except: return {'error': 'An error occurred while saving the watch-words file.'}
@app.route('/<filename>.png')
def serve_png(filename):
try:
secure_filename_str = secure_filename(f"{filename}.png")
return send_from_directory(LIBDIR, secure_filename_str)
except FileNotFoundError:
return "File not found", 404
@app.route('/<filename>.js')
def serve_js(filename):
try:
secure_filename_str = secure_filename(f"{filename}.js")
return send_from_directory(LIBDIR, secure_filename_str)
except FileNotFoundError:
return "File not found", 404
@app.route('/<filename>.otf')
def serve_font(filename):
try:
secure_filename_str = secure_filename(f"{filename}.otf")
return send_from_directory(LIBDIR, secure_filename_str)
except FileNotFoundError:
return "File not found", 404
@app.route('/favicon.ico')
def favicon():
return send_from_directory(LIBDIR, 'favicon.ico', mimetype='image/x-icon')
@app.route('/fetch_news', methods=['GET'])
def fetch_bbc_news():
url = "https://www.bbc.com/news/world"
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raise HTTPError for bad responses
data = response.text
soup = BeautifulSoup(data, 'html.parser')
headlines = soup.find('body').find_all('h2')
results = []
for headline in headlines:
if headline.text.strip() not in results:
results.append(headline.text.strip())
if len(results) >= 4:
break
return jsonify(results)
except requests.RequestException as e:
return jsonify(['', '', 'No headlines found']), 500
if __name__ == '__main__':
print_log(f"v{VERSION}: Initialising...")
read_locale()
generateQR(url=f'http{("s" if USE_SSL else "")}://{ip_address()}:{PORT}/', save_path=os.path.join(LIBDIR, QR_FILENAME))
app.run(debug=False, host='0.0.0.0', port=PORT, ssl_context='adhoc' if USE_SSL else None)