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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import sys
  4. import random
  5. from typing import List, Tuple
  6. import requests
  7. from requests.models import Response
  8. def find_links_in_text(text: str) -> List[str]:
  9. """Find links in a text and return a list of URLs."""
  10. link_pattern = re.compile(r'((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’]))')
  11. raw_links = re.findall(link_pattern, text)
  12. links = [
  13. str(raw_link[0]).rstrip('/') for raw_link in raw_links
  14. ]
  15. return links
  16. def find_links_in_file(filename: str) -> List[str]:
  17. """Find links in a file and return a list of URLs from text file."""
  18. with open(filename, mode='r', encoding='utf-8') as file:
  19. readme = file.read()
  20. index_section = readme.find('## Index')
  21. content = readme[index_section:]
  22. links = find_links_in_text(content)
  23. return links
  24. def check_duplicate_links(links: List[str]) -> Tuple[bool, List]:
  25. """Check for duplicated links.
  26. Returns a tuple with True or False and duplicate list.
  27. """
  28. seen = {}
  29. duplicates = []
  30. has_duplicate = False
  31. for link in links:
  32. if link not in seen:
  33. seen[link] = 1
  34. else:
  35. if seen[link] == 1:
  36. duplicates.append(link)
  37. if duplicates:
  38. has_duplicate = True
  39. return (has_duplicate, duplicates)
  40. def fake_user_agent() -> str:
  41. """Faking user agent as some hosting services block not-whitelisted UA."""
  42. user_agents = [
  43. 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36',
  44. 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko)',
  45. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
  46. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
  47. ]
  48. return random.choice(user_agents)
  49. def get_host_from_link(link: str) -> str:
  50. host = link.split('://', 1)[1] if '://' in link else link
  51. # Remove routes, arguments and anchors
  52. if '/' in host:
  53. host = host.split('/', 1)[0]
  54. elif '?' in host:
  55. host = host.split('?', 1)[0]
  56. elif '#' in host:
  57. host = host.split('#', 1)[0]
  58. return host
  59. def has_cloudflare_protection(resp: Response) -> bool:
  60. """Checks if there is any cloudflare protection in the response.
  61. Cloudflare implements multiple network protections on a given link,
  62. this script tries to detect if any of them exist in the response from request.
  63. Common protections have the following HTTP code as a response:
  64. - 403: When host header is missing or incorrect (and more)
  65. - 503: When DDOS protection exists
  66. See more about it at:
  67. - https://support.cloudflare.com/hc/en-us/articles/115003014512-4xx-Client-Error
  68. - https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors
  69. - https://www.cloudflare.com/ddos/
  70. - https://superuser.com/a/888526
  71. Discussions in issues and pull requests:
  72. - https://github.com/public-apis/public-apis/pull/2409
  73. - https://github.com/public-apis/public-apis/issues/2960
  74. """
  75. code = resp.status_code
  76. server = resp.headers.get('Server') or resp.headers.get('server')
  77. cloudflare_flags = [
  78. '403 Forbidden',
  79. 'cloudflare',
  80. 'Cloudflare',
  81. 'Security check',
  82. 'Please Wait... | Cloudflare',
  83. 'We are checking your browser...',
  84. 'Please stand by, while we are checking your browser...',
  85. 'Checking your browser before accessing',
  86. 'This process is automatic.',
  87. 'Your browser will redirect to your requested content shortly.',
  88. 'Please allow up to 5 seconds',
  89. 'DDoS protection by',
  90. 'Ray ID:',
  91. 'Cloudflare Ray ID:',
  92. '_cf_chl',
  93. '_cf_chl_opt',
  94. '__cf_chl_rt_tk',
  95. 'cf-spinner-please-wait',
  96. 'cf-spinner-redirecting'
  97. ]
  98. if code in [403, 503] and server == 'cloudflare':
  99. html = resp.text
  100. flags_found = [flag in html for flag in cloudflare_flags]
  101. any_flag_found = any(flags_found)
  102. if any_flag_found:
  103. return True
  104. return False
  105. def check_if_link_is_working(link: str) -> Tuple[bool, str]:
  106. """Checks if a link is working.
  107. If an error is identified when the request for the link occurs,
  108. the return will be a tuple with the first value True and the second
  109. value a string containing the error message.
  110. If no errors are identified, the return will be a tuple with the
  111. first value False and the second an empty string.
  112. """
  113. has_error = False
  114. error_message = ''
  115. try:
  116. resp = requests.get(link + '/', timeout=25, headers={
  117. 'User-Agent': fake_user_agent(),
  118. 'host': get_host_from_link(link)
  119. })
  120. code = resp.status_code
  121. if code >= 400 and not has_cloudflare_protection(resp):
  122. has_error = True
  123. error_message = f'ERR:CLT: {code} : {link}'
  124. except (TimeoutError, requests.exceptions.ConnectTimeout):
  125. has_error = True
  126. error_message = f'ERR:TMO: {link}'
  127. except requests.exceptions.SSLError as error:
  128. has_error = True
  129. error_message = f'ERR:SSL: {error} : {link}'
  130. except requests.exceptions.TooManyRedirects as error:
  131. has_error = True
  132. error_message = f'ERR:TMR: {error} : {link}'
  133. except Exception as error:
  134. has_error = True
  135. error_message = f'ERR:UKN: {error} : {link}'
  136. return (has_error, error_message)
  137. def check_if_list_of_links_are_working(list_of_links: List[str]) -> List[str]:
  138. error_messages = []
  139. for link in list_of_links:
  140. has_error, error_message = check_if_link_is_working(link)
  141. if has_error:
  142. error_messages.append(error_message)
  143. return error_messages
  144. if __name__ == '__main__':
  145. num_args = len(sys.argv)
  146. if num_args < 2:
  147. print('No .md file passed')
  148. sys.exit(1)
  149. links = find_links_in_file(sys.argv[1])
  150. print('Checking for duplicate links...')
  151. has_duplicate_link, duplicates_links = check_duplicate_links(links)
  152. if has_duplicate_link:
  153. print(f'Found duplicate links:')
  154. for duplicate_link in duplicates_links:
  155. print(duplicate_link)
  156. sys.exit(1)
  157. else:
  158. print('No duplicate links.')
  159. print(f'Checking if {len(links)} links are working...')
  160. errors = check_if_list_of_links_are_working(links)
  161. if errors:
  162. num_errors = len(errors)
  163. print(f'Apparently {num_errors} links are not working properly. See in:')
  164. for error_message in errors:
  165. print(error_message)
  166. sys.exit(1)