"""구독 주소는 회원이 직접 만든 경우에만 활성화한다. 주소의 비밀값은 해시로만 보관한다. 공유 범위와 해제 상태를 요청마다 확인하며 회원 정지와 탈퇴도 기존 주소에 즉시 적용한다. """ import asyncio from datetime import datetime import hashlib import json import logging import re import secrets import time from fastapi import HTTPException, Request from fastapi.responses import Response import calendar_export class HideFeedAddress(logging.Filter): def filter(self,record): # uvicorn 접근 로그에 개인 구독 주소가 기록되지 않게 한다. 프록시도 해당 경로의 접근 기록을 끈다. if isinstance(record.args,tuple):record.args=tuple(re.sub(r'/calendar/feed/[A-Za-z0-9_-]+\.ics','/calendar/feed/private.ics',value) if isinstance(value,str) else value for value in record.args) return True def install(app,db,identity,payload,snapshot,throttle,secret_hash,holidays,origin,prefix): with db() as conn: conn.execute('''CREATE TABLE IF NOT EXISTS calendar_feeds( calendar TEXT PRIMARY KEY REFERENCES calendars(id) ON DELETE CASCADE, hash TEXT UNIQUE NOT NULL, options TEXT NOT NULL, created INTEGER NOT NULL, content_hash TEXT NOT NULL DEFAULT '', sequence INTEGER NOT NULL DEFAULT 0, modified INTEGER NOT NULL DEFAULT 0)''') logging.getLogger('uvicorn.access').addFilter(HideFeedAddress()) @app.get(prefix+'/api/calendar-sharing') async def status(request:Request): client=identity(request) with db() as conn:row=conn.execute('SELECT options,created FROM calendar_feeds WHERE calendar=?',(client['calendar'],)).fetchone() return {'enabled':bool(row),'options':json.loads(row['options']) if row else None,'created':row['created'] if row else None} @app.post(prefix+'/api/calendar-sharing') async def change(request:Request): client=identity(request);throttle(request,'calendar-share',20,60);body=await payload(request) if body.get('action')=='disable': with db() as conn:conn.execute('DELETE FROM calendar_feeds WHERE calendar=?',(client['calendar'],)) return {'enabled':False} if body.get('action')!='create':raise HTTPException(400,'공유 작업을 확인해 주세요.') try:chosen=calendar_export.options(body.get('options')) except ValueError as error:raise HTTPException(400,str(error)) token=secrets.token_urlsafe(32) with db() as conn: conn.execute('INSERT INTO calendar_feeds(calendar,hash,options,created) VALUES(?,?,?,?) ON CONFLICT(calendar) DO UPDATE SET hash=excluded.hash,options=excluded.options,created=excluded.created,content_hash=\'\',sequence=0,modified=0', (client['calendar'],secret_hash(token),json.dumps(chosen),int(time.time()))) return {'enabled':True,'url':origin+prefix+'/feed/'+token+'.ics'} @app.post(prefix+'/api/calendar-export') async def export(request:Request): client=identity(request);throttle(request,'calendar-export',20,60);body=await payload(request) try:chosen=calendar_export.options(body) except ValueError as error:raise HTTPException(400,str(error)) with db() as conn:state=snapshot(conn,client['calendar']) saved=holidays.read()[0] try:content=await asyncio.to_thread(calendar_export.render,state,chosen,datetime.now(calendar_export.KOREA).date(),saved) except ValueError as error:raise HTTPException(400,str(error)) return Response(content,media_type='text/calendar; charset=utf-8',headers={'Content-Disposition':'attachment; filename="duty-calendar.ics"'}) @app.get(prefix+'/feed/{token}.ics') async def feed(request:Request,token:str): throttle(request,'calendar-feed',120,60) if not re.fullmatch(r'[A-Za-z0-9_-]{43}',token):raise HTTPException(404,'사용할 수 없는 구독 주소입니다.') hashed=secret_hash(token) with db() as conn: row=conn.execute('SELECT f.* FROM calendar_feeds f JOIN members m ON m.calendar=f.calendar WHERE f.hash=? AND m.active=1 AND m.must_change=0',(hashed,)).fetchone() if not row:raise HTTPException(404,'사용할 수 없는 구독 주소입니다.') state=snapshot(conn,row['calendar']);chosen=json.loads(row['options']) try:content=await asyncio.to_thread(calendar_export.render,state,chosen,datetime.now(calendar_export.KOREA).date(),holidays.read()[0]) except ValueError as error:raise HTTPException(400,str(error)) fingerprint=hashlib.sha256(content).hexdigest() # 회사 근무표나 공휴일 자료 변경도 구독 버전을 올린다. 개인 자료 revision만으로 판단하면 빠질 수 있다. with db() as conn: conn.execute('BEGIN IMMEDIATE') current=conn.execute('SELECT * FROM calendar_feeds WHERE hash=?',(hashed,)).fetchone() if not current:raise HTTPException(404,'사용할 수 없는 구독 주소입니다.') if current['content_hash']!=fingerprint: conn.execute('UPDATE calendar_feeds SET content_hash=?,sequence=sequence+1,modified=? WHERE hash=?',(fingerprint,int(time.time()),hashed)) current=conn.execute('SELECT sequence,modified FROM calendar_feeds WHERE hash=?',(hashed,)).fetchone() stamp=datetime.fromtimestamp(current['modified'],calendar_export.timezone.utc).strftime('%Y%m%dT%H%M%SZ') content=b'\r\n'.join(('SEQUENCE:'+str(current['sequence'])).encode() if line.startswith(b'SEQUENCE:') else ('DTSTAMP:'+stamp).encode() if line.startswith(b'DTSTAMP:') else line for line in content.split(b'\r\n')) etag='"'+hashlib.sha256(content).hexdigest()+'"' headers={'ETag':etag,'Content-Disposition':'inline; filename="duty-calendar.ics"'} if request.headers.get('if-none-match')==etag:return Response(status_code=304,headers=headers) return Response(content,media_type='text/calendar; charset=utf-8',headers=headers)