Compare commits
38 Commits
bb7e12a561
...
0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 277ff32b5d | |||
| 4a1b881d7b | |||
| ef6db806da | |||
| c231e38ade | |||
| bceaee1a10 | |||
| 8566eef924 | |||
| bbb0ed4a82 | |||
|
b41f00f412
|
|||
|
1bdd24d2dd
|
|||
| 0a431558da | |||
| 5b8bc067ca | |||
| 4df0516180 | |||
| 9359c8e503 | |||
| bcb36da020 | |||
| 3aa0bc7f1b | |||
| 10080e36f1 | |||
| 5c35a8586c | |||
| 5d99e78dea | |||
| cd663087c8 | |||
| 07e444c3b4 | |||
| 214d3502c0 | |||
|
|
27e8518be3 | ||
|
|
0e6fd73ee8 | ||
|
|
1d40830066 | ||
| a1de0af0b2 | |||
|
|
6841245187 | ||
| a5df05c463 | |||
| 7ca6878d0d | |||
| 980d12613c | |||
| f43a66275b | |||
| 3393290df2 | |||
| cd12dbc792 | |||
| 5b28213075 | |||
| e82672b8cb | |||
| 4fea7c1e86 | |||
| be3770956c | |||
| 5a0cc6011b | |||
| 81a99b6a80 |
1
.gitignore
vendored
@@ -62,6 +62,7 @@ db.sqlite3
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
src/static/uploads
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
47
README.md
@@ -1,48 +1,49 @@
|
||||
# Little Prynter
|
||||
---
|
||||
|
||||
> Print out shit from the cloud.
|
||||
<img src="src/static/images/little-printer_banner.png" style="padding:auto">
|
||||
|
||||

