Compare commits

...
16 changed files with 313 additions and 13 deletions

No files matched your search

+4 -1
View File
@@ -263,4 +263,7 @@
| [ ] | 인스타 토큰 자동 갱신 — 장기 토큰은 60일 만료. 워커에 주 1회 `refresh_access_token` 잡을 넣고 새 토큰을 어디에 둘지(.env는 재생성 필요 → DB/Redis 저장) 결정 | 인스타 연결 (10/23) | `backend/scheduler/`, `backend/services/external/instagram.py` |
| [ ] | 킹서버 `.env` 바꾼 뒤 `docker compose restart`는 환경변수를 다시 읽지 않음 — `docker compose up -d --force-recreate <서비스>`로 해야 함. deploy.sh/문서에 적기 | 인스타 연결 중 발견 (10/23) | `deploy.sh`, `backend/docs/README.md` |
| [ ] | 어제(10/23) 인스타 썸 타로 글(https://www.instagram.com/p/De1E3uRIKHE/)은 3번 장(드라이브각)이 그림 없이 아이콘 — 드라이브각 그림은 10/24 만들었지만 날짜가 지나 재게시 안 함. 그 글을 앱에서 지울지 그냥 둘지 결정 | 10/24 | — |
| [x] | 10/24 나들이 타로(등산각·드라이브각·한강각, 질문 "어느 곳으로 나들이를 가면 좋을까요?") 킹서버 카드 2 → 포스트 3648, 인스타 https://www.instagram.com/p/De3N7LnIJyZ/ 게시. 그림 생성 모델: `gpt-6-luna`는 그림을 파일로 저장 못 해 실패, `gpt-6-sol`·low로 바꿔 성공(장당 ~28k 토큰) | 사용자 요청 (10/24) | `admin/scripts/gen-image.mjs` |
| [x] | 10/24 나들이 타로(등산각·드라이브각·한강각, 질문 "어느 곳으로 나들이를 가면 좋을까요?") 킹서버 카드 2 → 포스트 3648, 인스타 https://www.instagram.com/p/De3N7LnIJyZ/ 게시. 같은 날 오늘의 코디(캐주얼, mild 구간 그림 재사용) 킹서버 카드 3 → 포스트 3649, 인스타 https://www.instagram.com/p/De3OVz6oC9e/. 그림 생성 모델: `gpt-6-luna`는 그림을 파일로 저장 못 해 실패, `gpt-6-sol`·low로 바꿔 성공(장당 ~28k 토큰) | 사용자 요청 (10/24) | `admin/scripts/gen-image.mjs` |
| [x] | 10/24 날씨각 소개 카드(인스타 전용, 8장, `intro` 템플릿 — Codex gpt-6-sol이 설계) 인스타 https://www.instagram.com/p/De3SUTtoDGR/ 게시. 킹서버엔 카드 4로 저장만(승인 대기, 피드엔 안 나감). 해시태그는 `card_set.hashtags`로 인스타 캡션에만 붙음(타로·코디 템플릿도 적용) | 사용자 요청 (10/24) | `admin/src/cards/templates.tsx`, `backend/router/v1/card/card.py` |
| [ ] | 인스타 릴스(20초, 2.5D: Codex 3D 렌더풍 배경 + 카메라 패럴랙스, 무료 BGM, API로 업로드) — 백엔드에 mp4 공개 주소 + REELS 게시 추가 필요 | 사용자 요청 (10/24) | `backend/services/external/instagram.py` |
+1 -1
View File
@@ -9,7 +9,7 @@ import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
import { resolve } from 'node:path'
const SLIDES = { tarot: 5, ootd: 6 }
const SLIDES = { tarot: 5, ootd: 6, intro: 8 }
// 기본 문구가 서비스 데이터 그대로라 Claude 기획이 꼭 필요한 템플릿 (src/cards/templates.tsx autoPlan)
const AUTO_PLAN = ['tarot']
// src/cards/themes.ts THEMES 의 id
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+157
View File
@@ -480,3 +480,160 @@
font-size: 27px;
line-height: 1.4;
}
/* 서비스 소개 (intro) */
.slide.intro {
--accent: var(--rust);
background: radial-gradient(80% 50% at 88% 98%, var(--stage), transparent 80%), var(--paper);
}
.intro .intro-title {
position: absolute;
top: 222px;
left: 80px;
right: 80px;
z-index: 2;
font: 98px/1.13 Jua, sans-serif;
letter-spacing: -3px;
word-break: keep-all;
}
.intro .intro-sub {
position: absolute;
top: 485px;
left: 80px;
right: 80px;
z-index: 2;
font: 650 44px/1.38 'Pretendard Variable', Pretendard, sans-serif;
letter-spacing: -1.5px;
word-break: keep-all;
}
.intro .intro-sub strong { font-weight: 800; }
.intro-cover .intro-title { top: 250px; font-size: 106px; }
.intro-cover .intro-sub { top: 540px; font-size: 46px; }
.intro-cover-stage {
position: absolute;
left: 115px;
top: 760px;
width: 850px;
height: 390px;
border-radius: 50%;
background: var(--stage);
}
.intro .intro-character {
position: absolute;
width: 260px;
height: 260px;
object-fit: contain;
z-index: 2;
filter: drop-shadow(0 18px 14px #28304a22);
}
.intro-cover .rabbit { left: 250px; top: 810px; transform: rotate(-9deg); }
.intro-cover .bear { right: 235px; top: 830px; transform: rotate(8deg); }
.intro .intro-turn {
position: absolute;
bottom: 90px;
right: 80px;
font: 700 38px/1.2 'Pretendard Variable', Pretendard, sans-serif;
color: var(--rust);
}
.intro-problem .intro-cloud { position: absolute; top: 230px; left: 80px; width: 140px; height: 140px; object-fit: contain; }
.intro-problem .intro-title { top: 425px; font-size: 88px; line-height: 1.2; }
.intro-problem .intro-sub { top: 715px; font-size: 48px; }
.intro-answer {
position: absolute;
top: 995px;
left: 80px;
right: 80px;
display: flex;
align-items: center;
gap: 32px;
padding: 28px 38px;
border-radius: 36px;
background: var(--stage);
font: 700 52px/1.2 'Pretendard Variable', Pretendard, sans-serif;
color: var(--rust);
}
.intro-answer img { width: 92px; height: 92px; object-fit: contain; }
.intro-scores .intro-title { font-size: 88px; }
.intro-scores .intro-scores {
position: absolute;
top: 555px;
left: 80px;
right: 80px;
display: grid;
gap: 20px;
}
.intro-score {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24px 40px;
border-radius: 28px;
background: var(--stage);
font: 700 48px/1.1 'Pretendard Variable', Pretendard, sans-serif;
}
.intro-score b { font: 68px/1 Jua, sans-serif; }
.intro-score.rank-1 { background: var(--rust); color: var(--paper); }
.intro-score.rank-2 { background: var(--orange); color: var(--paper); }
.intro-score.rank-3 { background: var(--soft); color: var(--ink); }
.intro-score.rank-4 { color: var(--muted); }
.intro-scores .intro-sub { top: 1175px; font-size: 40px; }
.intro-home .intro-title,
.intro-sky .intro-title { top: 205px; }
.intro-home .intro-sub,
.intro-sky .intro-sub { top: 450px; font-size: 42px; }
.intro-phone {
position: absolute;
overflow: hidden;
width: 390px;
height: 844px;
border: 8px solid var(--ink);
border-radius: 44px;
background: var(--paper);
box-shadow: 0 18px 0 var(--soft), 0 30px 58px #28304a28;
}
.intro-phone img { display: block; width: 100%; height: 100%; object-fit: cover; }
.intro-phone.home,
.intro-phone.sky { top: 620px; left: 345px; }
.intro-kinds .intro-title { top: 205px; font-size: 88px; }
.intro-gak-grid {
position: absolute;
top: 525px;
left: 80px;
right: 80px;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16px;
}
.intro-gak {
height: 186px;
border-radius: 28px;
background: var(--stage);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
}
.intro-gak img { width: 80px; height: 80px; object-fit: contain; }
.intro-gak span { font: 700 30px/1.2 'Pretendard Variable', Pretendard, sans-serif; white-space: nowrap; }
.intro-kinds .intro-sub { top: 1195px; font-size: 36px; }
.intro-more .intro-title { top: 215px; font-size: 88px; }
.intro-more .intro-sub { top: 455px; font-size: 44px; }
.intro-more-icons { position: absolute; top: 750px; left: 90px; display: flex; flex-direction: column; gap: 34px; }
.intro-more-icons img { width: 105px; height: 105px; object-fit: contain; }
.intro-phone.week { top: 705px; left: 510px; width: 275px; height: 595px; border-width: 6px; border-radius: 34px; }
.intro .intro-note {
position: absolute;
left: 80px;
right: 80px;
font: 650 38px/1.35 'Pretendard Variable', Pretendard, sans-serif;
letter-spacing: -1px;
word-break: keep-all;
}
.intro-more .intro-note { top: 1205px; width: 880px; z-index: 2; padding: 12px 18px; border-radius: 18px; background: var(--paper); }
.intro-cta .intro-title { top: 220px; font-size: 105px; }
.intro-cta .intro-sub { top: 470px; font-size: 48px; color: var(--rust); }
.intro-phone.gak { top: 650px; left: 370px; width: 280px; height: 560px; border-width: 6px; border-radius: 34px; }
.intro-cta .rabbit { width: 175px; height: 175px; left: 155px; top: 925px; transform: rotate(-8deg); }
.intro-cta .bear { width: 175px; height: 175px; right: 160px; top: 950px; transform: rotate(8deg); }
.intro-cta .intro-note { top: 1250px; font-size: 36px; text-align: center; }
+113 -5
View File
@@ -1,10 +1,14 @@
import type { ReactNode } from 'react'
import tarotBack from '../assets/tarot-back.webp'
import shotHome from '../assets/intro/shot-home.webp'
import shotGak from '../assets/intro/shot-gak.webp'
import shotSky from '../assets/intro/shot-sky.webp'
import shotWeek from '../assets/intro/shot-week.webp'
import type { CardData } from './data'
import { Frame, Lines } from './Frame'
import { tidy } from './text'
import { DEFAULT_STYLE, ootdBand, ootdOutfits, styleLabel } from './ootd'
import { gakArt } from './gaks'
import { gakArt, gakByCode } from './gaks'
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
const TAROT_BG = import.meta.glob<string>('../assets/tarot-bg/*.webp', { eager: true, import: 'default' })
@@ -34,7 +38,7 @@ export type Template = {
/** 처음 열 때 보여 주는 미리 만든 예시 문구 (그림도 미리 만들어 둠). 만들기를 누르면 그날 카드로 바뀐다 */
example?: Copy
/** 날씨각 피드 포스트 제목·설명 */
post: (d: CardData, c: Copy) => { title: string; caption: string }
post: (d: CardData, c: Copy) => { title: string; caption: string; hashtags?: string }
}
@@ -53,7 +57,11 @@ const ootd: Template = {
defaults: () => ({ title: '', style: DEFAULT_STYLE }),
// 예시: 17~22도 캐주얼 (Codex 그림 6장)
example: { style: 'casual', band: 'mild', theme: 'berry' },
post: (d, c) => ({ title: `오늘의 코디 · ${styleLabel(c.style)}`, caption: `낮 최고 ${d.maxC}도, 20대부터 40대~까지 오늘 입을 옷을 넘겨 보세요` }),
post: (d, c) => ({
title: `오늘의 코디 · ${styleLabel(c.style)}`,
caption: `낮 최고 ${d.maxC}도, 20대부터 40대~까지 오늘 입을 옷을 넘겨 보세요`,
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
}),
warnings: (d, c) => {
const missing = ootdOutfits(d.maxC, c.style).filter((o) => !o.image)
const id = `${ootdBand(d.maxC).id}`
@@ -89,7 +97,11 @@ const ootd: Template = {
const tarot: Template = {
id: 'tarot',
post: (_d, c) => ({ title: c.title.replaceAll('\n', ' ').replaceAll('*', ''), caption: `Q. ${c.question} 1·2·3 중 한 장을 골라 보세요` }),
post: (_d, c) => ({
title: c.title.replaceAll('\n', ' ').replaceAll('*', ''),
caption: `Q. ${c.question} 1·2·3 중 한 장을 골라 보세요`,
hashtags: '#날씨각 #날씨타로 #타로 #오늘의타로 #오늘의운세 #날씨 #오늘날씨 #서울날씨 #오늘뭐하지 #일상',
}),
name: '날씨 타로',
autoPlan: true,
about: '주제를 바꿔 가며 · 3장 중 고르기, 뒷면은 오늘 날씨',
@@ -218,6 +230,102 @@ const tarot: Template = {
},
}
export const TEMPLATES: Template[] = [tarot, ootd]
const INTRO_GAK_CODES = ['walk', 'camping', 'fishing', 'chimaek', 'jjamppong', 'carwash', 'laundry', 'vent', 'stars', 'hiking', 'date', 'golf']
const intro: Template = {
id: 'intro',
name: '날씨각 소개',
about: '날씨를 할 일로 바꿔 주는 서비스 소개 · 8장',
how: [
'소개 카드는 문구가 고정되어 있고 Claude 기획을 쓰지 않는다. 칸에서 직접 고칠 수 있다.',
'앱 화면은 src/assets/intro의 스크린샷 4장을 쓴다. 각 이름과 아이콘은 서비스의 GAK_DECK에서 가져온다.',
'날씨 데이터와 점수 계산은 쓰지 않는다. 화면의 예시 점수는 소개용 문구다.',
],
fields: [
{ key: 't1', label: '1장 제목' }, { key: 's1', label: '1장 부제' },
{ key: 't2', label: '2장 제목' }, { key: 's2', label: '2장 부제' },
{ key: 't3', label: '3장 제목' }, { key: 'g1', label: '3장 점수 1' },
{ key: 'g2', label: '3장 점수 2' }, { key: 'g3', label: '3장 점수 3' },
{ key: 'g4', label: '3장 점수 4' }, { key: 's3', label: '3장 부제' },
{ key: 't4', label: '4장 제목' }, { key: 's4', label: '4장 부제' },
{ key: 't5', label: '5장 제목' }, { key: 's5', label: '5장 부제' },
{ key: 't6', label: '6장 제목' }, { key: 's6', label: '6장 부제' },
{ key: 't7', label: '7장 제목' }, { key: 's7', label: '7장 부제' }, { key: 'n7', label: '7장 안내' },
{ key: 't8', label: '8장 제목' }, { key: 's8', label: '8장 링크' }, { key: 'n8', label: '8장 안내' },
],
defaults: () => ({
theme: 'sky',
t1: '오늘 뭐 하기\n좋은 날이지?', s1: '날씨를 *할 일*로 바꿔 주는 앱, 날씨각',
t2: '"흐림, 19도, 습도 70%"\n…그래서 오늘 뭐 하죠?', s2: '숫자만 보면 모르겠는 날,\n날씨각은 바로 답해요',
t3: '오늘 날씨에 맞는 일을\n*점수*로', g1: '한강각 91', g2: '드라이브각 89', g3: '세차각 72', g4: '빨래각 45', s3: "'각' = 그걸 하기 딱 좋은 때",
t4: '지금 내 동네\n1위는?', s4: '아침·지금·저녁으로 보여 주고,\n동네를 바꾸면 점수도 바뀌어요',
t5: '밖에서 놀기부터\n집안일까지 *68가지*', s5: '밖에서 놀기 · 먹고 마시기 · 집안일',
t6: '오늘 노을,\n몇 시에 어디서?', s6: '노을 점수 · 피크 시각 · 골든아워\n가까운 노을 명소까지',
t7: '주말 행사 · 단풍\n동네 사람들 이야기', s7: '가까운 축제, 단풍 시기,\n우리 동네 날씨 한마디', n7: "'내 각'은 내가 정한 조건으로 점수를 매겨요",
t8: '설치 없이 바로,\n*무료*', s8: '프로필 링크 → weather.o2o.kr', n8: '매일 아침 날씨 타로 · 오늘의 코디도 여기서',
}),
post: () => ({
title: '날씨각이 뭐예요?',
caption: "날씨각은 오늘 날씨에 맞는 '할 일'을 점수로 알려 주는 날씨 서비스예요. 세차각·빨래각·러닝각… 지금 내 동네 1위 각은 프로필 링크에서 👉",
hashtags: '#날씨각 #날씨 #오늘날씨 #날씨앱 #오늘뭐하지 #주말뭐하지 #노을 #노을맛집 #한강 #드라이브 #산책 #날씨타로 #오늘의코디 #서울날씨 #주말나들이 #가을 #일상',
}),
slides: (_d, c) => {
const phone = (src: string, name: string) => <div className={`intro-phone ${name}`}><img src={src} alt="" /></div>
const head = (text: string, name = '') => <h1 className={`intro-title ${name}`}><Lines text={tidy(text)} /></h1>
const sub = (text: string, name = '') => <p className={`intro-sub ${name}`}><Lines text={tidy(text)} /></p>
const frame = (page: number, className: string, children: ReactNode) => <Frame page={page} total={8} theme={c.theme || 'sky'} className={`intro intro-${className}`} key={page}>{children}</Frame>
return [
frame(0, 'cover', <>
{head(c.t1)}{sub(c.s1)}
<div className="intro-cover-stage" aria-hidden="true" />
<img className="intro-character rabbit" src={iconUrl('rabbit')} alt="" />
<img className="intro-character bear" src={iconUrl('bear')} alt="" />
<p className="intro-turn">넘겨 보세요 →</p>
</>),
frame(1, 'problem', <>
<img className="intro-cloud" src={iconUrl('cloud')} alt="" />
{head(c.t2)}{sub(c.s2)}
<div className="intro-answer" aria-hidden="true"><img src={iconUrl('hangang')} alt="" /><span>오늘은 한강각!</span></div>
</>),
frame(2, 'scores', <>
{head(c.t3)}
<div className="intro-scores">
{[c.g1, c.g2, c.g3, c.g4].map((score, i) => {
const match = score.match(/^(.*)\s(\d+)$/)
return <div className={`intro-score rank-${i + 1}`} key={i}><span>{match?.[1] || score}</span><b>{match?.[2] || ''}</b></div>
})}
</div>
{sub(c.s3)}
</>),
frame(3, 'home', <>{head(c.t4)}{sub(c.s4)}{phone(shotHome, 'home')}</>),
frame(4, 'kinds', <>
{head(c.t5)}
<div className="intro-gak-grid">
{INTRO_GAK_CODES.map((code) => {
const gak = gakByCode(code)
return gak && <div className="intro-gak" key={code}><img src={iconUrl(gak.icon)} alt="" /><span>{gak.name}</span></div>
})}
</div>
{sub(c.s5)}
</>),
frame(5, 'sky', <>{head(c.t6)}{sub(c.s6)}{phone(shotSky, 'sky')}</>),
frame(6, 'more', <>
{head(c.t7)}{sub(c.s7)}
<div className="intro-more-icons" aria-hidden="true"><img src={iconUrl('maple')} alt="" /><img src={iconUrl('camping')} alt="" /><img src={iconUrl('walk')} alt="" /></div>
{phone(shotWeek, 'week')}
<p className="intro-note"><Lines text={tidy(c.n7)} /></p>
</>),
frame(7, 'cta', <>
{head(c.t8)}{sub(c.s8)}
{phone(shotGak, 'gak')}
<img className="intro-character rabbit" src={iconUrl('rabbit')} alt="" />
<img className="intro-character bear" src={iconUrl('bear')} alt="" />
<p className="intro-note"><Lines text={tidy(c.n8)} /></p>
</>),
]
},
}
export const TEMPLATES: Template[] = [tarot, ootd, intro]
export const templateById = (id: string) => TEMPLATES.find((t) => t.id === id)
+1
View File
@@ -323,6 +323,7 @@ class CardSet(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
ig_media_id: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
hashtags: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
class CardImage(Base):
+1
View File
@@ -196,6 +196,7 @@ CREATE TABLE IF NOT EXISTS public.card_set (
published_at TIMESTAMPTZ NULL
);
ALTER TABLE public.card_set ADD COLUMN IF NOT EXISTS ig_media_id VARCHAR(40) NULL; -- 인스타에 올렸으면 그 미디어 id
ALTER TABLE public.card_set ADD COLUMN IF NOT EXISTS hashtags TEXT NULL; -- 인스타 캡션 뒤에만 붙는 해시태그
CREATE TABLE IF NOT EXISTS public.card_image (
card_id BIGINT NOT NULL REFERENCES public.card_set (card_id) ON DELETE CASCADE,
seq SMALLINT NOT NULL, -- 1부터, 슬라이드 순서
+2 -2
View File
@@ -82,7 +82,7 @@ async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList:
@router.post("", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다", dependencies=[Depends(require_admin)])
async def create_card(req: Req_CardCreate) -> Res_Card:
images = _jpegs(req.images)
card = CardSet(template=req.template, topic=req.topic, title=req.title, caption=req.caption, copy=req.texts, status=CardStatus.WAITING.value)
card = CardSet(template=req.template, topic=req.topic, title=req.title, caption=req.caption, hashtags=req.hashtags.strip() or None, copy=req.texts, status=CardStatus.WAITING.value)
err, card = await DB_SESSION_MNG.execute_lambda_write(lambda s: _crud.create(s, card, images))
if err is not ErrorType.SUCCESS:
return Res_Card(result=error_info(err))
@@ -129,7 +129,7 @@ async def publish_instagram(card_id: int = Path(...)) -> Res_Card:
return Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id, ig_media_id=card.ig_media_id)
_, counts = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image_counts(s, [card_id]))
urls = [instagram.public_image_url(image_url(card_id, i)) for i in range(1, (counts or {}).get(card_id, 0) + 1)]
caption = f"{card.title}\n\n{card.caption}".strip()
caption = "\n\n".join(part for part in (card.title, card.caption, card.hashtags) if part)
try:
media_id = await instagram.publish_carousel(urls, caption)
except instagram.InstagramError as e:
+1
View File
@@ -12,6 +12,7 @@ class Req_CardCreate(WebPacketProtocol):
topic: Optional[str] = Field(default=None, max_length=60)
title: str = Field(max_length=80, description="피드 포스트 제목")
caption: str = Field(default="", max_length=2000)
hashtags: str = Field(default="", max_length=600, description="인스타 캡션 뒤에만 붙는 해시태그. 날씨각 피드에는 안 나간다")
texts: dict = Field(default_factory=dict, description="카드 문구 (다시 그릴 때 쓴다)")
images: list[str] = Field(min_length=1, max_length=20, description="1080×1350 JPEG, base64. 슬라이드 순서대로")
publish: bool = Field(default=False, description="true 면 만들자마자 그날 피드에 올린다. false 면 승인 대기")
+13 -2
View File
@@ -1,10 +1,10 @@
from typing import Optional
from fastapi import APIRouter, Depends, Path, Query
from fastapi import APIRouter, Depends, Path, Query, Request
from common.auth import optional_user
from common.database.model.models import User
from common.enums import ErrorType
from common.enums import ErrorType, PostType
from common.liker import Liker, liker
from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post
@@ -13,15 +13,26 @@ from services.reaction_service import ReactionService
router = APIRouter(prefix="/v1/feed", tags=["feed"])
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
TOSS_KNOWN_MAX = PostType.UV.value
def _from_toss(request: Request) -> bool:
ref = request.headers.get("origin") or request.headers.get("referer") or ""
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed(
request: Request,
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed:
err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err))
if _from_toss(request):
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids)
+2 -2
View File
@@ -112,7 +112,7 @@ async def test_instagram_publish_carousel_and_store_media_id(offline, admin_key,
assert data["access_token"] == "tok"
if request.url.path.endswith("/1789/media"):
if data.get("media_type") == "CAROUSEL":
assert data["children"] == "c1,c2,c3" and data["caption"].startswith("오늘의 썸 타로")
assert data["children"] == "c1,c2,c3" and data["caption"] == "오늘의 썸 타로\n\n한 장 골라 보세요\n\n#날씨각 #날씨타로"
return httpx.Response(200, json={"id": "car"})
assert data["image_url"].startswith("https://weather.example/v1/card/") and data["is_carousel_item"] == "true"
return httpx.Response(200, json={"id": f"c{len([c for c in calls if 'is_carousel_item' in c[1]])}"})
@@ -126,7 +126,7 @@ async def test_instagram_publish_carousel_and_store_media_id(offline, admin_key,
real = httpx.AsyncClient
monkeypatch.setattr(instagram.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler)))
async with client() as c:
made = (await c.post("/v1/card", json=body(publish=True), headers=admin_key)).json()
made = (await c.post("/v1/card", json=body(publish=True, hashtags="#날씨각 #날씨타로"), headers=admin_key)).json()
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
again = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
listed = (await c.get("/v1/card", headers=admin_key)).json()["items"][0]
+18
View File
@@ -0,0 +1,18 @@
from starlette.requests import Request
from common.enums import PostType
from router.v1.feed.feed import TOSS_KNOWN_MAX, _from_toss
def _req(headers: dict) -> Request:
return Request({"type": "http", "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()]})
def test_from_toss_by_referer_or_user_agent():
assert _from_toss(_req({"referer": "https://nalssigak.apps.tossmini.com/"}))
assert _from_toss(_req({"user-agent": "Mozilla/5.0 ... AppsInToss TossApp/5.282.1"}))
assert not _from_toss(_req({"referer": "https://weather.o2o.kr/", "user-agent": "Mozilla/5.0 Safari"}))
def test_card_is_hidden_from_old_toss_bundle():
assert PostType.CARD.value > TOSS_KNOWN_MAX >= PostType.UV.value