import os import sys import requests import pdb class Gitea: name = 'Gitea API wrapper' def __init__(self, api_base_url=None, access_token=None): self.__gitea_config_path = "config/gitea.txt" is_setup = self.__check_setup(self) if is_setup: self.__api_base_url = self.__get_parameter("api_base_url", self.__gitea_config_path) self.__access_token = self.__get_parameter("access_token", self.__gitea_config_path) else: self.__api_base_url, self.__access_token = self.setup(self) def register_user(self, email, username, passwd): data = {'email':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 = self.__api_base_url + '/api/v1/admin/users?' response = requests.post(url = API_ENDPOINT + 'access_token=' + self.__access_token, data = data) is_registered = response.ok message = response.json()['message'] return (is_registered, message) def list_users(self): data = { } API_ENDPOINT = self._Gitea__api_base_url + '/api/v1/admin/users?' response = requests.get(url = API_ENDPOINT + 'token=' + self._Gitea__access_token, data = data) response_ok = response.ok user_list = response.json() return (response_ok, user_list) @staticmethod def __check_setup(self): is_setup = False if not os.path.isfile(self.__gitea_config_path): print(f"File {self.__gitea_config_path} not found, running setup.") else: is_setup = True return is_setup @staticmethod def setup(self): if not os.path.exists('config'): os.makedirs('config') api_base_url = input("Gitea API base url, in ex. 'https://yourgitea.instance': ") access_token = input("Gitea access token: ") if not os.path.exists(self.__gitea_config_path): with open(self.__gitea_config_path, 'w'): pass print(f"{self.__gitea_config_path} created!") with open(self.__gitea_config_path, 'a') as the_file: print("Writing gitea parameters to " + self.__gitea_config_path) the_file.write(f'api_base_url: {api_base_url}\n'+f'access_token: {access_token}\n') return (api_base_url, access_token) @staticmethod def __get_parameter(parameter, file_path ): with open( file_path ) as f: for line in f: if line.startswith( parameter ): return line.replace(parameter + ":", "").strip() print(f'{file_path} Missing parameter {parameter}') sys.exit(0)