util.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # Copyright (c) 2017 crocoite contributors
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. # THE SOFTWARE.
  20. """
  21. Random utility functions
  22. """
  23. import random, sys, platform, os, json, urllib
  24. from datetime import datetime
  25. import hashlib, pkg_resources
  26. from yarl import URL
  27. class StrJsonEncoder (json.JSONEncoder):
  28. """ JSON encoder that turns unknown classes into a string and thus never
  29. fails """
  30. def default (self, obj):
  31. if isinstance (obj, datetime):
  32. return obj.isoformat ()
  33. # make sure serialization always succeeds
  34. try:
  35. return json.JSONEncoder.default(self, obj)
  36. except TypeError:
  37. return str (obj)
  38. async def getFormattedViewportMetrics (tab):
  39. layoutMetrics = await tab.Page.getLayoutMetrics ()
  40. # XXX: I’m not entirely sure which one we should use here
  41. viewport = layoutMetrics['layoutViewport']
  42. return f"{viewport['clientWidth']}x{viewport['clientHeight']}"
  43. def getSoftwareInfo ():
  44. """ Get software info for inclusion into warcinfo """
  45. return {
  46. 'platform': platform.platform (),
  47. 'python': {
  48. 'implementation': platform.python_implementation(),
  49. 'version': platform.python_version (),
  50. 'build': platform.python_build ()
  51. },
  52. 'self': getRequirements (__package__)
  53. }
  54. def getRequirements (dist):
  55. """ Get dependencies of a package.
  56. Figure out packages’ dependencies based on setup/distutils, then look at
  57. modules loaded and compute hashes of each loaded dependency.
  58. This does not and cannot protect against malicious people. It’s only
  59. purpose is to recreate this exact environment.
  60. """
  61. pending = {dist}
  62. have = set ()
  63. packages = []
  64. while pending:
  65. d = pkg_resources.get_distribution (pending.pop ())
  66. modules = list (filter (lambda x: x, d.get_metadata ('top_level.txt').split ('\n')))
  67. modhashes = {}
  68. # hash loaded modules
  69. for m in sys.modules.values ():
  70. f = getattr (m, '__file__', None)
  71. pkg = getattr (m, '__package__', None)
  72. # is loaded?
  73. if pkg in modules:
  74. if f and os.path.isfile (f):
  75. with open (f, 'rb') as fd:
  76. contents = fd.read ()
  77. h = hashlib.new ('sha512')
  78. h.update (contents)
  79. modhashes[m.__name__] = {'sha512': h.hexdigest (), 'len': len (contents)}
  80. else:
  81. modhashes[m.__name__] = {}
  82. # only if one of the packages’ modules is actually loaded
  83. if modhashes:
  84. packages.append ({'projectName': d.project_name, 'modules': modhashes, 'version': d.version})
  85. have.add (dist)
  86. pending.update (d.requires ())
  87. pending.difference_update (have)
  88. return packages