/
dandud132
/
Vita
Обзор
Документация
Войти
/
dandud132
/
Vita
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
source_code/web_requests.py
108 строк
4 KB
Dan
feat: добавить чат-панель с шифрованием и интеграцией с GitVerse API
12 апр 2026, 14:10
12 апр 2026, 14:10
b91ad33
Код
Авторство
О чём код?
import requests import base64 import json from urllib.parse import quote def load_settings(path: str = r"E:\Vita\settings.json") -> dict: with open(path, "r", encoding="utf-8") as f: return json.load(f) settings = load_settings() GITVERSE_API = settings["gitverse"]["api_url"] TOKEN = settings["gitverse"]["token"] OWNER = settings["gitverse"]["owner"] REPO = settings["gitverse"]["repo"] DEFAULT_FILE_PATH = settings.get("file_path", "") BRANCH = settings["gitverse"]["branch"] HEADERS = { "Authorization": f"Bearer {TOKEN}", "Accept": "application/vnd.gitverse.object+json;version=1", "Content-Type": "application/json" } def post(text: str, path: str = None, branch: str = None) -> dict | None: path = path or DEFAULT_FILE_PATH branch = branch or BRANCH url = f"{GITVERSE_API}/repos/{OWNER}/{REPO}/contents/{path}" params = {"ref": branch} # 1. Пробуем получить файл get_resp = requests.get(url, params=params, headers=HEADERS) sha = None existing_content = "" if get_resp.status_code == 200: file_data = get_resp.json() sha = file_data.get("sha") # API возвращает содержимое в base64 encoded = file_data.get("content", "") if encoded: existing_content = base64.b64decode(encoded).decode("utf-8") elif get_resp.status_code != 404: print(f"❌ Ошибка при чтении файла: {get_resp.status_code} {get_resp.text}") return None # 404 означает, что файла ещё нет — создаём с нуля # 2. Формируем итоговое содержимое new_content = existing_content if new_content and not new_content.endswith("\n"): new_content += "\n" new_content += text # 3. Готовим payload data = { "message": "api", "content": base64.b64encode(new_content.encode("utf-8")).decode("utf-8"), "branch": branch } if sha: data["sha"] = sha # 4. Отправляем PUT (создание или обновление) put_resp = requests.put(url, headers=HEADERS, json=data) if put_resp.status_code in (200, 201): print("✅ Файл успешно обновлён/создан!") return put_resp.json() print(f"❌ Ошибка {put_resp.status_code}: {put_resp.text}") return None def get(path: str = None, branch: str = None) -> list[dict[str, str]] | None: """Получает содержимое файла и возвращает список {'content': '...'}""" path = path or DEFAULT_FILE_PATH branch = branch or BRANCH encoded_path = quote(path, safe='/') url = f"https://gitverse.ru/api/repos/{OWNER}/{REPO}/raw/branch/{branch}/{encoded_path}" r = requests.get(url) if r.status_code == 200: # Декодируем и разбиваем на строки text = r.content.decode('utf-8') lines = text.splitlines() # универсально: \n, \r\n, \r # Возвращаем список словарей в нужном формате return [{"content": line} for line in lines] print(f"❌ Ошибка GET raw: {r.status_code} | {r.text}") return None def get_group_list(path: str = "", branch: str = None) -> list | None: branch = branch or BRANCH url = f"{GITVERSE_API}/repos/{OWNER}/{REPO}/contents/{path}" r = requests.get(url, params={"ref": branch}, headers=HEADERS) if r.status_code == 200: data = r.json() entries = data["entries"] return [entry["name"] for entry in entries if "name" in entry] print(f"❌ Ошибка получения списка: {r.status_code}") return None