ScoDoc-PE/app/scodoc/sco_photos.py

379 lines
13 KiB
Python
Raw Normal View History

2020-09-26 16:19:37 +02:00
# -*- mode: python -*-
# -*- coding: utf-8 -*-
##############################################################################
#
# Gestion scolarite IUT
#
2021-01-01 17:51:08 +01:00
# Copyright (c) 1999 - 2021 Emmanuel Viennet. All rights reserved.
2020-09-26 16:19:37 +02:00
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Emmanuel Viennet emmanuel.viennet@gmail.com
#
##############################################################################
"""(Nouvelle) (Nouvelle) gestion des photos d'etudiants
Les images sont stockées dans .../var/scodoc/photos
L'attribut "photo_filename" de la table identite donne le nom du fichier image,
sans extension (e.g. "F44/RT_EID31545").
Toutes les images sont converties en jpg, et stockées dans photo_filename.jpg en taille originale.
Elles sont aussi réduites en 90 pixels de hauteur, et stockées dans photo_filename.h90.jpg
Les images sont servies par ScoDoc, via la méthode getphotofile?etudid=xxx
## Historique:
- jusqu'à novembre 2009, les images étaient stockées dans Zope (ZODB).
- jusqu'à v1908, stockées dans .../static/photos (et donc accessibles sans authentification).
- support for legacy ZODB removed in v1909.
"""
from app.scodoc.sco_exceptions import ScoGenError
2021-08-21 15:17:14 +02:00
import datetime
import glob
2021-07-26 15:23:07 +02:00
import io
2020-09-26 16:19:37 +02:00
import os
import random
2021-08-21 15:17:14 +02:00
import requests
import time
2020-09-26 16:19:37 +02:00
import traceback
2021-07-11 22:56:22 +02:00
import PIL
2021-08-21 15:17:14 +02:00
from PIL import Image as PILImage
2020-09-26 16:19:37 +02:00
2021-08-21 15:17:14 +02:00
from flask import request, g
2021-05-29 18:22:51 +02:00
from config import Config
2020-12-12 18:05:28 +01:00
from app.scodoc import sco_etud
from app.scodoc import sco_portal_apogee
from app.scodoc import sco_preferences
2021-08-29 19:57:32 +02:00
from app import log
from app.scodoc.scolog import logdb
import app.scodoc.notesdb as ndb
import app.scodoc.sco_utils as scu
2020-09-26 16:19:37 +02:00
# Full paths on server's filesystem. Something like "/opt/scodoc/var/scodoc/photos"
PHOTO_DIR = os.path.join(Config.SCODOC_VAR_DIR, "photos")
ICONS_DIR = os.path.join(Config.SCODOC_DIR, "app", "static", "icons")
2020-09-26 16:19:37 +02:00
UNKNOWN_IMAGE_PATH = os.path.join(ICONS_DIR, "unknown.jpg")
2020-12-12 18:05:28 +01:00
UNKNOWN_IMAGE_URL = "get_photo_image?etudid=" # with empty etudid => unknown face image
2020-09-26 16:19:37 +02:00
IMAGE_EXT = ".jpg"
JPG_QUALITY = 0.92
REDUCED_HEIGHT = 90 # pixels
MAX_FILE_SIZE = 1024 * 1024 # max allowed size for uploaded image, in bytes
H90 = ".h90" # suffix for reduced size images
def photo_portal_url(etud):
2020-09-26 16:19:37 +02:00
"""Returns external URL to retreive photo on portal,
or None if no portal configured"""
2021-08-20 10:51:42 +02:00
photo_url = sco_portal_apogee.get_photo_url()
2020-09-26 16:19:37 +02:00
if photo_url and etud["code_nip"]:
return photo_url + "?nip=" + etud["code_nip"]
else:
return None
2020-12-12 18:05:28 +01:00
def etud_photo_url(etud, size="small", fast=False):
2020-09-26 16:19:37 +02:00
"""url to the image of the student, in "small" size or "orig" size.
If ScoDoc doesn't have an image and a portal is configured, link to it.
"""
photo_url = scu.ScoURL() + "/get_photo_image?etudid=%s&size=%s" % (
etud["etudid"],
size,
)
if fast:
return photo_url
2021-08-20 10:51:42 +02:00
path = photo_pathname(etud, size=size)
2020-09-26 16:19:37 +02:00
if not path:
# Portail ?
ext_url = photo_portal_url(etud)
2020-09-26 16:19:37 +02:00
if not ext_url:
# fallback: Photo "unknown"
photo_url = scu.ScoURL() + "/" + UNKNOWN_IMAGE_URL
2020-09-26 16:19:37 +02:00
else:
# essaie de copier la photo du portail
new_path, _ = copy_portal_photo_to_fs(etud)
2020-09-26 16:19:37 +02:00
if not new_path:
# copy failed, can we use external url ?
# nb: rarement utile, car le portail est rarement accessible sans authentification
if scu.CONFIG.PUBLISH_PORTAL_PHOTO_URL:
2020-09-26 16:19:37 +02:00
photo_url = ext_url
else:
photo_url = UNKNOWN_IMAGE_URL
return photo_url
def get_photo_image(etudid=None, size="small", REQUEST=None):
2020-09-26 16:19:37 +02:00
"""Returns photo image (HTTP response)
If not etudid, use "unknown" image
"""
if not etudid:
filename = UNKNOWN_IMAGE_PATH
else:
2021-08-22 13:24:36 +02:00
etud = sco_etud.get_etud_info(filled=True, etudid=etudid)[0]
2021-08-20 10:51:42 +02:00
filename = photo_pathname(etud, size=size)
2020-09-26 16:19:37 +02:00
if not filename:
filename = UNKNOWN_IMAGE_PATH
return _http_jpeg_file(filename, REQUEST=REQUEST)
2020-09-26 16:19:37 +02:00
def _http_jpeg_file(filename, REQUEST=None):
2020-09-26 16:19:37 +02:00
"""returns an image.
This function will be modified when we kill #zope
"""
st = os.stat(filename)
last_modified = st.st_mtime # float timestamp
last_modified_str = time.strftime(
"%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last_modified)
)
file_size = st.st_size
RESPONSE = REQUEST.RESPONSE
RESPONSE.setHeader("Content-Type", "image/jpeg")
RESPONSE.setHeader("Last-Modified", last_modified_str)
RESPONSE.setHeader("Cache-Control", "max-age=3600")
RESPONSE.setHeader("Content-Length", str(file_size))
header = request.headers.get("If-Modified-Since")
2020-09-26 16:19:37 +02:00
if header is not None:
header = header.split(";")[0]
# Some proxies seem to send invalid date strings for this
# header. If the date string is not valid, we ignore it
# rather than raise an error to be generally consistent
# with common servers such as Apache (which can usually
# understand the screwy date string as a lucky side effect
# of the way they parse it).
try:
dt = datetime.datetime.strptime(header, "%a, %d %b %Y %H:%M:%S GMT")
mod_since = dt.timestamp()
except:
mod_since = None
if (mod_since is not None) and last_modified <= mod_since:
RESPONSE.setStatus(304) # not modified
return ""
return open(filename, mode="rb").read()
def etud_photo_is_local(etud, size="small"):
2021-08-20 10:51:42 +02:00
return photo_pathname(etud, size=size)
2020-09-26 16:19:37 +02:00
2021-09-24 12:10:53 +02:00
def etud_photo_html(etud=None, etudid=None, title=None, size="small"):
2020-12-12 18:05:28 +01:00
"""HTML img tag for the photo, either in small size (h90)
2020-09-26 16:19:37 +02:00
or original size (size=="orig")
"""
if not etud:
if etudid:
2021-08-22 13:24:36 +02:00
etud = sco_etud.get_etud_info(filled=True, etudid=etudid)[0]
2020-09-26 16:19:37 +02:00
else:
2020-12-12 18:05:28 +01:00
raise ValueError("etud_photo_html: either etud or etudid must be specified")
photo_url = etud_photo_url(etud, size=size)
2020-09-26 16:19:37 +02:00
nom = etud.get("nomprenom", etud["nom_disp"])
if title is None:
title = nom
if not etud_photo_is_local(etud):
2020-09-26 16:19:37 +02:00
fallback = (
2020-12-12 18:05:28 +01:00
"""onerror='this.onerror = null; this.src="%s"'""" % UNKNOWN_IMAGE_URL
2020-09-26 16:19:37 +02:00
)
else:
fallback = ""
if size == "small":
height_attr = 'height="%s"' % REDUCED_HEIGHT
else:
height_attr = ""
return '<img src="%s" alt="photo %s" title="%s" border="0" %s %s />' % (
photo_url,
nom,
title,
height_attr,
fallback,
)
2020-12-12 18:05:28 +01:00
def etud_photo_orig_html(etud=None, etudid=None, title=None, REQUEST=None):
2020-09-26 16:19:37 +02:00
"""HTML img tag for the photo, in full size.
Full-size images are always stored locally in the filesystem.
They are the original uploaded images, converted in jpeg.
"""
2021-09-24 12:10:53 +02:00
return etud_photo_html(etud=etud, etudid=etudid, title=title, size="orig")
2020-12-12 18:05:28 +01:00
2020-09-26 16:19:37 +02:00
2021-08-20 10:51:42 +02:00
def photo_pathname(etud, size="orig"):
2020-09-26 16:19:37 +02:00
"""Returns full path of image file if etud has a photo (in the filesystem), or False.
Do not distinguish the cases: no photo, or file missing.
"""
if size == "small":
version = H90
elif size == "orig":
version = ""
else:
raise ValueError("invalid size parameter for photo")
if not etud["photo_filename"]:
return False
path = os.path.join(PHOTO_DIR, etud["photo_filename"]) + version + IMAGE_EXT
if os.path.exists(path):
return path
else:
return False
def store_photo(etud, data):
2020-09-26 16:19:37 +02:00
"""Store image for this etud.
If there is an existing photo, it is erased and replaced.
2021-07-26 15:23:07 +02:00
data is a bytes string with image raw data.
2020-09-26 16:19:37 +02:00
Update database to store filename.
Returns (status, msg)
"""
# basic checks
filesize = len(data)
if filesize < 10 or filesize > MAX_FILE_SIZE:
return 0, "Fichier image de taille invalide ! (%d)" % filesize
try:
filename = save_image(etud["etudid"], data)
except PIL.UnidentifiedImageError:
raise ScoGenError(msg="Fichier d'image invalide ou non format non supporté")
2020-09-26 16:19:37 +02:00
# update database:
etud["photo_filename"] = filename
etud["foto"] = None
2021-06-15 13:59:56 +02:00
cnx = ndb.GetDBConnexion()
sco_etud.identite_edit_nocheck(cnx, etud)
2020-09-26 16:19:37 +02:00
cnx.commit()
#
2021-07-31 18:01:10 +02:00
logdb(cnx, method="changePhoto", msg=filename, etudid=etud["etudid"])
2020-09-26 16:19:37 +02:00
#
return 1, "ok"
def suppress_photo(etud, REQUEST=None):
2020-09-26 16:19:37 +02:00
"""Suppress a photo"""
log("suppress_photo etudid=%s" % etud["etudid"])
2021-08-20 10:51:42 +02:00
rel_path = photo_pathname(etud)
2020-09-26 16:19:37 +02:00
# 1- remove ref. from database
etud["photo_filename"] = None
2021-06-15 13:59:56 +02:00
cnx = ndb.GetDBConnexion()
sco_etud.identite_edit_nocheck(cnx, etud)
2020-09-26 16:19:37 +02:00
cnx.commit()
# 2- erase images files
if rel_path:
# remove extension and glob
rel_path = rel_path[: -len(IMAGE_EXT)]
filenames = glob.glob(rel_path + "*" + IMAGE_EXT)
for filename in filenames:
log("removing file %s" % filename)
os.remove(filename)
# 3- log
if REQUEST:
2021-07-31 18:01:10 +02:00
logdb(cnx, method="changePhoto", msg="suppression", etudid=etud["etudid"])
2020-09-26 16:19:37 +02:00
# ---------------------------------------------------------------------------
# Internal functions
2020-12-12 18:05:28 +01:00
def save_image(etudid, data):
"""data is a bytes string.
2020-09-26 16:19:37 +02:00
Save image in JPEG in 2 sizes (original and h90).
Returns filename (relative to PHOTO_DIR), without extension
"""
2021-07-26 15:23:07 +02:00
data_file = io.BytesIO()
2020-09-26 16:19:37 +02:00
data_file.write(data)
data_file.seek(0)
img = PILImage.open(data_file)
2021-08-20 10:51:42 +02:00
filename = get_new_filename(etudid)
2020-12-12 18:05:28 +01:00
path = os.path.join(PHOTO_DIR, filename)
2020-09-26 16:19:37 +02:00
log("saving %dx%d jpeg to %s" % (img.size[0], img.size[1], path))
img = img.convert("RGB")
2020-09-26 16:19:37 +02:00
img.save(path + IMAGE_EXT, format="JPEG", quality=92)
# resize:
img = scale_height(img)
log("saving %dx%d jpeg to %s.h90" % (img.size[0], img.size[1], filename))
img.save(path + H90 + IMAGE_EXT, format="JPEG", quality=92)
return filename
def scale_height(img, W=None, H=REDUCED_HEIGHT):
if W is None:
# keep aspect
2021-07-09 19:50:40 +02:00
W = int((img.size[0] * H) / img.size[1])
2020-09-26 16:19:37 +02:00
img.thumbnail((W, H), PILImage.ANTIALIAS)
return img
2021-08-20 10:51:42 +02:00
def get_new_filename(etudid):
2020-09-26 16:19:37 +02:00
"""Constructs a random filename to store a new image.
The path is constructed as: Fxx/etudid
"""
2021-08-21 15:17:14 +02:00
dept = g.scodoc_dept
2021-08-10 17:12:10 +02:00
return find_new_dir() + dept + "_" + str(etudid)
2020-09-26 16:19:37 +02:00
def find_new_dir():
"""select randomly a new subdirectory to store a new file.
We define 100 subdirectories named from F00 to F99.
Returns a path relative to the PHOTO_DIR.
"""
d = "F" + "%02d" % random.randint(0, 99)
path = os.path.join(PHOTO_DIR, d)
if not os.path.exists(path):
# ensure photos directory exists
if not os.path.exists(PHOTO_DIR):
os.mkdir(PHOTO_DIR)
# create subdirectory
log("creating directory %s" % path)
os.mkdir(path)
return d + "/"
def copy_portal_photo_to_fs(etud):
2020-09-26 16:19:37 +02:00
"""Copy the photo from portal (distant website) to local fs.
Returns rel. path or None if copy failed, with a diagnostic message
2020-09-26 16:19:37 +02:00
"""
sco_etud.format_etud_ident(etud)
url = photo_portal_url(etud)
2020-09-26 16:19:37 +02:00
if not url:
return None, "%(nomprenom)s: pas de code NIP" % etud
portal_timeout = sco_preferences.get_preference("portal_timeout")
2020-09-26 16:19:37 +02:00
f = None
try:
log("copy_portal_photo_to_fs: getting %s" % url)
2021-08-21 15:17:14 +02:00
r = requests.get(url, timeout=portal_timeout)
2020-09-26 16:19:37 +02:00
except:
# log("download failed: exception:\n%s" % traceback.format_exc())
# log("called from:\n" + "".join(traceback.format_stack()))
log("copy_portal_photo_to_fs: error.")
2020-09-26 16:19:37 +02:00
return None, "%s: erreur chargement de %s" % (etud["nomprenom"], url)
2021-08-21 15:17:14 +02:00
if r.status_code != 200:
log(f"copy_portal_photo_to_fs: download failed {r.status_code }")
2020-09-26 16:19:37 +02:00
return None, "%s: erreur chargement de %s" % (etud["nomprenom"], url)
2021-08-21 15:17:14 +02:00
data = r.content # image bytes
2020-09-26 16:19:37 +02:00
try:
status, diag = store_photo(etud, data)
2020-09-26 16:19:37 +02:00
except:
status = 0
diag = "Erreur chargement photo du portail"
log("copy_portal_photo_to_fs: failure (exception in store_photo)!")
if status == 1:
log("copy_portal_photo_to_fs: copied %s" % url)
2021-08-20 10:51:42 +02:00
return photo_pathname(etud), "%s: photo chargée" % etud["nomprenom"]
2020-09-26 16:19:37 +02:00
else:
return None, "%s: <b>%s</b>" % (etud["nomprenom"], diag)