2
0
Fork 0

Added a similar system for images to videos

This commit is contained in:
Thomas Touhey 2018-09-10 16:45:17 +02:00
parent dd19f7cf20
commit dcb8611e37
No known key found for this signature in database
GPG Key ID: 2ECEB0517AD947FB
7 changed files with 105 additions and 25 deletions

View File

@ -2,18 +2,21 @@
ST := pipenv run ./setup.py
DNAME := dist/$(shell $(ST) --name)-$(shell $(ST) --version).tar.gz
test tests:
test tests: -prepare
@$(ST) test
docs:
docs: -prepare
@$(ST) build_sphinx
dist: $(DNAME)
$(DNAME):
$(DNAME): -prepare
@$(ST) sdist
upload: $(DNAME)
@twine upload $(DNAME)
.PHONY: test tests dist docs
-prepare:
@pipenv sync
.PHONY: -prepare test tests dist docs
# End of file.

View File

@ -12,12 +12,12 @@ from io import StringIO as _StringIO
from ._options import TextoutOptions as Options, \
TextoutBlockTag as BlockTag, TextoutInlineTag as InlineTag, \
TextoutParagraphTag as ParagraphTag, TextoutSmiley as Smiley, \
TextoutVideo as Video
TextoutImage as Image, TextoutVideo as Video
from ._translate import Translator as _Translator
__all__ = ["version", "tohtml", "tolightscript",
"Options", "BlockTag", "ParagraphTag", "InlineTag",
"Smiley", "Video"]
"Smiley", "Image", "Video"]
version = "0.2"

View File

@ -22,7 +22,7 @@ from ._html import SmileyConvertor as _htmlsm
__all__ = ["TextoutOptions",
"TextoutTag", "TextoutBlockTag", "TextoutInlineTag", "TextoutParagraphTag",
"TextoutSmiley", "TextoutVideo"]
"TextoutSmiley", "TextoutImage", "TextoutVideo"]
def _getargscount(func):
try:
@ -40,7 +40,7 @@ def _getargscount(func):
class TextoutTag:
""" The textout tag base class.
Is initialized with these values:
<name><content><name>
| name: "<name>" (only special chars such as `)
| value: None
@ -156,6 +156,9 @@ class TextoutTag:
except KeyError:
return default
def image(self, *args, **kwargs):
return self.__options.get_image(*args, **kwargs)
def video(self, *args, **kwargs):
return self.__options.get_video(*args, **kwargs)
@ -194,18 +197,21 @@ class TextoutSmiley:
f"url = {repr(self.url)})"
# ---
# Videos.
# Multimedia.
# ---
class TextoutImage:
""" Base class for images. """
def __init__(self, url):
raise ValueError("no URL supported")
class TextoutVideo:
""" Base class for videos. """
def __init__(self, url):
raise ValueError("no URL supported")
def embed(self):
return "http://example.org/"
# ---
# Options extractor and manager.
# ---
@ -228,6 +234,7 @@ class TextoutOptions:
self._aliases = {}
self._s_aliases = {}
self._videos = []
self._images = []
if default:
self.add(_get_builtin_module())
@ -258,6 +265,10 @@ class TextoutOptions:
self._htmlsm = None
return True
if _isclass(element) and issubclass(element, TextoutImage):
if not any(image is element for image in self._images):
self._images.append(element)
if _isclass(element) and issubclass(element, TextoutVideo):
if not any(video is element for video in self._videos):
self._videos.append(element)
@ -314,6 +325,19 @@ class TextoutOptions:
raise ValueError("invalid video URL")
return v
def get_image(self, url):
""" Get an image using its URL. """
for image in self._images:
try:
i = image(url)
except:
continue
break
else:
raise ValueError("invalid image URL")
return i
def get_tag(self, name):
""" Get the tag class corresponding to a name. """

View File

@ -4,6 +4,8 @@
# This file is part of the textoutpc project, which is MIT-licensed.
#******************************************************************************
import urllib.parse as _urlparse
from .. import BlockTag as _BlockTag
from html import escape as _htmlescape
@ -41,6 +43,7 @@ class ImageTag(_BlockTag):
self._width = None
self._height = None
self._align = None
self._float = False
for arg in ("", value)[value is not None].split('|'):
if not arg:
@ -65,18 +68,21 @@ class ImageTag(_BlockTag):
if fl:
self._float = True
def _checkurl(self):
for prefix in ('http://', 'https://', 'ftp://', '/'):
if self._url.startswith(prefix):
break
else:
raise Exception("No allowed prefix!")
def preprocess(self, content):
self._url = content
self._checkurl()
try:
self._image = self.image(content)
except:
url = _urlparse.urlparse(content)
if url.scheme not in ('http', 'https'):
raise Exception("No allowed prefix!")
self._image = content
def content_html(self):
if isinstance(self._image, str):
url = _htmlescape(self._image)
return '<p><a href="{}">{}</a></p>'.format(url, url)
style = []
cls = []
if self._width:
@ -92,12 +98,12 @@ class ImageTag(_BlockTag):
elif self._align:
cls.append('img-{}'.format(self._align))
return '<img src="{}"{}{} />'.format(_htmlescape(self._url),
return '<img src="{}"{}{} />'.format(_htmlescape(self._image.embed),
' class="{}"'.format(' '.join(cls)) if cls else '',
' style="{}"'.format('; '.join(style)) if style else '')
def content_lightscript(self):
url = self._url.replace('[', '%5B').replace(']', '%5D')
url = self._image.embed.replace('[', '%5B').replace(']', '%5D')
return '[[image:{}]]'.format(url)

View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2018 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
# This file is part of the textoutpc project, which is MIT-licensed.
#******************************************************************************
import urllib.parse as _urlparse
from .. import Image as _Image
__all__ = ["GenericImage"]
class GenericImage(_Image):
""" Get a direct image. Actually this doesn't test anything, we should
use like the Embed module again, as for videos. """
# FIXME: make that disappear one day for the OpenWebImage.
def __init__(self, content):
url = _urlparse.urlparse(content)
if url.scheme not in ('http', 'https'):
raise Exception("No allowed prefix!")
self.embed = content
# WARNING: This is only for demonstration sake. Do not use without a cache!
# This demonstration class uses the `embed-python` module.
#
#from embed import Embed as _Embed
#
#class OpenWebImage(_Image):
# """ Decentralized way to gather an image data. """
#
# def __init__(self, url):
# u = _urlparse.urlparse(url)
# if not u.scheme in ('https',):
# raise Exception
#
# embed = _Embed(url)
# embed = embed.embed
# assert embed['type'] == 'image'
#
# self.embed = embed['url']
# End of file.

View File

@ -86,7 +86,7 @@ class VimeoVideo(_Video):
#
# def __init__(self, url):
# u = _urlparse.urlparse(url)
# if not u.scheme in ('https'):
# if not u.scheme in ('https',):
# raise Exception
#
# embed = _Embed(url)

View File

@ -25,9 +25,10 @@ from ._Text import *
from ._Title import *
from ._Video import *
# Other resources (smileys, videos).
# Other resources (smileys, multimedia).
from ._Smileys import *
from ._Images import *
from ._Videos import *
# End of file.