import contextlib
import re
import uuid
from base64 import b64decode
from datetime import datetime
import werkzeug.exceptions
import werkzeug.urls
import requests
from os.path import join as opj
from odoo import _, http, tools, SUPERUSER_ID
from odoo.addons.html_editor.tools import get_video_url_data
from odoo.exceptions import UserError, MissingError, AccessError
from odoo.http import request
from odoo.tools.mimetypes import guess_mimetype
from odoo.tools.misc import file_open
from odoo.addons.iap.tools import iap_tools
from odoo.addons.mail.tools import link_preview
from lxml import html
from ..models.ir_attachment import SUPPORTED_IMAGE_MIMETYPES
DEFAULT_LIBRARY_ENDPOINT = 'https://media-api.odoo.com'
DEFAULT_OLG_ENDPOINT = 'https://olg.api.odoo.com'
# Regex definitions to apply speed modification in SVG files
# Note : These regex patterns are duplicated on the server side for
# background images that are part of a CSS rule "background-image: ...". The
# client-side regex patterns are used for images that are part of an
# "src" attribute with a base64 encoded svg in the tag. Perhaps we should
# consider finding a solution to define them only once? The issue is that the
# regex patterns in Python are slightly different from those in JavaScript.
CSS_ANIMATION_RULE_REGEX = (
r"(?Panimation(-duration)?: .*?)"
+ r"(?P(\d+(\.\d+)?)|(\.\d+))"
+ r"(?Pms|s)"
+ r"(?P\s|;|\"|$)"
)
SVG_DUR_TIMECOUNT_VAL_REGEX = (
r"(?P\sdur=\"\s*)"
+ r"(?P(\d+(\.\d+)?)|(\.\d+))"
+ r"(?Ph|min|ms|s)?\s*\""
)
CSS_ANIMATION_RATIO_REGEX = (
r"(--animation_ratio: (?P\d*(\.\d+)?));"
)
def _get_shape_svg(self, module, *segments):
shape_path = opj(module, 'static', *segments)
try:
with file_open(shape_path, 'r', filter_ext=('.svg',)) as file:
return file.read()
except FileNotFoundError:
raise werkzeug.exceptions.NotFound()
def get_existing_attachment(IrAttachment, vals):
"""
Check if an attachment already exists for the same vals. Return it if
so, None otherwise.
"""
fields = dict(vals)
# Falsy res_id defaults to 0 on attachment creation.
fields['res_id'] = fields.get('res_id') or 0
raw, datas = fields.pop('raw', None), fields.pop('datas', None)
domain = [(field, '=', value) for field, value in fields.items()]
if fields.get('type') == 'url':
if 'url' not in fields:
return None
domain.append(('checksum', '=', False))
else:
if not (raw or datas):
return None
domain.append(('checksum', '=', IrAttachment._compute_checksum(raw or b64decode(datas))))
return IrAttachment.search(domain, limit=1) or None
class HTML_Editor(http.Controller):
def _get_shape_svg(self, module, *segments):
shape_path = opj(module, 'static', *segments)
try:
with file_open(shape_path, 'r', filter_ext=('.svg',)) as file:
return file.read()
except FileNotFoundError:
raise werkzeug.exceptions.NotFound()
def _update_svg_colors(self, options, svg):
user_colors = []
svg_options = {}
default_palette = {
'1': '#3AADAA',
'2': '#7C6576',
'3': '#F6F6F6',
'4': '#FFFFFF',
'5': '#383E45',
}
bundle_css = None
regex_hex = r'#[0-9A-F]{6,8}'
regex_rgba = r'rgba?\(\d{1,3}, ?\d{1,3}, ?\d{1,3}(?:, ?[0-9.]{1,4})?\)'
for key, value in options.items():
colorMatch = re.match('^c([1-5])$', key)
if colorMatch:
css_color_value = value
# Check that color is hex or rgb(a) to prevent arbitrary injection
if not re.match(r'(?i)^%s$|^%s$' % (regex_hex, regex_rgba), css_color_value.replace(' ', '')):
if re.match('^o-color-([1-5])$', css_color_value):
if not bundle_css:
bundle = 'web.assets_frontend'
asset = request.env["ir.qweb"]._get_asset_bundle(bundle)
bundle_css = asset.css().index_content
color_search = re.search(r'(?i)--%s:\s+(%s|%s)' % (css_color_value, regex_hex, regex_rgba), bundle_css)
if not color_search:
raise werkzeug.exceptions.BadRequest()
css_color_value = color_search.group(1)
else:
raise werkzeug.exceptions.BadRequest()
user_colors.append([tools.html_escape(css_color_value), colorMatch.group(1)])
else:
svg_options[key] = value
color_mapping = {default_palette[palette_number]: color for color, palette_number in user_colors}
# create a case-insensitive regex to match all the colors to replace, eg: '(?i)(#3AADAA)|(#7C6576)'
regex = '(?i)%s' % '|'.join('(%s)' % color for color in color_mapping.keys())
def subber(match):
key = match.group().upper()
return color_mapping[key] if key in color_mapping else key
return re.sub(regex, subber, svg), svg_options
def replace_animation_duration(self,
shape_animation_speed: float,
svg: str):
"""
Replace animation durations in SVG and CSS with modified values.
This function takes a speed value and an SVG string containing
animations. It uses regular expressions to find and replace the
duration values in both CSS animation rules and SVG duration attributes
based on the provided speed.
Parameters:
- speed (float): The speed used to calculate the new animation
durations.
- svg (str): The SVG string containing animations.
Returns:
str: The modified SVG string with updated animation durations.
"""
ratio = (1 + shape_animation_speed
if shape_animation_speed >= 0
else 1 / (1 - shape_animation_speed))
def callback_css_animation_rule(match):
# Extracting matched groups.
declaration, value, unit, separator = (
match.group("declaration"),
match.group("value"),
match.group("unit"),
match.group("separator"),
)
# Calculating new animation duration based on ratio.
value = str(float(value) / (ratio or 1))
# Constructing and returning the modified CSS animation rule.
return f"{declaration}{value}{unit}{separator}"
def callback_svg_dur_timecount_val(match):
attribute_name, value, unit = (
match.group("attribute_name"),
match.group("value"),
match.group("unit"),
)
# Calculating new duration based on ratio.
value = str(float(value) / (ratio or 1))
# Constructing and returning the modified SVG duration attribute.
return f'{attribute_name}{value}{unit or "s"}"'
def callback_css_animation_ratio(match):
ratio = match.group("ratio")
return f'--animation_ratio: {ratio};'
# Applying regex substitutions to modify animation speed in the
# 'svg' variable.
svg = re.sub(
CSS_ANIMATION_RULE_REGEX,
callback_css_animation_rule,
svg
)
svg = re.sub(
SVG_DUR_TIMECOUNT_VAL_REGEX,
callback_svg_dur_timecount_val,
svg
)
# Create or modify the css variable --animation_ratio for future
# purpose.
if re.match(CSS_ANIMATION_RATIO_REGEX, svg):
svg = re.sub(
CSS_ANIMATION_RATIO_REGEX,
callback_css_animation_ratio,
svg
)
else:
regex = r"