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.
 
 
 

154 lines
6.0 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 socket
  9. import sys
  10. import time
  11. HOST = 'web.archive.org'
  12. def make_connection():
  13. return http.client.HTTPSConnection(HOST, timeout = 60)
  14. def fetch(url, tries, connection):
  15. for i in range(tries):
  16. try:
  17. print(f'GET {url}', file = sys.stderr)
  18. connection.request('GET', url)
  19. r = connection.getresponse()
  20. status = r.status
  21. print(f'{status} {url}', file = sys.stderr)
  22. if status == 302 and r.getheader('Location') in ('https://web.archive.org/429.html', '/429.html'):
  23. # The CDX API is stupid and doesn't return 429s directly...
  24. print('Exceeded rate limit, waiting...', file = sys.stderr)
  25. time.sleep(30)
  26. raise RuntimeError(f'Rate-limited on {url}')
  27. if status != 200:
  28. raise RuntimeError(f'Could not fetch {url}')
  29. data = r.read()
  30. print(f'Read {len(data)} bytes from {url}', file = sys.stderr)
  31. o = json.loads(data)
  32. break
  33. except (RuntimeError, TimeoutError, socket.timeout, ConnectionError, http.client.HTTPException, json.JSONDecodeError) as e:
  34. # socket.timeout is an alias of TimeoutError from Python 3.10 but still needs to be caught explicitly for older versions
  35. print(f'Error retrieving {url}: {type(e).__module__}.{type(e).__name__} {e!s}', file = sys.stderr)
  36. connection.close()
  37. connection = make_connection()
  38. if i == tries - 1:
  39. raise
  40. return url, status, o, connection
  41. async def wait_first_and_print(tasks):
  42. if not tasks:
  43. return
  44. task = tasks.popleft()
  45. url, code, o, connection = await task
  46. if not o:
  47. print(f'Completed processing page {task._ia_cdx_page} (0 results)', file = sys.stderr)
  48. return task._ia_cdx_page, connection
  49. fields = o[0]
  50. assert all(len(v) == len(fields) for v in o[1:]), 'got unexpected response format'
  51. for row in o[1:]:
  52. print(json.dumps(dict(zip(fields, row))))
  53. print(f'Completed processing page {task._ia_cdx_page} ({len(o) - 1} results)', file = sys.stderr)
  54. return task._ia_cdx_page, connection
  55. async def main(query, concurrency = 1, tries = 1, startPage = None, numPages = None):
  56. assert (startPage is None) == (numPages is None)
  57. connections = collections.deque()
  58. for i in range(concurrency):
  59. connections.append(make_connection())
  60. baseUrl = f'/cdx/search/cdx?{query}'
  61. if startPage is None:
  62. url = f'{baseUrl}&showNumPages=true'
  63. connection = connections.popleft()
  64. _, _, numPages, connection = fetch(url, tries, connection)
  65. numPages = int(numPages)
  66. connections.append(connection)
  67. startPage = 0
  68. print(f'{numPages} pages', file = sys.stderr)
  69. loop = asyncio.get_running_loop()
  70. tasks = collections.deque()
  71. lastGoodPage = -1
  72. try:
  73. try:
  74. for page in range(startPage, numPages):
  75. while len(tasks) >= concurrency:
  76. lastGoodPage, connection = await wait_first_and_print(tasks)
  77. connections.append(connection)
  78. url = f'{baseUrl}&output=json&page={page}'
  79. connection = connections.popleft()
  80. task = loop.run_in_executor(None, fetch, url, tries, connection)
  81. task._ia_cdx_page = page
  82. tasks.append(task)
  83. while len(tasks) > 0:
  84. lastGoodPage, connection = await wait_first_and_print(tasks)
  85. connections.append(connection)
  86. except:
  87. # 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.
  88. for task in tasks:
  89. try:
  90. _, _, _, connection = await task
  91. except:
  92. pass
  93. else:
  94. connections.append(connection)
  95. for connection in connections:
  96. connection.close()
  97. raise
  98. except (RuntimeError, json.JSONDecodeError, AssertionError):
  99. concurrencyS = f'--concurrency {concurrency} ' if concurrency != 1 else ''
  100. triesS = f'--tries {tries} ' if tries != 1 else ''
  101. 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)
  102. raise
  103. except (BrokenPipeError, KeyboardInterrupt):
  104. pass
  105. def usage():
  106. print('Usage: ia-cdx-search [--concurrency N] [--tries N] [--page N --numpages N] QUERY', file = sys.stderr)
  107. print('Please refer to https://github.com/internetarchive/wayback/tree/master/wayback-cdx-server for the relevant query parameters', file = sys.stderr)
  108. print('The output, limit, resumeKey, showResumeKey, page, and showNumPages parameters must not be included.', file = sys.stderr)
  109. 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)
  110. print('Output is produces in JSONL format with one line per CDX entry.', file = sys.stderr)
  111. print('', file = sys.stderr)
  112. print('Examples:', file = sys.stderr)
  113. print(" - Subdomains: ia-cdx-search 'url=example.org&collapse=urlkey&fl=original&matchType=domain&filter=original:^https?://[^/]*example\.org(?::[0-9]*)?/'", file = sys.stderr)
  114. 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)
  115. print(" - Subdirectories: ia-cdex-search 'url=example.org&collapse=urlkey&fl=original&matchType=domain&filter=original:^https?://[^/]*example\.org(?::[0-9]*)?/[^/]*/'", file = sys.stderr)
  116. print(' The same caveat applies. The directory must have been retrieved directly without an additional trailing path or query string.', file = sys.stderr)
  117. sys.exit(1)
  118. args = sys.argv[1:]
  119. if args[0].lower() in ('-h', '--help'):
  120. usage()
  121. kwargs = {}
  122. while args[0].startswith('--'):
  123. if args[0] == '--concurrency':
  124. kwargs['concurrency'] = int(args[1])
  125. args = args[2:]
  126. elif args[0] == '--tries':
  127. kwargs['tries'] = int(args[1])
  128. args = args[2:]
  129. elif args[0] == '--page' and args[2].lower() == '--numpages':
  130. kwargs['startPage'] = int(args[1])
  131. kwargs['numPages'] = int(args[3])
  132. args = args[4:]
  133. else:
  134. break
  135. if len(args) != 1 or re.search(r'(^|&)(output|limit|resumekey|showresumekey|page|shownumpages)=', args[0], re.IGNORECASE):
  136. usage()
  137. query = args[0]
  138. asyncio.run(main(query, **kwargs))