diff --git a/.gitignore b/.gitignore
index 534d071..5732263 100644
--- a/.gitignore
+++ b/.gitignore
@@ -94,3 +94,16 @@ app.*.map.json
.env
.env.*
*.local
+
+# ==============================================================================
+# 7. Python 服务端构建与运行产物
+# ==============================================================================
+__pycache__/
+*.py[cod]
+*$py.class
+venv/
+.venv/
+data/
+*.db
+*.sqlite
+*.sqlite3
diff --git a/kouyu_english/android/app/src/main/AndroidManifest.xml b/kouyu_english/android/app/src/main/AndroidManifest.xml
index 029b199..d8d8aa5 100644
--- a/kouyu_english/android/app/src/main/AndroidManifest.xml
+++ b/kouyu_english/android/app/src/main/AndroidManifest.xml
@@ -3,7 +3,7 @@
{out_f} ({sz}x{sz})")
+
+ print("🎉 全部 Logo 和图标生成完成!")
diff --git a/kouyu_english/generate_logo_v2.py b/kouyu_english/generate_logo_v2.py
new file mode 100644
index 0000000..e1e47ea
--- /dev/null
+++ b/kouyu_english/generate_logo_v2.py
@@ -0,0 +1,308 @@
+import os
+import math
+from PIL import Image, ImageDraw, ImageFont, ImageFilter
+
+def cubic_bezier(p0, p1, p2, p3, steps=60):
+ points = []
+ for i in range(steps + 1):
+ t = i / float(steps)
+ x = (1-t)**3 * p0[0] + 3*(1-t)**2 * t * p1[0] + 3*(1-t) * t**2 * p2[0] + t**3 * p3[0]
+ y = (1-t)**3 * p0[1] + 3*(1-t)**2 * t * p1[1] + 3*(1-t) * t**2 * p2[1] + t**3 * p3[1]
+ points.append((x, y))
+ return points
+
+def create_sprout_icon(size=1024, supersample=4, transparent_bg=False):
+ ss = size * supersample
+ img = Image.new("RGBA", (ss, ss), (0, 0, 0, 0))
+
+ radius = int(ss * 0.225)
+ margin = int(ss * 0.045)
+
+ mask = Image.new("L", (ss, ss), 0)
+ mask_draw = ImageDraw.Draw(mask)
+ mask_draw.rounded_rectangle(
+ [margin, margin, ss - margin, ss - margin],
+ radius=radius,
+ fill=255
+ )
+
+ gradient = Image.new("RGBA", (ss, ss), (0, 0, 0, 0))
+ # Colors: top-left fresh emerald #198754, bottom-right deep forest #0D4E30
+ c_tl = (28, 148, 92)
+ c_br = (12, 68, 42)
+
+ for y in range(ss):
+ for x in range(0, ss, 4):
+ t = (x * 0.7 + y * 1.0) / (ss * 1.7)
+ t = max(0.0, min(1.0, t))
+ r = int(c_tl[0] * (1 - t) + c_br[0] * t)
+ g = int(c_tl[1] * (1 - t) + c_br[1] * t)
+ b = int(c_tl[2] * (1 - t) + c_br[2] * t)
+ for dx in range(4):
+ if x + dx < ss:
+ gradient.putpixel((x + dx, y), (r, g, b, 255))
+
+ bg = Image.composite(gradient, Image.new("RGBA", (ss, ss), (0, 0, 0, 0)), mask)
+
+ # Ambient subtle highlight on top edge
+ highlight = Image.new("RGBA", (ss, ss), (0, 0, 0, 0))
+ hl_draw = ImageDraw.Draw(highlight)
+ hl_draw.rounded_rectangle(
+ [margin + 4*supersample, margin + 4*supersample, ss - margin - 4*supersample, ss - margin - 4*supersample],
+ radius=radius - 4*supersample,
+ outline=(255, 255, 255, 35),
+ width=int(2.5 * supersample)
+ )
+ bg = Image.alpha_composite(bg, highlight)
+
+ cx, cy = ss // 2, ss // 2
+
+ # 2. Main Center Hero Badge: Rounded Speech Bubble with clean geometry
+ bw = int(580 * supersample)
+ bh = int(480 * supersample)
+ bx = cx - bw // 2
+ by = cy - bh // 2 - int(25 * supersample)
+ br = int(120 * supersample)
+
+ # Bubble Drop Shadow
+ bubble_shadow = Image.new("RGBA", (ss, ss), (0, 0, 0, 0))
+ bsh_draw = ImageDraw.Draw(bubble_shadow)
+ bsh_draw.rounded_rectangle(
+ [bx, by + int(18 * supersample), bx + bw, by + bh + int(18 * supersample)],
+ radius=br,
+ fill=(0, 0, 0, 75)
+ )
+ tail_pts_sh = [
+ (bx + int(90 * supersample), by + bh + int(10 * supersample)),
+ (bx + int(30 * supersample), by + bh + int(105 * supersample)),
+ (bx + int(190 * supersample), by + bh + int(10 * supersample)),
+ ]
+ bsh_draw.polygon(tail_pts_sh, fill=(0, 0, 0, 75))
+ bubble_shadow = bubble_shadow.filter(ImageFilter.GaussianBlur(radius=int(18 * supersample)))
+ bg = Image.alpha_composite(bg, bubble_shadow)
+
+ # Bubble Body (Pure White with subtle warm sheen)
+ bubble = Image.new("RGBA", (ss, ss), (0, 0, 0, 0))
+ b_draw = ImageDraw.Draw(bubble)
+ b_draw.rounded_rectangle(
+ [bx, by, bx + bw, by + bh],
+ radius=br,
+ fill=(255, 255, 255, 255)
+ )
+ tail_pts = [
+ (bx + int(90 * supersample), by + bh - int(8 * supersample)),
+ (bx + int(30 * supersample), by + bh + int(85 * supersample)),
+ (bx + int(190 * supersample), by + bh - int(8 * supersample)),
+ ]
+ b_draw.polygon(tail_pts, fill=(255, 255, 255, 255))
+ bg = Image.alpha_composite(bg, bubble)
+
+ # 3. Inside the Bubble: Sprout + Smile Soundwave Iconography
+ icx = bx + bw // 2
+ icy = by + bh // 2 - int(10 * supersample)
+
+ sprout_layer = Image.new("RGBA", (ss, ss), (0, 0, 0, 0))
+ sp_draw = ImageDraw.Draw(sprout_layer)
+
+ # 3.1 Right Leaf (Primary, lush emerald)
+ p0 = (icx - int(10 * supersample), icy + int(35 * supersample))
+ p1 = (icx + int(70 * supersample), icy + int(15 * supersample))
+ p2 = (icx + int(165 * supersample), icy - int(50 * supersample))
+ p3 = (icx + int(135 * supersample), icy - int(130 * supersample)) # Tip
+
+ p4 = (icx + int(60 * supersample), icy - int(115 * supersample))
+ p5 = (icx + int(0 * supersample), icy - int(45 * supersample))
+ p6 = p0
+
+ curve_right_top = cubic_bezier(p0, p1, p2, p3, steps=40)
+ curve_right_bot = cubic_bezier(p3, p4, p5, p6, steps=40)
+ right_leaf_pts = curve_right_top + curve_right_bot
+ sp_draw.polygon(right_leaf_pts, fill=(23, 107, 70, 255)) # #176B46
+
+ # 3.2 Left Leaf (Secondary, fresh bright mint green)
+ lp0 = (icx - int(18 * supersample), icy + int(50 * supersample))
+ lp1 = (icx - int(65 * supersample), icy + int(25 * supersample))
+ lp2 = (icx - int(135 * supersample), icy - int(15 * supersample))
+ lp3 = (icx - int(120 * supersample), icy - int(80 * supersample)) # Tip
+
+ lp4 = (icx - int(60 * supersample), icy - int(65 * supersample))
+ lp5 = (icx - int(15 * supersample), icy - int(10 * supersample))
+ lp6 = lp0
+
+ curve_left_top = cubic_bezier(lp0, lp1, lp2, lp3, steps=40)
+ curve_left_bot = cubic_bezier(lp3, lp4, lp5, lp6, steps=40)
+ left_leaf_pts = curve_left_top + curve_left_bot
+ sp_draw.polygon(left_leaf_pts, fill=(52, 185, 118, 255)) # Bright fresh green
+
+ # 3.3 Sprout Sun Dot / Golden Energy Droplet (Golden Sun #F59E0B)
+ dot_x = icx + int(148 * supersample)
+ dot_y = icy - int(142 * supersample)
+ dot_r = int(22 * supersample)
+ sp_draw.ellipse(
+ [dot_x - dot_r, dot_y - dot_r, dot_x + dot_r, dot_y + dot_r],
+ fill=(245, 158, 11, 255)
+ )
+
+ # 3.4 Smile / Vocal Flow Arc
+ smile_y = icy + int(135 * supersample)
+ smile_w = int(140 * supersample)
+ smile_pts = cubic_bezier(
+ (icx - smile_w, smile_y - int(15 * supersample)),
+ (icx - smile_w // 2, smile_y + int(30 * supersample)),
+ (icx + smile_w // 2, smile_y + int(30 * supersample)),
+ (icx + smile_w, smile_y - int(15 * supersample)),
+ steps=50
+ )
+ for i in range(len(smile_pts) - 1):
+ sp_draw.line([smile_pts[i], smile_pts[i+1]], fill=(23, 107, 70, 230), width=int(14 * supersample))
+
+ s_cap_r = int(7 * supersample)
+ sp_draw.ellipse([smile_pts[0][0]-s_cap_r, smile_pts[0][1]-s_cap_r, smile_pts[0][0]+s_cap_r, smile_pts[0][1]+s_cap_r], fill=(23, 107, 70, 230))
+ sp_draw.ellipse([smile_pts[-1][0]-s_cap_r, smile_pts[-1][1]-s_cap_r, smile_pts[-1][0]+s_cap_r, smile_pts[-1][0]+s_cap_r], fill=(23, 107, 70, 230))
+
+ # 3.5 Concentric Dynamic Sound Waves
+ w_cx = icx - int(55 * supersample)
+ w_cy = icy - int(55 * supersample)
+
+ wave_r1 = int(115 * supersample)
+ sp_draw.arc(
+ [w_cx - wave_r1, w_cy - wave_r1, w_cx + wave_r1, w_cy + wave_r1],
+ start=155, end=245,
+ fill=(52, 185, 118, 240),
+ width=int(12 * supersample)
+ )
+
+ wave_r2 = int(165 * supersample)
+ sp_draw.arc(
+ [w_cx - wave_r2, w_cy - wave_r2, w_cx + wave_r2, w_cy + wave_r2],
+ start=160, end=240,
+ fill=(245, 158, 11, 230),
+ width=int(12 * supersample)
+ )
+
+ bg = Image.alpha_composite(bg, sprout_layer)
+
+ # Downsample
+ final_icon = bg.resize((size, size), Image.Resampling.LANCZOS)
+ return final_icon
+
+def create_brand_banner(icon_img):
+ w, h = 1200, 600
+ banner = Image.new("RGBA", (w, h), (245, 247, 243, 255)) # AppColors.paper #F5F7F3
+ draw = ImageDraw.Draw(banner)
+
+ # Decorative background shapes
+ draw.ellipse([760, -120, 1360, 480], fill=(226, 243, 232, 140))
+ draw.ellipse([-80, 320, 420, 820], fill=(255, 240, 227, 130))
+
+ # Left Icon
+ icon_w = 340
+ icon_resized = icon_img.resize((icon_w, icon_w), Image.Resampling.LANCZOS)
+ banner.paste(icon_resized, (90, (h - icon_w) // 2), icon_resized)
+
+ font_path_candidates = [
+ "/System/Library/Fonts/PingFang.ttc",
+ "/System/Library/Fonts/Hiragino Sans GB.ttc",
+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
+ "/System/Library/Fonts/Supplemental/Arial.ttf"
+ ]
+
+ title_font = None
+ en_font = None
+ sub_font = None
+ desc_font = None
+ badge_font = None
+
+ for p in font_path_candidates:
+ if os.path.exists(p):
+ try:
+ title_font = ImageFont.truetype(p, 58, index=0)
+ en_font = ImageFont.truetype(p, 32, index=0)
+ sub_font = ImageFont.truetype(p, 23, index=0)
+ desc_font = ImageFont.truetype(p, 21, index=0)
+ badge_font = ImageFont.truetype(p, 17, index=0)
+ break
+ except Exception:
+ continue
+
+ if not title_font:
+ title_font = ImageFont.load_default()
+ en_font = ImageFont.load_default()
+ sub_font = ImageFont.load_default()
+ desc_font = ImageFont.load_default()
+ badge_font = ImageFont.load_default()
+
+ tx = 475
+ ty = 105
+
+ # Badge Pill
+ pill_w = 240
+ pill_h = 36
+ draw.rounded_rectangle([tx, ty, tx + pill_w, ty + pill_h], radius=18, fill=(226, 243, 232, 255))
+ # Small green dot in pill
+ draw.ellipse([tx + 14, ty + 12, tx + 26, ty + 24], fill=(23, 107, 70, 255))
+ draw.text((tx + 34, ty + 7), "AI 口语私教 · 零基础开口", fill=(23, 107, 70, 255), font=badge_font)
+
+ # Main Brand Name
+ draw.text((tx, ty + 52), "芽说英语", fill=(25, 33, 27, 255), font=title_font)
+ draw.text((tx + 270, ty + 72), "SpeakSprout", fill=(23, 107, 70, 255), font=en_font)
+
+ # Slogan
+ draw.text((tx, ty + 145), "“ 每一次开口,都是成长的萌芽 ”", fill=(100, 114, 104, 255), font=sub_font)
+
+ # Clean bullet features (using custom drawn colored dots instead of emoji glyphs)
+ features = [
+ ("1v1 智能语伴 Mia · 沉浸式情境真实对话", (23, 107, 70, 255)),
+ ("听 · 说 · 读 · 写 四维微习惯进阶体系", (52, 185, 118, 255)),
+ ("离线高精度语音识别 · 毫秒级跟读评分", (245, 158, 11, 255)),
+ ("间隔艾宾浩斯复习 · 真正打破哑巴英语", (23, 107, 70, 255))
+ ]
+ for i, (feat, dot_c) in enumerate(features):
+ fy = ty + 200 + i * 44
+ # Draw small clean bullet dot
+ draw.ellipse([tx, fy + 7, tx + 10, fy + 17], fill=dot_c)
+ draw.text((tx + 22, fy), feat, fill=(35, 45, 38, 245), font=desc_font)
+
+ return banner
+
+if __name__ == "__main__":
+ out_dir = "assets/branding"
+ os.makedirs(out_dir, exist_ok=True)
+
+ print("🎨 正在生成全新高清 Logo v2 (1024x1024)...")
+ icon1024 = create_sprout_icon(size=1024, supersample=4)
+ master_path = os.path.join(out_dir, "logo_master_1024.png")
+ icon1024.save(master_path, "PNG")
+ print(f"✅ 保存主图标: {master_path}")
+
+ # 512x512
+ icon512 = icon1024.resize((512, 512), Image.Resampling.LANCZOS)
+ p512 = os.path.join(out_dir, "logo_512.png")
+ icon512.save(p512, "PNG")
+
+ # Brand Banner
+ print("🖼️ 正在生成品牌展示图 (1200x600)...")
+ banner = create_brand_banner(icon1024)
+ banner_path = os.path.join(out_dir, "brand_banner.png")
+ banner.save(banner_path, "PNG")
+ print(f"✅ 保存品牌展示图: {banner_path}")
+
+ # Android launcher icons
+ mipmaps = {
+ "mipmap-mdpi": 48,
+ "mipmap-hdpi": 72,
+ "mipmap-xhdpi": 96,
+ "mipmap-xxhdpi": 144,
+ "mipmap-xxxhdpi": 192,
+ }
+
+ print("📱 正在更新 Android App 各分辨率图标...")
+ for folder, sz in mipmaps.items():
+ dir_path = os.path.join("android/app/src/main/res", folder)
+ os.makedirs(dir_path, exist_ok=True)
+ out_f = os.path.join(dir_path, "ic_launcher.png")
+ resized = icon1024.resize((sz, sz), Image.Resampling.LANCZOS)
+ resized.save(out_f, "PNG")
+ print(f" -> {out_f} ({sz}x{sz})")
+
+ print("🎉 全部 Logo 和图标生成完成!")
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png
index dc9ada4..9329393 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png
index 7353c41..377c1be 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png
index 797d452..6b6d7f5 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png
index 6ed2d93..5dd91be 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png
index 4cd7b00..ed6b2d8 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png
index fe73094..b6bc6f0 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png
index 321773c..60fd14e 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png
index 797d452..6b6d7f5 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png
index 502f463..75a3fee 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png
index 0ec3034..591a114 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png
index 0ec3034..591a114 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png
index e9f5fea..3bf0526 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png
index 84ac32a..b38e8cb 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png
index 8953cba..305536e 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ
diff --git a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png
index 0467bf1..532647a 100644
Binary files a/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/kouyu_english/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ
diff --git a/kouyu_english/ios/Runner/Info.plist b/kouyu_english/ios/Runner/Info.plist
index a69b455..c2564f0 100644
--- a/kouyu_english/ios/Runner/Info.plist
+++ b/kouyu_english/ios/Runner/Info.plist
@@ -7,7 +7,7 @@
CFBundleDevelopmentRegion
$(DEVELOPMENT_LANGUAGE)
CFBundleDisplayName
- Kouyu English
+ 芽说英语
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
diff --git a/kouyu_english/lib/core/ai_service.dart b/kouyu_english/lib/core/ai_service.dart
index d4cd8f8..045a54e 100644
--- a/kouyu_english/lib/core/ai_service.dart
+++ b/kouyu_english/lib/core/ai_service.dart
@@ -484,7 +484,7 @@ class AiService {
return null;
}
const system =
- 'You are Mia, a patient A0 English conversation partner. Use only very simple English. Reply in one short sentence or question. Do not explain grammar. Return JSON only, with exactly these fields: reply (string, maximum 20 English words), slots (object of short string values), evidence (array of exact learner quotes), suggestsComplete (boolean), feedback (string or null). The learner must now: ';
+ 'You are Mia, a patient A0 English conversation partner. Use only very simple English. Reply in one short sentence or question. Do not explain grammar. Return JSON only, with exactly these fields: reply (string, maximum 20 English words), translation (string, simplified Chinese translation of reply), slots (object of short string values), evidence (array of exact learner quotes), suggestsComplete (boolean), feedback (string or null). The learner must now: ';
try {
final response = await http
.post(
@@ -1011,8 +1011,10 @@ Learner wrote: $answer''';
if (item is! String || item.length > 240) return null;
evidence.add(item);
}
+ final translation = data['translation'] as String?;
return DialogueAiResponse(
reply: reply.trim(),
+ translation: translation?.trim(),
slots: slots,
evidence: evidence,
suggestsComplete: suggestsComplete,
diff --git a/kouyu_english/lib/core/app_state.dart b/kouyu_english/lib/core/app_state.dart
index e0ebd39..e481933 100644
--- a/kouyu_english/lib/core/app_state.dart
+++ b/kouyu_english/lib/core/app_state.dart
@@ -13,6 +13,7 @@ import 'seed_courses.dart';
import 'ai_config.dart';
import 'ai_service.dart';
import 'sherpa_stt_service.dart';
+import 'sync/sync_coordinator.dart';
class AppState extends ChangeNotifier {
static const _storageKey = 'learning_state_v1';
@@ -591,6 +592,7 @@ class AppState extends ChangeNotifier {
(turn) => DialogueTurn(
text: turn['text'] as String,
isLearner: turn['isLearner'] as bool? ?? false,
+ translation: turn['translation'] as String?,
),
)
.toList(),
@@ -763,6 +765,7 @@ class AppState extends ChangeNotifier {
(turn) => {
'text': turn.text,
'isLearner': turn.isLearner,
+ 'translation': turn.translation,
},
)
.toList(),
@@ -815,6 +818,7 @@ class AppState extends ChangeNotifier {
void finishOnboarding() {
onboardingComplete = true;
notifyListeners();
+ SyncCoordinator.instance.triggerBackgroundSync(this);
}
void setGoal(LearningGoal value) {
@@ -978,6 +982,7 @@ class AppState extends ChangeNotifier {
}
_resetLessonFlow();
notifyListeners();
+ SyncCoordinator.instance.triggerBackgroundSync(this);
}
void _resetLessonFlow() {
@@ -1006,6 +1011,7 @@ class AppState extends ChangeNotifier {
completeSegment(activeLessonId, index);
_resetLessonFlow();
notifyListeners();
+ SyncCoordinator.instance.triggerBackgroundSync(this);
}
void completeReview(
@@ -1066,6 +1072,7 @@ class AppState extends ChangeNotifier {
rawAnswer: rawAnswer,
);
notifyListeners();
+ SyncCoordinator.instance.triggerBackgroundSync(this);
}
void reportReviewFailure(ReviewItem item) {
diff --git a/kouyu_english/lib/core/models.dart b/kouyu_english/lib/core/models.dart
index 8ea392f..5eeeb42 100644
--- a/kouyu_english/lib/core/models.dart
+++ b/kouyu_english/lib/core/models.dart
@@ -81,10 +81,12 @@ class DialogueAiResponse {
required this.slots,
required this.evidence,
required this.suggestsComplete,
+ this.translation,
this.feedback,
});
final String reply;
+ final String? translation;
final Map slots;
final List evidence;
final bool suggestsComplete;
@@ -297,10 +299,27 @@ class MasteryItem {
}
class DialogueTurn {
- const DialogueTurn({required this.text, required this.isLearner});
+ const DialogueTurn({
+ required this.text,
+ required this.isLearner,
+ this.translation,
+ });
final String text;
final bool isLearner;
+ final String? translation;
+
+ DialogueTurn copyWith({
+ String? text,
+ bool? isLearner,
+ String? translation,
+ }) {
+ return DialogueTurn(
+ text: text ?? this.text,
+ isLearner: isLearner ?? this.isLearner,
+ translation: translation ?? this.translation,
+ );
+ }
}
/// Ephemeral presentation data for a completed controlled dialogue. The
diff --git a/kouyu_english/lib/core/seed_courses.dart b/kouyu_english/lib/core/seed_courses.dart
index 823f905..17058cc 100644
--- a/kouyu_english/lib/core/seed_courses.dart
+++ b/kouyu_english/lib/core/seed_courses.dart
@@ -1071,10 +1071,12 @@ class LessonDialogue {
required this.goal,
required this.prompts,
required this.hints,
+ this.translations = const [],
});
final String goal;
final List prompts;
final List hints;
+ final List translations;
}
const a0Dialogues = {
@@ -1092,6 +1094,12 @@ const a0Dialogues = {
'Hello!',
'What’s your name?',
],
+ translations: [
+ '嗨!我是 Mia。你叫什么名字?',
+ '很高兴认识你。请说:Nice to meet you, too(我也很高兴认识你)。',
+ '太棒了!再打一次招呼吧。',
+ '现在请问我的名字!',
+ ],
),
'a0-02': LessonDialogue(
goal: '介绍姓名并完整拼读名字',
@@ -1102,6 +1110,12 @@ const a0Dialogues = {
'Now ask me my name!',
],
hints: ['My name is Alex.', 'A-L-E-X.', 'A-L-E-X.', 'What’s your name?'],
+ translations: [
+ '嗨!你叫什么名字?',
+ '那个怎么拼写?',
+ '谢谢。请再拼写一次。',
+ '现在请问我的名字!',
+ ],
),
'a0-03': LessonDialogue(
goal: '询问状态、回答并反问',
@@ -1112,6 +1126,12 @@ const a0Dialogues = {
'Now say goodbye!',
],
hints: ['I’m good, thanks.', 'How are you?', 'I’m okay.', 'Bye!'],
+ translations: [
+ '嗨!你今天好吗?',
+ '很好!请问我:How are you(你好吗)?',
+ '我还好。请再说一次你的状态。',
+ '现在请说再见!',
+ ],
),
'a0-04': LessonDialogue(
goal: '报告一个虚拟三位号码并确认',
@@ -1127,6 +1147,12 @@ const a0Dialogues = {
'One-three-eight.',
'What’s your phone number?',
],
+ translations: [
+ '你的电话号码是多少?可以使用一个虚拟的三位数字。',
+ '我听到了 1-3-8。对吗?',
+ '请再说一遍这三个数字。',
+ '现在请问我的电话号码!',
+ ],
),
'a0-05': LessonDialogue(
goal: '询问并说出一个物品',
@@ -1137,6 +1163,12 @@ const a0Dialogues = {
'Great! Say one more object.',
],
hints: ['It’s a pen.', 'It’s a pen.', 'What’s this?', 'It’s a book.'],
+ translations: [
+ '这是什么?这是一支笔。',
+ '现在请说:It’s a pen(这是一支笔)。',
+ '请问我:What’s this(这是什么)?',
+ '太棒了!再说一个物品吧。',
+ ],
),
'a0-06': LessonDialogue(
goal: '说来自哪里并反问',
@@ -1152,6 +1184,12 @@ const a0Dialogues = {
'I’m from Hong Kong.',
'Bye!',
],
+ translations: [
+ '你来自哪里?',
+ '很好!请问我:Where are you from(你来自哪里)?',
+ '请再说一次你来自哪里。',
+ '请说再见!',
+ ],
),
'a0-07': LessonDialogue(
goal: '介绍一位家人或朋友',
@@ -1167,6 +1205,12 @@ const a0Dialogues = {
'Who is this?',
'This is my friend.',
],
+ translations: [
+ '这是谁?',
+ '很好。请说:This is my mother(这是我的妈妈)。',
+ '请问我:Who is this(这是谁)?',
+ '请再介绍一个人。',
+ ],
),
'a0-08': LessonDialogue(
goal: '说明星期或整点',
@@ -1182,6 +1226,12 @@ const a0Dialogues = {
'It’s three o’clock.',
'What day is it?',
],
+ translations: [
+ '今天星期几?',
+ '现在几点了?',
+ '请说一个完整的时间句子。',
+ '现在请问我今天是星期几!',
+ ],
),
'a0-09': LessonDialogue(
goal: '表达喜好、回答和反问',
@@ -1192,6 +1242,12 @@ const a0Dialogues = {
'Say your like one more time.',
],
hints: ['I like tea.', 'Yes, I do.', 'Do you like tea?', 'I like tea.'],
+ translations: [
+ '你喜欢什么?',
+ '你喜欢茶吗?',
+ '现在请问我喜欢什么。',
+ '请再说一次你的喜好。',
+ ],
),
'a0-10': LessonDialogue(
goal: '请求重复或放慢语速,并完成基础沟通',
@@ -1207,6 +1263,12 @@ const a0Dialogues = {
'What’s your name?',
'I like tea.',
],
+ translations: [
+ '请说:Please say that again(请再说一遍)。',
+ '请说:Please speak slowly(请说慢一点)。',
+ '现在请问我的名字或我来自哪里。',
+ '请说一件你喜欢的事物。',
+ ],
),
};
@@ -1215,31 +1277,37 @@ const a0SegmentDialogues = {
goal: '听辨并说出 0 到 5',
prompts: ['Say zero, one, two.', 'Now say three, four, five.'],
hints: ['zero, one, two', 'three, four, five'],
+ translations: ['请说 zero, one, two(0,1,2)。', '现在请说 three, four, five(3,4,5)。'],
),
'a0-04-b': LessonDialogue(
goal: '听辨 6 到 10 并认识 phone',
prompts: ['Say six, seven, eight.', 'What is this? Say: It is a phone.'],
hints: ['six, seven, eight', 'It is a phone.'],
+ translations: ['请说 six, seven, eight(6,7,8)。', '这是什么?请说:It is a phone(这是一部手机)。'],
),
'a0-04-c': LessonDialogue(
goal: '询问并报告三位号码',
prompts: ['What is your phone number?', 'Say a three-digit number again.'],
hints: ['My number is one-three-eight.', 'one-three-eight'],
+ translations: ['你的电话号码是多少?', '请再说一次三位数字。'],
),
'a0-08-a': LessonDialogue(
goal: '询问并说出星期一到三',
prompts: ['What day is it?', 'Say Monday, Tuesday, or Wednesday.'],
hints: ['What day is it?', 'It is Monday.'],
+ translations: ['今天星期几?', '请说 Monday, Tuesday, 或 Wednesday(周一、周二或周三)。'],
),
'a0-08-b': LessonDialogue(
goal: '说出星期四到日',
prompts: ['What day is it?', 'Say Thursday, Friday, Saturday, or Sunday.'],
hints: ['What day is it?', 'It is Friday.'],
+ translations: ['今天星期几?', '请说 Thursday, Friday, Saturday, 或 Sunday(周四、周五、周六或周日)。'],
),
'a0-08-c': LessonDialogue(
goal: '询问并说出整点',
prompts: ['What time is it?', 'Say one full time sentence.'],
hints: ['What time is it?', 'It is three o’clock.'],
+ translations: ['现在几点了?', '请说一个完整的时间句子。'],
),
};
diff --git a/kouyu_english/lib/core/sync/sync_coordinator.dart b/kouyu_english/lib/core/sync/sync_coordinator.dart
new file mode 100644
index 0000000..fd58251
--- /dev/null
+++ b/kouyu_english/lib/core/sync/sync_coordinator.dart
@@ -0,0 +1,240 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+import '../app_state.dart';
+import 'sync_merger.dart';
+import 'sync_models.dart';
+import 'sync_service.dart';
+
+/// 跨端学习进度同步协调器
+class SyncCoordinator extends ChangeNotifier {
+ static const _prefKey = 'sync_config_v1';
+
+ static final SyncCoordinator instance = SyncCoordinator._();
+ SyncCoordinator._({SyncService? service}) : _service = service ?? SyncService();
+
+ @visibleForTesting
+ factory SyncCoordinator.createForTesting({SyncService? service}) {
+ return SyncCoordinator._(service: service);
+ }
+
+ final SyncService _service;
+
+ SyncConfig _config = const SyncConfig();
+ SyncState _state = SyncState.idle;
+ String? _errorMessage;
+ bool _isInitialized = false;
+ DateTime? _lastSyncAttempt;
+
+ SyncConfig get config => _config;
+ SyncState get state => _state;
+ String? get errorMessage => _errorMessage;
+ bool get isInitialized => _isInitialized;
+ bool get isLoggedIn => _config.isLoggedIn;
+ String? get username => _config.username;
+ String get serverUrl => _config.serverUrl;
+ DateTime? get lastSyncTime => _config.lastSyncTime;
+ bool get autoSyncEnabled => _config.autoSyncEnabled;
+
+ /// 初始化并从本地存储加载配置
+ Future init() async {
+ if (_isInitialized) return;
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final raw = prefs.getString(_prefKey);
+ if (raw != null && raw.isNotEmpty) {
+ final map = jsonDecode(raw) as Map;
+ _config = SyncConfig.fromJson(map);
+ }
+ } catch (e) {
+ debugPrint('[SyncCoordinator] init error: $e');
+ } finally {
+ _isInitialized = true;
+ notifyListeners();
+ }
+ }
+
+ Future _saveConfig() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString(_prefKey, jsonEncode(_config.toJson()));
+ } catch (e) {
+ debugPrint('[SyncCoordinator] save config error: $e');
+ }
+ }
+
+ /// 更新服务器地址
+ Future updateServerUrl(String newUrl) async {
+ _config = _config.copyWith(serverUrl: newUrl.trim());
+ _errorMessage = null;
+ await _saveConfig();
+ notifyListeners();
+ }
+
+ /// 切换自动同步开关
+ Future setAutoSyncEnabled(bool enabled) async {
+ _config = _config.copyWith(autoSyncEnabled: enabled);
+ await _saveConfig();
+ notifyListeners();
+ }
+
+ /// 注册新用户并自动保存登录凭证
+ Future register({
+ required String serverUrl,
+ required String username,
+ required String password,
+ }) async {
+ _state = SyncState.syncing;
+ _errorMessage = null;
+ notifyListeners();
+
+ try {
+ final auth = await _service.register(
+ serverUrl: serverUrl,
+ username: username,
+ password: password,
+ );
+ _config = _config.copyWith(
+ serverUrl: serverUrl.trim(),
+ token: auth.token,
+ username: auth.username,
+ userId: auth.userId,
+ );
+ _state = SyncState.idle;
+ await _saveConfig();
+ notifyListeners();
+ return true;
+ } catch (e) {
+ _state = SyncState.error;
+ _errorMessage = e is HttpException ? e.message : e.toString();
+ notifyListeners();
+ return false;
+ }
+ }
+
+ /// 登录已有账号
+ Future login({
+ required String serverUrl,
+ required String username,
+ required String password,
+ }) async {
+ _state = SyncState.syncing;
+ _errorMessage = null;
+ notifyListeners();
+
+ try {
+ final auth = await _service.login(
+ serverUrl: serverUrl,
+ username: username,
+ password: password,
+ );
+ _config = _config.copyWith(
+ serverUrl: serverUrl.trim(),
+ token: auth.token,
+ username: auth.username,
+ userId: auth.userId,
+ );
+ _state = SyncState.idle;
+ await _saveConfig();
+ notifyListeners();
+ return true;
+ } catch (e) {
+ _state = SyncState.error;
+ _errorMessage = e is HttpException ? e.message : e.toString();
+ notifyListeners();
+ return false;
+ }
+ }
+
+ /// 登出并清除本地登录凭证
+ Future logout() async {
+ _config = SyncConfig(
+ serverUrl: _config.serverUrl,
+ autoSyncEnabled: _config.autoSyncEnabled,
+ );
+ _state = SyncState.idle;
+ _errorMessage = null;
+ await _saveConfig();
+ notifyListeners();
+ }
+
+ /// 测试与服务器的连接
+ Future testConnection([String? customUrl]) async {
+ return _service.testConnection(customUrl ?? _config.serverUrl);
+ }
+
+ /// 立即触发一次全量/增量双向同步 (Pull -> Merge -> Push)
+ Future syncNow(AppState appState) async {
+ if (!isLoggedIn) {
+ _errorMessage = '未登录同步账号';
+ _state = SyncState.error;
+ notifyListeners();
+ return false;
+ }
+
+ _state = SyncState.syncing;
+ _errorMessage = null;
+ notifyListeners();
+
+ try {
+ final sUrl = _config.serverUrl;
+ final token = _config.token!;
+
+ // 1. 增量拉取云端数据
+ final pullResp = await _service.pull(
+ serverUrl: sUrl,
+ token: token,
+ since: _config.lastSyncTime,
+ );
+
+ // 2. 本地智能合并 (CRDT/LWW)
+ final changed = SyncMerger.applyPullResponse(appState, pullResp);
+ if (changed) {
+ appState.notifyListeners();
+ }
+
+ // 3. 构建本地增量数据并推送至云端
+ final pushReq = SyncMerger.buildPushRequest(appState);
+ final sTime = await _service.push(
+ serverUrl: sUrl,
+ token: token,
+ request: pushReq,
+ );
+
+ // 4. 更新同步时间戳并保存
+ final syncSuccessTime = DateTime.tryParse(sTime) ?? DateTime.now();
+ _config = _config.copyWith(lastSyncTime: syncSuccessTime);
+ _state = SyncState.success;
+ _errorMessage = null;
+ await _saveConfig();
+ notifyListeners();
+ return true;
+ } catch (e) {
+ _state = SyncState.error;
+ _errorMessage = e is HttpException ? e.message : e.toString();
+ notifyListeners();
+ return false;
+ }
+ }
+
+ /// 满足条件时在后台静默触发同步
+ void triggerBackgroundSync(AppState appState) {
+ if (!autoSyncEnabled || !isLoggedIn || _state == SyncState.syncing) {
+ return;
+ }
+ // 简单防抖:距离上次同步尝试不足 3 秒则跳过
+ final now = DateTime.now();
+ if (_lastSyncAttempt != null &&
+ now.difference(_lastSyncAttempt!).inSeconds < 3) {
+ return;
+ }
+ _lastSyncAttempt = now;
+
+ // 异步执行,不阻塞主流程
+ unawaited(syncNow(appState));
+ }
+}
diff --git a/kouyu_english/lib/core/sync/sync_merger.dart b/kouyu_english/lib/core/sync/sync_merger.dart
new file mode 100644
index 0000000..d9df367
--- /dev/null
+++ b/kouyu_english/lib/core/sync/sync_merger.dart
@@ -0,0 +1,163 @@
+import '../models.dart';
+import '../app_state.dart';
+import 'sync_models.dart';
+
+/// 负责本地 AppState 与云端 DTO 之间的序列化与智能合并
+class SyncMerger {
+ /// 将本地 AppState 打包为增量推送请求
+ static SyncPushRequest buildPushRequest(AppState state, {String? deviceName}) {
+ final nowIso = DateTime.now().toUtc().toIso8601String();
+
+ final progressPayload = SyncProgressPayload(
+ activeLessonId: state.activeLessonId,
+ completedLessonIds: state.completedLessonIds.toList(),
+ completedSegmentIds: state.completedSegmentIds.toList(),
+ activeStep: state.lessonStep.name,
+ streakDays: state.completedLessons > 0 ? 1 : 0,
+ updatedAt: nowIso,
+ );
+
+ final masteryUpdates = state.mastery.values.map((m) {
+ // 查找对应复习到期时间
+ final review = state.reviewQueue.where((r) => r.id == m.id).firstOrNull;
+ final dueAt = review?.dueAt.toUtc().toIso8601String() ??
+ DateTime.now().toUtc().toIso8601String();
+ final attempts = review?.attempts ?? 0;
+ final successfulReviews = review?.successfulReviews ?? 0;
+
+ return SyncMasteryItemPayload(
+ itemId: m.id,
+ checkpoint: m.checkpoint,
+ status: m.status.name,
+ dueAt: dueAt,
+ successfulReviews: successfulReviews,
+ attempts: attempts,
+ payload: {
+ 'label': m.label,
+ 'evidence': m.evidence.map((e) => e.name).toList(),
+ 'needsReview': m.needsReview,
+ if (m.firstTaughtAt != null)
+ 'firstTaughtAt': m.firstTaughtAt!.toUtc().toIso8601String(),
+ },
+ updatedAt: nowIso,
+ );
+ }).toList();
+
+ final profilePayload = SyncProfilePayload(
+ onboardingComplete: state.onboardingComplete,
+ goal: state.goal.name,
+ placement: state.placement.name,
+ dailyMinutes: state.dailyMinutes,
+ showChineseHints: state.showChineseHints,
+ aiEndpoint: state.aiEndpoint,
+ aiModel: state.aiModel,
+ aiProvider: state.aiProvider.name,
+ settingsPayload: {
+ 'keepRecordings': state.keepRecordings,
+ },
+ updatedAt: nowIso,
+ );
+
+ return SyncPushRequest(
+ clientTime: nowIso,
+ deviceName: deviceName,
+ progress: progressPayload,
+ masteryUpdates: masteryUpdates,
+ profile: profilePayload,
+ );
+ }
+
+ /// 将云端拉取的进度合并到本地 AppState
+ static bool applyPullResponse(AppState state, SyncPullResponse response) {
+ var changed = false;
+
+ // 1. 合并课程关卡 (Union)
+ if (response.progress != null) {
+ final p = response.progress!;
+ for (final id in p.completedLessonIds) {
+ if (!state.completedLessonIds.contains(id)) {
+ state.completedLessonIds.add(id);
+ changed = true;
+ }
+ }
+ for (final sid in p.completedSegmentIds) {
+ if (!state.completedSegmentIds.contains(sid)) {
+ state.completedSegmentIds.add(sid);
+ changed = true;
+ }
+ }
+ if (state.completedLessonIds.length != state.completedLessons) {
+ state.completedLessons = state.completedLessonIds.length;
+ changed = true;
+ }
+ }
+
+ // 2. 合并复习掌握项 (Max Checkpoint)
+ for (final m in response.masteryUpdates) {
+ final local = state.mastery[m.itemId];
+ if (local == null) {
+ // 本地没有,直接添加
+ final status = _parseMasteryStatus(m.status);
+ final evidence = (m.payload['evidence'] as List? ?? [])
+ .whereType()
+ .map(_parseEvidenceKind)
+ .toList();
+
+ state.mastery[m.itemId] = MasteryItem(
+ id: m.itemId,
+ label: m.payload['label'] as String? ?? m.itemId,
+ status: status,
+ evidence: evidence,
+ needsReview: m.payload['needsReview'] as bool? ?? false,
+ checkpoint: m.checkpoint,
+ firstTaughtAt: m.payload['firstTaughtAt'] != null
+ ? DateTime.tryParse(m.payload['firstTaughtAt'] as String)
+ : null,
+ );
+ changed = true;
+ } else if (m.checkpoint > local.checkpoint) {
+ // 云端 Checkpoint 更高,升级本地状态
+ final status = _parseMasteryStatus(m.status);
+ state.mastery[m.itemId] = local.copyWith(
+ checkpoint: m.checkpoint,
+ status: status,
+ needsReview: m.payload['needsReview'] as bool? ?? local.needsReview,
+ );
+ changed = true;
+ }
+ }
+
+ // 3. 合并用户偏好设置 (按需合并)
+ if (response.profile != null) {
+ final prof = response.profile!;
+ if (!state.onboardingComplete && prof.onboardingComplete) {
+ state.onboardingComplete = true;
+ changed = true;
+ }
+ if (prof.goal.isNotEmpty) {
+ final g = _parseGoal(prof.goal);
+ if (g != state.goal) {
+ state.goal = g;
+ changed = true;
+ }
+ }
+ }
+
+ return changed;
+ }
+
+ static MasteryStatus _parseMasteryStatus(String str) {
+ return MasteryStatus.values.where((e) => e.name == str).firstOrNull ??
+ MasteryStatus.newItem;
+ }
+
+ static EvidenceKind _parseEvidenceKind(String str) {
+ return EvidenceKind.values.where((e) => e.name == str).firstOrNull ??
+ EvidenceKind.pending;
+ }
+
+ static LearningGoal _parseGoal(String str) {
+ return LearningGoal.values.where((e) => e.name == str).firstOrNull ??
+ LearningGoal.dailyLife;
+ }
+}
diff --git a/kouyu_english/lib/core/sync/sync_models.dart b/kouyu_english/lib/core/sync/sync_models.dart
new file mode 100644
index 0000000..8b771a1
--- /dev/null
+++ b/kouyu_english/lib/core/sync/sync_models.dart
@@ -0,0 +1,289 @@
+
+/// 同步状态枚举
+enum SyncState {
+ idle,
+ syncing,
+ success,
+ error,
+}
+
+/// 客户端同步配置与认证状态
+class SyncConfig {
+ final String serverUrl;
+ final String? token;
+ final String? username;
+ final String? userId;
+ final DateTime? lastSyncTime;
+ final bool autoSyncEnabled;
+
+ const SyncConfig({
+ this.serverUrl = 'https://syncenglish.slcydia.fun',
+ this.token,
+ this.username,
+ this.userId,
+ this.lastSyncTime,
+ this.autoSyncEnabled = true,
+ });
+
+ bool get isLoggedIn => token != null && token!.isNotEmpty;
+
+ SyncConfig copyWith({
+ String? serverUrl,
+ String? token,
+ String? username,
+ String? userId,
+ DateTime? lastSyncTime,
+ bool? autoSyncEnabled,
+ }) => SyncConfig(
+ serverUrl: serverUrl ?? this.serverUrl,
+ token: token ?? this.token,
+ username: username ?? this.username,
+ userId: userId ?? this.userId,
+ lastSyncTime: lastSyncTime ?? this.lastSyncTime,
+ autoSyncEnabled: autoSyncEnabled ?? this.autoSyncEnabled,
+ );
+
+ Map toJson() => {
+ 'serverUrl': serverUrl,
+ 'token': token,
+ 'username': username,
+ 'userId': userId,
+ 'lastSyncTime': lastSyncTime?.toUtc().toIso8601String(),
+ 'autoSyncEnabled': autoSyncEnabled,
+ };
+
+ factory SyncConfig.fromJson(Map json) => SyncConfig(
+ serverUrl: json['serverUrl'] as String? ?? 'https://syncenglish.slcydia.fun',
+ token: json['token'] as String?,
+ username: json['username'] as String?,
+ userId: json['userId'] as String?,
+ lastSyncTime: json['lastSyncTime'] != null
+ ? DateTime.tryParse(json['lastSyncTime'] as String)
+ : null,
+ autoSyncEnabled: json['autoSyncEnabled'] as bool? ?? true,
+ );
+}
+
+/// 认证响应
+class SyncAuthResponse {
+ final String userId;
+ final String username;
+ final String token;
+ final int expiresIn;
+
+ const SyncAuthResponse({
+ required this.userId,
+ required this.username,
+ required this.token,
+ required this.expiresIn,
+ });
+
+ factory SyncAuthResponse.fromJson(Map json) => SyncAuthResponse(
+ userId: json['user_id'] as String? ?? '',
+ username: json['username'] as String? ?? '',
+ token: json['token'] as String? ?? '',
+ expiresIn: json['expires_in'] as int? ?? 0,
+ );
+}
+
+/// 课程关卡进度 DTO
+class SyncProgressPayload {
+ final String activeLessonId;
+ final List completedLessonIds;
+ final List completedSegmentIds;
+ final String activeStep;
+ final int streakDays;
+ final String updatedAt;
+
+ const SyncProgressPayload({
+ required this.activeLessonId,
+ required this.completedLessonIds,
+ required this.completedSegmentIds,
+ this.activeStep = 'preview',
+ this.streakDays = 0,
+ required this.updatedAt,
+ });
+
+ Map toJson() => {
+ 'active_lesson_id': activeLessonId,
+ 'completed_lesson_ids': completedLessonIds,
+ 'completed_segment_ids': completedSegmentIds,
+ 'active_step': activeStep,
+ 'streak_days': streakDays,
+ 'updated_at': updatedAt,
+ };
+
+ factory SyncProgressPayload.fromJson(Map json) => SyncProgressPayload(
+ activeLessonId: json['active_lesson_id'] as String? ?? 'a0-01',
+ completedLessonIds: (json['completed_lesson_ids'] as List? ?? [])
+ .map((e) => e.toString())
+ .toList(),
+ completedSegmentIds: (json['completed_segment_ids'] as List? ?? [])
+ .map((e) => e.toString())
+ .toList(),
+ activeStep: json['active_step'] as String? ?? 'preview',
+ streakDays: json['streak_days'] as int? ?? 0,
+ updatedAt: json['updated_at'] as String? ?? DateTime.now().toUtc().toIso8601String(),
+ );
+}
+
+/// 艾宾浩斯与掌握度 DTO
+class SyncMasteryItemPayload {
+ final String itemId;
+ final int checkpoint;
+ final String status;
+ final String dueAt;
+ final int successfulReviews;
+ final int attempts;
+ final Map payload;
+ final String updatedAt;
+
+ const SyncMasteryItemPayload({
+ required this.itemId,
+ required this.checkpoint,
+ required this.status,
+ required this.dueAt,
+ this.successfulReviews = 0,
+ this.attempts = 0,
+ this.payload = const {},
+ required this.updatedAt,
+ });
+
+ Map toJson() => {
+ 'item_id': itemId,
+ 'checkpoint': checkpoint,
+ 'status': status,
+ 'due_at': dueAt,
+ 'successful_reviews': successfulReviews,
+ 'attempts': attempts,
+ 'payload': payload,
+ 'updated_at': updatedAt,
+ };
+
+ factory SyncMasteryItemPayload.fromJson(Map json) => SyncMasteryItemPayload(
+ itemId: json['item_id'] as String? ?? '',
+ checkpoint: json['checkpoint'] as int? ?? 0,
+ status: json['status'] as String? ?? 'learning',
+ dueAt: json['due_at'] as String? ?? DateTime.now().toUtc().toIso8601String(),
+ successfulReviews: json['successful_reviews'] as int? ?? 0,
+ attempts: json['attempts'] as int? ?? 0,
+ payload: json['payload'] is Map
+ ? json['payload'] as Map
+ : {},
+ updatedAt: json['updated_at'] as String? ?? DateTime.now().toUtc().toIso8601String(),
+ );
+}
+
+/// 用户画像与偏好 DTO
+class SyncProfilePayload {
+ final bool onboardingComplete;
+ final String goal;
+ final String placement;
+ final int dailyMinutes;
+ final bool showChineseHints;
+ final String aiEndpoint;
+ final String aiModel;
+ final String aiProvider;
+ final Map settingsPayload;
+ final String updatedAt;
+
+ const SyncProfilePayload({
+ this.onboardingComplete = true,
+ this.goal = 'travel',
+ this.placement = 'A0',
+ this.dailyMinutes = 20,
+ this.showChineseHints = true,
+ this.aiEndpoint = '',
+ this.aiModel = '',
+ this.aiProvider = '',
+ this.settingsPayload = const {},
+ required this.updatedAt,
+ });
+
+ Map toJson() => {
+ 'onboarding_complete': onboardingComplete,
+ 'goal': goal,
+ 'placement': placement,
+ 'daily_minutes': dailyMinutes,
+ 'show_chinese_hints': showChineseHints,
+ 'ai_endpoint': aiEndpoint,
+ 'ai_model': aiModel,
+ 'ai_provider': aiProvider,
+ 'settings_payload': settingsPayload,
+ 'updated_at': updatedAt,
+ };
+
+ factory SyncProfilePayload.fromJson(Map json) => SyncProfilePayload(
+ onboardingComplete: json['onboarding_complete'] as bool? ?? true,
+ goal: json['goal'] as String? ?? 'travel',
+ placement: json['placement'] as String? ?? 'A0',
+ dailyMinutes: json['daily_minutes'] as int? ?? 20,
+ showChineseHints: json['show_chinese_hints'] as bool? ?? true,
+ aiEndpoint: json['ai_endpoint'] as String? ?? '',
+ aiModel: json['ai_model'] as String? ?? '',
+ aiProvider: json['ai_provider'] as String? ?? '',
+ settingsPayload: json['settings_payload'] is Map
+ ? json['settings_payload'] as Map
+ : {},
+ updatedAt: json['updated_at'] as String? ?? DateTime.now().toUtc().toIso8601String(),
+ );
+}
+
+/// 增量推送请求
+class SyncPushRequest {
+ final String clientTime;
+ final String? deviceName;
+ final SyncProgressPayload? progress;
+ final List masteryUpdates;
+ final SyncProfilePayload? profile;
+
+ const SyncPushRequest({
+ required this.clientTime,
+ this.deviceName,
+ this.progress,
+ this.masteryUpdates = const [],
+ this.profile,
+ });
+
+ Map toJson() => {
+ 'client_time': clientTime,
+ if (deviceName != null) 'device_name': deviceName,
+ if (progress != null) 'progress': progress!.toJson(),
+ 'mastery_updates': masteryUpdates.map((m) => m.toJson()).toList(),
+ if (profile != null) 'profile': profile!.toJson(),
+ };
+}
+
+/// 增量拉取响应
+class SyncPullResponse {
+ final String serverTime;
+ final SyncProgressPayload? progress;
+ final List masteryUpdates;
+ final SyncProfilePayload? profile;
+
+ const SyncPullResponse({
+ required this.serverTime,
+ this.progress,
+ this.masteryUpdates = const [],
+ this.profile,
+ });
+
+ factory SyncPullResponse.fromJson(Map json) {
+ final data = json['data'] is Map
+ ? json['data'] as Map
+ : json;
+ return SyncPullResponse(
+ serverTime: data['server_time'] as String? ?? DateTime.now().toUtc().toIso8601String(),
+ progress: data['progress'] != null
+ ? SyncProgressPayload.fromJson(data['progress'] as Map)
+ : null,
+ masteryUpdates: (data['mastery_updates'] as List? ?? [])
+ .whereType