Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions mslib/mscolab/api/attachments.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
limitations under the License.
"""

# Formats of images, by the format PIL detects, with the extension they are stored with
IMAGE_FORMATS = {"PNG": "png", "JPEG": "jpg", "GIF": "gif", "BMP": "bmp", "WEBP": "webp"}
# Formats of images, by the format PIL detects, with the extension they are stored with. MPO is a JPEG with more
# pictures after the first one, e.g. the photos of many phones (portrait or depth photos); it is shown as JPEG.
IMAGE_FORMATS = {"PNG": "png", "JPEG": "jpg", "MPO": "jpg", "GIF": "gif", "BMP": "bmp", "WEBP": "webp"}
IMAGE_EXTENSIONS = ("png", "jpg", "jpeg", "gif", "bmp", "webp")

# Default of the server setting MSCOLAB_ATTACHMENT_EXTENSIONS. Left out on purpose: files a browser can run
Expand Down
46 changes: 35 additions & 11 deletions mslib/mscolab/file_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import git
import threading
import mimetypes
from pathlib import Path, PurePosixPath
from pathlib import Path, PurePosixPath, PureWindowsPath
from flask import current_app
from werkzeug.utils import secure_filename
from sqlalchemy import insert
Expand All @@ -53,6 +53,25 @@
UPDATABLE_OPERATION_ATTRIBUTES = ("path", "description", "category", "active", "last_used")


def stored_upload_path(file_path, upload_folder):
"""
The path of an uploaded file relative to UPLOAD_FOLDER, as stored in the database: with forward slashes also on
Windows, where send_from_directory refuses a backslash
"""
return file_path.relative_to(upload_folder).as_posix()


def profile_image_url_path(profile_image_path):
"""
The stored path of a profile image below UPLOAD_FOLDER with forward slashes

Servers on Windows stored it with backslashes (e.g. profile\\1-....png) before 12.0.0; send_from_directory
refuses those there, so the profile image was never shown. The file name is a secure_filename, a backslash
can only be a separator.
"""
return profile_image_path.replace("\\", "/")


class FileManager:
"""Class with handler functions for file related functionalities"""

Expand Down Expand Up @@ -323,15 +342,20 @@ def delete_user_profile_image(self, image_to_be_deleted):
"""
This function is called when deleting account or updating the profile picture
"""
upload_folder = current_app.config['UPLOAD_FOLDER']
if sys.platform.startswith('win'):
upload_folder = upload_folder.replace('\\', '/')

# Construct the full path to the image file
full_image_path = Path(upload_folder) / image_to_be_deleted
relative_path = profile_image_url_path(image_to_be_deleted)
parts = PurePosixPath(relative_path).parts
# the path comes from the database: checked by its parts, not resolved, so a directory below UPLOAD_FOLDER may
# be a symlink (e.g. to another volume), and an image that is a symlink is removed itself, not its target.
# An image is a file in a directory below UPLOAD_FOLDER (e.g. profile/<name>), never a directory of it:
# "profile" or "profile/." would remove the link of a symlinked profile directory
if (PurePosixPath(relative_path).is_absolute() or PureWindowsPath(relative_path).anchor
or ".." in parts or len(parts) < 2):
logging.error(f"Not deleting the profile image {image_to_be_deleted}, it is no file below UPLOAD_FOLDER")
return
full_image_path = Path(current_app.config['UPLOAD_FOLDER'], *parts)

# Check if the file exists and delete it
if full_image_path.exists() and full_image_path.is_file():
# Check if the file exists and delete it; a link to a directory is kept
if full_image_path.is_file() or (full_image_path.is_symlink() and not full_image_path.is_dir()):
try:
full_image_path.unlink() # Delete the file
logging.debug(f"Successfully deleted image: {image_to_be_deleted}")
Expand Down Expand Up @@ -383,7 +407,7 @@ def upload_file(self, file, subfolder=None, identifier=None, include_prefix=Fals
# directory, which is configurable, and always uses forward slashes.
static_file_path = str(PurePosixPath(ATTACHMENTS_URL_PREFIX, str(subfolder), file_name))
else:
static_file_path = str(Path(file_path).relative_to(Path(upload_folder)))
static_file_path = stored_upload_path(file_path, Path(upload_folder))

logging.debug(f'Relative Path: {static_file_path}')
return static_file_path
Expand Down Expand Up @@ -423,7 +447,7 @@ def get_user_profile_image(self, user_id, op_id, requesting_user_id):
user = db.session.get(User, user_id)
if user:
if user.profile_image_path:
return True, user.profile_image_path
return True, profile_image_url_path(user.profile_image_path)
return False, "Profile image not found"
else:
return False, "User not found"
Expand Down
161 changes: 104 additions & 57 deletions mslib/msui/mscolab.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,10 @@
import types
import requests
import re
import mimetypes
import urllib.parse
from pathlib import Path

from PIL import Image, UnidentifiedImageError
from PIL import Image, ImageOps, UnidentifiedImageError

from mslib.msui import flighttrack as ft
from mslib.msui import mscolab_chat as mc
Expand All @@ -53,7 +52,9 @@
from mslib.msui.mscolab_archive_browser import MSColab_OperationArchiveBrowser
from mslib.msui.mscolab_connect_dialog import MSColab_ConnectDialog
from mslib.mscolab.api import endpoints
from mslib.mscolab.api.attachments import IMAGE_EXTENSIONS, IMAGE_FORMATS
from mslib.mscolab.api.schemas import (
AUTH_FAILED_TEXT,
MAX_VERSION_NAME_LENGTH,
CreateOperationRequest,
CreateOperationResponse,
Expand Down Expand Up @@ -308,7 +309,9 @@ def after_login(self, emailid, url, response):
"""Finish the login with the response of POST endpoints.TOKEN.

