12 Commits

Author SHA1 Message Date
吕新雨
4838bcef4b fix:更新图片 2026-02-24 10:44:36 +08:00
吕新雨
0fcf85a081 更新任务生成 2026-02-13 22:46:01 +08:00
吕新雨
62fcc4bfce fix:每日推荐修复 2026-02-12 13:54:34 +08:00
吕新雨
eef5210c99 fix:更新定时任务push 2026-02-11 13:50:02 +08:00
吕新雨
402cbf90eb 修复:定时任务 2026-02-11 11:14:51 +08:00
decc7f9564 Merge pull request 'chore: App 名稱 Hey Mama → Dear Mama + 相關修復' (#22) from Lei-0210 into main
Reviewed-on: #22
2026-02-10 09:24:25 +00:00
173cee75d5 Merge pull request 'damer-0210' (#21) from damer-0210 into main
Reviewed-on: #21
2026-02-10 09:24:00 +00:00
吕新雨
076bd5636f fix:更新APP-PUSH 2026-02-10 17:23:38 +08:00
吕新雨
154f347ddb 注册token排查 2026-02-10 16:57:36 +08:00
吕新雨
dec3ac82e1 fix:后端错误 2026-02-10 16:47:18 +08:00
雷汀岚
e552e22de9 chore: App 名稱 Hey Mama → Dear Mama + 相關修復
- 品牌與顯示:app.json、Info.plist、package scheme、iOS 產物 DearMama.app
- 協議與條款:隱私協議/使用條款全文、設計文檔、server legal_docs + legal API、push 預設 title
- 多語言:all.json / zh-TW / zh-CN / en / es / pt 的 consent、widget 標題與引導文案
- 小工具:EmotionWidget.swift 品牌文案、Dear Mama.xcscheme
- CocoaPods:project.pbxproj objectVersion 70→56 以通過 pod install
- Metro:react-native-text-size 用 require + extraNodeModules 解析
- textWrap:measureWidthImpl 改為 require 載入 react-native-text-size

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-10 16:16:02 +08:00
吕新雨
1fbc0aa3f8 fix:重复点击 2026-02-10 15:06:50 +08:00
46 changed files with 782 additions and 212 deletions

View File

@@ -1,6 +1,6 @@
{
"expo": {
"name": "Hey Mama",
"name": "Dear Mama",
"slug": "client",
"version": "1.0.0",
"orientation": "portrait",

View File

@@ -113,6 +113,18 @@ export default function HomeScreen() {
const [cardWidth, setCardWidth] = useState<number | null>(null);
const [wrappedText, setWrappedText] = useState<string>('');
const wrapLogRef = useRef<{ key: string } | null>(null);
const busyRef = useRef(false);
const indexRef = useRef(0);
const currentFeedRef = useRef<FeedItem[]>([]);
const likedIdsRef = useRef<Set<string>>(new Set());
const likeInFlightRef = useRef(false);
useEffect(() => {
busyRef.current = busy;
}, [busy]);
useEffect(() => {
indexRef.current = index;
}, [index]);
// 解决语言切换时重复触发拉取/清空导致“文案不停跳动”的问题:
// 用 ref 持有最新状态,避免 useCallback 依赖 feedItems/isFetching 造成函数 identity 变化 → effect 重复执行
@@ -183,6 +195,9 @@ export default function HomeScreen() {
text: t(item.textKey)
}));
}, [feedItems, t]);
useEffect(() => {
currentFeedRef.current = currentFeed;
}, [currentFeed]);
const item = useMemo(() => {
const data = currentFeed[index % currentFeed.length];
@@ -430,24 +445,60 @@ export default function HomeScreen() {
transform: [{ scale: likeScale.value }],
}));
const setBusySafe = useCallback((next: boolean) => {
busyRef.current = next;
setBusy(next);
}, []);
const setLikeInFlight = useCallback((next: boolean) => {
likeInFlightRef.current = next;
}, []);
const syncLikeFilledByIndex = useCallback((nextIndex: number) => {
const list = currentFeedRef.current;
const len = list.length;
if (!len) {
setLikeFilled(false);
return;
}
const safe = ((nextIndex % len) + len) % len;
const nextId = String(list[safe]?.content_id);
setLikeFilled(likedIdsRef.current.has(nextId));
}, []);
const applyIndexChange = useCallback((nextIndex: number) => {
indexRef.current = nextIndex;
setIndex(nextIndex);
syncLikeFilledByIndex(nextIndex);
}, [syncLikeFilledByIndex]);
const maybeFetchNewFeedIfNeeded = useCallback((nextIndex: number) => {
const len = currentFeedRef.current.length;
if (!len) return;
// 当接近当前列表末尾时(例如还剩 5 条)提前拉取
if (nextIndex + 5 >= len && !isFetchingRef.current) {
fetchNewFeed();
}
}, [fetchNewFeed]);
// 切换到下一条文案的统一动画逻辑
const triggerNextContent = useCallback(() => {
if (busy) return;
setBusy(true);
if (busyRef.current) return;
setBusySafe(true);
// 注意:不要在 Reanimated worklet 回调里读取 React ref例如 indexRef/currentFeedRef会导致值不更新或异常
const nextIndex = indexRef.current + 1;
// 1. 当前文案向上移动并消失
translateY.value = withTiming(-40, { duration: 300, easing: Easing.out(Easing.quad) });
opacity.value = withTiming(0, { duration: 300 }, (finished) => {
if (finished) {
// 2. 切换数据索引
runOnJS(setIndex)(index + 1);
runOnJS(setLikeFilled)(false);
runOnJS(applyIndexChange)(nextIndex);
runOnJS(advanceSuixinOnNextContent)();
// 检查是否需要拉取新文案(当接近当前列表末尾时,例如还剩 5 条
if (index + 5 >= currentFeed.length && !isFetching) {
runOnJS(fetchNewFeed)();
}
// 检查是否需要拉取新文案(注意:不要把匿名函数塞进 runOnJS可能导致原生崩溃
runOnJS(maybeFetchNewFeedIfNeeded)(nextIndex);
// 3. 准备下一条文案:先瞬移到下方 40pt
translateY.value = 40;
@@ -456,26 +507,29 @@ export default function HomeScreen() {
translateY.value = withTiming(0, { duration: 400, easing: Easing.out(Easing.back(1)) });
opacity.value = withTiming(1, { duration: 400 }, (finished) => {
if (finished) {
runOnJS(setBusy)(false);
runOnJS(setBusySafe)(false);
}
});
}
});
}, [busy, index, currentFeed.length, isFetching, fetchNewFeed, translateY, opacity]);
}, [applyIndexChange, setBusySafe, translateY, opacity, advanceSuixinOnNextContent, maybeFetchNewFeedIfNeeded]);
// 切换到上一条文案的统一动画逻辑(下滑触发)
const triggerPrevContent = useCallback(() => {
if (busy) return;
setBusy(true);
if (busyRef.current) return;
setBusySafe(true);
// 注意:同上,不要在 worklet 里读取 React ref
const len = currentFeedRef.current.length;
const raw = indexRef.current - 1;
const nextIndex = len ? ((raw % len) + len) % len : Math.max(0, raw);
// 1. 当前文案向下移动并消失
translateY.value = withTiming(40, { duration: 300, easing: Easing.out(Easing.quad) });
opacity.value = withTiming(0, { duration: 300 }, (finished) => {
if (finished) {
// 2. 切换数据索引(循环回退)
const nextIndex = index - 1 < 0 ? Math.max(0, currentFeed.length - 1) : index - 1;
runOnJS(setIndex)(nextIndex);
runOnJS(setLikeFilled)(false);
runOnJS(applyIndexChange)(nextIndex);
// 3. 准备上一条文案:先瞬移到上方 40pt
translateY.value = -40;
@@ -484,12 +538,12 @@ export default function HomeScreen() {
translateY.value = withTiming(0, { duration: 400, easing: Easing.out(Easing.back(1)) });
opacity.value = withTiming(1, { duration: 400 }, (finished) => {
if (finished) {
runOnJS(setBusy)(false);
runOnJS(setBusySafe)(false);
}
});
}
});
}, [busy, index, currentFeed.length, translateY, opacity]);
}, [applyIndexChange, setBusySafe, translateY, opacity]);
const lastTapRef = useRef<number>(0);
@@ -533,7 +587,21 @@ export default function HomeScreen() {
).current;
async function onPressLike() {
if (busy) return;
if (busyRef.current) return;
if (likeInFlightRef.current) return;
// 已经喜欢过:不重复写入收藏,直接当作“下一条”
if (likeFilled || likedIdsRef.current.has(item.id)) {
triggerNextContent();
return;
}
likeInFlightRef.current = true;
const likedItemId = item.id;
const likedItemText = item.text;
// 先记下“已喜欢”,保证回退时能恢复点亮状态(即便异步保存稍后才完成)
likedIdsRef.current.add(likedItemId);
setLikeFilled(true);
// 1. 获取当前日期
@@ -543,24 +611,33 @@ export default function HomeScreen() {
// 2. 保存到收藏夹,包含当前背景信息
const favItem = {
favId: String(Date.now()), // 生成唯一 ID
id: item.id,
text: item.text,
id: likedItemId,
text: likedItemText,
date: dateStr,
themeMode: themeMode,
background: themeMode === 'scenery' ? String(natureImageIndex) : backgroundColor,
};
console.log('Home: Triggering addFavorite', JSON.stringify(favItem));
await addFavorite(favItem);
try {
await addFavorite(favItem);
} catch (error) {
console.error('Home: addFavorite 失败', error);
}
// 3. 记录到后端 Reaction喜欢
console.log('Home: Triggering setReaction', item.id);
await setReaction(item.id, 'like');
try {
await setReaction(item.id, 'like');
} catch (error) {
console.error('Home: setReaction 失败', error);
}
// 4. 爱心缩放动画
likeScale.value = withSequence(
withTiming(0.8, { duration: 100 }),
withTiming(1.2, { duration: 150 }),
withTiming(1, { duration: 100 }, (finished) => {
runOnJS(setLikeInFlight)(false);
if (finished) {
console.log('Home: Like animation finished, triggering next content');
runOnJS(triggerNextContent)();

View File

@@ -12,7 +12,7 @@ import { buildUserProfileFromQuestionnaire, mapOnboardingSelectionsToQuestionnai
import { ensureDailyWidgetRecoUpToDate, syncWidgetConfig, syncWidgetUserProfileFromScoring } from '@/src/modules/dailyWidgetReco';
import { toBackendLocaleFromLanguageTag } from '@/src/i18n/locale';
import { fetchRecoFeed } from '@/src/services/recoApi';
import { getExpoPushTokenOrThrow, registerPushToken, setPushPreferences } from '@/src/services/pushApi';
import { ensurePushTokenRegisteredIfPermitted, setPushPreferences } from '@/src/services/pushApi';
import {
recordRecoFeedServed,
setOnboardingCompleted,
@@ -44,6 +44,7 @@ export default function OnboardingScreen() {
const [name, setName] = useState('');
const [selections, setSelections] = useState<Record<string, string[]>>({});
const [reminderTimes, setReminderTimes] = useState(3);
const [finishing, setFinishing] = useState(false);
const currentStep = STEPS[stepIndex];
const currentTitle = useMemo(() => t(`onboardingSurvey.steps.${currentStep.id}.title`), [t, currentStep.id]);
@@ -56,6 +57,9 @@ export default function OnboardingScreen() {
}, [t, currentStep]);
async function onFinish() {
if (finishing) return;
setFinishing(true);
try {
// 用户选择每日次数 > 0在此页直接触发系统通知权限已移除单独的 push 引导页)。
const wantsPush = reminderTimes > 0;
@@ -124,7 +128,8 @@ export default function OnboardingScreen() {
await setPushPromptState('unknown');
try {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') {
// iOS 可能出现 provisional临时授权也应视为“已授权”
if (status !== 'granted' && status !== ('provisional' as any)) {
await setPushPromptState('skipped');
return;
}
@@ -136,10 +141,8 @@ export default function OnboardingScreen() {
return;
}
// 1) 获取 Expo Push Token失败才认为“推送开启失败”)
const expoPushToken = await getExpoPushTokenOrThrow();
// 2) 上报 token 到后端(幂等;失败才认为“推送开启失败”)
await registerPushToken({ pushToken: expoPushToken });
// 1) 上报 token 到后端(幂等;失败才认为“推送开启失败”)
await ensurePushTokenRegisteredIfPermitted();
// 3) 上报推送偏好(幂等)
// 注意:这一步失败时,后端仍可能已成功接收 token。
@@ -159,9 +162,17 @@ export default function OnboardingScreen() {
} finally {
router.replace('/(app)/home');
}
} catch (e) {
// 极端情况下(例如本地存储/初始化异常)避免卡死在 loading提示并允许用户重试
const msg = e instanceof Error ? e.message : String(e);
console.warn('[OnboardingFinish] 异常:', msg);
Alert.alert(t('push.errorTitle'), t('push.errorDesc'));
setFinishing(false);
}
}
const onNext = () => {
if (finishing) return;
if (stepIndex < STEPS.length - 1) {
setStepIndex(stepIndex + 1);
} else {
@@ -170,6 +181,7 @@ export default function OnboardingScreen() {
};
const onBack = () => {
if (finishing) return;
if (stepIndex > 0) {
setStepIndex(stepIndex - 1);
}
@@ -177,6 +189,7 @@ export default function OnboardingScreen() {
/** 只跳過當前這一步(不填/不選當前題,進入下一步) */
const handleSkipCurrentStep = () => {
if (finishing) return;
if (currentStep.type === 'name') {
onNext();
} else if (currentStep.type === 'selection') {
@@ -200,6 +213,7 @@ export default function OnboardingScreen() {
};
const handleSkipStep = () => {
if (finishing) return;
setSelections((prev) => ({ ...prev, [currentStep.id]: [] }));
onNext();
};
@@ -236,6 +250,7 @@ export default function OnboardingScreen() {
value={Math.max(1, reminderTimes)}
onChange={setReminderTimes}
onFinish={onFinish}
loading={finishing}
onSkip={() => {
// 跳过每日提醒:视为 0 次(关闭)
setReminderTimes(0);

View File

@@ -12,6 +12,7 @@ import { useColorScheme } from '@/components/useColorScheme';
import { initI18n } from '@/src/i18n';
import { ensureDailyWidgetRecoUpToDate, syncWidgetConfig, syncWidgetUserProfileFromStorage } from '@/src/modules/dailyWidgetReco';
import { getOrCreateClientUserId } from '@/src/storage/appStorage';
import { ensurePushTokenRegisteredIfPermitted } from '@/src/services/pushApi';
// 配置通知处理方式(即使不发送也建议配置,以确保权限接口正常)
Notifications.setNotificationHandler({
@@ -75,6 +76,28 @@ export default function RootLayout() {
});
}, []);
useEffect(() => {
// 只要系统通知权限已经 granted就主动上报 Push Token不依赖用户在“每日提醒”里点确认
ensurePushTokenRegisteredIfPermitted()
.then((res) => {
if (__DEV__) console.log('[push_token_sync]', res);
})
.catch((e) => {
if (__DEV__) console.warn('[push_token_sync] 失败(不阻塞启动)', e);
});
}, []);
useEffect(() => {
// 兜底:当用户在系统弹窗/系统设置里变更权限后App 回到前台时再同步一次 token
const sub = AppState.addEventListener('change', (state) => {
if (state !== 'active') return;
ensurePushTokenRegisteredIfPermitted().catch(() => {
// ignore不阻塞
});
});
return () => sub.remove();
}, []);
useEffect(() => {
// 字体与 i18n 都准备好后,允许渲染 App原生 splash 的隐藏交给 onLayout避免“硬切/闪白”)
if (loaded && i18nReady) setAppReady(true);
@@ -113,7 +136,7 @@ export default function RootLayout() {
<Animated.View pointerEvents="none" style={[StyleSheet.absoluteFill, { opacity: splashOpacity }]}>
<View style={styles.splashOverlay}>
<Image
source={require('../assets/images/splashScreen.png')}
source={require('../assets/images/Screen_page.png')}
style={styles.splashImage}
resizeMode="contain"
/>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

View File

@@ -41,7 +41,7 @@ import QuestionIcon from '@/assets/images/home/Profile/widget/question_icon.svg'
import * as Notifications from 'expo-notifications';
import { changeLanguage } from '@/src/i18n';
import { fetchLegalLinks } from '@/src/services/legalApi';
import { getExpoPushTokenOrThrow, registerPushToken, setPushPreferences } from '@/src/services/pushApi';
import { ensurePushTokenRegisteredIfPermitted, setPushPreferences } from '@/src/services/pushApi';
const { width } = Dimensions.get('window');
@@ -430,14 +430,13 @@ function DailyReminderPage({ visible, onDone }: { visible: boolean; onDone: () =
// 调试:打印状态
console.log('Push Permission Status:', status);
if (status === 'granted') {
if (status === 'granted' || (status as any) === 'provisional') {
setPushEnabled(true);
setHasSystemPermission(true);
// 获取 token 并上报后端(幂等)
try {
const expoPushToken = await getExpoPushTokenOrThrow();
await registerPushToken({ pushToken: expoPushToken });
await ensurePushTokenRegisteredIfPermitted();
// 偏好同步失败不应被用户感知为“开启失败”
// (常见现象:后端已接收 token但偏好接口短暂失败/超时)
try {
@@ -479,6 +478,13 @@ function DailyReminderPage({ visible, onDone }: { visible: boolean; onDone: () =
const next: DailyReminderSettings = { timesPerDay: nextTimes, pushEnabled: nextEnabled };
await setDailyReminderSettings(next);
// 若系统权限已授予且用户意愿为开启:兜底同步一次 token避免“没点开关/没触发 toggle 导致后端无 token”
if (nextEnabled) {
ensurePushTokenRegisteredIfPermitted().catch(() => {
// ignore不阻塞保存
});
}
// 同步后端偏好(幂等;失败不阻塞)
try {
await setPushPreferences({ enabled: nextEnabled, timesPerDay: nextTimes });

View File

@@ -1,7 +1,8 @@
import React from 'react';
import { View, StyleSheet, TouchableOpacity, Text, Platform } from 'react-native';
import { View, StyleSheet, TouchableOpacity, Text, Platform, ActivityIndicator } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import { OnboardingColors } from '@/constants/OnboardingTheme';
import AddIcon from '@/assets/images/icon/add_icon.svg';
import ReduceIcon from '@/assets/images/icon/reduce_icon.svg';
@@ -12,9 +13,11 @@ interface ReminderStepProps {
onChange: (value: number) => void;
onFinish: () => void;
onSkip?: () => void;
/** 完成后请求通知权限时的加载态 */
loading?: boolean;
}
export function ReminderStep({ value, onChange, onFinish }: ReminderStepProps) {
export function ReminderStep({ value, onChange, onFinish, loading = false }: ReminderStepProps) {
const { t } = useTranslation();
const insets = useSafeAreaInsets();
@@ -30,7 +33,7 @@ export function ReminderStep({ value, onChange, onFinish }: ReminderStepProps) {
return (
<View style={styles.container}>
<View style={styles.counterContainer}>
<TouchableOpacity onPress={handleReduce} activeOpacity={0.7}>
<TouchableOpacity onPress={handleReduce} disabled={loading} activeOpacity={0.7}>
<ReduceIcon width={47} height={47} />
</TouchableOpacity>
@@ -41,14 +44,27 @@ export function ReminderStep({ value, onChange, onFinish }: ReminderStepProps) {
</Text>
</View>
<TouchableOpacity onPress={handleAdd} activeOpacity={0.7}>
<TouchableOpacity onPress={handleAdd} disabled={loading} activeOpacity={0.7}>
<AddIcon width={47} height={47} />
</TouchableOpacity>
</View>
<View style={[styles.footer, { bottom: insets.bottom + 16 }]}>
<TouchableOpacity onPress={onFinish} activeOpacity={0.8}>
<BtnClicked width={87} height={57} />
<TouchableOpacity onPress={onFinish} disabled={loading} activeOpacity={0.8}>
<View style={styles.finishWrap}>
{loading ? (
<LinearGradient
colors={['#F69F7B', '#F99CC0']}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
style={[styles.loadingPill, styles.finishDisabled]}
>
<ActivityIndicator size="small" color="#FFFFFF" />
</LinearGradient>
) : (
<BtnClicked width={87} height={57} />
)}
</View>
</TouchableOpacity>
</View>
</View>
@@ -92,4 +108,20 @@ const styles = StyleSheet.create({
position: 'absolute',
alignItems: 'center',
},
finishWrap: {
width: 87,
height: 57,
alignItems: 'center',
justifyContent: 'center',
},
finishDisabled: {
opacity: 0.7,
},
loadingPill: {
width: 87,
height: 57,
borderRadius: 28.5,
alignItems: 'center',
justifyContent: 'center',
},
});

View File

@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 70;
objectVersion = 56;
objects = {
/* Begin PBXBuildFile section */
@@ -11,7 +11,7 @@
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
1A1DE01D4133812B2E2BA692 /* libPods-client.a in Frameworks */ = {isa = PBXBuildFile; fileRef = E3328F0E595C1F4A244DF238 /* libPods-client.a */; };
3E461D99554A48A4959DE609 /* SplashScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = AA286B85B6C04FC6940260E9 /* SplashScreen.storyboard */; };
A1B2C3D4E5F60718293A4B5C /* 情绪小组件/EmotionWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F60718293A4B5B /* 情绪小组件/EmotionWidget.swift */; };
A1B2C3D4E5F60718293A4B5C /* EmotionWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F60718293A4B5B /* EmotionWidget.swift */; };
A8C1D2E3F4A5B6C7D8E9F0A2 /* AppGroupStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8C1D2E3F4A5B6C7D8E9F0A1 /* AppGroupStorage.swift */; };
A8C1D2E3F4A5B6C7D8E9F0A3 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EB3DAF802F2A4B8D00450593 /* WidgetKit.framework */; };
A8C1D2E3F4A5B6C7D8E9F0B2 /* AppGroupStorageBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = A8C1D2E3F4A5B6C7D8E9F0B1 /* AppGroupStorageBridge.m */; };
@@ -49,12 +49,12 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
13B07F961A680F5B00A75B9A /* HeyMama.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HeyMama.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07F961A680F5B00A75B9A /* DearMama.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DearMama.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = client/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = client/Info.plist; sourceTree = "<group>"; };
3C76CA16D0801CBF0D731C7C /* Pods-client.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-client.release.xcconfig"; path = "Target Support Files/Pods-client/Pods-client.release.xcconfig"; sourceTree = "<group>"; };
75F52ADE07CAE9D9736D7671 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = client/PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
A1B2C3D4E5F60718293A4B5B /* 情绪小组件/EmotionWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "情绪小组件/EmotionWidget.swift"; sourceTree = "<group>"; };
A1B2C3D4E5F60718293A4B5B /* EmotionWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "情绪小组件/EmotionWidget.swift"; sourceTree = "<group>"; };
A8C1D2E3F4A5B6C7D8E9F0A1 /* AppGroupStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppGroupStorage.swift; path = client/AppGroupStorage.swift; sourceTree = "<group>"; };
A8C1D2E3F4A5B6C7D8E9F0B1 /* AppGroupStorageBridge.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = AppGroupStorageBridge.m; path = client/AppGroupStorageBridge.m; sourceTree = "<group>"; };
AA286B85B6C04FC6940260E9 /* SplashScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = SplashScreen.storyboard; path = client/SplashScreen.storyboard; sourceTree = "<group>"; };
@@ -74,7 +74,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
EB3DAF952F2A4B8F00450593 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
EB3DAF952F2A4B8F00450593 /* Exceptions for "情绪小组件" folder in "情绪小组件Extension" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
EmotionWidget.swift,
@@ -85,7 +85,18 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
EB3DAF842F2A4B8E00450593 /* 情绪小组件 */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (EB3DAF952F2A4B8F00450593 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = "情绪小组件"; sourceTree = "<group>"; };
EB3DAF842F2A4B8E00450593 /* 情绪小组件 */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
EB3DAF952F2A4B8F00450593 /* Exceptions for "情绪小组件" folder in "情绪小组件Extension" target */,
);
explicitFileTypes = {
};
explicitFolders = (
);
path = "情绪小组件";
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -175,7 +186,7 @@
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* HeyMama.app */,
13B07F961A680F5B00A75B9A /* DearMama.app */,
EB3DAF7F2F2A4B8D00450593 /* 情绪小组件Extension.appex */,
);
name = Products;
@@ -202,7 +213,7 @@
EB3DAFD42F2A5FC100450593 /* Recovered References */ = {
isa = PBXGroup;
children = (
A1B2C3D4E5F60718293A4B5B /* 情绪小组件/EmotionWidget.swift */,
A1B2C3D4E5F60718293A4B5B /* EmotionWidget.swift */,
);
name = "Recovered References";
sourceTree = "<group>";
@@ -239,7 +250,7 @@
);
name = client;
productName = client;
productReference = 13B07F961A680F5B00A75B9A /* HeyMama.app */;
productReference = 13B07F961A680F5B00A75B9A /* DearMama.app */;
productType = "com.apple.product-type.application";
};
EB3DAF7E2F2A4B8D00450593 /* 情绪小组件Extension */ = {
@@ -471,7 +482,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A1B2C3D4E5F60718293A4B5C /* 情绪小组件/EmotionWidget.swift in Sources */,
A1B2C3D4E5F60718293A4B5C /* EmotionWidget.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -516,7 +527,7 @@
);
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";
PRODUCT_BUNDLE_IDENTIFIER = com.damer.mindfulness;
PRODUCT_NAME = HeyMama;
PRODUCT_NAME = DearMama;
SKIP_INSTALL = NO;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;
@@ -557,7 +568,7 @@
);
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
PRODUCT_BUNDLE_IDENTIFIER = com.damer.mindfulness;
PRODUCT_NAME = HeyMama;
PRODUCT_NAME = DearMama;
SKIP_INSTALL = NO;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO;

View File

@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "HeyMama.app"
BuildableName = "DearMama.app"
BlueprintName = "client"
ReferencedContainer = "container:client.xcodeproj">
</BuildableReference>
@@ -44,7 +44,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "HeyMama.app"
BuildableName = "DearMama.app"
BlueprintName = "client"
ReferencedContainer = "container:client.xcodeproj">
</BuildableReference>
@@ -61,7 +61,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "HeyMama.app"
BuildableName = "DearMama.app"
BlueprintName = "client"
ReferencedContainer = "container:client.xcodeproj">
</BuildableReference>
@@ -72,7 +72,7 @@
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
customArchiveName = "Hey Mama"
customArchiveName = "Dear Mama"
revealArchiveInOrganizer = "YES">
<PostActions>
<ExecutionAction
@@ -85,7 +85,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "HeyMama.app"
BuildableName = "DearMama.app"
BlueprintName = "client"
ReferencedContainer = "container:client.xcodeproj">
</BuildableReference>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 143 KiB

View File

@@ -7,7 +7,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Hey Mama</string>
<string>Dear Mama</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>

View File

@@ -42,7 +42,7 @@ if [[ -z "$APP_PLIST" ]]; then
fi
APP_DIR="$(/usr/bin/dirname "$APP_PLIST")"
APP_NAME="$(/usr/bin/basename "$APP_DIR")" # 例如 HeyMama.app
APP_NAME="$(/usr/bin/basename "$APP_DIR")" # 例如 DearMama.app
APP_REL_PATH="Applications/$APP_NAME"
bundle_id="$(/usr/bin/plutil -extract CFBundleIdentifier raw -o - "$APP_PLIST" 2>/dev/null || true)"

View File

@@ -41,8 +41,8 @@ private func resolveLang() -> String {
}
private func resolveTitle(lang: String) -> String {
// Hey Mama
return "Hey Mama"
// Dear Mama
return "Dear Mama"
}
private func resolveFooterHint(lang: String) -> String {

View File

@@ -1,5 +1,6 @@
// Metro 配置:支持 import 本地 .svg 为 React 组件
// 说明Expo SDK 54 + react-native-svg-transformer 的常见配置方式
const path = require('path');
const { getDefaultConfig } = require('expo/metro-config');
/** @type {import('expo/metro-config').MetroConfig} */
@@ -14,6 +15,10 @@ config.resolver = {
...config.resolver,
assetExts: config.resolver.assetExts.filter((ext) => ext !== 'svg'),
sourceExts: [...config.resolver.sourceExts, 'svg'],
// 确保 react-native-text-size 从项目 node_modules 解析(避免 Metro 解析不到)
extraNodeModules: {
'react-native-text-size': path.resolve(__dirname, 'node_modules/react-native-text-size'),
},
};
module.exports = config;

View File

@@ -9719,6 +9719,7 @@
"version": "4.0.0-rc.1",
"resolved": "https://registry.npmmirror.com/react-native-text-size/-/react-native-text-size-4.0.0-rc.1.tgz",
"integrity": "sha512-CysqjU2jK6Yc+a+kEI222pUyTY2ywcU2HqbFqf1KHymW6OPTdvBBHqbEJKL0QiLhQaFYDbqicM+h990s9TP00g==",
"license": "BSD-2-Clause",
"peerDependencies": {
"react-native": ">=0.59.0"
}

View File

@@ -6,8 +6,8 @@
"start": "expo start",
"start:clean": "expo start -c",
"android": "expo run:android",
"ios": "expo run:ios --scheme \"Hey Mama\"",
"ios:clean": "npm run clean:cache && npm run clean:ios-build && expo run:ios --scheme \"Hey Mama\"",
"ios": "expo run:ios --scheme \"Dear Mama\"",
"ios:clean": "npm run clean:cache && npm run clean:ios-build && expo run:ios --scheme \"Dear Mama\"",
"web": "expo start --web",
"test": "vitest run",
"clean:cache": "rm -rf node_modules/.cache .expo 2>/dev/null; echo 'Cleared .expo and node_modules/.cache'",

View File

@@ -27,7 +27,7 @@ export type AppRuntimeEnv = 'local' | 'dev' | 'prod';
* 默认回退到 prod避免误打到 localhost 导致真机“无法发起网络请求”)。
*/
const DEFAULT_RUNTIME_ENV: AppRuntimeEnv =
typeof __DEV__ !== 'undefined' && __DEV__ ? 'local' : 'prod';
typeof __DEV__ !== 'undefined' && __DEV__ ? 'local' : 'dev';
export const APP_ENV = (getOptionalEnv('EXPO_PUBLIC_ENV', DEFAULT_RUNTIME_ENV) as AppRuntimeEnv) ?? DEFAULT_RUNTIME_ENV;
@@ -46,7 +46,7 @@ function getApiBaseUrl(env: AppRuntimeEnv): string {
return getOptionalEnv('EXPO_PUBLIC_API_BASE_URL_PROD', getOptionalEnv('EXPO_PUBLIC_API_BASE_URL_LOCAL', 'https://api.damer.fun'));
}
export const API_BASE_URL = getApiBaseUrl(APP_ENV);
export const API_BASE_URL = getApiBaseUrl(APPpai qa
/**
* 调试:打印环境变量注入结果(仅开发环境)

View File

@@ -20,11 +20,12 @@ type TextSizeMeasureParams = {
type TextSizeMeasureResult = { width: number };
async function loadReactNativeTextSize(): Promise<{
function loadReactNativeTextSize(): {
measure: (params: TextSizeMeasureParams) => Promise<TextSizeMeasureResult>;
}> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mod: any = await import('react-native-text-size');
} {
// 使用 require 确保 Metro 能解析并打包该原生模块(动态 import 在某些环境下无法被正确解析)
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
const mod: any = require('react-native-text-size');
return mod?.default ?? mod;
}
@@ -42,7 +43,7 @@ function toTextSizeFontSpecs(fontSpec: FontSpec): Pick<TextSizeMeasureParams, 'f
* - usePreciseWidth=true取更精确的宽度开销更大但对本算法更稳定
*/
export const defaultMeasureWidthImpl: MeasureWidthImpl = async ({ text, fontSpec }) => {
const TextSize = await loadReactNativeTextSize();
const TextSize = loadReactNativeTextSize();
if (!TextSize || typeof TextSize.measure !== 'function') {
// 典型原因:在 Expo Go 中运行,或没有使用包含该原生模块的 Development Build。
// 这里抛出更明确的错误,方便上层捕获并在 meta.reason=MEASURE_FAILED 时看到根因。

View File

@@ -88,7 +88,7 @@
"errorDesc": "Its okay if enabling fails. You can keep using the app."
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "Like",
"dislike": "Dislike",
"favorites": "Favorites",
@@ -127,7 +127,7 @@
"homeScreen": "Home Screen Widget",
"howToTitle": "How to add the widget",
"howToDesc1": "Long-press on the Home Screen until the apps jiggle, then tap “+” in the top-left corner.",
"howToDesc2": "Search “Hey Mama”, choose a widget size you like, then tap “Add Widget”.",
"howToDesc2": "Search “Dear Mama”, choose a widget size you like, then tap “Add Widget”.",
"previewDate": "Thu, Jan 29",
"previewQuote": "Im proud of who I am, even while becoming who I want to be."
},
@@ -141,10 +141,10 @@
"language": "Language",
"version": "Version",
"widgetTitle": "iOS Widget",
"widgetDesc": "Put gentle reminders on your home screen: long-press → tap “+” → search “Hey Mama” → add a size you like."
"widgetDesc": "Put gentle reminders on your home screen: long-press → tap “+” → search “Dear Mama” → add a size you like."
},
"consent": {
"title": "Hey mama.",
"title": "Dear mama.",
"subtitle": "Youre doing okay\nright now.",
"subtitleSecondary": "",
"agree": "Agree & Continue",
@@ -260,7 +260,7 @@
"errorDesc": "開啟失敗也沒關係,你仍然可以繼續使用應用。"
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "喜歡",
"dislike": "不喜歡",
"favorites": "收藏",
@@ -299,7 +299,7 @@
"homeScreen": "桌面小工具",
"howToTitle": "如何加入小工具",
"howToDesc1": "長按主畫面空白處進入編輯,點左上角「+」新增小工具。",
"howToDesc2": "搜尋「Hey Mama」選擇喜歡的尺寸點「加入小工具」。",
"howToDesc2": "搜尋「Dear Mama」選擇喜歡的尺寸點「加入小工具」。",
"previewDate": "1月29日週四 · 已至臘月十一",
"previewQuote": "我也對現在的自己感到滿意,即使我仍在努力成為想成為的人。"
},
@@ -313,7 +313,7 @@
"language": "語言",
"version": "版本",
"widgetTitle": "iOS 小工具",
"widgetDesc": "把溫柔提醒放到桌面上:長按主畫面 → 點「+」 → 搜尋「Hey Mama」 → 添加你喜歡的尺寸。"
"widgetDesc": "把溫柔提醒放到桌面上:長按主畫面 → 點「+」 → 搜尋「Dear Mama」 → 添加你喜歡的尺寸。"
},
"consent": {
"title": "我們知道,",

View File

@@ -32,7 +32,7 @@
"errorDesc": "Its okay if enabling fails. You can keep using the app."
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "Like",
"dislike": "Dislike",
"favorites": "Favorites",
@@ -80,7 +80,7 @@
"language": "Language",
"version": "Version",
"widgetTitle": "iOS Widget",
"widgetDesc": "Put gentle reminders on your home screen: long-press → tap “+” → search “Hey Mama” → add a size you like."
"widgetDesc": "Put gentle reminders on your home screen: long-press → tap “+” → search “Dear Mama” → add a size you like."
},
"consent": {
"title": "You Are Perfect.",

View File

@@ -30,7 +30,7 @@
"errorDesc": "No pasa nada si falla. Puedes seguir usando la app."
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "Me gusta",
"dislike": "No me gusta",
"favorites": "Favoritos",
@@ -78,7 +78,7 @@
"language": "Idioma",
"version": "Versión",
"widgetTitle": "Widget de iOS",
"widgetDesc": "Pon recordatorios en tu pantalla: mantén pulsado → “+” → busca “Hey Mama” → añade el tamaño."
"widgetDesc": "Pon recordatorios en tu pantalla: mantén pulsado → “+” → busca “Dear Mama” → añade el tamaño."
},
"consent": {
"agree": "Aceptar y Continuar",

View File

@@ -30,7 +30,7 @@
"errorDesc": "Tudo bem se falhar. Você pode continuar usando o app."
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "Curtir",
"dislike": "Não curtir",
"favorites": "Favoritos",
@@ -78,7 +78,7 @@
"language": "Idioma",
"version": "Versão",
"widgetTitle": "Widget do iOS",
"widgetDesc": "Coloque lembretes na tela inicial: pressione e segure → “+” → procure “Hey Mama” → adicione o tamanho."
"widgetDesc": "Coloque lembretes na tela inicial: pressione e segure → “+” → procure “Dear Mama” → adicione o tamanho."
},
"consent": {
"agree": "Concordar e Continuar",

View File

@@ -33,7 +33,7 @@
"errorDesc": "开启失败,请稍后重试(模拟器可能无法获取推送 Token建议用真机测试。"
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "点赞",
"dislike": "讨厌",
"favorites": "收藏",
@@ -81,7 +81,7 @@
"language": "语言",
"version": "版本",
"widgetTitle": "iOS 小组件",
"widgetDesc": "把温柔提醒放到桌面上:长按主屏幕 → 点“+” → 搜索“Hey Mama” → 添加你喜欢的尺寸。"
"widgetDesc": "把温柔提醒放到桌面上:长按主屏幕 → 点“+” → 搜索“Dear Mama” → 添加你喜欢的尺寸。"
},
"consent": {
"title": "你本就完美。",

View File

@@ -92,7 +92,7 @@
"errorDesc": "開啟失敗也沒關係,你仍然可以繼續使用應用。"
},
"home": {
"title": "Hey Mama",
"title": "Dear Mama",
"like": "喜歡",
"dislike": "不喜歡",
"favorites": "收藏",
@@ -131,7 +131,7 @@
"homeScreen": "桌面小工具",
"howToTitle": "如何加入小工具",
"howToDesc1": "長按主畫面空白處進入編輯,點左上角「+」新增小工具。",
"howToDesc2": "搜尋「Hey Mama」選擇喜歡的尺寸點「加入小工具」。",
"howToDesc2": "搜尋「Dear Mama」選擇喜歡的尺寸點「加入小工具」。",
"previewDate": "1月29日週四 · 已至臘月十一",
"previewQuote": "我也對現在的自己感到滿意,即使我仍在努力成為想成為的人。"
},
@@ -145,7 +145,7 @@
"language": "語言",
"version": "版本",
"widgetTitle": "iOS 小工具",
"widgetDesc": "把溫柔提醒放到桌面上:長按主畫面 → 點「+」 → 搜尋「Hey Mama」 → 添加你喜歡的尺寸。"
"widgetDesc": "把溫柔提醒放到桌面上:長按主畫面 → 點「+」 → 搜尋「Dear Mama」 → 添加你喜歡的尺寸。"
},
"consent": {
"title": "我們知道,",

View File

@@ -5,7 +5,13 @@ import { Platform } from 'react-native';
import { httpJson } from '../utils/http';
import { APP_ENV } from '../constants/env';
import { getDailyReminderSettings, getOrCreateClientUserId, getUserProfileScoring } from '../storage/appStorage';
import {
getDailyReminderSettings,
getLastRegisteredPushPayload,
getOrCreateClientUserId,
getUserProfileScoring,
setLastRegisteredPushPayload,
} from '../storage/appStorage';
import type { UserProfileScoring } from '../storage/appStorage';
import { toBackendLocaleFromLanguageTag } from '../i18n/locale';
@@ -154,6 +160,40 @@ export async function registerPushToken(args: { pushToken: string }): Promise<vo
});
}
function isSystemNotificationPermissionGranted(status: unknown): boolean {
// iOS 可能出现 provisional临时授权在 Push 场景也应视为“可获取 token 并上报”
return status === 'granted' || status === 'provisional';
}
export async function ensurePushTokenRegisteredIfPermitted(): Promise<{ ok: boolean; reason: string }> {
// 只要系统权限已授权,就应尽早把 token 写入后端(不依赖用户在“每日提醒”里点确认)
const settings = await Notifications.getPermissionsAsync();
if (!isSystemNotificationPermissionGranted(settings.status)) return { ok: false, reason: 'permission_not_granted' };
const clientUserId = await getOrCreateClientUserId();
const token = await getExpoPushTokenOrThrow();
const env = toPushEnv(APP_ENV);
const appId = pickAppId();
// 去重规则(更严格):
// - 只有当 token + client_user_id + env + app_id 全都一致时才跳过
// - 避免出现“client_user_id 变化但 token 没变,导致后端绑定不更新”的问题
const last = await getLastRegisteredPushPayload().catch(() => null);
if (
last &&
last.pushToken === token &&
last.clientUserId === clientUserId &&
last.env === env &&
last.appId === appId
) {
return { ok: true, reason: 'already_registered' };
}
await registerPushToken({ pushToken: token });
await setLastRegisteredPushPayload({ pushToken: token, clientUserId, env, appId });
return { ok: true, reason: 'registered' };
}
export async function setPushPreferences(args: { enabled: boolean; timesPerDay: number }): Promise<PushPreferencesResponse> {
const clientUserId = await getOrCreateClientUserId();
const tz = pickTimezone();

View File

@@ -18,6 +18,9 @@ const KEY_RECO_FEED_HISTORY = 'reco.feedHistory';
const KEY_UI_THEME_MODE = 'ui.theme.mode';
const KEY_UI_THEME_SUIXIN_STATE = 'ui.theme.suixin.state';
const KEY_DAILY_REMINDER_SETTINGS = 'dailyReminder.settings';
const KEY_PUSH_LAST_REGISTERED_TOKEN = 'push.lastRegisteredToken'; // 旧:仅 token保留兼容读取
const KEY_PUSH_LAST_REGISTERED_AT = 'push.lastRegisteredAt'; // 旧:时间(保留兼容)
const KEY_PUSH_LAST_REGISTERED_PAYLOAD = 'push.lastRegisteredPayload'; // 新token+client_user_id+env+app_id
export type PushPromptState = 'enabled' | 'skipped' | 'unknown';
export type Reaction = 'like' | 'dislike';
@@ -69,6 +72,46 @@ export type DailyReminderSettings = {
pushEnabled: boolean;
};
export async function getLastRegisteredPushToken(): Promise<string | null> {
const raw = await AsyncStorage.getItem(KEY_PUSH_LAST_REGISTERED_TOKEN);
return raw ? String(raw) : null;
}
export async function setLastRegisteredPushToken(token: string): Promise<void> {
await AsyncStorage.setItem(KEY_PUSH_LAST_REGISTERED_TOKEN, String(token));
await AsyncStorage.setItem(KEY_PUSH_LAST_REGISTERED_AT, new Date().toISOString());
}
export type LastRegisteredPushPayload = {
pushToken: string;
clientUserId: string;
env: 'dev' | 'prod';
appId: string;
savedAt: string; // ISO8601
};
export async function getLastRegisteredPushPayload(): Promise<LastRegisteredPushPayload | null> {
const raw = await AsyncStorage.getItem(KEY_PUSH_LAST_REGISTERED_PAYLOAD);
if (!raw) return null;
try {
const obj = JSON.parse(raw) as Partial<LastRegisteredPushPayload>;
if (!obj || typeof obj !== 'object') return null;
if (!obj.pushToken || !obj.clientUserId || !obj.env || !obj.appId || !obj.savedAt) return null;
if (obj.env !== 'dev' && obj.env !== 'prod') return null;
return obj as LastRegisteredPushPayload;
} catch {
return null;
}
}
export async function setLastRegisteredPushPayload(payload: Omit<LastRegisteredPushPayload, 'savedAt'>): Promise<void> {
const savedAt = new Date().toISOString();
const full: LastRegisteredPushPayload = { ...payload, savedAt };
await AsyncStorage.setItem(KEY_PUSH_LAST_REGISTERED_PAYLOAD, JSON.stringify(full));
// 同时写入旧 key便于兼容老逻辑/快速排查
await setLastRegisteredPushToken(payload.pushToken);
}
export type RecoFeedCacheItem = {
content_id: number;
text: string;
@@ -188,7 +231,7 @@ export async function setReaction(contentId: string, reaction: Reaction): Promis
}
export type FavoriteItem = {
favId: string; // 唯一标识,支持重复点赞同一文案
favId: string; // 唯一标识
id: string;
/**
* 收藏时的文案快照(强烈建议写入,避免后续 cache 覆盖导致无法还原文案)
@@ -200,13 +243,28 @@ export type FavoriteItem = {
};
export async function getFavorites(): Promise<FavoriteItem[]> {
return await getJson<FavoriteItem[]>(KEY_FAVORITES_ITEMS, []);
const raw = await getJson<FavoriteItem[]>(KEY_FAVORITES_ITEMS, []);
// 去重:同一条文案只保留最新的一条,防止重复点击喜欢导致弹窗重复展示
const seen = new Set<string>();
const deduped: FavoriteItem[] = [];
for (const item of raw) {
const key = String(item.id);
if (seen.has(key)) continue;
seen.add(key);
deduped.push(item);
}
// 若发现历史数据有重复,顺便写回清理后的版本
if (deduped.length !== raw.length) {
await setJson(KEY_FAVORITES_ITEMS, deduped);
}
return deduped;
}
export async function addFavorite(item: FavoriteItem): Promise<void> {
const list = await getFavorites();
// 允许重复点赞,不再根据 id 去重
const newList = [item, ...list];
// 幂等写入:同一条文案只保留一条(最新),避免重复点击喜欢产生重复项
const filtered = list.filter(x => String(x.id) !== String(item.id));
const newList = [item, ...filtered];
console.log('Adding to favorites:', JSON.stringify(item));
await setJson(KEY_FAVORITES_ITEMS, newList);
}

View File

@@ -0,0 +1,31 @@
"""add push_send_log payload snapshot
Revision ID: 0003_add_push_send_log_payload
Revises: 0002_init_push_tables
Create Date: 2026-02-12
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0003_add_push_send_log_payload"
down_revision = "0002_init_push_tables"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("push_send_log", sa.Column("content_id", sa.Integer(), nullable=True, comment="推送文案内容 ID可选"))
op.add_column("push_send_log", sa.Column("title", sa.String(length=128), nullable=True, comment="推送标题(可选)"))
op.add_column("push_send_log", sa.Column("body", sa.Text(), nullable=True, comment="推送正文(可选)"))
def downgrade() -> None:
op.drop_column("push_send_log", "body")
op.drop_column("push_send_log", "title")
op.drop_column("push_send_log", "content_id")

View File

@@ -111,7 +111,7 @@ async def get_privacy_policy(request: Request) -> HTMLResponse:
accept_language = request.headers.get("accept-language")
lang = _resolve_lang(accept_language)
content, resolved = choose_content_by_lang(PRIVACY_POLICY_MD, lang)
title = "Hey Mama | Privacy Policy" if resolved == "en" else "Hey Mama隱私權政策"
title = "Dear Mama | Privacy Policy" if resolved == "en" else "Dear Mama隱私權政策"
page = render_as_simple_html(title=title, content=content)
return HTMLResponse(content=page, headers={"Content-Language": "en" if resolved == "en" else "zh-Hant"})
@@ -125,7 +125,7 @@ async def get_terms_of_use(request: Request) -> HTMLResponse:
accept_language = request.headers.get("accept-language")
lang = _resolve_lang(accept_language)
content, resolved = choose_content_by_lang(TERMS_OF_USE_MD, lang)
title = "Hey Mama Terms of Use" if resolved == "en" else "Hey Mama 使用條款"
title = "Dear Mama Terms of Use" if resolved == "en" else "Dear Mama 使用條款"
page = render_as_simple_html(title=title, content=content)
return HTMLResponse(content=page, headers={"Content-Language": "en" if resolved == "en" else "zh-Hant"})

View File

@@ -7,7 +7,7 @@ import httpx
import redis
from fastapi import APIRouter, Depends, Header, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.limits import rate_limit_push_by_ip
@@ -153,6 +153,32 @@ async def register(req: PushRegisterRequest, db: AsyncSession = Depends(get_db))
token.is_active = True
token.last_seen_at = _ensure_utc(now)
# 额外:尽早写入/补齐时区与语言(用于按用户时区生成排程)
# 说明:
# - 用户首次授权后会立即调用 /register但不一定马上进入“每日提醒”确认页
# - 若 push_preferences 里 timezone 为空,会导致排程回退到 UTC体验不符合预期
if req.device_meta:
tz = (req.device_meta.timezone or "").strip() or None
loc = (req.device_meta.locale or "").strip() or None
if tz or loc:
qpref = select(PushPreference).where(PushPreference.client_user_id == req.client_user_id)
rpref = await db.execute(qpref)
pref = rpref.scalar_one_or_none()
if pref is None:
pref = PushPreference(
client_user_id=req.client_user_id,
enabled=False,
times_per_day=0,
timezone=tz,
locale=loc,
)
db.add(pref)
else:
if tz and not (pref.timezone or "").strip():
pref.timezone = tz
if loc and not (pref.locale or "").strip():
pref.locale = loc
await db.commit()
return {"status": "ok"}
@@ -187,16 +213,20 @@ async def put_preferences(req: PushPreferencesRequest, db: AsyncSession = Depend
else:
pref.enabled = enabled
pref.times_per_day = times
pref.timezone = req.timezone
pref.locale = req.locale
# 注意:只在客户端显式传入时覆盖,避免把已保存的 timezone/locale 清空导致排程回退到 UTC
if req.timezone is not None:
pref.timezone = req.timezone
if req.locale is not None:
pref.locale = req.locale
if req.user_profile is not None:
pref.user_profile_json = req.user_profile.model_dump(mode="json")
await db.commit()
# 返回更新时间(从 ORM 读取到的可能不包含 server_onupdate这里用 now 兜底)
updated_at = getattr(pref, "updated_at", None)
updated_at_iso = updated_at.isoformat() if isinstance(updated_at, datetime) else None
# 返回更新时间
# - 某些运行环境/驱动组合下commit 后访问 ORM 字段可能触发隐式 IO导致 async 下报 MissingGreenlet。
# - 这里直接用当前时间兜底(字段本身为可选,仅用于前端展示)。
updated_at_iso = datetime.now(timezone.utc).isoformat()
return PushPreferencesResponse(
client_user_id=req.client_user_id,
@@ -256,7 +286,7 @@ async def test_push(
_ = UserProfileV1_2.model_validate(pref.user_profile_json)
# V1先发固定测试文案后续在定时任务中替换为推荐模块的 push 场景模板
title = req.title or "Hey Mama"
title = req.title or "Dear Mama"
body = req.body or "这是一条测试推送dev"
expo_res = await _send_expo_push(to=token.push_token, title=title, body=body, data={"client_user_id": req.client_user_id})
@@ -296,6 +326,7 @@ async def scheduler_health(db: AsyncSession = Depends(get_db)) -> dict[str, Any]
"worker": {"ok": False, "worker_count": 0},
"beat": {"ok": False, "last_heartbeat_at": None, "age_seconds": None},
"db": {"ok": False, "push_send_log_latest_created_at": None},
"db_push_tokens": {"ok": False, "count": None, "latest": None},
"now_utc": datetime.now(timezone.utc).isoformat(),
}
@@ -342,5 +373,36 @@ async def scheduler_health(db: AsyncSession = Depends(get_db)) -> dict[str, Any]
except Exception as e:
out["db"]["error"] = f"{type(e).__name__}: {e}"
# 4) DB查询 push_tokens 计数与最近一条(用于确认 /v1/push/register 是否真正落库)
try:
qcount = select(func.count()).select_from(PushToken)
rcount = await db.execute(qcount)
cnt = int(rcount.scalar_one() or 0)
qlatest = select(PushToken).order_by(PushToken.last_seen_at.desc()).limit(1)
rlatest = await db.execute(qlatest)
t = rlatest.scalar_one_or_none()
latest_obj = None
if t is not None:
tok = str(t.push_token or "")
masked = tok[:10] + "***" + tok[-6:] if len(tok) > 20 else (tok[:6] + "***" if tok else "")
latest_obj = {
"id": int(getattr(t, "id", 0) or 0),
"client_user_id": str(t.client_user_id),
"env": str(t.env),
"app_id": str(t.app_id),
"platform": str(t.platform),
"is_active": bool(t.is_active),
"last_seen_at": t.last_seen_at.isoformat() if t.last_seen_at else None,
"push_token_masked": masked,
}
out["db_push_tokens"]["ok"] = True
out["db_push_tokens"]["count"] = cnt
out["db_push_tokens"]["latest"] = latest_obj
except Exception as e:
out["db_push_tokens"]["error"] = f"{type(e).__name__}: {e}"
return out

View File

@@ -2,7 +2,7 @@ from __future__ import annotations
from datetime import date, datetime
from sqlalchemy import Date, DateTime, Index, SmallInteger, String, Text, UniqueConstraint, func
from sqlalchemy import Date, DateTime, Index, Integer, SmallInteger, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base
@@ -33,5 +33,10 @@ class PushSendLog(Base):
status: Mapped[str] = mapped_column(String(length=16), nullable=False, server_default="scheduled", comment="scheduled/sent/failed")
error: Mapped[str | None] = mapped_column(Text, nullable=True, comment="失败原因(可选)")
# 发送内容快照(用于观测 + 去重)
content_id: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="推送文案内容 ID可选")
title: Mapped[str | None] = mapped_column(String(length=128), nullable=True, comment="推送标题(可选)")
body: Mapped[str | None] = mapped_column(Text, nullable=True, comment="推送正文(可选)")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now(), comment="创建时间")

View File

@@ -11,21 +11,21 @@ ResolvedLang = Literal["en", "tc"]
# 协议原文(直接来自仓库中的 Markdown 文档)。
# 说明:为了保证“点击一定有内容”,这里在后端内置了一份可展示的协议文本。
# 线上若你们有官网/静态站点托管页面,可通过环境变量 LEGAL_* 覆盖为外部链接。
PRIVACY_POLICY_MD = """Hey Mama | Privacy Policy
PRIVACY_POLICY_MD = """Dear Mama | Privacy Policy
Last updated: February 2026
1. Introduction
Welcome to Hey Mama (“the App,” “we,” “us”).
Welcome to Dear Mama (“the App,” “we,” “us”).
We respect your privacy and are committed to protecting your personal information. This Privacy Policy explains how we collect, use, store, and protect information when you use the App.
By downloading, accessing, or using the App, you acknowledge that you have read, understood, and agreed to this Privacy Policy.
2. Data Controller and Scope
The App is operated and maintained by the Hey Mama team.
The App is operated and maintained by the Dear Mama team.
This Privacy Policy applies to information processing activities related to your use of the App.
3. Information We Collect
3.1 Information You Provide
Hey Mama does not require account registration and does not require you to provide personally identifiable information.
Dear Mama does not require account registration and does not require you to provide personally identifiable information.
During your use of the App, you may optionally provide or generate the following information:
- Reminder settings (e.g., reminder frequency)
- Text content you view, save as favorites, or create within the App (if available)
@@ -59,7 +59,7 @@ We do not:
- Use your data for third-party advertising purposes
7. Third-Party Services
Hey Mama currently does not integrate third-party advertising or marketing services.
Dear Mama currently does not integrate third-party advertising or marketing services.
The App may rely on necessary operating system and app store services to provide functionality (for example, push notification delivery mechanisms).
If we later integrate third-party analytics or technical services, we will update this Privacy Policy accordingly.
@@ -67,7 +67,7 @@ If we later integrate third-party analytics or technical services, we will updat
We retain information only for as long as necessary to achieve the purposes described above. We implement reasonable technical and organizational measures to protect information against unauthorized access, disclosure, alteration, or loss.
9. Minors
Hey Mama is not designed for children, and we do not knowingly collect personal information from users under the age of 13.
Dear Mama is not designed for children, and we do not knowingly collect personal information from users under the age of 13.
If you are a minor, please use the App with the consent and supervision of a parent or guardian.
10. Changes to This Privacy Policy
@@ -75,17 +75,17 @@ We may update this Privacy Policy from time to time. The updated version will be
---
Hey Mama隱私權政策
Dear Mama隱私權政策
最後更新日期2026 年 2 月
一、前言
歡迎使用 Hey Mama以下簡稱「本 App」、「我們」
我們重視您的隱私,並致力於保護您的個人資料安全。本隱私權政策說明您在使用 Hey Mama 時,我們如何收集、使用、保存與保護相關資訊。
歡迎使用 Dear Mama以下簡稱「本 App」、「我們」
我們重視您的隱私,並致力於保護您的個人資料安全。本隱私權政策說明您在使用 Dear Mama 時,我們如何收集、使用、保存與保護相關資訊。
當您下載、存取或使用本 App即表示您已閱讀、理解並同意本隱私權政策之內容。
二、我們收集的資訊
1. 使用者主動提供的資訊
Hey Mama 不要求建立帳號,亦不強制使用者提供可識別個人身分的資料。
Dear Mama 不要求建立帳號,亦不強制使用者提供可識別個人身分的資料。
在使用過程中,您可能會選擇性提供或產生以下資訊:
- 提醒設定(例如提醒頻率)
- 使用者在 App 內閱讀、收藏或建立的文字內容(如有)
@@ -99,7 +99,7 @@ Hey Mama 不要求建立帳號,亦不強制使用者提供可識別個人身
這些資訊無法直接識別您的身分,僅用於維持 App 穩定性與改善使用體驗。
三、推送通知
在取得您同意後,Hey Mama 可能會向您發送提醒推送,例如每日肯定語提示。
在取得您同意後,Dear Mama 可能會向您發送提醒推送,例如每日肯定語提示。
- 推送內容僅包含一般文字資訊
- 不包含任何敏感個人資料
- 您可隨時於裝置系統設定中關閉通知功能
@@ -117,14 +117,14 @@ Hey Mama 不要求建立帳號,亦不強制使用者提供可識別個人身
- 將資料用於第三方廣告投放
六、第三方服務
目前 Hey Mama 未整合第三方廣告或行銷服務。
目前 Dear Mama 未整合第三方廣告或行銷服務。
如未來整合第三方分析或技術服務,我們將於本政策中另行說明並更新。
七、資料保存與安全
我們僅在達成上述目的所需期間內保存相關資訊,並採取合理的技術與管理措施,以防止資料遭未經授權存取、洩漏、竄改或遺失。
八、未成年人說明
Hey Mama 並非專為兒童設計,亦不刻意收集未滿 13 歲使用者的個人資料。
Dear Mama 並非專為兒童設計,亦不刻意收集未滿 13 歲使用者的個人資料。
若您為未成年人,請在監護人同意與陪同下使用本 App。
九、隱私權政策的變更
@@ -132,17 +132,17 @@ Hey Mama 並非專為兒童設計,亦不刻意收集未滿 13 歲使用者的
更新後的版本將公布於 App 內或相關頁面,您於政策更新後繼續使用本 App即視為同意更新內容。
"""
TERMS_OF_USE_MD = """Hey Mama Terms of Use
TERMS_OF_USE_MD = """Dear Mama Terms of Use
Last updated: February 2026
Welcome to Hey Mama (“the App,” “we,” or “us”).
Welcome to Dear Mama (“the App,” “we,” or “us”).
Please read these Terms of Use carefully before downloading, accessing, or using the App. By using the App, you agree to be bound by these Terms.
1. Intended Audience
Hey Mama is intended for adults only.
Dear Mama is intended for adults only.
The App is not designed for children, and users must ensure they have the legal capacity to use the App under applicable laws.
2. Services Provided
Hey Mama provides text-based content and features, including but not limited to:
Dear Mama provides text-based content and features, including but not limited to:
- Daily affirmations and mindfulness text
- User-configured reminders and push notifications
- Home screen widgets displaying affirmation text
@@ -184,17 +184,17 @@ Updated versions will be made available within the App or related pages. Continu
These Terms shall be governed by and construed in accordance with the applicable laws of our operating jurisdiction.
---
Hey Mama 使用條款
Dear Mama 使用條款
最後更新日期2026 年 2 月
歡迎使用 Hey Mama以下簡稱「本 App」、「我們」
歡迎使用 Dear Mama以下簡稱「本 App」、「我們」
在下載、存取或使用本 App 前,請您仔細閱讀本使用條款。當您開始使用本 App即表示您已閱讀、理解並同意遵守本條款。
1. 服務對象與使用資格
Hey Mama 僅供成年人使用intended for adults
Dear Mama 僅供成年人使用intended for adults
本 App 並非為兒童設計,使用者應確認自己具備依所在地法律使用本服務的完全行為能力。
2. 服務內容
Hey Mama 提供以文字形式為主的內容與功能,包括但不限於:
Dear Mama 提供以文字形式為主的內容與功能,包括但不限於:
- 每日肯定語與正念文字內容
- 使用者設定的提醒與推送通知
- 桌面小組件顯示肯定語文字

View File

@@ -9,7 +9,7 @@ from zoneinfo import ZoneInfo
import httpx
from celery import current_app, shared_task
from sqlalchemy import select
from sqlalchemy import select, update
from app.core.config import get_settings
from app.db.models.push_preference import PushPreference
@@ -44,7 +44,8 @@ def _pick_reco_locale(pref_locale: Optional[str]) -> str:
def _pick_title(locale: str) -> str:
return "每日提醒" if str(locale) == "tc" else "Daily Reminder"
# 需求tc 语言使用繁体标题
return "每日推薦" if str(locale) == "tc" else "Daily Reminder"
async def _send_expo_push(*, to: str, title: str, body: str, data: Optional[dict[str, Any]] = None) -> dict[str, Any]:
@@ -67,7 +68,11 @@ async def _send_expo_push(*, to: str, title: str, body: str, data: Optional[dict
def _uniform_jitter_times(*, start: datetime, end: datetime, n: int) -> list[datetime]:
"""
将窗口均匀切分为 n 个区间,并在每段内随机取一个时间点(抖动)
将窗口均匀切分为 n 个区间,并在每段内取“中点 + 受限抖动”的时间点
目的:
- 尽量均匀分布(避免相邻两条推送随机到非常接近的时间)
- 仍保留一定随机性,避免过于机械
"""
if n <= 0:
@@ -84,8 +89,15 @@ def _uniform_jitter_times(*, start: datetime, end: datetime, n: int) -> list[dat
if seg <= 0:
out.append(seg_start)
continue
jitter = random.random() * seg
out.append(seg_start + timedelta(seconds=jitter))
# 受限抖动:在每段的 [25%, 75%] 区间内取点
# 这样相邻两段的最小间隔为 50% 段长,能显著减少“随机挤在一起”。
mid = seg_start + timedelta(seconds=seg * 0.5)
jitter = (random.random() - 0.5) * (seg * 0.5) # [-0.25*seg, +0.25*seg]
out.append(mid + timedelta(seconds=jitter))
# 保序(理论上天然有序,这里再保险)
out.sort()
return out
@@ -167,16 +179,25 @@ async def _generate_schedule_once(*, now_utc: datetime, max_users: int = 5000) -
created += 1
# 投递 ETA 发送任务
current_app.send_task(
"tasks.push.send_scheduled",
kwargs={
"client_user_id": pref.client_user_id,
"local_date": target.local_date.isoformat(),
"slot_index": int(idx),
},
eta=dt_utc,
)
scheduled += 1
try:
current_app.send_task(
"tasks.push.send_scheduled",
kwargs={
"client_user_id": pref.client_user_id,
"local_date": target.local_date.isoformat(),
"slot_index": int(idx),
},
eta=dt_utc,
)
scheduled += 1
except Exception as e:
# 关键:如果投递失败(例如 broker 短暂不可用),不要让 log 永远卡在 scheduled
log.status = "failed"
log.error = f"enqueue_failed:{type(e).__name__}"
try:
await session.commit()
except Exception:
await session.rollback()
return {"created": created, "scheduled": scheduled}
@@ -209,6 +230,34 @@ async def _send_once_async(*, client_user_id: str, local_date: date, slot_index:
return {"status": "noop", "reason": "no_log"}
if str(log.status) == "sent":
return {"status": "noop", "reason": "already_sent"}
if str(log.status) not in ("scheduled", "sending"):
# 例如 failed/skipped不再重复尝试
return {"status": "noop", "reason": f"not_retryable:{log.status}"}
# 原子抢占:避免重复发送
# - scheduled正常抢占 scheduled -> sending
# - sending如果长时间卡在 sending进程崩溃/网络异常等),允许“超时接管”继续执行
now_utc_naive = datetime.now(timezone.utc).replace(tzinfo=None)
steal_cutoff = now_utc_naive - timedelta(minutes=10)
res = await session.execute(
update(PushSendLog)
.where(
PushSendLog.id == log.id,
(
(PushSendLog.status == "scheduled")
| (
(PushSendLog.status == "sending")
& (PushSendLog.sent_at.is_(None))
& (PushSendLog.scheduled_at <= steal_cutoff)
)
),
)
.values(status="sending", error=None)
)
await session.commit()
if (res.rowcount or 0) <= 0:
return {"status": "noop", "reason": "already_in_progress_or_processed"}
log.status = "sending"
# 2) 当前偏好检查(用户可能中途关闭/改次数)
qpref = select(PushPreference).where(PushPreference.client_user_id == client_user_id)
@@ -235,71 +284,123 @@ async def _send_once_async(*, client_user_id: str, local_date: date, slot_index:
await session.commit()
return {"status": "failed", "reason": "no_active_token"}
# 4) 生成文案(复用推荐模块 push 场景)
reco_locale = str(normalize_locale(_pick_reco_locale(pref.locale)))
title = _pick_title(reco_locale)
if pref.user_profile_json:
user_profile = UserProfileV1_2.model_validate(pref.user_profile_json)
else:
# 无画像:用“全跳过”的默认画像(降个性化/降风险)
user_profile = UserProfileV1_2.model_validate(
build_user_profile_from_questionnaire(QuestionnaireAnswersV1_2()).model_dump()
)
# 直接复用 reco 的 Celery 任务实现(同步函数)
from app.tasks.reco import generate as reco_generate
reco_payload = reco_generate(scene="push", user_profile=user_profile.model_dump(), k=1, locale=reco_locale)
body = ""
try:
items = (reco_payload or {}).get("items") or []
if items and isinstance(items, list):
body = str(items[0].get("text") or "").strip()
except Exception:
# 4) 生成文案(复用推荐模块 push 场景)
reco_locale = str(normalize_locale(_pick_reco_locale(pref.locale)))
title = _pick_title(reco_locale)
if pref.user_profile_json:
user_profile = UserProfileV1_2.model_validate(pref.user_profile_json)
else:
# 无画像:用“全跳过”的默认画像(降个性化/降风险)
user_profile = UserProfileV1_2.model_validate(
build_user_profile_from_questionnaire(QuestionnaireAnswersV1_2()).model_dump()
)
# 关键:这里不能调用 tasks.reco.generate内部会 asyncio.run否则会嵌套事件循环崩溃。
from app.tasks.reco import run_reco_payload_async
# 去重:用户推送过的内容尽量不再推送
# 说明:
# - 依赖 push_send_log.content_id需先完成对应 DB 迁移)
# - 为避免历史过长导致 already_recommended_ids 过大,这里取“最近若干条已推送内容”近似全量去重
used_ids: list[int] = []
try:
qused = (
select(PushSendLog.content_id)
.where(
PushSendLog.client_user_id == client_user_id,
PushSendLog.content_id.is_not(None),
PushSendLog.id != log.id,
)
# 优先排除最近发送过的内容
.order_by(PushSendLog.local_date.desc(), PushSendLog.slot_index.desc())
.limit(5000)
)
rused = await session.execute(qused)
used_ids = [int(x) for x in rused.scalars().all() if x is not None]
except Exception:
used_ids = []
body = ""
picked_content_id: int | None = None
try:
reco_payload = await run_reco_payload_async(
scene="push",
user_profile=user_profile,
k=3,
locale=reco_locale,
already_recommended_ids=used_ids,
)
items = (reco_payload or {}).get("items") or []
if items and isinstance(items, list):
for it in items:
if not isinstance(it, dict):
continue
cid = it.get("content_id")
txt = str(it.get("text") or "").strip()
if not txt:
continue
if cid is not None:
try:
cid_i = int(cid)
except Exception:
cid_i = None
else:
cid_i = None
if cid_i is not None and cid_i in used_ids:
continue
picked_content_id = cid_i
body = txt
break
except Exception:
body = ""
if not body:
body = "给自己一句温柔的话。"
if not body:
# tc 语言兜底文案使用繁体
body = "給自己一句溫柔的話。" if reco_locale == "tc" else "给自己一句温柔的话。"
# 5) 发送
try:
# 5) 发送
expo_res = await _send_expo_push(
to=str(token.push_token),
title=title,
body=body,
data={"client_user_id": client_user_id, "scene": "push"},
)
# 6) 解析 Expo 回执,必要时停用 token
try:
data_list = (expo_res or {}).get("data") or []
if data_list and isinstance(data_list, list):
first = data_list[0] or {}
if first.get("status") == "error":
details = first.get("details") or {}
err = str(details.get("error") or first.get("message") or "expo_error")
log.status = "failed"
log.error = err
if "DeviceNotRegistered" in err:
token.is_active = False
await session.commit()
return {"status": "failed", "expo": expo_res}
except Exception:
# 忽略解析异常,继续按成功处理
pass
log.status = "sent"
log.sent_at = datetime.now(timezone.utc).replace(tzinfo=None)
log.error = None
log.title = title
log.body = body
log.content_id = picked_content_id
await session.commit()
return {"status": "sent", "expo": expo_res}
except Exception as e:
# 兜底:任何未预期异常都不要让状态卡在 sending
log.status = "failed"
log.error = f"send_failed:{type(e).__name__}"
log.error = f"unexpected:{type(e).__name__}"
await session.commit()
return {"status": "failed", "error": str(e)}
# 6) 解析 Expo 回执,必要时停用 token
try:
data_list = (expo_res or {}).get("data") or []
if data_list and isinstance(data_list, list):
first = data_list[0] or {}
if first.get("status") == "error":
details = first.get("details") or {}
err = str(details.get("error") or first.get("message") or "expo_error")
log.status = "failed"
log.error = err
if "DeviceNotRegistered" in err:
token.is_active = False
await session.commit()
return {"status": "failed", "expo": expo_res}
except Exception:
# 忽略解析异常,继续按成功处理
pass
log.status = "sent"
log.sent_at = datetime.now(timezone.utc).replace(tzinfo=None)
log.error = None
await session.commit()
return {"status": "sent", "expo": expo_res}
@shared_task(name="tasks.push.send_scheduled")
def send_scheduled(*, client_user_id: str, local_date: str, slot_index: int) -> dict[str, Any]:
@@ -310,3 +411,50 @@ def send_scheduled(*, client_user_id: str, local_date: str, slot_index: int) ->
d = date.fromisoformat(str(local_date))
return asyncio.run(_send_once_async(client_user_id=str(client_user_id), local_date=d, slot_index=int(slot_index)))
@shared_task(name="tasks.push.requeue_overdue")
def requeue_overdue(*, grace_seconds: int = 300, limit: int = 200) -> dict[str, Any]:
"""
补偿任务:扫描“已到时间但仍处于 scheduled”的记录并重新投递发送任务。
目的:
- 覆盖 broker 短暂不可用、worker 重启、ETA 任务丢失等导致的“scheduled 卡住”
- 与 send_scheduled 内部的原子状态抢占配合,避免重复发送
"""
now_utc_naive = datetime.now(timezone.utc).replace(tzinfo=None)
cutoff = now_utc_naive - timedelta(seconds=int(grace_seconds))
async def _run() -> dict[str, Any]:
requeued = 0
async with AsyncSessionLocal() as session:
q = (
select(PushSendLog)
.where(
PushSendLog.status.in_(("scheduled", "sending")),
PushSendLog.sent_at.is_(None),
PushSendLog.scheduled_at <= cutoff,
)
.order_by(PushSendLog.scheduled_at.asc())
.limit(int(limit))
)
rows = await session.execute(q)
logs = list(rows.scalars().all())
for log in logs:
try:
current_app.send_task(
"tasks.push.send_scheduled",
kwargs={
"client_user_id": str(log.client_user_id),
"local_date": str(log.local_date),
"slot_index": int(log.slot_index),
},
)
requeued += 1
except Exception:
# 忽略单条投递失败,交给下一轮补偿
continue
return {"status": "ok", "requeued": requeued, "cutoff": cutoff.isoformat()}
return asyncio.run(_run())

View File

@@ -53,6 +53,45 @@ async def _run_reco_async(
)
async def run_reco_payload_async(
*,
scene: Scene,
user_profile: UserProfileV1_2,
already_recommended_ids: Optional[list[Any]] = None,
touched_or_viewed_ids: Optional[list[Any]] = None,
k: Optional[int] = None,
now: Optional[datetime] = None,
locale: Optional[str] = None,
) -> dict[str, Any]:
"""
在“已有事件循环”内运行推荐并返回 payload。
用途:
- 供 Push 等 async 任务内部调用,避免 `asyncio.run()` 嵌套导致 RuntimeError
- 也便于未来在 API/任务间复用
"""
effective_now = _ensure_now(now)
effective_locale = _ensure_locale(locale)
# k 默认按场景(与 generate 保持一致)
if k is None:
k_i = 30 if scene == "feed" else 1
else:
k_i = int(k)
result = await _run_reco_async(
scene=scene,
user_profile=user_profile,
already_recommended_ids=list(already_recommended_ids or []),
touched_or_viewed_ids=list(touched_or_viewed_ids or []),
k=int(k_i),
now=effective_now,
locale=effective_locale,
)
return result.model_dump()
def _run_reco_sync(
*,
scene: Scene,

View File

@@ -53,10 +53,19 @@ celery_app.conf.beat_schedule = {
},
"push-generate-daily-schedule": {
"task": "tasks.push.generate_daily_schedule",
"schedule": crontab(minute=10, hour=0),
# 由“每天一次”调整为“每 2 小时一次”UTC
"schedule": crontab(minute=10, hour="*/2"),
"kwargs": {"max_users": 5000},
"options": {"queue": f"{prefix}:celery"},
}
,
# 补偿:每 5 分钟扫描一次 overdue scheduled 并重投递
"push-requeue-overdue": {
"task": "tasks.push.requeue_overdue",
"schedule": crontab(minute="*/5"),
"kwargs": {"grace_seconds": 300, "limit": 200},
"options": {"queue": f"{prefix}:celery"},
},
}
# 自动发现任务(约定:导入 app.tasks 触发其内部对子模块的显式导入)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -39,6 +39,7 @@
- **已完成编码(阶段性)**
- 客户端:新增 `client_user_id`UUID v4生成与持久化每日提醒次数范围修正为 **05**0 表示关闭)
- 客户端Onboarding 结束页(每日提醒)在用户选择次数 > 0 时**直接触发系统权限申请**;授权后获取 Expo Push Token 并调用后端 `register/preferences`(移除单独的 push 引导页)
- 客户端Onboarding 问卷完成后“开通推送权限”流程增加 **loading 态**(完成按钮转圈 + 全页禁用交互,避免重复触发/重复上报)
- 客户端:个人主页“每日提醒”弹窗移除测试模式强制无权限逻辑,改为真实读取系统权限;并在开关/点击 OK 时同步后端偏好
- 客户端:新增推送接口封装 `client/src/services/pushApi.ts`token 获取、register/preferences/get、自动上报时区与 locale并携带用户画像供后端 Push 模板使用)
- 后端:新增 Push 数据模型 + Alembic 迁移(`push_tokens` / `push_preferences` / `push_send_log`
@@ -88,7 +89,9 @@
- iOS 构建号已提升到 `2`,并将 `client/ios/client/Info.plist` 改为自动跟随 `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION`
- 推送 entitlements 的 `aps-environment` 已切到 `production`(用于 TestFlight/线上包)
- 清理未接入编译的 WidgetKit 骨架残留:移除磁盘上的 `client/ios/MindfulnessWidget/` 文件,并从 `client/ios/client.xcodeproj/project.pbxproj` 删除对应工程引用(避免 Xcode 显示幽灵文件)
- 修复 Xcode Archive 偶发显示 “Generic Xcode Archive”在共享 scheme `Hey Mama` 的 Archive Post-actions 自动补齐 `.xcarchive/Info.plist``ApplicationProperties`,并在缺失时补齐 `Name`/`SchemeName` + 自检提示(根治 Organizer 无法识别主 App、无法分发/上传 TestFlight 的问题)
- 修复 Xcode Archive 偶发显示 “Generic Xcode Archive”在共享 scheme `Dear Mama` 的 Archive Post-actions 自动补齐 `.xcarchive/Info.plist``ApplicationProperties`,并在缺失时补齐 `Name`/`SchemeName` + 自检提示(根治 Organizer 无法识别主 App、无法分发/上传 TestFlight 的问题)
- Widget 名称与描述支持多语言TC/EN默认 ENWidget Extension 增加 `Localizable.strings``en.lproj` / `zh-Hant.lproj``EmotionWidget.swift` 使用本地化 key 作为 `.configurationDisplayName/.description`
- 个人主页弹窗:小工具入口**暂时隐藏**锁屏小工具说明;桌面小工具引导弹窗标题(繁中/TC更新为“**如何加入小工具**”(并统一弹窗标题使用该文案);品牌文案改为 **Dear Mama**(含引导搜索词与 Widget 标题)
## Text Wrap
@@ -169,6 +172,10 @@
- `spec_kit/Text Wrap/modules/integration/tasks.md`
- **接入情况**
- HomeAPP已在 `client/app/(app)/home.tsx` 接入 `wrapText()` 渲染 `wrappedText`(含 `\n`
- iOS WidgetWidgetKitApp 侧在写入 `widget.dailyReco.v1` 缓存时,额外生成 `wrapped_text_by_family`small/medium/large并写入 App GroupWidget 侧按 `WidgetFamily` 优先读取该字段渲染(保证换行一致且无需在 Extension 内跑 JS
- **近期变更**
- Widget 接入:`client/src/modules/dailyWidgetReco/index.ts` 生成 `wrapped_text_by_family``client/ios/情绪小组件/EmotionWidget.swift` 按 family 读取;`client/app/(app)/home.tsx` 前台触发一次“尽力而为”的补齐/刷新
- Home 排版风格微调:支持 `scoringOverrides`,在 Home 里对 TC 做“更偏好标点停顿/更好看”的权重与理想宽度微调(不影响默认 v1
## Splash Consent

View File

@@ -1,14 +1,14 @@
Hey Mama Terms of Use
Dear Mama Terms of Use
Last updated: February 2026
Welcome to Hey Mama (“the App,” “we,” or “us”).
Welcome to Dear Mama (“the App,” “we,” or “us”).
Please read these Terms of Use carefully before downloading, accessing, or using the App. By using the App, you agree to be bound by these Terms.
1. Intended Audience
Hey Mama is intended for adults only.
Dear Mama is intended for adults only.
The App is not designed for children, and users must ensure they have the legal capacity to use the App under applicable laws.
2. Services Provided
Hey Mama provides text-based content and features, including but not limited to:
Dear Mama provides text-based content and features, including but not limited to:
- Daily affirmations and mindfulness text
- User-configured reminders and push notifications
- Home screen widgets displaying affirmation text
@@ -50,17 +50,17 @@ Updated versions will be made available within the App or related pages. Continu
These Terms shall be governed by and construed in accordance with the applicable laws of our operating jurisdiction.
---
Hey Mama 使用條款
Dear Mama 使用條款
最後更新日期2026 年 2 月
歡迎使用 Hey Mama以下簡稱「本 App」、「我們」
歡迎使用 Dear Mama以下簡稱「本 App」、「我們」
在下載、存取或使用本 App 前,請您仔細閱讀本使用條款。當您開始使用本 App即表示您已閱讀、理解並同意遵守本條款。
1. 服務對象與使用資格
Hey Mama 僅供成年人使用intended for adults
Dear Mama 僅供成年人使用intended for adults
本 App 並非為兒童設計,使用者應確認自己具備依所在地法律使用本服務的完全行為能力。
2. 服務內容
Hey Mama 提供以文字形式為主的內容與功能,包括但不限於:
Dear Mama 提供以文字形式為主的內容與功能,包括但不限於:
- 每日肯定語與正念文字內容
- 使用者設定的提醒與推送通知
- 桌面小組件顯示肯定語文字

View File

@@ -1,18 +1,18 @@
Hey Mama | Privacy Policy
Dear Mama | Privacy Policy
Last updated: February 2026
1. Introduction
Welcome to Hey Mama (“the App,” “we,” “us”).
Welcome to Dear Mama (“the App,” “we,” “us”).
We respect your privacy and are committed to protecting your personal information. This Privacy Policy explains how we collect, use, store, and protect information when you use the App.
By downloading, accessing, or using the App, you acknowledge that you have read, understood, and agreed to this Privacy Policy.
2. Data Controller and Scope
The App is operated and maintained by the Hey Mama team.
The App is operated and maintained by the Dear Mama team.
This Privacy Policy applies to information processing activities related to your use of the App.
3. Information We Collect
3.1 Information You Provide
Hey Mama does not require account registration and does not require you to provide personally identifiable information.
Dear Mama does not require account registration and does not require you to provide personally identifiable information.
During your use of the App, you may optionally provide or generate the following information:
- Reminder settings (e.g., reminder frequency)
- Text content you view, save as favorites, or create within the App (if available)
@@ -46,7 +46,7 @@ We do not:
- Use your data for third-party advertising purposes
7. Third-Party Services
Hey Mama currently does not integrate third-party advertising or marketing services.
Dear Mama currently does not integrate third-party advertising or marketing services.
The App may rely on necessary operating system and app store services to provide functionality (for example, push notification delivery mechanisms).
If we later integrate third-party analytics or technical services, we will update this Privacy Policy accordingly.
@@ -54,7 +54,7 @@ If we later integrate third-party analytics or technical services, we will updat
We retain information only for as long as necessary to achieve the purposes described above. We implement reasonable technical and organizational measures to protect information against unauthorized access, disclosure, alteration, or loss.
9. Minors
Hey Mama is not designed for children, and we do not knowingly collect personal information from users under the age of 13.
Dear Mama is not designed for children, and we do not knowingly collect personal information from users under the age of 13.
If you are a minor, please use the App with the consent and supervision of a parent or guardian.
10. Changes to This Privacy Policy
@@ -62,17 +62,17 @@ We may update this Privacy Policy from time to time. The updated version will be
---
Hey Mama隱私權政策
Dear Mama隱私權政策
最後更新日期2026 年 2 月
一、前言
歡迎使用 Hey Mama以下簡稱「本 App」、「我們」
我們重視您的隱私,並致力於保護您的個人資料安全。本隱私權政策說明您在使用 Hey Mama 時,我們如何收集、使用、保存與保護相關資訊。
歡迎使用 Dear Mama以下簡稱「本 App」、「我們」
我們重視您的隱私,並致力於保護您的個人資料安全。本隱私權政策說明您在使用 Dear Mama 時,我們如何收集、使用、保存與保護相關資訊。
當您下載、存取或使用本 App即表示您已閱讀、理解並同意本隱私權政策之內容。
二、我們收集的資訊
1. 使用者主動提供的資訊
Hey Mama 不要求建立帳號,亦不強制使用者提供可識別個人身分的資料。
Dear Mama 不要求建立帳號,亦不強制使用者提供可識別個人身分的資料。
在使用過程中,您可能會選擇性提供或產生以下資訊:
- 提醒設定(例如提醒頻率)
- 使用者在 App 內閱讀、收藏或建立的文字內容(如有)
@@ -86,7 +86,7 @@ Hey Mama 不要求建立帳號,亦不強制使用者提供可識別個人身
這些資訊無法直接識別您的身分,僅用於維持 App 穩定性與改善使用體驗。
三、推送通知
在取得您同意後,Hey Mama 可能會向您發送提醒推送,例如每日肯定語提示。
在取得您同意後,Dear Mama 可能會向您發送提醒推送,例如每日肯定語提示。
- 推送內容僅包含一般文字資訊
- 不包含任何敏感個人資料
- 您可隨時於裝置系統設定中關閉通知功能
@@ -104,14 +104,14 @@ Hey Mama 不要求建立帳號,亦不強制使用者提供可識別個人身
- 將資料用於第三方廣告投放
六、第三方服務
目前 Hey Mama 未整合第三方廣告或行銷服務。
目前 Dear Mama 未整合第三方廣告或行銷服務。
如未來整合第三方分析或技術服務,我們將於本政策中另行說明並更新。
七、資料保存與安全
我們僅在達成上述目的所需期間內保存相關資訊,並採取合理的技術與管理措施,以防止資料遭未經授權存取、洩漏、竄改或遺失。
八、未成年人說明
Hey Mama 並非專為兒童設計,亦不刻意收集未滿 13 歲使用者的個人資料。
Dear Mama 並非專為兒童設計,亦不刻意收集未滿 13 歲使用者的個人資料。
若您為未成年人,請在監護人同意與陪同下使用本 App。
九、隱私權政策的變更