identicon_resource.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from pydenticon import Generator
  15. from twisted.web.resource import Resource
  16. FOREGROUND = [
  17. "rgb(45,79,255)",
  18. "rgb(254,180,44)",
  19. "rgb(226,121,234)",
  20. "rgb(30,179,253)",
  21. "rgb(232,77,65)",
  22. "rgb(49,203,115)",
  23. "rgb(141,69,170)"
  24. ]
  25. BACKGROUND = "rgb(224,224,224)"
  26. SIZE = 5
  27. class IdenticonResource(Resource):
  28. isLeaf = True
  29. def __init__(self):
  30. Resource.__init__(self)
  31. self.generator = Generator(
  32. SIZE, SIZE, foreground=FOREGROUND, background=BACKGROUND,
  33. )
  34. def generate_identicon(self, name, width, height):
  35. v_padding = width % SIZE
  36. h_padding = height % SIZE
  37. top_padding = v_padding // 2
  38. left_padding = h_padding // 2
  39. bottom_padding = v_padding - top_padding
  40. right_padding = h_padding - left_padding
  41. width -= v_padding
  42. height -= h_padding
  43. padding = (top_padding, bottom_padding, left_padding, right_padding)
  44. identicon = self.generator.generate(
  45. name, width, height, padding=padding
  46. )
  47. return identicon
  48. def render_GET(self, request):
  49. name = "/".join(request.postpath)
  50. width = int(request.args.get("width", [96])[0])
  51. height = int(request.args.get("height", [96])[0])
  52. identicon_bytes = self.generate_identicon(name, width, height)
  53. request.setHeader(b"Content-Type", b"image/png")
  54. request.setHeader(
  55. b"Cache-Control", b"public,max-age=86400,s-maxage=86400"
  56. )
  57. return identicon_bytes