This code gets all peers from running Mastodon, Pleroma or Lemmy host server and then all peers from host server's peers. Goal is to collect maximum number of alive fediverse's servers by querying their API and then post servers and registered users.
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.

188 lines
6.3 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import getpass
  4. from mastodon import Mastodon
  5. from mastodon.Mastodon import MastodonMalformedEventError, MastodonNetworkError, MastodonReadTimeout, MastodonAPIError, MastodonIllegalArgumentError
  6. import fileinput,re
  7. import os
  8. import sys
  9. def create_dir():
  10. if not os.path.exists('secrets'):
  11. os.makedirs('secrets')
  12. def create_file():
  13. if not os.path.exists('secrets/secrets.txt'):
  14. with open('secrets/secrets.txt', 'w'): pass
  15. print(secrets_filepath + " created!")
  16. def create_config():
  17. if not os.path.exists('config'):
  18. os.makedirs('config')
  19. if not os.path.exists(config_filepath):
  20. print(config_filepath + " created!")
  21. with open('config/config.txt', 'w'): pass
  22. def write_params():
  23. with open(secrets_filepath, 'a') as the_file:
  24. print("Writing secrets parameter names to " + secrets_filepath)
  25. the_file.write('uc_client_id: \n'+'uc_client_secret: \n'+'uc_access_token: \n')
  26. def write_config():
  27. with open(config_filepath, 'a') as the_file:
  28. the_file.write('mastodon_hostname: \n')
  29. print("adding parameter name 'mastodon_hostname' to "+ config_filepath)
  30. def read_client_lines(self):
  31. client_path = 'app_clientcred.txt'
  32. with open(client_path) as fp:
  33. line = fp.readline()
  34. cnt = 1
  35. while line:
  36. if cnt == 1:
  37. print("Writing client id to " + secrets_filepath)
  38. modify_file(secrets_filepath, "uc_client_id: ", value=line.rstrip())
  39. elif cnt == 2:
  40. print("Writing client secret to " + secrets_filepath)
  41. modify_file(secrets_filepath, "uc_client_secret: ", value=line.rstrip())
  42. line = fp.readline()
  43. cnt += 1
  44. def read_token_line(self):
  45. token_path = 'app_usercred.txt'
  46. with open(token_path) as fp:
  47. line = fp.readline()
  48. print("Writing access token to " + secrets_filepath)
  49. modify_file(secrets_filepath, "uc_access_token: ", value=line.rstrip())
  50. def read_config_line():
  51. with open(config_filepath) as fp:
  52. line = fp.readline()
  53. modify_file(config_filepath, "mastodon_hostname: ", value=hostname)
  54. def log_in():
  55. error = 0
  56. try:
  57. global hostname
  58. hostname = input("Enter Mastodon hostname: ")
  59. user_name = input("User name, ex. user@" + hostname +"? ")
  60. user_password = getpass.getpass("User password? ")
  61. app_name = input("This app name? ")
  62. Mastodon.create_app(app_name, scopes=["read","write"],
  63. to_file="app_clientcred.txt", api_base_url=hostname)
  64. mastodon = Mastodon(client_id = "app_clientcred.txt", api_base_url = hostname)
  65. mastodon.log_in(
  66. user_name,
  67. user_password,
  68. scopes = ["read", "write"],
  69. to_file = "app_usercred.txt"
  70. )
  71. except MastodonIllegalArgumentError as i_error:
  72. error = 1
  73. if os.path.exists("secrets/secrets.txt"):
  74. print("Removing secrets/secrets.txt file..")
  75. os.remove("secrets/secrets.txt")
  76. if os.path.exists("app_clientcred.txt"):
  77. print("Removing app_clientcred.txt file..")
  78. os.remove("app_clientcred.txt")
  79. sys.exit(i_error)
  80. except MastodonNetworkError as n_error:
  81. error = 1
  82. if os.path.exists("secrets/secrets.txt"):
  83. print("Removing secrets/secrets.txt file..")
  84. os.remove("secrets/secrets.txt")
  85. if os.path.exists("app_clientcred.txt"):
  86. print("Removing app_clientcred.txt file..")
  87. os.remove("app_clientcred.txt")
  88. sys.exit(n_error)
  89. except MastodonReadTimeout as r_error:
  90. error = 1
  91. if os.path.exists("secrets/secrets.txt"):
  92. print("Removing secrets/secrets.txt file..")
  93. os.remove("secrets/secrets.txt")
  94. if os.path.exists("app_clientcred.txt"):
  95. print("Removing app_clientcred.txt file..")
  96. os.remove("app_clientcred.txt")
  97. sys.exit(r_error)
  98. except MastodonAPIError as a_error:
  99. error = 1
  100. if os.path.exists("secrets/secrets.txt"):
  101. print("Removing secrets/secrets.txt file..")
  102. os.remove("secrets/secrets.txt")
  103. if os.path.exists("app_clientcred.txt"):
  104. print("Removing app_clientcred.txt file..")
  105. os.remove("app_clientcred.txt")
  106. sys.exit(a_error)
  107. finally:
  108. if error == 0:
  109. create_dir()
  110. create_file()
  111. write_params()
  112. client_path = 'app_clientcred.txt'
  113. read_client_lines(client_path)
  114. token_path = 'app_usercred.txt'
  115. read_token_line(token_path)
  116. if os.path.exists("app_clientcred.txt"):
  117. print("Removing app_clientcred.txt temp file..")
  118. os.remove("app_clientcred.txt")
  119. if os.path.exists("app_usercred.txt"):
  120. print("Removing app_usercred.txt temp file..")
  121. os.remove("app_usercred.txt")
  122. print("Secrets setup done!\n")
  123. def modify_file(file_name,pattern,value=""):
  124. fh=fileinput.input(file_name,inplace=True)
  125. for line in fh:
  126. replacement=pattern + value
  127. line=re.sub(pattern,replacement,line)
  128. sys.stdout.write(line)
  129. fh.close()
  130. # Returns the parameter from the specified file
  131. def get_parameter( parameter, file_path ):
  132. # Check if secrets file exists
  133. if not os.path.isfile(file_path):
  134. print("File %s not found, creating it."%file_path)
  135. log_in()
  136. # Find parameter in file
  137. with open( file_path ) as f:
  138. for line in f:
  139. if line.startswith( parameter ):
  140. return line.replace(parameter + ":", "").strip()
  141. # Cannot find parameter, exit
  142. print(file_path + " Missing parameter %s "%parameter)
  143. sys.exit(0)
  144. # Returns the parameter from the specified file
  145. def get_hostname( parameter, config_filepath ):
  146. # Check if secrets file exists
  147. if not os.path.isfile(config_filepath):
  148. print("File %s not found, creating it."%config_filepath)
  149. create_config()
  150. # Find parameter in file
  151. with open( config_filepath ) as f:
  152. for line in f:
  153. if line.startswith( parameter ):
  154. return line.replace(parameter + ":", "").strip()
  155. # Cannot find parameter, exit
  156. print(config_filepath + " Missing parameter %s "%parameter)
  157. write_config()
  158. read_config_line()
  159. print("setup done!")
  160. sys.exit(0)
  161. # Load secrets from secrets file
  162. secrets_filepath = "secrets/secrets.txt"
  163. uc_client_id = get_parameter("uc_client_id", secrets_filepath)
  164. uc_client_secret = get_parameter("uc_client_secret", secrets_filepath)
  165. uc_access_token = get_parameter("uc_access_token", secrets_filepath)
  166. # Load configuration from config file
  167. config_filepath = "config/config.txt"
  168. mastodon_hostname = get_hostname("mastodon_hostname", config_filepath)