tools.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # Copyright (c) 2018 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. Misc tools
  22. """
  23. import shutil, sys, os, logging, argparse, json
  24. from io import BytesIO
  25. from warcio.archiveiterator import ArchiveIterator
  26. from warcio.warcwriter import WARCWriter
  27. from yarl import URL
  28. from pkg_resources import parse_version, parse_requirements
  29. from .util import getSoftwareInfo, StrJsonEncoder
  30. from .warc import jsonMime, makeContentType
  31. def mergeWarc (files, output):
  32. # stats
  33. unique = 0
  34. revisit = 0
  35. uniqueLength = 0
  36. revisitLength = 0
  37. payloadMap = {}
  38. writer = WARCWriter (output, gzip=True)
  39. # Add an additional warcinfo record, describing the transformations. This
  40. # is not ideal, since
  41. # “A ‘warcinfo’ record describes the records that
  42. # follow it […] until next ‘warcinfo’”
  43. # -- https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/#warcinfo
  44. # A warcinfo record is expected at the beginning of every file. But it
  45. # might have written by a different software, so we don’t want to
  46. # strip/replace that information, but supplement it.
  47. warcinfo = {
  48. 'software': getSoftwareInfo (),
  49. 'tool': 'crocoite-merge', # not the name of the cli tool
  50. 'parameters': {'inputs': files},
  51. }
  52. payload = BytesIO (json.dumps (warcinfo, indent=2).encode ('utf-8'))
  53. record = writer.create_warc_record ('', 'warcinfo',
  54. payload=payload,
  55. warc_headers_dict={'Content-Type': makeContentType (jsonMime, 'utf-8')})
  56. writer.write_record (record)
  57. for l in files:
  58. with open (l, 'rb') as fd:
  59. for record in ArchiveIterator (fd):
  60. if record.rec_type in {'resource', 'response'}:
  61. headers = record.rec_headers
  62. rid = headers.get_header('WARC-Record-ID')
  63. csum = headers.get_header('WARC-Payload-Digest')
  64. length = int (headers.get_header ('Content-Length'))
  65. dup = payloadMap.get (csum, None)
  66. if dup is None:
  67. payloadMap[csum] = {'uri': headers.get_header('WARC-Target-URI'),
  68. 'id': rid, 'date': headers.get_header('WARC-Date')}
  69. unique += 1
  70. uniqueLength += length
  71. else:
  72. logging.debug (f'Record {rid} is duplicate of {dup["id"]}')
  73. # Payload may be identical, but HTTP headers are
  74. # (probably) not. Include them.
  75. record = writer.create_revisit_record (
  76. headers.get_header('WARC-Target-URI'), digest=csum,
  77. refers_to_uri=dup['uri'], refers_to_date=dup['date'],
  78. http_headers=record.http_headers)
  79. record.rec_headers.add_header ('WARC-Truncated', 'length')
  80. record.rec_headers.add_header ('WARC-Refers-To', dup['id'])
  81. revisit += 1
  82. revisitLength += length
  83. else:
  84. unique += 1
  85. writer.write_record (record)
  86. json.dump (dict (
  87. unique=dict (records=unique, bytes=uniqueLength),
  88. revisit=dict (records=revisit, bytes=revisitLength),
  89. ratio=dict (
  90. records=unique/(unique+revisit),
  91. bytes=uniqueLength/(uniqueLength+revisitLength)
  92. ),
  93. ),
  94. sys.stdout,
  95. cls=StrJsonEncoder)
  96. sys.stdout.write ('\n')
  97. def mergeWarcCli():
  98. parser = argparse.ArgumentParser(description='Merge WARCs, reads filenames from stdin.')
  99. parser.add_argument('--verbose', '-v', action='store_true')
  100. parser.add_argument('output', type=argparse.FileType ('wb'), help='Output WARC')
  101. args = parser.parse_args()
  102. loglevel = logging.DEBUG if args.verbose else logging.INFO
  103. logging.basicConfig (level=loglevel)
  104. mergeWarc([l.strip() for l in sys.stdin], args.output)
  105. def extractScreenshot ():
  106. """
  107. Extract page screenshots from a WARC generated by crocoite into files
  108. """
  109. parser = argparse.ArgumentParser(description='Extract screenshots from '
  110. 'WARC, write JSON info to stdout.')
  111. parser.add_argument('-f', '--force', action='store_true',
  112. help='Overwrite existing files')
  113. parser.add_argument('-1', '--one', action='store_true',
  114. help='Only extract the first screenshot into a file named prefix')
  115. parser.add_argument('input', type=argparse.FileType ('rb'),
  116. help='Input WARC')
  117. parser.add_argument('prefix', help='Output file prefix')
  118. args = parser.parse_args()
  119. i = 0
  120. with args.input:
  121. for record in ArchiveIterator (args.input):
  122. headers = record.rec_headers
  123. if record.rec_type != 'conversion' or \
  124. headers['Content-Type'] != 'image/png' or \
  125. 'X-Crocoite-Screenshot-Y-Offset' not in headers:
  126. continue
  127. url = URL (headers.get_header ('WARC-Target-URI'))
  128. yoff = int (headers.get_header ('X-Crocoite-Screenshot-Y-Offset'))
  129. outpath = f'{args.prefix}{i:05d}.png' if not args.one else args.prefix
  130. if args.force or not os.path.exists (outpath):
  131. json.dump ({'file': outpath, 'url': url, 'yoff': yoff},
  132. sys.stdout, cls=StrJsonEncoder)
  133. sys.stdout.write ('\n')
  134. with open (outpath, 'wb') as out:
  135. shutil.copyfileobj (record.raw_stream, out)
  136. i += 1
  137. else:
  138. print (f'not overwriting {outpath}', file=sys.stderr)
  139. if args.one:
  140. break
  141. class Errata:
  142. __slots__ = ('uuid', 'description', 'url', 'affects')
  143. def __init__ (self, uuid, description, affects, url=None):
  144. self.uuid = uuid
  145. self.description = description
  146. self.url = url
  147. # slightly abusing setuptool’s version parsing/matching here
  148. self.affects = list (parse_requirements(affects))
  149. def __contains__ (self, pkg):
  150. """
  151. Return True if the versions in pkg are affected by this errata
  152. pkg must be a mapping from project_name to version
  153. """
  154. matchedAll = []
  155. for a in self.affects:
  156. haveVersion = pkg.get (a.project_name, None)
  157. matchedAll.append (haveVersion is not None and haveVersion in a)
  158. return all (matchedAll)
  159. def __repr__ (self):
  160. return f'{self.__class__.__name__}({self.uuid!r}, {self.description!r}, {self.affects!r})'
  161. @property
  162. def fixable (self):
  163. return getattr (self, 'applyFix', None) is not None
  164. def toDict (self):
  165. return {'uuid': self.uuid,
  166. 'description': self.description,
  167. 'url': self.url,
  168. 'affects': list (map (str, self.affects)),
  169. 'fixable': self.fixable}
  170. class FixableErrata(Errata):
  171. __slots__ = ('stats')
  172. def __init__ (self, uuid, description, affects, url=None):
  173. super().__init__ (uuid, description, affects, url)
  174. # statistics for fixable erratas
  175. self.stats = dict (records=dict (fixed=0, processed=0))
  176. def applyFix (self, record):
  177. raise NotImplementedError () # pragma: no cover
  178. class ContentTypeErrata (FixableErrata):
  179. def __init__ (self):
  180. super().__init__ (
  181. uuid='552c13dc-56e5-4539-9ad8-184ccae60930',
  182. description='Content-Type header uses wrong argument name encoding instead of charset.',
  183. url='https://github.com/PromyLOPh/crocoite/issues/19',
  184. affects=['crocoite==1.0.0'])
  185. def applyFix (self, record):
  186. # XXX: this is ugly. warcio’s write_record replaces any Content-Type
  187. # header we’re setting with this one. But printing rec_headers shows
  188. # the header, not .content_type.
  189. contentType = record.content_type
  190. if '; encoding=' in contentType:
  191. contentType = contentType.replace ('; encoding=', '; charset=')
  192. record.content_type = contentType
  193. self.stats['records']['fixed'] += 1
  194. self.stats['records']['processed'] += 1
  195. return record
  196. bugs = [
  197. Errata (uuid='34a176b3-ad3d-430f-a082-68087f304572',
  198. description='Generated by version < 1.0. No erratas are supported for this version.',
  199. affects=['crocoite<1.0'],
  200. ),
  201. ContentTypeErrata (),
  202. ]
  203. def makeReport (fd):
  204. alreadyFixed = set ()
  205. for record in ArchiveIterator (fd):
  206. if record.rec_type == 'warcinfo':
  207. try:
  208. data = json.load (record.raw_stream)
  209. # errata records precceed everything else and indicate which
  210. # ones were fixed already
  211. if data['tool'] == 'crocoite-errata':
  212. alreadyFixed.update (data['parameters']['errata'])
  213. else:
  214. haveVersions = dict ([(pkg['projectName'], parse_version(pkg['version'])) for pkg in data['software']['self']])
  215. yield from filter (lambda b: haveVersions in b and b.uuid not in alreadyFixed, bugs)
  216. except json.decoder.JSONDecodeError:
  217. pass
  218. def errataCheck (args):
  219. hasErrata = False
  220. for item in makeReport (args.input):
  221. json.dump (item.toDict (), sys.stdout)
  222. sys.stdout.write ('\n')
  223. sys.stdout.flush ()
  224. hasErrata = True
  225. return int (hasErrata)
  226. def errataFix (args):
  227. errata = args.errata
  228. with args.input as infd, args.output as outfd:
  229. writer = WARCWriter (outfd, gzip=True)
  230. warcinfo = {
  231. 'software': getSoftwareInfo (),
  232. 'tool': 'crocoite-errata', # not the name of the cli tool
  233. 'parameters': {'errata': [errata.uuid]},
  234. }
  235. payload = BytesIO (json.dumps (warcinfo, indent=2).encode ('utf-8'))
  236. record = writer.create_warc_record ('', 'warcinfo',
  237. payload=payload,
  238. warc_headers_dict={'Content-Type': makeContentType (jsonMime, 'utf-8')})
  239. writer.write_record (record)
  240. for record in ArchiveIterator (infd):
  241. fixedRecord = errata.applyFix (record)
  242. writer.write_record (fixedRecord)
  243. json.dump (errata.stats, sys.stdout)
  244. sys.stdout.write ('\n')
  245. sys.stdout.flush ()
  246. def uuidToErrata (uuid, onlyFixable=True):
  247. try:
  248. e = next (filter (lambda x: x.uuid == uuid, bugs))
  249. except StopIteration:
  250. raise argparse.ArgumentTypeError (f'Errata {uuid} does not exist')
  251. if not isinstance (e, FixableErrata):
  252. raise argparse.ArgumentTypeError (f'Errata {uuid} is not fixable')
  253. return e
  254. def errata ():
  255. parser = argparse.ArgumentParser(description=f'Show/fix erratas for WARCs generated by {__package__}.')
  256. parser.add_argument('input', metavar='INPUT', type=argparse.FileType ('rb'), help='Input WARC')
  257. # XXX: required argument does not work here?!
  258. subparsers = parser.add_subparsers()
  259. checkparser = subparsers.add_parser('check', help='Show erratas')
  260. checkparser.set_defaults (func=errataCheck)
  261. fixparser = subparsers.add_parser('fix', help='Fix erratas')
  262. fixparser.add_argument('errata', metavar='UUID', type=uuidToErrata, help='Apply fix for this errata')
  263. fixparser.add_argument('output', metavar='OUTPUT', type=argparse.FileType ('wb'), help='Output WARC')
  264. fixparser.set_defaults (func=errataFix)
  265. args = parser.parse_args()
  266. if not hasattr (args, 'func'):
  267. parser.print_usage ()
  268. parser.exit ()
  269. return args.func (args)