Returns False and keeps the connect dialog open when the response
can't be read or the socket connection fails, True otherwise.
can't be read or the socket connection fails. Returns False as well when
the session expired while fetching the profile image: then msui has already
logged out and the connect dialog is closed. True otherwise.
"""
logging.debug("after login %s %s", emailid, url)
# after_login is only ever called once the caller has already checked
Expand Down Expand Up @@ -369,7 +372,8 @@ def after_login(self, emailid, url, response):
self.ui.usernameLabel.setText(f"{self.user['username']}")
self.ui.usernameLabel.show()
self.ui.userOptionsTb.show()
self.fetch_profile_image()
if not self.fetch_profile_image():
return False
# enable add operation menu action
self.ui.actionAddOperation.setEnabled(True)
self.ui.actionCopyIntoNewMSColabOperation.setEnabled(True)
Expand Down Expand Up @@ -409,13 +413,29 @@ def set_profile_pixmap(self, img_data):
self.ui.userOptionsTb.setIcon(icon)

def fetch_profile_image(self, refresh=False):
"""Shows the profile image of the server, else the Gravatar; False if the session expired (logged out)"""
req = FetchProfileImageRequest(user_id=str(self.user["id"]))
try:
response = self.conn.request_get(endpoints.FETCH_PROFILE_IMAGE, req.to_params())
except MSColabConnectionError:
except MSColabSessionExpiredError as ex:
# a subclass of MSColabConnectionError, it fell back to the Gravatar
show_popup(self.ui, "Error", str(ex))
# closes the profile dialog too
self.logout()
return False
except (MSColabConnectionError, requests.exceptions.RequestException):
# no profile image on the server, or the server can't be reached
self.fetch_gravatar(refresh)
else:
self.set_profile_pixmap(response.content)
self.show_server_profile_image(response.content)
return True

def show_server_profile_image(self, img_data):
"""Shows the profile image of the server, which is no Gravatar"""
self.set_profile_pixmap(img_data)
# "Remove Gravatar" replaced it with the default avatar, e.g. after "Fetch Gravatar" before
self.remove_temporary_gravatar()
self.gravatar = None

def fetch_gravatar(self, refresh):
# Display default gravatar if custom profile image is not set
Expand Down Expand Up @@ -504,6 +524,19 @@ def set_gravatar(self, gravatar=None):
if self.prof_diag is not None:
self.profile_dialog.gravatarLabel.setPixmap(pixmap)

def remove_temporary_gravatar(self):
"""Removes the shown Gravatar from the cache, unless the address is in gravatar_ids"""
config_path = Path(constants.MSUI_CONFIG_PATH)
gravatar_path = Path(constants.GRAVATAR_DIR_PATH)
# ToDo simplify
if (config_path / "gravatars").exists() and self.gravatar is not None:
if self.email not in config_loader(dataset="gravatar_ids"):
try:
(gravatar_path / Path(self.gravatar).name).unlink(missing_ok=True)
except OSError as ex:
# e.g. held open by another program on Windows; it is only a cache, the upload or logout goes on
logging.warning("can't remove the cached Gravatar %s: %s", self.gravatar, ex)

def remove_gravatar(self):
if self.gravatar is None:
return
Expand All @@ -512,7 +545,12 @@ def remove_gravatar(self):

# remove cached gravatar image if not found in config
if gravatar_img_path.exists():
gravatar_img_path.unlink()
try:
gravatar_img_path.unlink()
except OSError as ex:
# e.g. held open by another program on Windows; it stays shown, as it would be shown again
show_popup(self.prof_diag, "Error", f"Can't remove the cached Gravatar: {ex}")
return
if self.email in config_loader(dataset="gravatar_ids"):
show_popup(
self.prof_diag,
Expand Down Expand Up @@ -549,7 +587,8 @@ def on_context_menu(point):

# add context menu for right click on image
self.gravatar_menu = QtWidgets.QMenu()
self.gravatar_menu.addAction('Fetch Gravatar', lambda: self.fetch_profile_image(refresh=True))
# the Gravatar also when the server has an uploaded image
self.gravatar_menu.addAction('Fetch Gravatar', lambda: self.fetch_gravatar(refresh=True))
self.gravatar_menu.addAction('Remove Gravatar', lambda: self.remove_gravatar())
self.profile_dialog.gravatarLabel.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.profile_dialog.gravatarLabel.customContextMenuRequested.connect(on_context_menu)
Expand All @@ -558,47 +597,62 @@ def on_context_menu(point):
self.fetch_profile_image()

def upload_image(self, _=None):
file_name, _ = QFileDialog.getOpenFileName(self.prof_diag, "Open Image", "",
"Image (*.png *.gif *.jpg *.jpeg *.bpm)")
if file_name:
# Determine the image format
mime_type, _ = mimetypes.guess_type(file_name)
file_format = mime_type.split('/')[1].upper()
try:
# Resize the image and set profile image pixmap
image = Image.open(file_name)
image = image.resize((64, 64), Image.LANCZOS)
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format=file_format)
img_byte_arr.seek(0)
self.set_profile_pixmap(img_byte_arr.getvalue())

# Prepare the file data for upload
try:
img_byte_arr.seek(0) # Reset buffer position
# the image is stored for the user of the token
response = self.conn.request_post(
endpoints.UPLOAD_PROFILE_IMAGE,
files={'image': (os.path.basename(file_name), img_byte_arr, mime_type)})

# Check response status
if response.status_code == 200:
QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully")
self.fetch_profile_image(refresh=True)
else:
# the answer comes from the MSColab server
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f"Failed to upload image: {sc.response_message(response, response.text)}"))

except requests.exceptions.RequestException as e:
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(f"Error occurred: {e}"))

except UnidentifiedImageError as e:
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f'Cannot identify image file. Please check the file format. Error : {e}'))
except OSError as e:
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f'Cannot identify image file. Please check the file format. Error: {e}'))
# also in upper case, e.g. IMG_1234.JPG of a phone: the dialog of GTK matches the patterns case-sensitively
patterns = ' '.join(f'*.{ext}' for ext in (*IMAGE_EXTENSIONS, *(ext.upper() for ext in IMAGE_EXTENSIONS)))
file_name, _ = QFileDialog.getOpenFileName(self.prof_diag, "Open Image", "", f"Image ({patterns})")
if not file_name:
return
formats = ", ".join(ext.upper() for ext in dict.fromkeys(IMAGE_FORMATS.values()))
try:
# only the formats the server accepts, e.g. EPS would run Ghostscript. The format is the one of the content,
# not a MIME type guessed from the file name: on Windows that comes from the registry, e.g. image/x-png,
# which Pillow can't save, and a name without an extension has none.
# MPO has no opener of its own (KeyError), the JPEG plugin opens such files as MPO
with Image.open(file_name, formats=[name for name in IMAGE_FORMATS if name != "MPO"]) as image:
# the photo of a phone (MPO) as its first picture
file_format = "JPEG" if image.format == "MPO" else image.format
# upright as it was taken, and cut to a square instead of squeezed
avatar = ImageOps.fit(ImageOps.exif_transpose(image), (64, 64), Image.LANCZOS)
except UnidentifiedImageError:
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f"{os.path.basename(file_name)} is no image of a format the server accepts: {formats}."))
return
except (Image.DecompressionBombError, OSError, ValueError, SyntaxError, EOFError) as e:
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f"Cannot read the image {os.path.basename(file_name)}: {e}"))
return
img_byte_arr = io.BytesIO()
try:
avatar.save(img_byte_arr, format=file_format)
except (OSError, ValueError, KeyError) as e:
# e.g. a Pillow without WEBP support
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f"Cannot convert the image to {file_format}: {e}"))
return
try:
# the image is stored for the user of the token. The name fits the content: servers before 12.0.0 store
# the image with the extension of that name, e.g. .unknown for a file name without one
response = self.conn.request_post(
endpoints.UPLOAD_PROFILE_IMAGE,
files={'image': (f"profile.{IMAGE_FORMATS[file_format]}", io.BytesIO(img_byte_arr.getvalue()),
Image.MIME.get(file_format, "application/octet-stream"))})
except requests.exceptions.RequestException as e:
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(f"Error occurred: {e}"))
return
if response.content == AUTH_FAILED_TEXT.encode():
# the server answers a rejected token with HTTP 200 and "False", nothing was stored
show_popup(self.prof_diag, "Error", "Session expired, new login required")
# closes the profile dialog too
self.logout()
elif response.status_code == 200:
# shown only once the server has it, and without fetching it back: when that failed, e.g.
# from a server on Windows before 12.0.0, msui fell back to the Gravatar
self.show_server_profile_image(img_byte_arr.getvalue())
QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully")
else:
# the answer comes from the MSColab server
QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(
f"Failed to upload image: {sc.response_message(response, response.text)}"))

def delete_own_account(self, _=None):
reply = QMessageBox.question(
Expand Down Expand Up @@ -1841,14 +1895,7 @@ def logout(self):
self.ui.workLocallyCheckbox.setChecked(False)
self.ui.workLocallyCheckbox.blockSignals(False)

# remove temporary gravatar image
config_path = Path(constants.MSUI_CONFIG_PATH)
gravatar_path = Path(constants.GRAVATAR_DIR_PATH)
# ToDo simplify
if (config_path / "gravatars").exists() and self.gravatar is not None:
if (self.email not in config_loader(dataset="gravatar_ids") and
(gravatar_path / Path(self.gravatar).name).exists()):
(gravatar_path / Path(self.gravatar).name).unlink()
self.remove_temporary_gravatar()
# clear gravatar image path
self.gravatar = None
# clear user email
Expand Down
10 changes: 10 additions & 0 deletions tests/_test_mscolab/test_file_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import pytest
import os
import mock
from pathlib import PurePosixPath, PureWindowsPath

from werkzeug.datastructures import FileStorage

Expand All @@ -38,10 +39,19 @@
from mslib.mscolab.seed import add_user, get_user, add_operation
from mslib.mscolab.utils import ATTACHMENTS_URL_PREFIX, get_operation_dir
from mslib.mscolab.seed import XML_CONTENT_INIT
from mslib.mscolab.file_manager import stored_upload_path

from flask import current_app


def test_stored_upload_path_with_forward_slashes():
"""A server on Windows stored profile\\..., send_from_directory refused it there with 404 (#3403)"""
upload_folder = PureWindowsPath("C:/mss/colabdata/uploads")
assert stored_upload_path(upload_folder / "profile" / "1-x.png", upload_folder) == "profile/1-x.png"
upload_folder = PurePosixPath("/srv/mss/colabdata/uploads")
assert stored_upload_path(upload_folder / "profile" / "1-x.png", upload_folder) == "profile/1-x.png"


class Test_FileManager:
@pytest.fixture(autouse=True)
def setup(self, mscolab_app, mscolab_managers):
Expand Down
Loading
Loading