Skip to content

Instantly share code, notes, and snippets.

@intellisense
Created December 18, 2017 19:23
Show Gist options
  • Save intellisense/46538f858de8bf9bceee6a7fe0b0f245 to your computer and use it in GitHub Desktop.
Save intellisense/46538f858de8bf9bceee6a7fe0b0f245 to your computer and use it in GitHub Desktop.
libthumbor CryptoURL patch to support PDF preview URL
from __future__ import absolute_import
import base64
from six import text_type, PY3
from libthumbor import CryptoURL as BaseCryptoURL
from libthumbor.url import get_url_parts
class CryptoURL(BaseCryptoURL):
"""Class responsible for generating encrypted URLs for thumbor"""
def plain_image_url(self, **options):
is_pdf = options.pop('pdf', False)
url_parts = get_url_parts(**options)
if is_pdf:
url_parts.append('pdf')
url_parts.append(options['image_url'])
return '/'.join(url_parts)
def generate_new(self, options):
url = self.plain_image_url(**options)
_hmac = self.hmac.copy()
_hmac.update(text_type(url).encode('utf-8'))
signature = base64.urlsafe_b64encode(_hmac.digest())
if PY3:
signature = signature.decode('ascii')
return '/%s/%s' % (signature, url)
def unsafe_url(self, **options):
"""Returns the unsafe url with the specified options"""
return 'unsafe/%s' % self.plain_image_url(**options)
def generate(self, **options):
"""Generates an encrypted URL with the specified options"""
if options.get('unsafe', False):
return self.unsafe_url(**options)
else:
return self.generate_new(options)
@intellisense
Copy link
Author

libthumbor.CryptoURL patch to support generation of PDF Preview URL, to be used with tc_pdf:

from crypto import CryptoURL

crypto = CryptoURL(key='my-security-key')

encrypted_url = crypto.generate(
    width=300,
    height=200,
    smart=True,
    image_url='/path/to/my/pdf_file.pdf',
    pdf=True, # <-- Pass this
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment