identicon_resource.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. from synapse.http.servlet import parse_integer
  17. FOREGROUND = [
  18. "rgb(45,79,255)",
  19. "rgb(254,180,44)",
  20. "rgb(226,121,234)",
  21. "rgb(30,179,253)",
  22. "rgb(232,77,65)",
  23. "rgb(49,203,115)",
  24. "rgb(141,69,170)"
  25. ]
  26. BACKGROUND = "rgb(224,224,224)"
  27. SIZE = 5
  28. class IdenticonResource(Resource):
  29. isLeaf = True
  30. def __init__(self):
  31. Resource.__init__(self)
  32. self.generator = Generator(
  33. SIZE, SIZE, foreground=FOREGROUND, background=BACKGROUND,
  34. )
  35. def generate_identicon(self, name, width, height):
  36. v_padding = width % SIZE
  37. h_padding = height % SIZE
  38. top_padding = v_padding // 2
  39. left_padding = h_padding // 2
  40. bottom_padding = v_padding - top_padding
  41. right_padding = h_padding - left_padding
  42. width -= v_padding
  43. height -= h_padding
  44. padding = (top_padding, bottom_padding, left_padding, right_padding)
  45. identicon = self.generator.generate(
  46. name, width, height, padding=padding
  47. )
  48. return identicon
  49. def render_GET(self, request):
  50. name = "/".join(request.postpath)
  51. width = parse_integer(request, "width", default=96)
  52. height = parse_integer(request, "height", default=96)
  53. identicon_bytes = self.generate_identicon(name, width, height)
  54. request.setHeader(b"Content-Type", b"image/png")
  55. request.setHeader(
  56. b"Cache-Control", b"public,max-age=86400,s-maxage=86400"
  57. )
  58. return identicon_bytes