pilpil-client/app.py

253 lines
7.0 KiB
Python
Raw Normal View History

2022-10-06 11:47:21 +02:00
#!/usr/bin/env python
2022-11-24 20:15:22 +01:00
# pilpil-client 0.1
2022-11-05 20:05:09 +01:00
# abelliqueux <contact@arthus.net>
2022-11-24 20:15:22 +01:00
from flask import Flask, flash, request, redirect, url_for, send_file
2022-10-06 11:47:21 +02:00
from flask_httpauth import HTTPBasicAuth
2022-11-05 20:05:09 +01:00
import gettext
import os
import subprocess
import threading
import time
import toml
from waitress import serve
2022-10-06 11:47:21 +02:00
from werkzeug.security import generate_password_hash, check_password_hash
2022-10-19 15:14:43 +02:00
from werkzeug.utils import secure_filename
2022-10-19 16:22:05 +02:00
2022-11-03 14:42:17 +01:00
# l10n
LOCALE = os.getenv('LANG', 'en')
_ = gettext.translation('template', localedir='locales', languages=[LOCALE]).gettext
2022-11-05 20:05:09 +01:00
app = Flask(__name__)
2022-10-19 16:22:05 +02:00
app.config.from_file("defaults.toml", load=toml.load)
config_locations = ["./", "~/.", "~/.config/"]
for location in config_locations:
# Optional config files, ~ is expanded to $HOME on *nix, %USERPROFILE% on windows
2022-11-24 20:15:22 +01:00
if app.config.from_file(os.path.expanduser(location + "pilpil-client.toml"), load=toml.load, silent=True):
print(_("Found configuration file in {}").format(os.path.expanduser(location)))
2022-10-19 16:22:05 +02:00
2022-11-05 20:05:09 +01:00
upload_folder = os.path.expanduser(app.config['DEFAULT']['media_folder_local'])
media_exts = app.config['DEFAULT']['media_exts']
HTTP_secret = str(app.config['DEFAULT']['auth'])
debug = app.config['DEFAULT']['debug']
useSSL = app.config['DEFAULT']['useSSL']
2022-11-05 20:05:09 +01:00
rssi_signal = 0
2022-11-24 20:15:22 +01:00
thumbnails_folder = "thumb"
2022-10-06 11:47:21 +02:00
2022-11-05 20:05:09 +01:00
# HTTP upload settings
app.config['UPLOAD_FOLDER'] = upload_folder
2022-10-19 15:14:43 +02:00
# Max upload size 100M ( see nginx default also )
app.config['MAX_CONTENT_LENGTH'] = 100 * 1000 * 1000
2022-10-06 11:47:21 +02:00
2022-11-05 20:05:09 +01:00
# HTTP auth settings
2022-10-06 11:47:21 +02:00
auth = HTTPBasicAuth()
users = {
2022-11-05 20:05:09 +01:00
"": generate_password_hash(HTTP_secret),
2022-10-06 11:47:21 +02:00
}
HTTP_url_scheme = "http"
if useSSL:
HTTP_url_scheme += "s"
if debug:
print(HTTP_url_scheme)
2022-11-24 20:15:22 +01:00
2022-10-06 11:47:21 +02:00
@auth.verify_password
def verify_password(username, password):
2022-11-05 20:05:09 +01:00
'''
Check HTTP auth username and password
'''
2022-10-06 11:47:21 +02:00
if username in users and check_password_hash(users.get(username), password):
return username
2022-11-24 20:15:22 +01:00
2022-11-05 20:05:09 +01:00
def allowed_ext(filename):
'''
Check if filename has an allowed extension.
'''
2022-10-19 15:14:43 +02:00
# Check for dot in filename
if "." in filename:
# Split from right at first dot to find ext and allow files with "." in name
2022-11-24 20:15:22 +01:00
if filename.rsplit(".", 1)[-1] in media_exts:
2022-10-19 15:14:43 +02:00
return True
2022-11-08 15:28:53 +01:00
2022-11-24 20:15:22 +01:00
2022-11-07 12:53:26 +01:00
def XMLify(string, child_node_name="child"):
'''
'''
root_element = "root"
if debug:
print("<{0}><{1}>{2}</{1}></{0}>".format(root_element, child_node_name, string))
return "<{0}><{1}>{2}</{1}></{0}>".format(root_element, child_node_name, string)
2022-11-24 20:15:22 +01:00
2022-11-05 20:05:09 +01:00
def get_RSSI():
'''
Get wireless signal level to AP
'''
with open("/proc/net/wireless", "r") as wl:
for line in wl:
pass
last_line = line
rssi_signal = last_line.split(' ')[3][:-1].strip("-").strip("\n")
if debug:
print(rssi_signal)
2022-11-07 12:53:26 +01:00
return XMLify(rssi_signal, child_node_name="rssi")
2022-11-05 20:05:09 +01:00
2022-11-24 20:15:22 +01:00
2022-11-15 15:57:59 +01:00
def running_on_rpi():
with open("/proc/cpuinfo", "r") as wl:
for line in wl:
2022-11-24 20:15:22 +01:00
if line.lower().find("raspberry") > 0:
2022-11-15 15:57:59 +01:00
return True
return False
2022-11-24 20:15:22 +01:00
2022-11-05 20:05:09 +01:00
def led_init():
'''
Set ACT and PWR leds trigger and turn them off
'''
2022-10-24 19:57:39 +02:00
os.system('echo none | sudo tee /sys/class/leds/led0/trigger')
os.system('echo none | sudo tee /sys/class/leds/led1/trigger')
2022-11-05 20:05:09 +01:00
led_set(0, 0)
led_set(1, 0)
2022-11-24 20:15:22 +01:00
2022-11-05 20:05:09 +01:00
def led_set(led_id, state):
'''
Set led with id led_id to state.
'''
# led_id : 0 = PWR, 1 = ACT
# state : 0 = off, 1 = on
os.system("echo {} | sudo tee /sys/class/leds/led{}/brightness".format(str(state), str(led_id)))
2022-11-24 20:15:22 +01:00
2022-11-05 20:05:09 +01:00
def blink_pi(n):
'''
Blink ACT and PWR leds altenatively n times to allow physical identification.
'''
for i in range(n):
led_set(0, 1)
led_set(1, 0)
2022-10-06 11:47:21 +02:00
time.sleep(.2)
2022-11-05 20:05:09 +01:00
led_set(0, 0)
led_set(1, 1)
2022-10-06 11:47:21 +02:00
time.sleep(.2)
2022-10-24 19:42:11 +02:00
# restore default behavior
2022-11-05 20:05:09 +01:00
led_set(0, 0)
led_set(1, 0)
2022-10-06 11:47:21 +02:00
return "OK"
2022-11-24 20:15:22 +01:00
2022-11-05 20:05:09 +01:00
def thread_blink():
'''
Blink leds as a thread to avoid blocking.
'''
th = threading.Thread(target=blink_pi, args=(16,))
2022-10-25 12:50:56 +02:00
th.start()
2022-11-08 15:28:53 +01:00
2022-11-24 20:15:22 +01:00
2022-11-08 15:28:53 +01:00
def list_media_files(folder):
'''
List files in folder which extension is allowed (exists in media_exts).
'''
if os.path.exists(folder):
2022-11-24 20:15:22 +01:00
files = os.listdir(folder)
2022-11-08 15:28:53 +01:00
medias = []
for fd in files:
if len(fd.split('.')) > 1:
if fd.split('.')[1] in media_exts:
medias.append(fd)
return medias
else:
return []
2022-11-24 20:15:22 +01:00
def generate_thumbnails():
media_files = list_media_files(upload_folder)
for media in media_files:
subprocess.call(['ffmpeg', '-i', upload_folder + "/" + media, '-q:v', '30', '-s' , '160x120' , '-vf' , 'boxblur=2' , '-ss', '00:00:01.000', '-vframes', '1', thumbnails_folder + "/" + media + ".jpg", "-y"])
2022-10-06 11:47:21 +02:00
@app.route("/")
@auth.login_required
def main():
2022-11-03 14:42:17 +01:00
return _("Nothing to see here !")
2022-10-06 11:47:21 +02:00
2022-11-24 20:15:22 +01:00
2022-10-06 11:47:21 +02:00
@app.route("/rssi")
@auth.login_required
2022-10-25 12:50:56 +02:00
def rssi():
2022-11-05 20:05:09 +01:00
return get_RSSI()
2022-10-06 11:47:21 +02:00
2022-11-24 20:15:22 +01:00
2022-10-06 11:47:21 +02:00
@app.route("/blink")
@auth.login_required
def blink():
2022-11-15 17:02:38 +01:00
if running_on_rpi():
thread_blink()
2022-11-03 14:42:17 +01:00
return _("Blinkin")
2022-10-06 11:47:21 +02:00
2022-11-24 20:15:22 +01:00
2022-10-06 11:47:21 +02:00
@app.route("/reboot")
@auth.login_required
def reboot():
stdout = subprocess.run(["sudo", "/usr/sbin/reboot"], capture_output=True)
print(stdout)
2022-11-03 14:42:17 +01:00
return _("Rebooting...")
2022-10-06 11:47:21 +02:00
2022-11-24 20:15:22 +01:00
2022-10-06 11:47:21 +02:00
@app.route("/poweroff")
@auth.login_required
def shutdown():
stdout = subprocess.run(["sudo", "/usr/sbin/poweroff"], capture_output=True)
print(stdout)
2022-11-03 14:42:17 +01:00
return _("Shutting down...")
2022-10-06 11:47:21 +02:00
2022-10-19 15:14:43 +02:00
# File upload
2022-11-24 20:15:22 +01:00
2022-10-19 15:14:43 +02:00
@app.route('/upload', methods=['GET', 'POST'])
@auth.login_required
2022-11-08 16:55:32 +01:00
def upload_file(over_write=1):
if debug:
print("Existing files : {}".format(str(list_media_files(upload_folder))))
2022-11-05 20:05:09 +01:00
if request.method == "POST":
# Check if the post request has the file part
if "file" not in request.files:
2022-11-03 14:42:17 +01:00
return _("No file part: {}").format(str(request.files))
2022-11-05 20:05:09 +01:00
file = request.files["file"]
2022-10-19 15:14:43 +02:00
# If the user does not select a file, the browser submits an
# empty file without a filename.
2022-11-05 20:05:09 +01:00
if file.filename == "":
2022-11-03 14:42:17 +01:00
return _("No selected file")
2022-11-05 20:05:09 +01:00
if file and allowed_ext(file.filename):
2022-11-08 15:28:53 +01:00
if debug:
2022-11-08 16:55:32 +01:00
print("Uploading file {} in {}.".format(str(file.filename.strip("/")), upload_folder))
if (file.filename.strip("/") not in list_media_files(upload_folder)) and over_write:
2022-11-08 15:28:53 +01:00
filename = secure_filename(file.filename)
file.save(os.path.join(upload_folder, filename))
return _("File saved in {}").format(upload_folder)
2022-11-08 16:55:32 +01:00
if debug:
print("File exists, skipping...")
2022-11-08 15:28:53 +01:00
return "File exists, skipping..."
2022-10-19 15:14:43 +02:00
return "OK"
2022-11-24 20:15:22 +01:00
@app.route("/thumb/<media>")
@auth.login_required
def get_thumbnail(media):
2022-11-24 20:19:27 +01:00
if media and os.path.exists(thumbnails_folder + os.sep + media):
return send_file(thumbnails_folder + os.sep + media + ".jpg", mimetype='image/jpg')
2022-11-24 20:15:22 +01:00
2022-10-06 11:47:21 +02:00
if __name__ == '__main__':
2022-11-24 20:15:22 +01:00
generate_thumbnails()
2022-10-25 12:50:56 +02:00
# Turn ACT and POW leds off on start
2022-11-15 15:57:59 +01:00
if running_on_rpi():
led_init()
# ~ app.run()
serve(app, host='127.0.0.1', port=5000, url_scheme=HTTP_url_scheme)