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.

274 rivejä
7.8 KiB

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