99 lines
4.0 KiB
Python
99 lines
4.0 KiB
Python
import json
|
|
import requests
|
|
import time
|
|
import tqdm
|
|
|
|
class Non200StatusCodeError(Exception):
|
|
def __init__(self, status_code, message="Сервер вернул не 200 код"):
|
|
self.status_code = status_code
|
|
self.message = message
|
|
super().__init__(self.message)
|
|
|
|
def __str__(self):
|
|
return f"{self.message}. Код статуса: {self.status_code}"
|
|
|
|
class ResultFileWriter:
|
|
def __init__(self, filename):
|
|
self.filename = filename
|
|
self.file = None
|
|
self.last_auditorium = ""
|
|
self.last_day_of_week = ""
|
|
|
|
def __enter__(self):
|
|
self.file = open(self.filename, "w", encoding="utf-8")
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
if self.file:
|
|
self.file.close()
|
|
|
|
def write_lecture(self, lecture, url):
|
|
"""Записывает информацию о лекции в файл"""
|
|
if lecture['auditorium'] != self.last_auditorium:
|
|
if self.last_auditorium != "":
|
|
self._write_line("\n========================\n")
|
|
self._write_line(lecture['auditorium'] + "\n")
|
|
self.last_auditorium = lecture['auditorium']
|
|
self.last_day_of_week = ""
|
|
|
|
if lecture['day_of_week'] != self.last_day_of_week:
|
|
prefix = f" {lecture['day_of_week']} "
|
|
self.last_day_of_week = lecture['day_of_week']
|
|
else:
|
|
prefix = " " * 6
|
|
|
|
self._write_line(f"{prefix} #{lecture['pair_number']} - {lecture['name']}\n")
|
|
self._write_line(" " * 12 + url + "\n")
|
|
|
|
def _write_line(self, line):
|
|
"""Вспомогательный метод для записи строки в файл"""
|
|
self.file.write(line)
|
|
self.file.flush() # Принудительно сбрасываем буфер
|
|
|
|
def do_request(name, start, end):
|
|
response = requests.post(
|
|
"https://ulsu.ru/oto/api/production/external/createKtalkMeeting.php",
|
|
data={
|
|
"name": name,
|
|
"desc": "Встреча создана средствами API (Copyright © 2023 Kravenrus), обработка расписания © Kozhilya",
|
|
"startAt": start,
|
|
"endAt": end,
|
|
"stateAnonymous": "true",
|
|
"stateSessionHalls": "false",
|
|
"stateLobby": "false",
|
|
"stateSip": "false",
|
|
"stateAutoRecording": "true",
|
|
"stateAudioPolicy": "false",
|
|
"stateVideoPolicy": "false",
|
|
"stateScreenSharePolicy": "false",
|
|
"pinCode": "false"
|
|
},
|
|
headers={
|
|
"Referer": "https://ulsu.ru/oto/ktalk/"
|
|
}
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
time.sleep(5)
|
|
data = response.json()
|
|
return f"https://{data['meetingData']['global']['space']}.ktalk.ru/{data['createdMeeting']['roomName']}"
|
|
else:
|
|
raise Non200StatusCodeError(response.status_code, "Ответ сервера: " + response.text)
|
|
|
|
if __name__ == "__main__":
|
|
with open("lecture.json", "r", encoding="utf-8") as f:
|
|
lectures = json.load(f)
|
|
|
|
# Используем контекстный менеджер для работы с файлом
|
|
with ResultFileWriter("result.txt") as writer:
|
|
for lecture in tqdm.tqdm(lectures):
|
|
try:
|
|
url = do_request(lecture['name'], lecture['start'], lecture['end'])
|
|
writer.write_lecture(lecture, url)
|
|
except Exception as e:
|
|
# Записываем информацию об ошибке в файл
|
|
error_line = f"\nОШИБКА при обработке лекции '{lecture['name']}': {str(e)}\n\n"
|
|
writer._write_line(error_line)
|
|
print(f"Произошла ошибка: {e}")
|
|
# Продолжаем обработку следующих лекций
|
|
continue |