|
||||
[CC-BY oomlout](https://commons.wikimedia.org/wiki/File:TPRI-01_(14335248671).jpg)
|
||||
> Print out shit from the cloud on a thermal paper.
|
||||
|
||||
## About
|
||||
|
||||
This project started when I got a Thermal Printer from a friend. I don't really know if you can do anything more, but I guess it's fun.
|
||||
|
||||
This project started when I got a Thermal Printer from a friend. It's now evolved to a complete web solution to print out text and images.
|
||||
|
||||
## Requirements
|
||||
|
||||
To make this project work, you will need :
|
||||
- A Thermal Printer :
|
||||
- I used Adafruit's thermal printer at first, but it broke down. You can get it [here](https://www.adafruit.com/product/597).
|
||||
- I then used a EPSON TM-T2OIII. It's expensive, but it's also high quality, and has better CUPS and specific library support.
|
||||
- I used *Adafruit's thermal printer* at first, but it broke down. You can get it [here](https://www.adafruit.com/product/597).
|
||||
- I then used an *EPSON TM-T2OIII*. It's expensive, but it's also high quality, and has better CUPS and specific library support.
|
||||
- A Raspberry Pi or any computer with USB or Serial.
|
||||
- Some electric wires.
|
||||
- Some knowledge of the command line,
|
||||
- Some knowledge of Python.
|
||||
- 3h of your time, 5h if things need debugging.
|
||||
- `git`, `virtualenv`,`pip` and `python` >= 3.8.6.
|
||||
- A webcam for the webcam page to work. Will work on a smartphone. Not required.
|
||||
|
||||
## Installation
|
||||
## Context
|
||||
|
||||
For the EPSON TM-T20III, you can get the CUPS driver from [here](https://download.epson-biz.com/modules/pos/index.php?page=soft&scat=32). It's not specific to the printer I've been using, so you can try with other printers.
|
||||
|
||||
With that, you can try out your printer and print normal text, images or pdf documents for example. LittlePrynter itself does not require any other software than the ones installed with it, i.e the ones listed in the `requirements.txt` file.
|
||||
|
||||
|
||||
|
||||
For the Adafruit printer, start by following the guide [here](https://learn.adafruit.com/networked-thermal-printer-using-cups-and-raspberry-pi) to install the CUPS software needed to print images. If you want, you can install it via the command line, [following this guide](https://help.ubuntu.com/lts/serverguide/cups.html).
|
||||
|
||||
You can also get some information from [here](https://learn.adafruit.com/mini-thermal-receipt-printer) and [here](https://learn.adafruit.com/instant-camera-using-raspberry-pi-and-thermal-printer) if you're stuck.
|
||||
|
||||
Then, setup the project :
|
||||
The version for the EPSON TM-T20III uses a library called `python-escpos`, which doesn't need a CUPS driver or anything else. It's included in the Python dependencies.
|
||||
|
||||
The project only supports the EPSON printer, but you can try to adapt it for other printers using the `adafruit-thermal` branch, but I won't offer support for it.
|
||||
|
||||
### Install & setup the project :
|
||||
```
|
||||
git clone https://git.n07070.xyz/n07070/LittlePrynter
|
||||
virtualenv LittlePrynter
|
||||
cd LittlePrynter
|
||||
source bin/activate
|
||||
pip install -r requirements.txt
|
||||
$ git clone https://git.n07070.xyz/n07070/LittlePrynter
|
||||
$ virtualenv LittlePrynter
|
||||
$ cd LittlePrynter
|
||||
$ source bin/activate
|
||||
$ pip install -r requirements.txt
|
||||
```
|
||||
|
||||
> tip : when you're done, you can get out of the virtualenv either by closing your terminal, or by running `deactivate`.
|
||||
@@ -52,14 +53,24 @@ You should see a folder named `configuration`. Enter it, and duplicate the file
|
||||
You can now start the web server with
|
||||
|
||||
```
|
||||
export FLASK_APP=main.py
|
||||
flask run
|
||||
$ export FLASK_APP=src/main.py
|
||||
$ flask run
|
||||
```
|
||||
|
||||
This command should start a web server with which you can test your configuration. If you plan on exposing your printer to the Internet, and give it an IP / URL, _please, please, please_, don't run it this way. Look at Flask's documentation and read about running a production server. It's a little more work, but it will prevent your computer/server being hacked in too easily.
|
||||
|
||||
Voilà !
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
> The first page. You can print a picture, or a short message. It's basically exposing the API in html.
|
||||
|
||||

|
||||
> Using the webcam via Javascript, you can print out a picture from your phone, webcam, or any other video device.
|
||||
|
||||

|
||||
|
||||
## More
|
||||
|
||||
If you liked this project, feel free to support my work !
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
[printer]
|
||||
vendor_id = 0x04b8
|
||||
device_id = 0x0e28
|
||||
upload_folder = "src/static/uploads"
|
||||
|
||||
# Users = Password
|
||||
[users]
|
||||
|
||||
|
Before Width: | Height: | Size: 20 KiB |
@@ -1,13 +1,31 @@
|
||||
Adafruit-Thermal>=1.1.0
|
||||
Click>=7.0
|
||||
Flask>=1.0.2
|
||||
Flask-Limiter>=1.0.1
|
||||
itsdangerous>=0.24
|
||||
Jinja2>=2.10
|
||||
limits>=1.3
|
||||
MarkupSafe>=1.0
|
||||
Pillow>=5.3.0
|
||||
pyserial>=3.4
|
||||
six>=1.11.0
|
||||
Unidecode>=1.0.22
|
||||
Werkzeug>=0.14.1
|
||||
Adafruit-Thermal~=1.1.0
|
||||
appdirs~=1.4.4
|
||||
argcomplete~=2.0.0
|
||||
click~=8.1.3
|
||||
commonmark~=0.9.1
|
||||
Deprecated~=1.2.13
|
||||
escpos~=1.9
|
||||
Flask~=2.1.2
|
||||
Flask-Limiter~=2.4.5.1
|
||||
future~=0.18.2
|
||||
itsdangerous~=2.1.2
|
||||
Jinja2~=3.1.2
|
||||
limits~=2.6.1
|
||||
MarkupSafe~=2.1.1
|
||||
packaging~=21.3
|
||||
Pillow~=9.1.0
|
||||
Pygments~=2.12.0
|
||||
pyparsing~=3.0.8
|
||||
pyserial~=3.5
|
||||
python-barcode~=0.13.1
|
||||
pyusb~=1.2.1
|
||||
PyYAML~=6.0
|
||||
qrcode~=7.3.1
|
||||
rich~=12.4.1
|
||||
six~=1.16.0
|
||||
toml~=0.10.2
|
||||
typing_extensions~=4.2.0
|
||||
Unidecode~=1.3.4
|
||||
viivakoodi~=0.8.0
|
||||
Werkzeug~=2.1.2
|
||||
wrapt~=1.14.1
|
||||
|
||||
7
run.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
virtualenv .
|
||||
|
||||
pip install -r requirements.txt
|
||||
|
||||
export FLASK_APP=src/main.py
|
||||
export FLASK_ENV=development
|
||||
flask run --host 192.168.0.42 --debugger --eager-loading
|
||||
98
src/main.py
@@ -18,30 +18,40 @@ import time # To sleep
|
||||
import os # For VARS from the shell.
|
||||
# Variables
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Load the configuration file
|
||||
try:
|
||||
app.logger.debug("Loading config file...")
|
||||
configuration_file = toml.load("configuration/config.toml")
|
||||
except TypeError :
|
||||
print("Unable to load the config file: invalid type or is a list containing invalid types")
|
||||
app.logger.error("Unable to load the config file: invalid type or is a list containing invalid types")
|
||||
exit(-1)
|
||||
except toml.TomlDecodeError:
|
||||
print("An error occured while decoding the file")
|
||||
app.logger.error("An error occured while decoding the file")
|
||||
exit(-1)
|
||||
except Exception as e:
|
||||
print("Error while loading file : " + str(e))
|
||||
app.logger.error("Error while loading file : " + str(e))
|
||||
exit(-1)
|
||||
|
||||
app.logger.debug("Config file loaded !")
|
||||
# Define the USB connections here.
|
||||
vendor_id = configuration_file["printer"]["vendor_id"]
|
||||
device_id = configuration_file["printer"]["device_id"]
|
||||
UPLOAD_FOLDER = str(configuration_file["printer"]["upload_folder"])
|
||||
|
||||
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
|
||||
|
||||
# Output the config file
|
||||
if os.getenv('LIPY_DEBUG') == True:
|
||||
pprint.pprint(configuration_file)
|
||||
|
||||
# We define the app module used by Flask
|
||||
app = Flask(__name__)
|
||||
app.secret_key = configuration_file["secrets"]["flask_secret_key"]
|
||||
|
||||
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||||
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS
|
||||
app.config['MAX_CONTENT_LENGTH'] = 3 * 1000 * 1000 # Maximum 3Mb for a file upload
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||
|
||||
# Printer connection
|
||||
# Uses the class defined in the printer.py file
|
||||
@@ -55,14 +65,21 @@ web = Web(app, printer)
|
||||
limiter = Limiter(
|
||||
app,
|
||||
key_func=get_remote_address,
|
||||
default_limits=["200 per day", "50 per hour"]
|
||||
default_limits=["1500 per day", "500 per hour"]
|
||||
)
|
||||
|
||||
@app.route('/')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def index():
|
||||
app.logger.debug("Loading index")
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route('/webcam')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def webcam():
|
||||
app.logger.debug("Loading webcam interface")
|
||||
return render_template('webcam.html')
|
||||
|
||||
# API routes
|
||||
# The api has the following methods
|
||||
# api/print/{sms,img,letter,qr,barcode}
|
||||
@@ -74,46 +91,93 @@ def index():
|
||||
@app.route('/api/print')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def api_index():
|
||||
app.logger.debug("Loading API")
|
||||
return render_template("api.html")
|
||||
|
||||
|
||||
@app.route('/api/print/sms', methods=['POST'])
|
||||
@limiter.limit("2/minute", override_defaults=False)
|
||||
@limiter.limit("6/minute", override_defaults=False)
|
||||
def api_print_sms():
|
||||
app.logger.debug("Printing an sms")
|
||||
try:
|
||||
txt = request.form["txt"]
|
||||
sign = request.form["signature"]
|
||||
except Exception as e:
|
||||
flash(e)
|
||||
flash(e,'error')
|
||||
redirect(url_for('index'))
|
||||
|
||||
flash(web.print_sms(txt,sign))
|
||||
try:
|
||||
web.print_sms(txt,sign)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
return redirect(url_for('index'))
|
||||
|
||||
@app.route('/api/print/image', methods=['POST'])
|
||||
@limiter.limit("2/minute", override_defaults=False)
|
||||
@app.route('/api/print/img', methods=['POST'])
|
||||
@limiter.limit("6/minute", override_defaults=False)
|
||||
def api_print_image():
|
||||
flash(web.print_image())
|
||||
return "print image"
|
||||
app.logger.debug("Printing an image")
|
||||
|
||||
try:
|
||||
sign = request.form["signature"]
|
||||
except Exception as e:
|
||||
flash(str(e),'error')
|
||||
app.logger.error(str(e) + " - Whoops, no forms submitted or missing signature.")
|
||||
return redirect(url_for('index'))
|
||||
|
||||
if request.method == 'POST':
|
||||
# check if the post request has the file part
|
||||
try:
|
||||
if 'img' not in request.files:
|
||||
flash('No file found. Did you use the good form ?', 'error')
|
||||
app.logger.error("No file found. Did you use the good form ?")
|
||||
return redirect(url_for("index"))
|
||||
else:
|
||||
file = request.files['img']
|
||||
except Exception as e:
|
||||
if sign is not None and photo is not None:
|
||||
pass
|
||||
else:
|
||||
flash(str(e), 'error')
|
||||
app.logger.error("Couldn't get an image nor signature : " + str(e))
|
||||
|
||||
# If the user does not select a file, the browser submits an
|
||||
# empty file without a filename.
|
||||
if file.filename == '':
|
||||
app.logger.error("Submitted file has no filename !")
|
||||
flash('No file submitted, please select a file','error')
|
||||
return redirect(url_for("index"))
|
||||
|
||||
try:
|
||||
app.logger.debug("Sending the image to the printer.")
|
||||
web.print_image(file, sign)
|
||||
except Exception as e:
|
||||
pass
|
||||
else:
|
||||
flash('Cannot access to page with this method.','error')
|
||||
app.logger.debug('Bad access type to this API.')
|
||||
|
||||
return redirect(url_for("index"))
|
||||
|
||||
@app.route('/login')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def login_page():
|
||||
# web.login(username,password)
|
||||
return render_template("index.html")
|
||||
return redirect(url_for("index"))
|
||||
|
||||
@app.route('/logout')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def logout_page():
|
||||
# web.logout(username, password)
|
||||
return render_template("index.html")
|
||||
return redirect(url_for("index"))
|
||||
|
||||
@app.errorhandler(429)
|
||||
def ratelimit_handler(e):
|
||||
flash("Rate limit reached, please slow down :) ( Currently at "+ e.description + ")", 'error')
|
||||
return render_template('index.html')
|
||||
return redirect(url_for("index"))
|
||||
|
||||
@app.route("/ping")
|
||||
@limiter.exempt
|
||||
def ping():
|
||||
return "PONG"
|
||||
flash("🏓 Pong !",'info')
|
||||
return redirect(url_for("index"))
|
||||
|
||||
@@ -3,6 +3,7 @@ from flask import flash
|
||||
from escpos.printer import Usb, USBNotFoundError
|
||||
from time import sleep, gmtime, strftime
|
||||
import os.path
|
||||
from PIL import Image
|
||||
|
||||
|
||||
class Printer(object):
|
||||
@@ -120,29 +121,58 @@ class Printer(object):
|
||||
return False
|
||||
|
||||
if not os.getenv('LIPY_DEBUG') == True:
|
||||
self.printer.open(self.usb_args);
|
||||
self.printer.set(align='left', font='a', bold=False, underline=0, width=1, height=1, density=8, invert=False, smooth=True, flip=False, double_width=False, double_height=False, custom_size=False)
|
||||
self.printer.textln(clean_msg)
|
||||
self.printer.set(align='left', font='b', bold=False, underline=1, width=1, height=1, density=9, invert=False, smooth=True, flip=False, double_width=False, double_height=False, custom_size=False)
|
||||
self.printer.textln("> " + clean_signature + " @ " + strftime("%Y-%m-%d %H:%M:%S", gmtime()))
|
||||
self.printer.cut()
|
||||
self.printer.close()
|
||||
try:
|
||||
self.printer.open(self.usb_args);
|
||||
self.printer.set(align='left', font='a', bold=False, underline=0, width=1, height=1, density=8, invert=False, smooth=True, flip=False, double_width=False, double_height=False, custom_size=False)
|
||||
self.printer.textln(clean_msg)
|
||||
self.printer.set(align='left', font='b', bold=False, underline=1, width=1, height=1, density=9, invert=False, smooth=True, flip=False, double_width=False, double_height=False, custom_size=False)
|
||||
self.printer.textln("> " + clean_signature + " @ " + strftime("%Y-%m-%d %H:%M:%S", gmtime()))
|
||||
self.printer.cut()
|
||||
self.printer.close
|
||||
except Exception as e:
|
||||
flash("Unable to print because : " + e)
|
||||
|
||||
flash("Message printed : " + clean_msg ,category='info')
|
||||
return True
|
||||
|
||||
def print_img(self, path):
|
||||
def print_img(self, path, sign):
|
||||
clean_signature = str(sign)
|
||||
|
||||
if os.path.isfile(str(path)):
|
||||
pass
|
||||
else:
|
||||
if not os.path.isfile(str(path)):
|
||||
self.app.logger.warning("File does not exist : " + str(path))
|
||||
flash('The file path for this image :' + str(path) + " wasn't found. Please try again.", 'error')
|
||||
return False
|
||||
else:
|
||||
self.app.logger.debug("Printing file from " + str(path))
|
||||
|
||||
|
||||
|
||||
try:
|
||||
self.app.logger.debug("Resizing the image")
|
||||
with Image.open(path) as im:
|
||||
|
||||
basewidth = 575
|
||||
img = Image.open(path)
|
||||
wpercent = (basewidth/float(img.size[0]))
|
||||
hsize = int((float(img.size[1])*float(wpercent)))
|
||||
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
|
||||
if img.height > 1000:
|
||||
flash("Image is too long, sorry ! Keep it below 500×1000 pixels.",'error')
|
||||
return False
|
||||
img.save(path)
|
||||
except Exception as e:
|
||||
flash(str(e))
|
||||
self.app.logger.error(str(e))
|
||||
|
||||
try:
|
||||
self.printer.open(self.usb_args)
|
||||
self.printer.textln("> " + clean_signature + " @ " + strftime("%Y-%m-%d %H:%M:%S", gmtime()))
|
||||
self.printer.image(path)
|
||||
self.printer.cut()
|
||||
self.printer.close()
|
||||
self.app.logger.debug("Printed an image : " + str(path))
|
||||
return True
|
||||
except Exception as e:
|
||||
self.printer.close()
|
||||
return e
|
||||
else:
|
||||
self.app.logging.debug("Printed an image : " + str(path))
|
||||
flash(str(e),'error')
|
||||
return False
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
body {
|
||||
/* body {
|
||||
margin-left: 20%;
|
||||
margin-right: 20%;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-top: 3em;
|
||||
}
|
||||
} */
|
||||
|
||||
/*// Small devices (landscape phones, 576px and up)*/
|
||||
@media (min-width: 576px) {
|
||||
@@ -14,8 +10,8 @@ button {
|
||||
|
||||
/*// Medium devices (tablets, 768px and up)*/
|
||||
@media (min-width: 768px) {
|
||||
margin-left: 0%;
|
||||
margin-right: 0%;
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
/*// Large devices (desktops, 992px and up)*/
|
||||
|
||||
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 280 KiB |
|
Before Width: | Height: | Size: 82 KiB |
|
Before Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 236 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 149 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 207 KiB |
|
Before Width: | Height: | Size: 83 KiB |
BIN
src/static/images/homepage.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
src/static/images/little-printer_banner.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
src/static/images/photomaton.png
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
src/static/images/result.jpg
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
275
src/static/js/webcam.js
Normal file
@@ -0,0 +1,275 @@
|
||||
let streaming;
|
||||
var current_stream;
|
||||
var current_camera_is;
|
||||
|
||||
var width = document.getElementById("video").parentNode.parentElement.clientWidth;
|
||||
var height = width / (4 / 3);
|
||||
|
||||
function startup(){
|
||||
video = document.getElementById('video');
|
||||
canvas = document.getElementById('canvas');
|
||||
photo = document.getElementById('photo');
|
||||
switch_cameras = document.getElementById('flip')
|
||||
printButton = document.getElementById('print_button');
|
||||
|
||||
if (check_webcam() === true ){
|
||||
setup_events();
|
||||
clear_canvas();
|
||||
} else {
|
||||
no_webcam_error();
|
||||
console.log("Seems like it's impossible to get a webcam.");
|
||||
}
|
||||
}
|
||||
|
||||
function check_webcam(){
|
||||
console.log("Cheking for a camera...");
|
||||
if (get_front_webcam()) {
|
||||
console.log("Got front camera !");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (get_any_webcam()) {
|
||||
console.log("Got a webcam !");
|
||||
return true;
|
||||
}
|
||||
console.log("Nope");
|
||||
return false;
|
||||
}
|
||||
|
||||
function setup_events(){
|
||||
|
||||
// When the video is ready, we start streaming it to the canvas.
|
||||
// The canvas is hidden, but it still exists in the browser.
|
||||
video.addEventListener('canplay', function(ev) {
|
||||
if (!streaming) {
|
||||
height = video.videoHeight / (video.videoWidth / width);
|
||||
|
||||
if (isNaN(height)) {
|
||||
height = width / (4 / 3);
|
||||
}
|
||||
|
||||
video.setAttribute('width', width);
|
||||
video.setAttribute('height', height);
|
||||
canvas.setAttribute('width', width);
|
||||
canvas.setAttribute('height', height);
|
||||
|
||||
photo.setAttribute('width', width);
|
||||
photo.setAttribute('height', height);
|
||||
|
||||
|
||||
streaming = true;
|
||||
printButton.removeAttribute("disabled","");
|
||||
switch_cameras.removeAttribute("disabled","");
|
||||
|
||||
|
||||
}
|
||||
}, false);
|
||||
|
||||
switch_cameras.addEventListener('click', function(ev) {
|
||||
flip_cameras();
|
||||
}, false );
|
||||
|
||||
printButton.addEventListener('click', function(ev){
|
||||
data = take_picture();
|
||||
try {
|
||||
print_picture(data);
|
||||
} catch (e) {
|
||||
alert("Failed to print a picture because : " + e);
|
||||
}
|
||||
|
||||
ev.preventDefault();
|
||||
}, false);
|
||||
|
||||
}
|
||||
|
||||
function clear_canvas() {
|
||||
var context = canvas.getContext('2d');
|
||||
context.fillStyle = "#AAA";
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
var data = canvas.toDataURL('image/png');
|
||||
photo.setAttribute('src', data);
|
||||
}
|
||||
|
||||
function dataURLtoFile(dataurl, filename) {
|
||||
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
|
||||
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
|
||||
while(n--){
|
||||
u8arr[n] = bstr.charCodeAt(n);
|
||||
}
|
||||
return new File([u8arr], filename, {type:mime});
|
||||
}
|
||||
|
||||
function take_picture(){
|
||||
var context = canvas.getContext('2d');
|
||||
if (width && height) {
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
context.drawImage(video, 0, 0, width, height);
|
||||
|
||||
var data = canvas.toDataURL('image/png');
|
||||
photo.setAttribute('src', data);
|
||||
} else {
|
||||
clear_canvas();
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function print_picture(data){
|
||||
var url = "/api/print/img"
|
||||
var picture = dataURLtoFile(data);
|
||||
const formData = new FormData();
|
||||
let currentDate = new Date();
|
||||
let time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
|
||||
|
||||
formData.set("img", picture, "picture.png");
|
||||
formData.set("signature", "Printed via the webcam @ " + time)
|
||||
|
||||
fetch(url, {
|
||||
method: 'POST', // or 'PUT'
|
||||
body: formData,
|
||||
// headers:{
|
||||
// 'Content-Type': 'multipart/form-data'
|
||||
// }
|
||||
}).then(function(response) { console.log('Success:', response); alert("Picture printed."); } , true)
|
||||
.catch(error => console.error('Error:', error), false);
|
||||
|
||||
}
|
||||
|
||||
function flip_cameras(){
|
||||
switch (current_camera_is) {
|
||||
case "front":
|
||||
try {
|
||||
get_any_webcam();
|
||||
} catch (e) {
|
||||
console.log("Could not get another camera");
|
||||
get_front_webcam();
|
||||
}
|
||||
break;
|
||||
case "any":
|
||||
try {
|
||||
get_front_webcam();
|
||||
} catch (e) {
|
||||
console.log("Could not get another camera");
|
||||
get_any_webcam();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
console.log("Impossible to switch cameras : none is selected.");
|
||||
}
|
||||
}
|
||||
|
||||
function stop_video_streams(){
|
||||
console.log("Stopping existing video streams.");
|
||||
// Stop the tracks
|
||||
try {
|
||||
if (current_stream) {
|
||||
const tracks = current_stream.getTracks();
|
||||
tracks.forEach(track => track.stop());
|
||||
console.log("Stopped playing current videostreams.");
|
||||
return true;
|
||||
} else {
|
||||
console.log("No streams currently playing.");
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Could not stop playing current streams." + e);
|
||||
}
|
||||
}
|
||||
|
||||
async function get_webcam(options){
|
||||
stop_video_streams();
|
||||
|
||||
try {
|
||||
await navigator.mediaDevices.getUserMedia(options)
|
||||
.then(function(stream) {
|
||||
// on success, stream it in video tag
|
||||
// the video tag is hidden, as is the canvas.
|
||||
console.log("Got a camera ( generic )");
|
||||
|
||||
printButton.removeAttribute("disabled","");
|
||||
current_stream = stream;
|
||||
video.srcObject = stream;
|
||||
video.play();
|
||||
return true;
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.log("Didn't manage to get a camera :" + err);
|
||||
return false;
|
||||
});
|
||||
} catch (err) {
|
||||
console.log("Didn't manage to get a camera :" + err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function get_any_webcam(){
|
||||
var camera_options = {
|
||||
video: {
|
||||
facingMode: 'environment', // Or 'environment' if we want a camera facing away
|
||||
},
|
||||
audio: false
|
||||
};
|
||||
|
||||
if(get_webcam(camera_options)){
|
||||
console.log("Got any camera, or environment camera.");
|
||||
current_camera_is = "any";
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function get_front_webcam(){
|
||||
// We try to start with the front facing camera,
|
||||
// if we have no support, we switch back to a normal camera.
|
||||
try {
|
||||
const supports = navigator.mediaDevices.getSupportedConstraints();
|
||||
if (!supports['facingMode']) {
|
||||
throw new Error("This browser does not support facingMode!");
|
||||
} else {
|
||||
var camera_options = {
|
||||
video: {
|
||||
facingMode: 'user', // Or 'environment' if we want a camera facing away
|
||||
},
|
||||
audio: false
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Resetting to default camera : " + e);
|
||||
var camera_options = {
|
||||
video: true,
|
||||
audio: false
|
||||
};
|
||||
}
|
||||
|
||||
if(get_webcam(camera_options)){
|
||||
console.log("Got the front camera");
|
||||
current_camera_is = "front";
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function no_webcam_error(){
|
||||
console.log("Seems like they is no webcam available.")
|
||||
|
||||
// We disable the print button is it cannot be clicked.
|
||||
printButton.setAttribute("disabled","");
|
||||
|
||||
// We create an alert message.
|
||||
const frame_div = document.getElementById("image_dither");
|
||||
frame_div.removeAttribute('class');
|
||||
|
||||
const alert_div = document.createElement("div");
|
||||
alert_div.setAttribute("class", "alert alert-warning");
|
||||
alert_div.setAttribute("role", "alert");
|
||||
|
||||
var alert_message = document.createTextNode("We where unable to get a Webcam device, this page will not work.");
|
||||
alert_div.appendChild(alert_message);
|
||||
frame_div.appendChild(alert_div);
|
||||
throw new Error("Unable to get a video device, stopping the photobooth.");
|
||||
}
|
||||
|
||||
window.addEventListener('load', startup, false);
|
||||
|
Before Width: | Height: | Size: 8.7 KiB |
21
src/templates/banner.html
Normal file
@@ -0,0 +1,21 @@
|
||||
<body class="container">
|
||||
<div class="col-md-7 offset-md-2">
|
||||
<a href="/"><img class="rounded" width="100px" src="{{ url_for('static', filename='images/little-printer.png') }}" alt="LittlePrynter icon"></a><h1 class="card-title font-weight-bold">Little Prynter</h1>
|
||||
<hr>
|
||||
<div class="alert alert-dark" role="alert">LittlePrynter is under heavy developpement, you may encounter bugs ! If so, try again. Thanks !</div>
|
||||
<br>
|
||||
{% with messages = get_flashed_messages(category_filter=('error')) %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-danger" role="alert">⚠️ {{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
{% with messages = get_flashed_messages(category_filter=('info')) %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-info" role="alert">ℹ️ {{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
59
src/templates/base.html
Normal file
@@ -0,0 +1,59 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LittlePrynter</title>
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
|
||||
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
|
||||
</head>
|
||||
<body class="container">
|
||||
<div class="col-auto">
|
||||
<a href="/"><img class="rounded" width="100px" src="{{ url_for('static', filename='images/little-printer.png') }}" alt="LittlePrynter icon"></a><h1 class="card-title font-weight-bold">Little Prynter</h1>
|
||||
<hr>
|
||||
<nav class="navbar navbar-expand-lg navbar-light bg-light">
|
||||
<div class="container-fluid">
|
||||
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link active" aria-current="page" href="/">Home</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/webcam">Webcam</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<br>
|
||||
|
||||
<div class="alert alert-dark" role="alert">LittlePrynter is under heavy developpement, you may encounter bugs ! If so, try again. Thanks !</div>
|
||||
<br>
|
||||
{% with messages = get_flashed_messages(category_filter=('error')) %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-danger" role="alert">⚠️ {{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
{% with messages = get_flashed_messages(category_filter=('info')) %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-info" role="alert">ℹ️ {{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
|
||||
{% block content %}
|
||||
|
||||
|
||||
{% endblock %}
|
||||
<hr>
|
||||
|
||||
<footer class="row">
|
||||
<p class=" text-center">Little Prynter is built by <a href="https://n07070.xyz/about-me/">n07070</a> because it's fun :) | <a href="https://git.n07070.xyz/n07070/littleprynter">Source code - AGPLv3</a></p>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
5
src/templates/footer.html
Normal file
@@ -0,0 +1,5 @@
|
||||
<hr>
|
||||
<footer>Little Prynter is built by <a href="https://n07070.xyz/about-me/">n07070</a> because it's fun :) | <a href="https://git.n07070.xyz/n07070/littleprynter/src/branch/epson-tm-t20iii">Source code - AGPLv3</a></footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
10
src/templates/header.html
Normal file
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LittlePrynter</title>
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
|
||||
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
|
||||
</head>
|
||||
@@ -1,60 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LittlePrynter</title>
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
|
||||
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
|
||||
</head>
|
||||
<body class="container">
|
||||
<div class="col-md-6 offset-md-3">
|
||||
<img class="rounded" width="100px" src="{{ url_for('static', filename='images/little-printer.png') }}" alt="LittlePrynter icon"><h1 class="card-title font-weight-bold">Little Prynter</h1>
|
||||
<hr>
|
||||
<br>
|
||||
{% with messages = get_flashed_messages(category_filter=('error')) %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-warning" role="alert">{{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% with messages = get_flashed_messages(category_filter=('info')) %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-info" role="alert">{{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
{% block content %}
|
||||
|
||||
<!-- <br>
|
||||
<h3>Imprimer une image aléatoire</h3>
|
||||
<a class="btn btn-primary btn-lg" href="/api/print/image"> Imprimer</a>
|
||||
<hr>
|
||||
<br> -->
|
||||
<div class="card">
|
||||
<h3 class="card-header">Print a short message</h3>
|
||||
<div class="card-body">
|
||||
<div class="card">
|
||||
<h3 class="card-header">Print a short message</h3>
|
||||
<div class="card-body">
|
||||
<form class="form-group" action="/api/print/sms" method="post">
|
||||
<input class="form-control" type="text" name="txt" placeholder="200 chars or less " maxlength="200" required><br>
|
||||
<input class="form-control" type="text" name="signature" placeholder="Signature or pseudo" maxlength="200" required><br>
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="form-group" action="/api/print/sms" method="post">
|
||||
<input class="form-control" type="text" name="txt" placeholder="200 chars or less " maxlength="200"><br>
|
||||
<input class="form-control" type="text" name="signature" placeholder="Signature or pseudo" maxlength="200"><br>
|
||||
<br>
|
||||
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="pbar" style="display:none">
|
||||
<img src="{{ url_for('static',filename='load.gif') }}" alt="loading wheel">
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<br>
|
||||
<br>
|
||||
<hr>
|
||||
<footer>Little Prynter is built for fun by <a href="https://n07070.xyz/about-me/">n07070</a> for fun :) </footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
<div class="card">
|
||||
<h3 class="card-header">Print an image</h3>
|
||||
<div class="card-body">
|
||||
<form enctype="multipart/form-data" class="form-group" action="/api/print/img" method="post">
|
||||
<input class="form-control" type="file" name="img" required><br>
|
||||
<input class="form-control" type="text" name="signature" placeholder="Signature or pseudo" maxlength="200" required><br>
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
0
src/templates/login.html
Normal file
0
src/templates/print.html
Normal file
111
src/templates/webcam.html
Normal file
@@ -0,0 +1,111 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<noscript class="d-block">
|
||||
<div class="alert alert-warning " role="alert">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bug-fill" viewBox="0 0 16 16">
|
||||
<path d="M4.978.855a.5.5 0 1 0-.956.29l.41 1.352A4.985 4.985 0 0 0 3 6h10a4.985 4.985 0 0 0-1.432-3.503l.41-1.352a.5.5 0 1 0-.956-.29l-.291.956A4.978 4.978 0 0 0 8 1a4.979 4.979 0 0 0-2.731.811l-.29-.956z"/>
|
||||
<path d="M13 6v1H8.5v8.975A5 5 0 0 0 13 11h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 1 0 1 0v-.5a1.5 1.5 0 0 0-1.5-1.5H13V9h1.5a.5.5 0 0 0 0-1H13V7h.5A1.5 1.5 0 0 0 15 5.5V5a.5.5 0 0 0-1 0v.5a.5.5 0 0 1-.5.5H13zm-5.5 9.975V7H3V6h-.5a.5.5 0 0 1-.5-.5V5a.5.5 0 0 0-1 0v.5A1.5 1.5 0 0 0 2.5 7H3v1H1.5a.5.5 0 0 0 0 1H3v1h-.5A1.5 1.5 0 0 0 1 11.5v.5a.5.5 0 1 0 1 0v-.5a.5.5 0 0 1 .5-.5H3a5 5 0 0 0 4.5 4.975z"/>
|
||||
</svg>
|
||||
|
||||
This page will need Javascript and your authorization to use the webcam to work. It is not possible because Javascript seems to be deactived on this page.
|
||||
</div>
|
||||
</noscript>
|
||||
|
||||
<div class="card">
|
||||
<h3 class="card-header">Photomaton</h3>
|
||||
<div class="card-body row">
|
||||
|
||||
<canvas id="canvas"></canvas>
|
||||
<video id="video" class="">Video stream not available.</video>
|
||||
|
||||
<div class="container-sm">
|
||||
<div class="row">
|
||||
<button class="col-sm col-lg-3 offset-lg-2 btn btn-primary justify-content-center" name="print_picture" id="print_button" data-bs-toggle="tooltip" data-bs-placement="top" title="Snap & print a picture" disabled="">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="54" height="54" fill="currentColor" class="bi bi-camera" viewBox="0 0 16 16">
|
||||
<path d="M15 12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h1.172a3 3 0 0 0 2.12-.879l.83-.828A1 1 0 0 1 6.827 3h2.344a1 1 0 0 1 .707.293l.828.828A3 3 0 0 0 12.828 5H14a1 1 0 0 1 1 1v6zM2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4H2z"/>
|
||||
<path d="M8 11a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5zm0 1a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7zM3 6.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0z"/>
|
||||
</svg>
|
||||
<b>&</b>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="54" height="54" fill="currentColor" class="bi bi-printer" viewBox="0 0 16 16">
|
||||
<path d="M2.5 8a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1z"/>
|
||||
<path d="M5 1a2 2 0 0 0-2 2v2H2a2 2 0 0 0-2 2v3a2 2 0 0 0 2 2h1v1a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-1h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-1V3a2 2 0 0 0-2-2H5zM4 3a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2H4V3zm1 5a2 2 0 0 0-2 2v1H2a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v-1a2 2 0 0 0-2-2H5zm7 2v3a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="col-sm col-lg-3 offset-lg-2 btn btn-secondary justify-content-center" name="flip" id="flip" data-bs-toggle="tooltip" data-bs-placement="top" title="Change camera" disabled="">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="54" height="54" fill="currentColor" class="bi bi-arrow-repeat" viewBox="0 0 16 16">
|
||||
<path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
|
||||
<path fill-rule="evenodd" d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
<div class="image_dither" id="image_dither">
|
||||
<picture>
|
||||
<img id="photo" class="justify-content-center">
|
||||
</picture>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
This is a as-close-as-possible representation of what is printed on the thermal printer.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<style media="screen">
|
||||
canvas {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* video {
|
||||
display: none;
|
||||
} */
|
||||
|
||||
.image_dither {
|
||||
/* width: 300px;
|
||||
height: 400px; */
|
||||
image-rendering: smooth;
|
||||
filter: saturate(0) contrast(250);
|
||||
}
|
||||
|
||||
picture {
|
||||
image-rendering: smooth;
|
||||
}
|
||||
|
||||
.image_dither > picture::after {
|
||||
content: '';
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
position: fixed;
|
||||
display: block;
|
||||
z-index: 2;
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAOklEQVR4nC3KQQFAQAAAwd0EIohANA0uiiiugQgiiLA+5j0AVBewVa/VUGd1qBNgrR5gqW6r8x+7Oj8/xCBur9LU/wAAAABJRU5ErkJggg==');
|
||||
background-repeat: repeat;
|
||||
}
|
||||
|
||||
|
||||
#photo {
|
||||
background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
|
||||
padding: 0;
|
||||
max-width: 100%;
|
||||
vertical-align: middle;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
<script type="text/javascript" src="{{ url_for('static',filename='js/webcam.js') }}"></script>
|
||||
|
||||
<br>
|
||||
|
||||
{% endblock %}
|
||||
33
src/user.py
@@ -4,3 +4,36 @@ class User(object):
|
||||
def __init__(self, arg):
|
||||
super(User, self).__init__()
|
||||
self.arg = arg
|
||||
|
||||
# @app.route('/login', methods=['POST','GET'])
|
||||
# @limiter.limit("100 per minute", error_message=error_handler_limiter)
|
||||
def login():
|
||||
if request.method == 'POST':
|
||||
if not session.get('logged_in'):
|
||||
if request.form['username'] and request.form['password']:
|
||||
# Get the json
|
||||
with open('users.json') as f:
|
||||
users_file = json.load(f)
|
||||
for user in users_file["users"]:
|
||||
if users_file["users"][user] == request.form['password']:
|
||||
session['logged_in'] = True
|
||||
session['user'] = request.form['username']
|
||||
|
||||
if not session.get('logged_in'):
|
||||
flash('Mot de passe ou pseudo invalide.','danger')
|
||||
return redirect(url_for('login'))
|
||||
else:
|
||||
return redirect(url_for('display_index_page'))
|
||||
else:
|
||||
flash('Incorrect logins')
|
||||
return render_template('password.html')
|
||||
else:
|
||||
return render_template('password.html')
|
||||
else:
|
||||
return render_template('password.html')
|
||||
|
||||
@app.route("/logout")
|
||||
def logout():
|
||||
session['logged_in'] = False
|
||||
flash('Tu est déconnecté', 'info')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
49
src/web.py
@@ -1,4 +1,5 @@
|
||||
from flask import Flask, request
|
||||
from werkzeug.utils import secure_filename
|
||||
from printer import Printer
|
||||
import time
|
||||
import os
|
||||
@@ -13,17 +14,55 @@ class Web(object):
|
||||
|
||||
def print_sms(self, texte, sign: str):
|
||||
# TODO: verify the texte before printing it here ?
|
||||
self.app.logger.debug("Printing : " + str(texte))
|
||||
self.app.logger.debug("Printing : " + str(texte) + " from " + str(sign))
|
||||
if not os.getenv('LIPY_DEBUG'):
|
||||
time.sleep(10)
|
||||
time.sleep(1)
|
||||
|
||||
return self.printer.print_sms(texte, sign)
|
||||
|
||||
def print_image(self, image):
|
||||
pass
|
||||
|
||||
def print_image(self, image, sign: str) -> bool:
|
||||
self.app.logger.debug("Uploading file")
|
||||
try:
|
||||
self.app.logger.debug("Uploading file from " + str(sign))
|
||||
if self.upload_file(image):
|
||||
self.app.logger.debug("File has been uploaded, printing...")
|
||||
self.printer.print_img(os.path.join(self.app.config['UPLOAD_FOLDER'], secure_filename(image.filename)), sign)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
except Exception as e:
|
||||
self.app.logger.error(e)
|
||||
raise Exception
|
||||
|
||||
else:
|
||||
flash("Could not upload file.",'error')
|
||||
return False
|
||||
|
||||
def login(username: str,password: str) -> bool:
|
||||
pass
|
||||
|
||||
def logout(username: str, password: str) -> bool:
|
||||
pass
|
||||
|
||||
def allowed_file(self, filename) -> bool:
|
||||
self.app.logger.debug("Is the filename allowed ?")
|
||||
return '.' in filename and filename.rsplit('.', 1)[1].lower() in self.app.config['ALLOWED_EXTENSIONS']
|
||||
|
||||
def upload_file(self, image)-> bool:
|
||||
self.app.logger.debug("Validating file")
|
||||
if image and self.allowed_file(image.filename):
|
||||
filename = secure_filename(image.filename)
|
||||
self.app.logger.debug("File valid")
|
||||
try:
|
||||
image.save(os.path.join(self.app.config['UPLOAD_FOLDER'], filename))
|
||||
self.app.logger.debug("File saved")
|
||||
except Exception as e:
|
||||
self.app.logger.error("Could not save file")
|
||||
flash(e,'error')
|
||||
return False
|
||||
|
||||
self.app.logger.debug("File saved to " + str(os.path.join(self.app.config['UPLOAD_FOLDER'], filename)))
|
||||
return True
|
||||
else:
|
||||
self.app.logger.error("Could not save file " + str(filename))
|
||||
return False
|
||||
|
||||