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.
 
 
 

95 lines
3.9 KiB

  1. #!/usr/bin/env python3
  2. import asyncio
  3. import collections
  4. import json
  5. import re
  6. import shlex
  7. import sys
  8. import urllib.request
  9. def fetch(url):
  10. print(f'GET {url}', file = sys.stderr)
  11. req = urllib.request.Request(url)
  12. with urllib.request.urlopen(req) as r:
  13. if r.code != 200:
  14. raise RuntimeError(f'Could not fetch {url}')
  15. code = r.code
  16. o = json.load(r)
  17. return url, code, o
  18. async def wait_first_and_print(tasks):
  19. if not tasks:
  20. return
  21. task = tasks.popleft()
  22. url, code, o = await task
  23. print(f'{code} {url}')
  24. assert o, 'got empty response'
  25. fields = o[0]
  26. assert all(len(v) == len(fields) for v in o[1:]), 'got unexpected response format'
  27. for row in o[1:]:
  28. print(json.dumps(dict(zip(fields, row))))
  29. return task._ia_cdx_page
  30. async def main(query, concurrency = 1, startPage = None, numPages = None):
  31. assert (startPage is None) == (numPages is None)
  32. baseUrl = f'https://web.archive.org/cdx/search/cdx?{query}'
  33. if startPage is None:
  34. url = f'{baseUrl}&showNumPages=true'
  35. numPages = int(fetch(url)[2])
  36. startPage = 0
  37. print(f'{numPages} pages', file = sys.stderr)
  38. loop = asyncio.get_running_loop()
  39. tasks = collections.deque()
  40. lastGoodPage = -1
  41. try:
  42. try:
  43. for page in range(startPage, numPages):
  44. while len(tasks) >= concurrency:
  45. lastGoodPage = await wait_first_and_print(tasks)
  46. url = f'{baseUrl}&output=json&page={page}'
  47. task = loop.run_in_executor(None, fetch, url)
  48. task._ia_cdx_page = page
  49. tasks.append(task)
  50. while len(tasks) > 0:
  51. lastGoodPage = await wait_first_and_print(tasks)
  52. except:
  53. # 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.
  54. try:
  55. await asyncio.gather(*tasks)
  56. except:
  57. pass
  58. raise
  59. except (RuntimeError, json.JSONDecodeError, AssertionError):
  60. concurrencyS = f'{concurrency} ' if concurrency != 1 else ''
  61. print(f'To resume this search from where it crashed, run: ia-cdx-search {shlex.quote(query)} {concurrencyS}{lastGoodPage + 1} {numPages}', file = sys.stderr)
  62. raise
  63. except (BrokenPipeError, KeyboardInterrupt):
  64. pass
  65. args = sys.argv[1:]
  66. if not 1 <= len(args) <= 4 or args[0].lower() in ('-h', '--help') or re.search(r'(^|&)(output|limit|resumekey|showresumekey|page|shownumpages)=', args[0], re.IGNORECASE):
  67. print('Usage: ia-cdx-search QUERY [CONCURRENCY] [PAGE NUMPAGES]', file = sys.stderr)
  68. print('Please refer to https://github.com/internetarchive/wayback/tree/master/wayback-cdx-server for the relevant query parameters', file = sys.stderr)
  69. print('The output, limit, resumeKey, showResumeKey, page, and showNumPages parameters must not be included.', file = sys.stderr)
  70. 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)
  71. print('Output is produces in JSONL format with one line per CDX entry.', file = sys.stderr)
  72. print('', file = sys.stderr)
  73. print('Examples:', file = sys.stderr)
  74. print(" - Subdomains: ia-cdx-search 'url=example.org&collapse=urlkey&fl=original&matchType=domain&filter=original:^https?://[^/]*example\.org(?::[0-9]*)?/'", file = sys.stderr)
  75. 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)
  76. print(" - Subdirectories: ia-cdex-search 'url=example.org&collapse=urlkey&fl=original&matchType=domain&filter=original:^https?://[^/]*example\.org(?::[0-9]*)?/[^/]*/'", file = sys.stderr)
  77. print(' The same caveat applies. The directory must have been retrieved directly without an additional trailing path or query string.', file = sys.stderr)
  78. sys.exit(1)
  79. query = args[0]
  80. kwargs = {}
  81. if len(args) in (2, 4):
  82. kwargs['concurrency'] = int(args[1])
  83. if len(args) in (3, 4):
  84. kwargs['startPage'], kwargs['numPages'] = map(int, args[-2:])
  85. asyncio.run(main(query, **kwargs))