morozovka-portal/app/google_sync.py
2026-10-20 03:27:14 +03:00

82 lines
3.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from datetime import datetime, timezone, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build
from sqlmodel import Session, select
from .db import engine
from .models import Event
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
SERVICE_ACCOUNT_FILE = '/opt/morozovka-portal/google_credentials.json'
# !!! ВАЖНО: Укажи здесь свой реальный email, к которому привязан календарь !!!
CALENDAR_ID = 'korneshoc@gmail.com' # <--- ИЗМЕНИ ЭТО
def sync_google_calendar():
"""Забирает события из Google Calendar и обновляет локальную БД."""
print("[Google Sync] Начинаем синхронизацию...", flush=True)
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('calendar', 'v3', credentials=creds)
# Берем события начиная с 30 дней назад (чтобы точно захватить тесты)
time_min = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
print(f"[Google Sync] Запрашиваем календарь: {CALENDAR_ID}", flush=True)
events_result = service.events().list(
calendarId=CALENDAR_ID,
timeMin=time_min,
maxResults=100,
singleEvents=True,
orderBy='startTime'
).execute()
google_events = events_result.get('items', [])
print(f"[Google Sync] Найдено событий в Google API: {len(google_events)}", flush=True)
count = 0
with Session(engine) as session:
for g_event in google_events:
g_id = g_event['id']
# Парсим время
start = g_event['start'].get('dateTime', g_event['start'].get('date'))
end = g_event['end'].get('dateTime', g_event['end'].get('date'))
if 'T' not in start:
continue
start_dt = datetime.fromisoformat(start.replace('Z', '+00:00'))
end_dt = datetime.fromisoformat(end.replace('Z', '+00:00'))
# Ищем событие в БД по google_event_id
existing = session.exec(select(Event).where(Event.google_event_id == g_id)).first()
if existing:
if getattr(existing, 'manually_edited', False):
continue
existing.title = g_event.get('summary', 'Без названия')
existing.start_time = start_dt
existing.end_time = end_dt
existing.location = g_event.get('location')
existing.description = g_event.get('description')
session.add(existing)
else:
new_event = Event(
google_event_id=g_id,
title=g_event.get('summary', 'Без названия'),
event_type='lecture',
start_time=start_dt,
end_time=end_dt,
location=g_event.get('location'),
description=g_event.get('description'),
is_public=True
)
session.add(new_event)
count += 1
session.commit()
print(f"[Google Sync] Успешно сохранено новых событий в БД: {count}", flush=True)