Files
duty-calendar/server/calendar_sharing.py
T
블리어 eccce7adb0 당직근무 0.15.5 (웹 2026-11-25.9): 다른 달력 연동에 일반근무 날 빼기, 기본은 앱과 같게
사용자 지시(2026-11-25): 구글 달력 연동 옵션에 일반근무 빼는 기능(일반근무 날 통째로 빼기), 기본은 어플과 같게, 내 계정에 적용.

- 구독 주소 options.skipRegular: 켜면 일반근무 날은 이름까지 보내지 않는다. 없으면 끔.
- 끄면 앱 달력과 같게: 근무 순서 이름 줄마다 표시를 따르고 일반근무 글자 숨기기(hideRegular)를 켜면 이름만 보내며 이름이 없으면 그날 근무 일정을 만들지 않는다(앱 ShiftNames.externalTitle, 서버 calendar_export.project).
- 웹 달력 연동: 일반근무 날 빼기 칸과 항목만 바꾸기(주소 그대로, action update).
- 앱 기본 달력 자동 반영: 일반근무 날 빼기 칸(기기 설정 calendar_mirror.skipRegular).
- 기기 시험 CalendarBridgeCheck에 일반근무 빼기·앱과 같게 단계 추가.
- 앱 0.15.5 / 설치 번호 29. APK 877370바이트, SHA-256 819342ea62e549fc8ceb2dff1c30082b45e031b49d2d232c98beda0a00032f29
2026-11-25 05:44:32 +00:00

97 lines
6.6 KiB
Python

"""구독 주소는 회원이 직접 만든 경우에만 활성화한다. 주소의 비밀값은 해시로만 보관한다.
공유 범위와 해제 상태를 요청마다 확인하며 회원 정지와 탈퇴도 기존 주소에 즉시 적용한다.
"""
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')=='update':
# 주소는 그대로 두고 내보낼 항목만 바꾼다. 다른 달력은 다음 갱신 때 바뀐 내용을 가져간다.
try:chosen=calendar_export.options(body.get('options'))
except ValueError as error:raise HTTPException(400,str(error))
with db() as conn:
if not conn.execute('UPDATE calendar_feeds SET options=? WHERE calendar=?',(json.dumps(chosen),client['calendar'])).rowcount:
raise HTTPException(400,'먼저 구독 주소를 만들어 주세요.')
return {'enabled':True,'options':chosen}
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)