Merge pull request 'epson-tm-t20iii' (#1) from epson-tm-t20iii into master
Reviewed-on: http://git.n07070.xyz/n07070/littleprynter/pulls/1
4
.gitignore
vendored
@ -24,6 +24,9 @@ wheels/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
bin/
|
||||
share/
|
||||
pyvenv.cfg
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
@ -59,6 +62,7 @@ db.sqlite3
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
src/static/uploads
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
56
README.md
@ -1,49 +1,70 @@
|
||||
# Little Prynter
|
||||
---
|
||||
|
||||
> Print out shit from the cloud.
|
||||
> Print out shit from the cloud on a thermal paper.
|
||||
|
||||
![LittlePrynter Logo](src/static/images/little-printer.png)
|
||||
|
||||
## 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](https://www.adafruit.com/product/597)
|
||||
- A Raspberry Pi
|
||||
- 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 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
|
||||
- 3h of your time
|
||||
- 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.
|
||||
|
||||
## Installation
|
||||
## Context
|
||||
|
||||
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).
|
||||
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
|
||||
cd LittlePrynter
|
||||
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
|
||||
```
|
||||
Now, edit `the users.json` and add a user. **Don't forget to remove the test user.**
|
||||
|
||||
> tip : when you're done, you can get out of the virtualenv either by closing your terminal, or by running `deactivate`.
|
||||
|
||||
You should see a folder named `configuration`. Enter it, and duplicate the file named `config.toml.sample`, and rename the copy to `config.toml`. Now, edit this file by following the comments in the file itself.
|
||||
|
||||
You can now start the web server with
|
||||
|
||||
```
|
||||
export FLASK_APP=littleprynter.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à !
|
||||
|
||||
## More
|
||||
|
||||
If you liked this project, feel free to support my work !
|
||||
|
||||
[https://n07070.xyz/post/about-me/about-me/](Donations welcome :-])
|
||||
[Donations welcome ! :)](https://n07070.xyz/about-me)
|
||||
|
||||
## Links
|
||||
|
||||
@ -51,7 +72,6 @@ If you liked this project, feel free to support my work !
|
||||
- [Github repo with CUPS drivers for the Adafruit Thermal Printer ( zj-58 )](https://github.com/klirichek/zj-58)
|
||||
- [A link to buy one in Europe](https://rlx.sk/sk/various-boards/1829-mini-thermal-receipt-printer-adafruit-597.html)
|
||||
- [Another link to buy one, direct from factory](https://www.cashinotech.com/csn-a2-58mm-mini-panel-thermal-receipt-printer_p11.html)
|
||||
-
|
||||
|
||||
|
||||
## Licence
|
||||
|
15
configuration/config.toml
Normal file
@ -0,0 +1,15 @@
|
||||
# Configuration file the LittlePrynter
|
||||
|
||||
# Printer settings
|
||||
[printer]
|
||||
vendor_id = 0x04b8
|
||||
device_id = 0x0e28
|
||||
upload_folder = "src/static/uploads"
|
||||
|
||||
# Users = Password
|
||||
[users]
|
||||
admin = "admin"
|
||||
|
||||
# Secrets for flask
|
||||
[secrets]
|
||||
flask_secret_key = "ChÕÓhÑLa)Ù<î=F;ÑÊÝ5fV÷}º35+FâXg£Ì;Ñ58ëȤ^ìãtzº<$úÌ¢ü>A¡ÿ:--_Uc²æmÇ)ëÛòöéZ¥÷Z¯¦`,ç¶B°>Å:Zÿ¼Á@ªu-º´¬XäwYÃ`c>YÜYÏJ${_f{MJ[ÙkNzg_WZv"
|
15
configuration/config.toml.sample
Normal file
@ -0,0 +1,15 @@
|
||||
# Configuration file the LittlePrynter
|
||||
|
||||
# Printer settings
|
||||
[printer]
|
||||
vendor_id = "0x04b8"
|
||||
device_id = "0x0e28"
|
||||
|
||||
# Users = Password
|
||||
[users]
|
||||
admin = "admin"
|
||||
|
||||
# Secrets for flask
|
||||
# See "How to generate good secret keys" in https://flask.palletsprojects.com/en/1.1.x/quickstart/
|
||||
[secrets]
|
||||
flask_secret_key = "random string to do things"
|
BIN
configuration/hello_world.png
Normal file
After Width: | Height: | Size: 62 KiB |
BIN
dither_it_cover.png
Normal file
After Width: | Height: | Size: 20 KiB |
BIN
docs/Epson TM-T20 ESC-POS Quick Reference Guide .pdf
Normal file
BIN
docs/Epson-TM-T20-Series-datasheet.pdf
Normal file
BIN
docs/tm-t20iii_trg_en_reva.pdf
Normal file
BIN
docs/tmx-cups-src-ThermalReceipt-3.0.0.0.tar.gz
Normal file
@ -1,13 +1,13 @@
|
||||
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
|
||||
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
|
||||
|
3
run.sh
Executable file
@ -0,0 +1,3 @@
|
||||
export FLASK_APP=src/main.py
|
||||
export FLASK_ENV=development
|
||||
flask run --host 192.168.0.42 --debugger --eager-loading
|
169
src/main.py
Normal file
@ -0,0 +1,169 @@
|
||||
# Welcome to the LittlePrynter's source code.
|
||||
# This program expose a web interface, with user authentification, that makes it possible to print messages from the web.
|
||||
# It also exposes a API, making it possible to print and interface with much of the printer's abilities.
|
||||
|
||||
# We first define the connection to the printer itself,
|
||||
# Then we build the API around Flask,
|
||||
# Then we build the web interface, using the simple Jinja2 templating.
|
||||
|
||||
# Following are the librairies we import,
|
||||
from flask import Flask, request, render_template, flash, abort, redirect, url_for, make_response, jsonify # Used for the web framework
|
||||
from flask_limiter import Limiter
|
||||
from flask_limiter.util import get_remote_address
|
||||
from printer import Printer # The wrapper for the printer class
|
||||
from web import Web # Wrapper for the web routes and API
|
||||
import toml # Used for the config file parsing
|
||||
import pprint # To pretty print JSON
|
||||
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 :
|
||||
app.logger.error("Unable to load the config file: invalid type or is a list containing invalid types")
|
||||
exit(-1)
|
||||
except toml.TomlDecodeError:
|
||||
app.logger.error("An error occured while decoding the file")
|
||||
exit(-1)
|
||||
except Exception as 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.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
|
||||
|
||||
# Printer connection
|
||||
# Uses the class defined in the printer.py file
|
||||
printer = Printer(app,0x04b8, 0x0e28)
|
||||
printer.init_printer()
|
||||
|
||||
# Web routes
|
||||
web = Web(app, printer)
|
||||
|
||||
|
||||
limiter = Limiter(
|
||||
app,
|
||||
key_func=get_remote_address,
|
||||
default_limits=["200 per day", "50 per hour"]
|
||||
)
|
||||
|
||||
@app.route('/')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def index():
|
||||
app.logger.debug("Loading index")
|
||||
return render_template('index.html')
|
||||
|
||||
# API routes
|
||||
# The api has the following methods
|
||||
# api/print/{sms,img,letter,qr,barcode}
|
||||
# api/auth/{login,logout}
|
||||
# api/status/{paper,ping,stats}
|
||||
|
||||
# If you just call the api route, you get a help back.
|
||||
@app.route('/api')
|
||||
@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)
|
||||
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,'error')
|
||||
redirect(url_for('index'))
|
||||
|
||||
try:
|
||||
web.print_sms(txt,sign)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
return redirect(url_for('index'))
|
||||
|
||||
@app.route('/api/print/img', methods=['POST'])
|
||||
@limiter.limit("2/minute", override_defaults=False)
|
||||
def api_print_image():
|
||||
app.logger.debug("Printing an image")
|
||||
|
||||
try:
|
||||
sign = request.form["signature"]
|
||||
except Exception as e:
|
||||
flash(str(e),'error')
|
||||
redirect(url_for('index'))
|
||||
|
||||
if request.method == 'POST':
|
||||
# check if the post request has the file part
|
||||
|
||||
if 'img' not in request.files:
|
||||
flash('No file found. Did you use the good form ?', 'error')
|
||||
return redirect(url_for("index"))
|
||||
else:
|
||||
file = request.files['img']
|
||||
|
||||
|
||||
# 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 redirect(url_for("index"))
|
||||
|
||||
@app.route('/logout')
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def logout_page():
|
||||
# web.logout(username, password)
|
||||
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 redirect(url_for("index"))
|
||||
|
||||
@app.route("/ping")
|
||||
@limiter.exempt
|
||||
def ping():
|
||||
flash("🏓 Pong !",'info')
|
||||
return redirect(url_for("index"))
|
178
src/printer.py
Normal file
@ -0,0 +1,178 @@
|
||||
# Importing the module to mage the connection to the printer.
|
||||
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):
|
||||
"""
|
||||
# The connection is based on the ESC/POS library
|
||||
|
||||
## Connection to the USB printer
|
||||
|
||||
## Making sure the printer is alive
|
||||
|
||||
## Making sure it has paper
|
||||
|
||||
## Define default print settings
|
||||
|
||||
## Print starting message, log time of first print, cut.
|
||||
|
||||
## Annonce readyness : return a positive pong message.
|
||||
"""
|
||||
|
||||
# Is the printer ready to accept a new print ?
|
||||
ready = False
|
||||
|
||||
def __init__(self, app, device_id, vendor_id):
|
||||
super(Printer, self).__init__()
|
||||
self.app = app
|
||||
self.ready = False
|
||||
self.printer = None
|
||||
self.device_id = device_id
|
||||
self.vendor_id = vendor_id
|
||||
self.usb_args = {}
|
||||
self.usb_args['idVendor'] = self.device_id
|
||||
self.usb_args['idProduct'] = self.vendor_id
|
||||
|
||||
def check_paper(self) -> bool:
|
||||
# Let's check paper status
|
||||
self.app.logger.debug('Checking paper status...')
|
||||
self.printer.open(self.usb_args)
|
||||
status = self.printer.paper_status()
|
||||
match status:
|
||||
case 0:
|
||||
self.app.logger.error('Printer has no more paper, aborting...')
|
||||
flash("No more paper on the printer. Sorry.",category='error')
|
||||
self.printer.close()
|
||||
return False
|
||||
case 1:
|
||||
self.app.logger.warning('Printer needs paper to be changed very soon ! ')
|
||||
flash('Printer needs paper to be changed very soon ! ', category='info')
|
||||
self.printer.close()
|
||||
return True
|
||||
case 2:
|
||||
self.app.logger.debug('Printer has paper, good to go')
|
||||
self.printer.close()
|
||||
return True
|
||||
|
||||
def init_printer(self):
|
||||
|
||||
# Is the printer online ? Is the communication with the printer successfull ?
|
||||
waiting_elapsed = 30
|
||||
self.app.logger.debug('Waiting for printer to get online...')
|
||||
|
||||
while not self.ready:
|
||||
try:
|
||||
# This also calls open(), which we need to close()
|
||||
# or else the device will appear as busy.
|
||||
p = Usb(self.device_id, self.vendor_id, 0, profile="TM-P80")
|
||||
except USBNotFoundError as e:
|
||||
self.app.logger.error("The USB device is not plugged in, trying again : " + str(e))
|
||||
pass
|
||||
|
||||
try:
|
||||
if p.is_online():
|
||||
self.ready = True
|
||||
self.app.logger.debug('Printer online !')
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
sleep(1)
|
||||
waiting_elapsed -= 1
|
||||
if waiting_elapsed < 1:
|
||||
self.app.logger.error('Printer took more than 30 seconds to get online, aborting...')
|
||||
waiting_elapsed = 30 # Reset the waiting time for the next print.
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
# Setting up the printing options.
|
||||
p.set(align='center', font='a', bold=False, underline=0, width=1, height=1, density=9, invert=False, smooth=False, flip=False, double_width=False, double_height=False, custom_size=False)
|
||||
# Beware : if we print every time the printer becomes ready, it means
|
||||
# we are printing before and after every print !
|
||||
self.printer = p
|
||||
self.ready = True;
|
||||
self.printer.close();
|
||||
|
||||
if not self.check_paper():
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def print_sms(self, msg, signature) -> bool:
|
||||
clean_msg = str(msg)
|
||||
clean_signature = str(signature)
|
||||
|
||||
if not self.check_paper():
|
||||
return False
|
||||
|
||||
if len(clean_msg) > 256 or len(clean_msg) < 3 :
|
||||
self.app.logger.warning("Could not print message of this length: " + str(len(clean_msg)))
|
||||
flash("Could not print message of this length :" + str(len(clean_msg)) + ", needs to between 3 and 256 caracters long.",category='error')
|
||||
return False
|
||||
|
||||
if len(signature) > 256 or len(signature) < 3:
|
||||
self.app.logger.warning("Could not print message without a signature.")
|
||||
flash("Could not print message without a signature.",category='error')
|
||||
return False
|
||||
|
||||
if not os.getenv('LIPY_DEBUG') == True:
|
||||
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, sign):
|
||||
clean_signature = str(sign)
|
||||
|
||||
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()
|
||||
flash(str(e),'error')
|
||||
return False
|
7
src/static/css/bootstrap.min.css
vendored
Normal file
BIN
src/static/favicon.ico
Normal file
After Width: | Height: | Size: 14 KiB |
BIN
src/static/images/little-printer.png
Normal file
After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 8.7 KiB After Width: | Height: | Size: 8.7 KiB |
10
src/templates/api.html
Normal file
@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" dir="ltr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LittlePrynter API</title>
|
||||
</head>
|
||||
<body>
|
||||
"Welcome to the printing software's API. Please see the index page to get started.
|
||||
</body>
|
||||
</html>
|
0
src/templates/footer.html
Normal file
0
src/templates/header.html
Normal file
71
src/templates/index.html
Normal file
@ -0,0 +1,71 @@
|
||||
<!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-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 %}
|
||||
|
||||
<!-- <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">
|
||||
|
||||
<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>
|
||||
|
||||
<br>
|
||||
|
||||
<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 id="pbar" style="display:none">
|
||||
<img src="{{ url_for('static',filename='load.gif') }}" alt="loading wheel">
|
||||
</div> -->
|
||||
</div>
|
||||
<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>
|
0
src/templates/login.html
Normal file
0
src/templates/print.html
Normal file
39
src/user.py
Normal file
@ -0,0 +1,39 @@
|
||||
class User(object):
|
||||
"""docstring for User."""
|
||||
|
||||
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'))
|
68
src/web.py
Normal file
@ -0,0 +1,68 @@
|
||||
from flask import Flask, request
|
||||
from werkzeug.utils import secure_filename
|
||||
from printer import Printer
|
||||
import time
|
||||
import os
|
||||
|
||||
class Web(object):
|
||||
"""docstring for web."""
|
||||
|
||||
def __init__(self, app, printer ):
|
||||
super(Web).__init__()
|
||||
self.printer = printer
|
||||
self.app = app
|
||||
|
||||
def print_sms(self, texte, sign: str):
|
||||
# TODO: verify the texte before printing it here ?
|
||||
self.app.logger.debug("Printing : " + str(texte) + " from " + str(sign))
|
||||
if not os.getenv('LIPY_DEBUG'):
|
||||
time.sleep(1)
|
||||
|
||||
return self.printer.print_sms(texte, sign)
|
||||
|
||||
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
|
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 |
@ -1,75 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LittlePrynter</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
|
||||
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
|
||||
</head>
|
||||
<body class="container">
|
||||
<div class="col-md-6 offset-md-3">
|
||||
<h1 class="font-weight-bold">Little Prynter</h1>
|
||||
<hr>
|
||||
<br>
|
||||
{% with messages = get_flashed_messages() %}
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div class="alert alert-danger" role="alert">{{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
<br>
|
||||
<h3>Imprimer une image aléatoire</h3>
|
||||
<a class="btn btn-primary btn-lg btn-block" href="/print/image"> Imprimer</a>
|
||||
<hr>
|
||||
<br>
|
||||
<h3>Imprimer ton propre texte</h3>
|
||||
<form class="form-group" action="/print/text" method="post">
|
||||
<input class="form-control" type="text" name="message" placeholder="200 caractères ou moins " maxlength="200"><br>
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
</form>
|
||||
|
||||
<div id="pbar" style="display:none">
|
||||
<img src="{{ url_for('static',filename='load.gif') }}" alt="loading wheel">
|
||||
</div>
|
||||
<br>
|
||||
<br>
|
||||
<footer><a href="/logout">Se déconnecter</a></footer>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
<script>
|
||||
|
||||
function printImage() {
|
||||
// Make an ajax call to the flask server on the /print/image route to trigger an image to be printer.
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
var x = document.getElementById("pbar");
|
||||
if (x.style.display === "none") {
|
||||
x.style.display = "inline";
|
||||
}
|
||||
if (this.readyState == 4 && this.status == 429) {
|
||||
x.style.display = "none";
|
||||
alert("Hé, attends un peu avant d'imprimer une autre image, je me repose...");
|
||||
} else if (this.readyState == 4 && this.status == 200) {
|
||||
x.style.display = "none";
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/print/image", true);
|
||||
xhttp.send();
|
||||
}
|
||||
|
||||
function printText(){
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 400) {
|
||||
alert("Le text est trop long !");
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/print/text", true);
|
||||
xhttp.send();
|
||||
}
|
||||
|
||||
</script>
|
||||
</html>
|