No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 

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