The little things give you away... A collection of various small helper stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

144 lines
5.4 KiB

  1. #!/usr/bin/env python3
  2. import asyncio
  3. import collections
  4. import http.client
  5. import json
  6. import re
  7. import shlex
  8. import sys
  9. HOST = 'web.archive.org'
  10. def make_connection():
  11. return http.client.HTTPSConnection(HOST, timeout = 60)
  12. def fetch(url, tries, connection):
  13. for i in range(tries):
  14. try:
  15. print(f'GET {url}', file = sys.stderr)
  16. connection.request('GET', url)
  17. r = connection.getresponse()
  18. status = r.status
  19. print(f'{status} {url}', file = sys.stderr)
  20. if status != 200:
  21. raise RuntimeError(f'Could not fetch {url}')
  22. data = r.read()
  23. print(f'Read {len(data)} bytes from {url}', file = sys.stderr)
  24. o = json.loads(data)
  25. break
  26. except (RuntimeError, TimeoutError, http.client.HTTPException, json.JSONDecodeError) as e:
  27. print(f'Error retrieving {url}: {type(e).__module__}.{type(e).__name__} {e!s}', file = sys.stderr)
  28. connection.close()
  29. connection = make_connection()
  30. if i == tries - 1:
  31. raise
  32. return url, status, o, connection
  33. async def wait_first_and_print(tasks):
  34. if not tasks:
  35. return
  36. task = tasks.popleft()
  37. url, code, o, connection = await task
  38. assert o, 'got empty response'
  39. fields = o[0]
  40. assert all(len(v) == len(fields) for v in o[1:]), 'got unexpected response format'
  41. for row in o[1:]:
  42. print(json.dumps(dict(zip(fields, row))))
  43. print(f'Completed processing page {task._ia_cdx_page}', file = sys.stderr)
  44. return task._ia_cdx_page, connection
  45. async def main(query, concurrency = 1, tries = 1, startPage = None, numPages = None):
  46. assert (startPage is None) == (numPages is None)
  47. connections = collections.deque()
  48. for i in range(concurrency):
  49. connections.append(make_connection())
  50. baseUrl = f'/cdx/search/cdx?{query}'
  51. if startPage is None:
  52. url = f'{baseUrl}&showNumPages=true'
  53. connection = connections.popleft()
  54. _, _, numPages, connection = fetch(url, tries, connection)
  55. numPages = int(numPages)
  56. connections.append(connection)
  57. startPage = 0
  58. print(f'{numPages} pages', file = sys.stderr)
  59. loop = asyncio.get_running_loop()
  60. tasks = collections.deque()
  61. lastGoodPage = -1
  62. try:
  63. try:
  64. for page in range(startPage, numPages):
  65. while len(tasks) >= concurrency:
  66. lastGoodPage, connection = await wait_first_and_print(tasks)
  67. connections.append(connection)
  68. url = f'{baseUrl}&output=json&page={page}'
  69. connection = connections.popleft()
  70. task = loop.run_in_executor(None, fetch, url, tries, connection)
  71. task._ia_cdx_page = page
  72. tasks.append(task)
  73. while len(tasks) > 0:
  74. lastGoodPage, connection = await wait_first_and_print(tasks)
  75. connections.append(connection)
  76. except:
  77. # It isn't possible to actually cancel a task running in a thread, so need to await them and discard any additional errors that occur.
  78. for task in tasks:
  79. try:
  80. _, _, _, connection = await task
  81. except:
  82. pass
  83. else:
  84. connections.append(connection)
  85. for connection in connections:
  86. connection.close()
  87. raise
  88. except (RuntimeError, json.JSONDecodeError, AssertionError):
  89. concurrencyS = f'--concurrency {concurrency} ' if concurrency != 1 else ''
  90. triesS = f'--tries {tries} ' if tries != 1 else ''
  91. print(f'To resume this search from where it crashed, run: ia-cdx-search {concurrencyS}{triesS}--page {lastGoodPage + 1} --numpages {numPages} {shlex.quote(query)}', file = sys.stderr)
  92. raise
  93. except (BrokenPipeError, KeyboardInterrupt):
  94. pass
  95. def usage():
  96. print('Usage: ia-cdx-search [--concurrency N] [--tries N] [--page N --numpages N] QUERY', file = sys.stderr)
  97. print('Please refer to https://github.com/internetarchive/wayback/tree/master/wayback-cdx-server for the relevant query parameters', file = sys.stderr)
  98. print('The output, limit, resumeKey, showResumeKey, page, and showNumPages parameters must not be included.', file = sys.stderr)
  99. print('To resume a search that failed for some reason, provide the page number and number of pages through the second argument instead.', file = sys.stderr)
  100. print('Output is produces in JSONL format with one line per CDX entry.', file = sys.stderr)
  101. print('', file = sys.stderr)
  102. print('Examples:', file = sys.stderr)
  103. print(" - Subdomains: ia-cdx-search 'url=example.org&collapse=urlkey&fl=original&matchType=domain&filter=original:^https?://[^/]*example\.org(?::[0-9]*)?/'", file = sys.stderr)
  104. print(' Note that this will only find subdomains whose homepages are in the Wayback Machine. To discover all known subdomains, remove the filter and then extract the domains from the results.', file = sys.stderr)
  105. print(" - Subdirectories: ia-cdex-search 'url=example.org&collapse=urlkey&fl=original&matchType=domain&filter=original:^https?://[^/]*example\.org(?::[0-9]*)?/[^/]*/'", file = sys.stderr)
  106. print(' The same caveat applies. The directory must have been retrieved directly without an additional trailing path or query string.', file = sys.stderr)
  107. sys.exit(1)
  108. args = sys.argv[1:]
  109. if args[0].lower() in ('-h', '--help'):
  110. usage()
  111. kwargs = {}
  112. while args[0].startswith('--'):
  113. if args[0] == '--concurrency':
  114. kwargs['concurrency'] = int(args[1])
  115. args = args[2:]
  116. elif args[0] == '--tries':
  117. kwargs['tries'] = int(args[1])
  118. args = args[2:]
  119. elif args[0] == '--page' and args[2].lower() == '--numpages':
  120. kwargs['startPage'] = int(args[1])
  121. kwargs['numPages'] = int(args[3])
  122. args = args[4:]
  123. else:
  124. break
  125. if len(args) != 1 or re.search(r'(^|&)(output|limit|resumekey|showresumekey|page|shownumpages)=', args[0], re.IGNORECASE):
  126. usage()
  127. query = args[0]
  128. asyncio.run(main(query, **kwargs))