First release
This commit is contained in:
pare
f1c301bbc3
commit
61f4303d0b
S'han modificat 4 arxius amb 483 adicions i 3 eliminacions
28
README.md
28
README.md
|
@ -1,8 +1,30 @@
|
||||||
# gitea API
|
# giteacat
|
||||||
Testing Gitea Authentication
|
This Python script allows sign in to a Gitea instance to all local users of a Mastodon server.
|
||||||
|
|
||||||
### Dependencies
|
### Dependencies
|
||||||
|
|
||||||
- **Python 3**
|
- **Python 3**
|
||||||
- Gitea running server.
|
- Gitea running server with admin access account
|
||||||
|
- Mastodon's bot account
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
From the Mastodon account where this bot is running:
|
||||||
|
|
||||||
|
@bot_username registre
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Clone this repo: git clone https://git.mastodont.cat/spla/giteacat.git <target dir>
|
||||||
|
|
||||||
|
2. cd into your <target dir> and create the Python Virtual Environment: `python3.x -m venv .`
|
||||||
|
|
||||||
|
3. Activate the Python Virtual Environment: `source bin/activate`
|
||||||
|
|
||||||
|
4. Run `pip install -r requirements.txt` to install needed libraries.
|
||||||
|
|
||||||
|
5. Run `python setup.py` to setup the Mastodon bot account, bot's access tokens, gitea hostname and gitea access token (admin account).
|
||||||
|
|
||||||
|
6 Use your favourite scheduling method to set `python viquicat.py` to run every minute.
|
||||||
|
|
||||||
|
|
||||||
|
|
254
giteacat.py
Normal file
254
giteacat.py
Normal file
|
@ -0,0 +1,254 @@
|
||||||
|
from mastodon import Mastodon
|
||||||
|
import re
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import os.path
|
||||||
|
import string
|
||||||
|
import secrets
|
||||||
|
import requests
|
||||||
|
import pdb
|
||||||
|
|
||||||
|
def cleanhtml(raw_html):
|
||||||
|
cleanr = re.compile('<.*?>')
|
||||||
|
cleantext = re.sub(cleanr, '', raw_html)
|
||||||
|
return cleantext
|
||||||
|
|
||||||
|
def unescape(s):
|
||||||
|
s = s.replace("'", "'")
|
||||||
|
return s
|
||||||
|
|
||||||
|
def generate_email():
|
||||||
|
|
||||||
|
alphabet = string.ascii_letters + string.digits
|
||||||
|
|
||||||
|
while True:
|
||||||
|
|
||||||
|
email_address = ''.join(secrets.choice(alphabet) for i in range(6))
|
||||||
|
|
||||||
|
if (any(c.islower() for c in email_address)
|
||||||
|
and any(c.isupper() for c in email_address)
|
||||||
|
and sum(c.isdigit() for c in email_address) >= 3):
|
||||||
|
break
|
||||||
|
|
||||||
|
email_address = email_address + '@mastodont.cat'
|
||||||
|
|
||||||
|
return email_address
|
||||||
|
|
||||||
|
def generate_pass():
|
||||||
|
|
||||||
|
alphabet = string.ascii_letters + string.digits
|
||||||
|
|
||||||
|
while True:
|
||||||
|
|
||||||
|
password = ''.join(secrets.choice(alphabet) for i in range(10))
|
||||||
|
|
||||||
|
if (any(c.islower() for c in password)
|
||||||
|
and any(c.isupper() for c in password)
|
||||||
|
and sum(c.isdigit() for c in password) >= 3):
|
||||||
|
break
|
||||||
|
|
||||||
|
return password
|
||||||
|
|
||||||
|
def register_user(username, passwd):
|
||||||
|
|
||||||
|
user_email = generate_email()
|
||||||
|
|
||||||
|
data = {'email':user_email,
|
||||||
|
'full_name':username,
|
||||||
|
'login_name':username,
|
||||||
|
'must_change_password':True,
|
||||||
|
'password':passwd,
|
||||||
|
'restricted':False,
|
||||||
|
'send_notify':True,
|
||||||
|
'source_id':'0',
|
||||||
|
'username':username,
|
||||||
|
'visibility':'public'
|
||||||
|
}
|
||||||
|
API_ENDPOINT = 'https://' + gitea_hostname + '/api/v1/admin/users?'
|
||||||
|
response = requests.post(url = API_ENDPOINT + 'access_token=' + gitea_access_token, data = data)
|
||||||
|
|
||||||
|
is_registered = response.ok
|
||||||
|
|
||||||
|
return is_registered
|
||||||
|
|
||||||
|
def get_data(notif):
|
||||||
|
|
||||||
|
notification_id = notif.id
|
||||||
|
|
||||||
|
if notif.type != 'mention':
|
||||||
|
|
||||||
|
print(f'dismissing notification {notification_id}')
|
||||||
|
|
||||||
|
mastodon.notifications_dismiss(notification_id)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
account_id = notif.account.id
|
||||||
|
|
||||||
|
username = notif.account.acct
|
||||||
|
|
||||||
|
if '@' in username:
|
||||||
|
|
||||||
|
print(f'dismissing notification {notification_id}')
|
||||||
|
|
||||||
|
mastodon.notifications_dismiss(notification_id)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
status_id = notif.status.id
|
||||||
|
|
||||||
|
text = notif.status.content
|
||||||
|
|
||||||
|
visibility = notif.status.visibility
|
||||||
|
|
||||||
|
reply, query_word = replying(text)
|
||||||
|
|
||||||
|
if reply:
|
||||||
|
|
||||||
|
if query_word == 'registre':
|
||||||
|
|
||||||
|
user_pass = generate_pass()
|
||||||
|
|
||||||
|
is_registered = register_user(username, user_pass)
|
||||||
|
|
||||||
|
if is_registered:
|
||||||
|
|
||||||
|
toot_text = f'@{username} registrat amb èxit!\n\n'
|
||||||
|
|
||||||
|
toot_text += f'instància Gitea: https://{gitea_hostname} \n'
|
||||||
|
|
||||||
|
toot_text += f'usuari: {username}\n'
|
||||||
|
|
||||||
|
toot_text += f'contrasenya: {user_pass}\n\n'
|
||||||
|
|
||||||
|
toot_text += "nota: aquesta contrasenya s'ha generat aleatòriament però l'hauràs de canviar "
|
||||||
|
|
||||||
|
toot_text += f"desprès d'iniciar sessió a {gitea_hostname}\n\n"
|
||||||
|
|
||||||
|
toot_text += f"Compte! a {gitea_hostname} tens assignada una adreça de correu aleatoria però falsa, sota el domini mastodont.cat. "
|
||||||
|
|
||||||
|
toot_text += "L'hauràs de canviar per a poder rebre notificacions per correu electrònic."
|
||||||
|
|
||||||
|
mastodon.status_post(toot_text, in_reply_to_id=status_id,visibility='direct')
|
||||||
|
|
||||||
|
mastodon.notifications_dismiss(notification_id)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
toot_text = f'@{username} error en el registre!'
|
||||||
|
|
||||||
|
mastodon.status_post(toot_text, in_reply_to_id=status_id,visibility=visibility)
|
||||||
|
|
||||||
|
mastodon.notifications_dismiss(notification_id)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
mastodon.status_post(toot_text, in_reply_to_id=status_id,visibility=visibility)
|
||||||
|
|
||||||
|
mastodon.notifications_dismiss(notification_id)
|
||||||
|
|
||||||
|
def replying(text):
|
||||||
|
|
||||||
|
reply = False
|
||||||
|
|
||||||
|
content = cleanhtml(text)
|
||||||
|
content = unescape(content)
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
start = content.index("@")
|
||||||
|
|
||||||
|
end = content.index(" ")
|
||||||
|
|
||||||
|
if len(content) > end:
|
||||||
|
|
||||||
|
content = content[0: start:] + content[end +1::]
|
||||||
|
|
||||||
|
cleanit = content.count('@')
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
while i < cleanit :
|
||||||
|
|
||||||
|
start = content.rfind("@")
|
||||||
|
end = len(content)
|
||||||
|
content = content[0: start:] + content[end +1::]
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
content = content.lower()
|
||||||
|
|
||||||
|
query_word = content
|
||||||
|
|
||||||
|
if query_word == 'registre':
|
||||||
|
|
||||||
|
reply = True
|
||||||
|
|
||||||
|
except:
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
return (reply, query_word)
|
||||||
|
|
||||||
|
def log_in():
|
||||||
|
|
||||||
|
# Load secrets from secrets file
|
||||||
|
secrets_filepath = "secrets/secrets.txt"
|
||||||
|
uc_client_id = get_parameter("uc_client_id", secrets_filepath)
|
||||||
|
uc_client_secret = get_parameter("uc_client_secret", secrets_filepath)
|
||||||
|
uc_access_token = get_parameter("uc_access_token", secrets_filepath)
|
||||||
|
|
||||||
|
# Load configuration from config file
|
||||||
|
config_filepath = "config/config.txt"
|
||||||
|
mastodon_hostname = get_parameter("mastodon_hostname", config_filepath)
|
||||||
|
|
||||||
|
# Initialise Mastodon API
|
||||||
|
mastodon = Mastodon(
|
||||||
|
client_id = uc_client_id,
|
||||||
|
client_secret = uc_client_secret,
|
||||||
|
access_token = uc_access_token,
|
||||||
|
api_base_url = 'https://' + mastodon_hostname,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialise access headers
|
||||||
|
headers={ 'Authorization': 'Bearer %s'%uc_access_token }
|
||||||
|
|
||||||
|
return mastodon
|
||||||
|
|
||||||
|
def get_gitea_hostname():
|
||||||
|
|
||||||
|
config_filepath = "config/config.txt"
|
||||||
|
gitea_hostname = get_parameter("gitea_hostname", config_filepath)
|
||||||
|
gitea_access_token = get_parameter("gitea_access_token", config_filepath)
|
||||||
|
|
||||||
|
return (gitea_hostname, gitea_access_token)
|
||||||
|
|
||||||
|
def get_parameter( parameter, file_path ):
|
||||||
|
|
||||||
|
# Check if secrets file exists
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
print("File %s not found, exiting."%file_path)
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
# Find parameter in file
|
||||||
|
with open( file_path ) as f:
|
||||||
|
for line in f:
|
||||||
|
if line.startswith( parameter ):
|
||||||
|
return line.replace(parameter + ":", "").strip()
|
||||||
|
|
||||||
|
# Cannot find parameter, exit
|
||||||
|
print(file_path + " Missing parameter %s "%parameter)
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
###############################################################################
|
||||||
|
# main
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
mastodon = log_in()
|
||||||
|
|
||||||
|
gitea_hostname, gitea_access_token = get_gitea_hostname()
|
||||||
|
|
||||||
|
notifications = mastodon.notifications()
|
||||||
|
|
||||||
|
for notif in notifications:
|
||||||
|
|
||||||
|
get_data(notif)
|
1
requirements.txt
Normal file
1
requirements.txt
Normal file
|
@ -0,0 +1 @@
|
||||||
|
Mastodon.py>=1.5.1
|
203
setup.py
Normal file
203
setup.py
Normal file
|
@ -0,0 +1,203 @@
|
||||||
|
import getpass
|
||||||
|
from mastodon import Mastodon
|
||||||
|
from mastodon.Mastodon import MastodonMalformedEventError, MastodonNetworkError, MastodonReadTimeout, MastodonAPIError, MastodonIllegalArgumentError
|
||||||
|
import fileinput,re
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def create_dir():
|
||||||
|
if not os.path.exists('secrets'):
|
||||||
|
os.makedirs('secrets')
|
||||||
|
|
||||||
|
def create_file():
|
||||||
|
if not os.path.exists('secrets/secrets.txt'):
|
||||||
|
with open('secrets/secrets.txt', 'w'): pass
|
||||||
|
print(secrets_filepath + " created!")
|
||||||
|
|
||||||
|
def create_config():
|
||||||
|
if not os.path.exists('config'):
|
||||||
|
os.makedirs('config')
|
||||||
|
if not os.path.exists(config_filepath):
|
||||||
|
print(config_filepath + " created!")
|
||||||
|
with open('config/config.txt', 'w'): pass
|
||||||
|
|
||||||
|
def create_lang_config():
|
||||||
|
if not os.path.exists(lang_config_filepath):
|
||||||
|
print(lang_config_filepath + " created!")
|
||||||
|
with open('config/lang_config.txt', 'w'): pass
|
||||||
|
|
||||||
|
def write_params():
|
||||||
|
with open(secrets_filepath, 'a') as the_file:
|
||||||
|
print("Writing secrets parameter names to " + secrets_filepath)
|
||||||
|
the_file.write('uc_client_id: \n'+'uc_client_secret: \n'+'uc_access_token: \n')
|
||||||
|
|
||||||
|
def write_config():
|
||||||
|
with open(config_filepath, 'a') as the_file:
|
||||||
|
print("Writing parameters names 'mastodon_hostname', 'bot_username', 'gitea_hostname' and 'gitea_access_token' to " + config_filepath)
|
||||||
|
the_file.write('mastodon_hostname: \n' + 'bot_username: \n' + 'gitea_hostname: \n' + 'gitea_access_token: \n')
|
||||||
|
|
||||||
|
def read_client_lines(self):
|
||||||
|
client_path = 'app_clientcred.txt'
|
||||||
|
with open(client_path) as fp:
|
||||||
|
line = fp.readline()
|
||||||
|
cnt = 1
|
||||||
|
while line:
|
||||||
|
if cnt == 1:
|
||||||
|
print("Writing client id to " + secrets_filepath)
|
||||||
|
modify_file(secrets_filepath, "uc_client_id: ", value=line.rstrip())
|
||||||
|
elif cnt == 2:
|
||||||
|
print("Writing client secret to " + secrets_filepath)
|
||||||
|
modify_file(secrets_filepath, "uc_client_secret: ", value=line.rstrip())
|
||||||
|
line = fp.readline()
|
||||||
|
cnt += 1
|
||||||
|
|
||||||
|
def read_token_line(self):
|
||||||
|
token_path = 'app_usercred.txt'
|
||||||
|
with open(token_path) as fp:
|
||||||
|
line = fp.readline()
|
||||||
|
print("Writing access token to " + secrets_filepath)
|
||||||
|
modify_file(secrets_filepath, "uc_access_token: ", value=line.rstrip())
|
||||||
|
|
||||||
|
def read_config_line():
|
||||||
|
with open(config_filepath) as fp:
|
||||||
|
line = fp.readline()
|
||||||
|
modify_file(config_filepath, "mastodon_hostname: ", value=hostname)
|
||||||
|
modify_file(config_filepath, "bot_username: ", value=bot_username)
|
||||||
|
modify_file(config_filepath, "gitea_hostname: ", value=gitea_hostname)
|
||||||
|
modify_file(config_filepath, "gitea_access_token: ", value=gitea_access_token)
|
||||||
|
|
||||||
|
def log_in():
|
||||||
|
error = 0
|
||||||
|
try:
|
||||||
|
global hostname, bot_username, gitea_hostname, gitea_access_token
|
||||||
|
hostname = input("Enter Mastodon hostname: ")
|
||||||
|
user = input("User name, ex. user@" + hostname +"? ")
|
||||||
|
user_password = getpass.getpass("User password? ")
|
||||||
|
bot_username = input("Bot's username, ex. welcome: ")
|
||||||
|
app_name = input("This app name? ")
|
||||||
|
gitea_hostname = input("Enter Gitea hostname: ")
|
||||||
|
gitea_access_token = input(f"{gitea_hostname} access token: ")
|
||||||
|
|
||||||
|
Mastodon.create_app(app_name, scopes=["read","write"],
|
||||||
|
to_file="app_clientcred.txt", api_base_url=hostname)
|
||||||
|
mastodon = Mastodon(client_id = "app_clientcred.txt", api_base_url = hostname)
|
||||||
|
mastodon.log_in(
|
||||||
|
user,
|
||||||
|
user_password,
|
||||||
|
scopes = ["read", "write"],
|
||||||
|
to_file = "app_usercred.txt"
|
||||||
|
)
|
||||||
|
except MastodonIllegalArgumentError as i_error:
|
||||||
|
error = 1
|
||||||
|
if os.path.exists("secrets/secrets.txt"):
|
||||||
|
print("Removing secrets/secrets.txt file..")
|
||||||
|
os.remove("secrets/secrets.txt")
|
||||||
|
if os.path.exists("app_clientcred.txt"):
|
||||||
|
print("Removing app_clientcred.txt file..")
|
||||||
|
os.remove("app_clientcred.txt")
|
||||||
|
sys.exit(i_error)
|
||||||
|
except MastodonNetworkError as n_error:
|
||||||
|
error = 1
|
||||||
|
if os.path.exists("secrets/secrets.txt"):
|
||||||
|
print("Removing secrets/secrets.txt file..")
|
||||||
|
os.remove("secrets/secrets.txt")
|
||||||
|
if os.path.exists("app_clientcred.txt"):
|
||||||
|
print("Removing app_clientcred.txt file..")
|
||||||
|
os.remove("app_clientcred.txt")
|
||||||
|
sys.exit(n_error)
|
||||||
|
except MastodonReadTimeout as r_error:
|
||||||
|
error = 1
|
||||||
|
if os.path.exists("secrets/secrets.txt"):
|
||||||
|
print("Removing secrets/secrets.txt file..")
|
||||||
|
os.remove("secrets/secrets.txt")
|
||||||
|
if os.path.exists("app_clientcred.txt"):
|
||||||
|
print("Removing app_clientcred.txt file..")
|
||||||
|
os.remove("app_clientcred.txt")
|
||||||
|
sys.exit(r_error)
|
||||||
|
except MastodonAPIError as a_error:
|
||||||
|
error = 1
|
||||||
|
if os.path.exists("secrets/secrets.txt"):
|
||||||
|
print("Removing secrets/secrets.txt file..")
|
||||||
|
os.remove("secrets/secrets.txt")
|
||||||
|
if os.path.exists("app_clientcred.txt"):
|
||||||
|
print("Removing app_clientcred.txt file..")
|
||||||
|
os.remove("app_clientcred.txt")
|
||||||
|
sys.exit(a_error)
|
||||||
|
finally:
|
||||||
|
if error == 0:
|
||||||
|
|
||||||
|
create_dir()
|
||||||
|
create_file()
|
||||||
|
write_params()
|
||||||
|
client_path = 'app_clientcred.txt'
|
||||||
|
read_client_lines(client_path)
|
||||||
|
token_path = 'app_usercred.txt'
|
||||||
|
read_token_line(token_path)
|
||||||
|
if os.path.exists("app_clientcred.txt"):
|
||||||
|
print("Removing app_clientcred.txt temp file..")
|
||||||
|
os.remove("app_clientcred.txt")
|
||||||
|
if os.path.exists("app_usercred.txt"):
|
||||||
|
print("Removing app_usercred.txt temp file..")
|
||||||
|
os.remove("app_usercred.txt")
|
||||||
|
print("Secrets setup done!\n")
|
||||||
|
|
||||||
|
def modify_file(file_name,pattern,value=""):
|
||||||
|
fh=fileinput.input(file_name,inplace=True)
|
||||||
|
for line in fh:
|
||||||
|
replacement=pattern + value
|
||||||
|
line=re.sub(pattern,replacement,line)
|
||||||
|
sys.stdout.write(line)
|
||||||
|
fh.close()
|
||||||
|
|
||||||
|
# Returns the parameter from the specified file
|
||||||
|
def get_parameter( parameter, file_path ):
|
||||||
|
# Check if secrets file exists
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
print("File %s not found, creating it."%file_path)
|
||||||
|
log_in()
|
||||||
|
|
||||||
|
# Find parameter in file
|
||||||
|
with open( file_path ) as f:
|
||||||
|
for line in f:
|
||||||
|
if line.startswith( parameter ):
|
||||||
|
return line.replace(parameter + ":", "").strip()
|
||||||
|
|
||||||
|
# Cannot find parameter, exit
|
||||||
|
print(file_path + " Missing parameter %s "%parameter)
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
# Returns the parameter from the specified file
|
||||||
|
def get_hostname( parameter, config_filepath ):
|
||||||
|
# Check if secrets file exists
|
||||||
|
if not os.path.isfile(config_filepath):
|
||||||
|
print("File %s not found, creating it."%config_filepath)
|
||||||
|
create_config()
|
||||||
|
|
||||||
|
# Find parameter in file
|
||||||
|
with open( config_filepath ) as f:
|
||||||
|
for line in f:
|
||||||
|
if line.startswith( parameter ):
|
||||||
|
return line.replace(parameter + ":", "").strip()
|
||||||
|
|
||||||
|
# Cannot find parameter, exit
|
||||||
|
print(config_filepath + " Missing parameter %s "%parameter)
|
||||||
|
write_config()
|
||||||
|
read_config_line()
|
||||||
|
print("setup done!")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
###############################################################################
|
||||||
|
# main
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
# Load secrets from secrets file
|
||||||
|
secrets_filepath = "secrets/secrets.txt"
|
||||||
|
uc_client_id = get_parameter("uc_client_id", secrets_filepath)
|
||||||
|
uc_client_secret = get_parameter("uc_client_secret", secrets_filepath)
|
||||||
|
uc_access_token = get_parameter("uc_access_token", secrets_filepath)
|
||||||
|
|
||||||
|
# Load configuration from config file
|
||||||
|
config_filepath = "config/config.txt"
|
||||||
|
mastodon_hostname = get_hostname("mastodon_hostname", config_filepath)
|
||||||
|
bot_username = get_parameter("bot_username", config_filepath)
|
Loading…
Referencia en una nova incidència