feat: 修复清除数据、语音缓存、排行榜限制,新增项目配置文件
- 修复 cloud.clearAll 静默失败导致重启后数据恢复 - 清除数据弹窗改用自定义 ui-modal 替代 wx.showModal - TTS 语音合成增加 fileID 持久化缓存,重启不再重新合成 - 排行榜限制前15名,maxRank 参数化到 config.js - 新增 config.js 统一管理版本号/更新日期/开发者/排行榜限制 - progress-ring 消除 getSystemInfoSync 弃用警告 - voice.js 增加 InnerAudioContext 错误监听 - storage/util 完善用户资料、打卡日期精度、记录日志
This commit is contained in:
+99
-43
@@ -4,7 +4,10 @@ const ENV_ID = 'cloudbase-d1g56kl2q8f4f7d8a'
|
||||
let _db = null
|
||||
let _pushTimer = null
|
||||
let _enabled = false
|
||||
let _docId = null // cache doc id after first successful query
|
||||
let _docId = null // cache doc id after first successful push
|
||||
let _openid = null // cache openid from first successful add, used to
|
||||
// re-locate our doc when _docId goes stale
|
||||
// (e.g. user manually deleted the doc in the console)
|
||||
|
||||
const getDb = () => {
|
||||
if (!_enabled) return null
|
||||
@@ -27,36 +30,55 @@ const pullAll = async () => {
|
||||
const db = getDb()
|
||||
if (!db) return null
|
||||
try {
|
||||
// First try cached doc id
|
||||
if (_docId) {
|
||||
try {
|
||||
const res = await db.collection(DB_COLLECTION).doc(_docId).get()
|
||||
if (res && res.data) return res.data
|
||||
} catch (e) {
|
||||
_docId = null // doc deleted or inaccessible
|
||||
}
|
||||
// Always need the openid to safely locate OUR doc under the custom
|
||||
// security rule. Cache it on first call so subsequent pulls are fast.
|
||||
if (!_openid) {
|
||||
_openid = await _fetchOpenid()
|
||||
}
|
||||
// Query: rely on security rules to scope to current user
|
||||
const res = await db.collection(DB_COLLECTION).limit(1).get()
|
||||
if (res && res.data && res.data.length > 0) {
|
||||
_docId = res.data[0]._id
|
||||
return res.data[0]
|
||||
if (!_openid) return null // cloud function call failed; bail
|
||||
|
||||
// Locate our doc by _openid, not by limit(1) which can pick someone
|
||||
// else's doc when the custom rule is in effect.
|
||||
const mine = await db.collection(DB_COLLECTION)
|
||||
.where({ _openid: _openid })
|
||||
.limit(1)
|
||||
.get()
|
||||
if (mine && mine.data && mine.data.length > 0) {
|
||||
_docId = mine.data[0]._id
|
||||
return mine.data[0]
|
||||
}
|
||||
// No doc for us — that's a fresh install on a new device with no
|
||||
// history, or the user cleared their cloud data. Either way, nothing
|
||||
// to restore.
|
||||
_docId = null
|
||||
return null
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// One-shot helper: call the getOpenid cloud function and return the
|
||||
// openid string. Returns null on any failure (function not deployed,
|
||||
// network error, etc.) — pullAll then bails cleanly.
|
||||
const _fetchOpenid = async () => {
|
||||
try {
|
||||
const res = await wx.cloud.callFunction({ name: 'getOpenid' })
|
||||
if (res && res.result && res.result.openid) return res.result.openid
|
||||
} catch (e) { /* function not deployed, etc. */ }
|
||||
return null
|
||||
}
|
||||
|
||||
const pushAll = () => {
|
||||
if (!_enabled) return
|
||||
if (!_enabled) { console.log('[cloud] pushAll skipped (not enabled)'); return }
|
||||
if (_pushTimer) clearTimeout(_pushTimer)
|
||||
console.log('[cloud] pushAll scheduled')
|
||||
_pushTimer = setTimeout(() => _doPush(), 2000)
|
||||
}
|
||||
|
||||
const _doPush = async () => {
|
||||
console.log('[cloud] _doPush starting...')
|
||||
const db = getDb()
|
||||
if (!db) return
|
||||
if (!db) { console.log('[cloud] _doPush aborted (no db)'); return }
|
||||
try {
|
||||
const storage = require('./storage')
|
||||
const themeMod = require('./theme')
|
||||
@@ -66,55 +88,89 @@ const _doPush = async () => {
|
||||
settings: storage.getSettings(),
|
||||
streak: storage.getStreak(),
|
||||
customPlans: storage.getCustomPlans(),
|
||||
profile: storage.getProfile(),
|
||||
themeId: themeMod.getCurrentTheme().id,
|
||||
updatedAt: db.serverDate()
|
||||
}
|
||||
console.log('[cloud] _doPush records keys:', Object.keys(data.records || {}))
|
||||
|
||||
// Use cached doc id if available
|
||||
if (_docId) {
|
||||
try {
|
||||
await db.collection(DB_COLLECTION).doc(_docId).update({ data })
|
||||
console.log('[cloud] _doPush update ok')
|
||||
return
|
||||
} catch (e) {
|
||||
_docId = null // doc may have been deleted
|
||||
// Most commonly: doc was deleted out from under us (user cleared
|
||||
// the collection in the console). The custom write rule evaluates
|
||||
// `doc._openid == auth.openid` → `undefined == openid` → false,
|
||||
// so this surfaces as -502003 rather than "not found". Either way,
|
||||
// fall through and re-locate the doc via cached _openid (or add).
|
||||
console.log('[cloud] _doPush cached _docId stale, clearing:', e.message)
|
||||
_docId = null
|
||||
}
|
||||
}
|
||||
|
||||
// Query for existing doc (relies on security rules to scope to current user)
|
||||
const existing = await db.collection(DB_COLLECTION).limit(1).get()
|
||||
if (existing && existing.data && existing.data.length > 0) {
|
||||
_docId = existing.data[0]._id
|
||||
await db.collection(DB_COLLECTION).doc(_docId).update({ data })
|
||||
} else {
|
||||
const res = await db.collection(DB_COLLECTION).add({ data })
|
||||
if (res && res._id) _docId = res._id
|
||||
// Fallback: locate OUR doc by _openid (cached from a previous add) and
|
||||
// update it. If we have no cached openid yet (first ever push) just add.
|
||||
if (_openid) {
|
||||
const existing = await db.collection(DB_COLLECTION)
|
||||
.where({ _openid: _openid })
|
||||
.limit(1)
|
||||
.get()
|
||||
if (existing && existing.data && existing.data.length > 0) {
|
||||
_docId = existing.data[0]._id
|
||||
await db.collection(DB_COLLECTION).doc(_docId).update({ data })
|
||||
console.log('[cloud] _doPush update ok (re-located by _openid)')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// First push ever, or our doc was deleted and no other doc exists.
|
||||
const res = await db.collection(DB_COLLECTION).add({ data })
|
||||
if (res && res._id) _docId = res._id
|
||||
if (res && res._openid) _openid = res._openid
|
||||
console.log('[cloud] _doPush add ok, docId=', _docId)
|
||||
} catch (e) {
|
||||
// Silently retry on next write
|
||||
console.log('[cloud] _doPush error:', e.message || e)
|
||||
}
|
||||
}
|
||||
|
||||
const clearAll = async () => {
|
||||
const db = getDb()
|
||||
if (!db) return
|
||||
try {
|
||||
if (_docId) {
|
||||
try {
|
||||
await db.collection(DB_COLLECTION).doc(_docId).remove()
|
||||
_docId = null
|
||||
return
|
||||
} catch (e) {
|
||||
_docId = null
|
||||
}
|
||||
}
|
||||
const existing = await db.collection(DB_COLLECTION).limit(1).get()
|
||||
if (existing && existing.data && existing.data.length > 0) {
|
||||
await db.collection(DB_COLLECTION).doc(existing.data[0]._id).remove()
|
||||
}
|
||||
_docId = null
|
||||
} catch (e) {
|
||||
// Nothing to clear
|
||||
|
||||
// Ensure _openid is cached before trying to delete — without it we
|
||||
// can't reliably locate the user's doc (add() only returns _id).
|
||||
if (!_openid) {
|
||||
_openid = await _fetchOpenid()
|
||||
}
|
||||
if (!_openid) {
|
||||
console.log('[cloud] clearAll: cannot fetch openid, giving up')
|
||||
return
|
||||
}
|
||||
|
||||
// Always locate by _openid (never by cached _docId alone) so we're
|
||||
// guaranteed to target OUR doc under the custom permission rule.
|
||||
const mine = await db.collection(DB_COLLECTION)
|
||||
.where({ _openid: _openid })
|
||||
.limit(1)
|
||||
.get()
|
||||
if (mine && mine.data && mine.data.length > 0) {
|
||||
const myDocId = mine.data[0]._id
|
||||
try {
|
||||
await db.collection(DB_COLLECTION).doc(myDocId).remove()
|
||||
console.log('[cloud] clearAll: removed doc', myDocId)
|
||||
} catch (e) {
|
||||
console.log('[cloud] clearAll: remove failed:', e.message || e)
|
||||
}
|
||||
} else {
|
||||
console.log('[cloud] clearAll: no doc found for openid')
|
||||
}
|
||||
|
||||
// Always invalidate cached ids so the next _doPush starts fresh
|
||||
// instead of trying to update a now-deleted or foreign doc.
|
||||
_docId = null
|
||||
}
|
||||
|
||||
module.exports = { init, pullAll, pushAll, clearAll, get enabled() { return _enabled } }
|
||||
|
||||
+56
-14
@@ -1,10 +1,11 @@
|
||||
const { formatDate } = require('./util')
|
||||
const { formatDate, dateOnly } = require('./util')
|
||||
const cloud = require('./cloud')
|
||||
|
||||
const RECORDS_KEY = 'training_records'
|
||||
const SETTINGS_KEY = 'user_settings'
|
||||
const STREAK_KEY = 'current_streak'
|
||||
const CUSTOM_PLANS_KEY = 'custom_plans'
|
||||
const PROFILE_KEY = 'user_profile'
|
||||
|
||||
/**
|
||||
* Backfill an `id` for any record that doesn't have one.
|
||||
@@ -52,6 +53,7 @@ const saveRecord = (record) => {
|
||||
records[month].push(record)
|
||||
records[month].sort((a, b) => b.date.localeCompare(a.date))
|
||||
wx.setStorageSync(RECORDS_KEY, records)
|
||||
console.log('[storage] saveRecord date=' + record.date + ' duration=' + record.duration)
|
||||
cloud.pushAll()
|
||||
}
|
||||
|
||||
@@ -105,6 +107,34 @@ const saveSettings = (settings) => {
|
||||
cloud.pushAll()
|
||||
}
|
||||
|
||||
/**
|
||||
* User profile (nickname + avatar). Stored locally and pushed to the
|
||||
* cloud alongside records/settings so the leaderboard can show real
|
||||
* names instead of masked openids.
|
||||
*
|
||||
* Shape: { nickname: string, avatarUrl: string (wxfile://...) }
|
||||
* Both fields are optional; absent profile returns `{}`.
|
||||
*/
|
||||
const getProfile = () => {
|
||||
const raw = wx.getStorageSync(PROFILE_KEY)
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw
|
||||
return {}
|
||||
}
|
||||
|
||||
const saveProfile = (profile) => {
|
||||
// Strip empties so we don't push {nickname: '', avatarUrl: ''}
|
||||
const clean = {}
|
||||
if (profile && typeof profile.nickname === 'string' && profile.nickname.trim()) {
|
||||
clean.nickname = profile.nickname.trim().slice(0, 16)
|
||||
}
|
||||
if (profile && typeof profile.avatarUrl === 'string' && profile.avatarUrl) {
|
||||
clean.avatarUrl = profile.avatarUrl
|
||||
}
|
||||
wx.setStorageSync(PROFILE_KEY, clean)
|
||||
cloud.pushAll()
|
||||
return clean
|
||||
}
|
||||
|
||||
const getStreak = () => wx.getStorageSync(STREAK_KEY) || { count: 0, lastDate: '' }
|
||||
|
||||
/**
|
||||
@@ -142,25 +172,30 @@ const resetCustomPlan = (planId) => {
|
||||
* Validate streak against actual training records.
|
||||
* Call on app launch to correct any inconsistencies
|
||||
* (e.g. after deleting the only record for a day).
|
||||
*
|
||||
* Streak compares date-ONLY portions of `lastDate` so that training
|
||||
* twice on the same day (with different seconds in `record.date`)
|
||||
* doesn't accidentally reset the streak.
|
||||
*/
|
||||
const validateStreak = () => {
|
||||
const streak = getStreak()
|
||||
if (!streak.lastDate) return streak
|
||||
|
||||
const today = getToday()
|
||||
const yesterday = getDateOffset(today, -1)
|
||||
const todayOnly = dateOnly(today)
|
||||
const yesterdayOnly = dateOnly(getDateOffset(today, -1))
|
||||
const records = getRecords()
|
||||
const allDates = new Set()
|
||||
Object.values(records).forEach(monthRecs => {
|
||||
monthRecs.forEach(r => allDates.add(r.date))
|
||||
monthRecs.forEach(r => allDates.add(dateOnly(r.date)))
|
||||
})
|
||||
|
||||
// If lastDate is today, check today still has records
|
||||
if (streak.lastDate === today) {
|
||||
if (!allDates.has(today)) {
|
||||
if (dateOnly(streak.lastDate) === todayOnly) {
|
||||
if (!allDates.has(todayOnly)) {
|
||||
// Today's records were deleted
|
||||
if (allDates.has(yesterday)) {
|
||||
streak.lastDate = yesterday
|
||||
if (allDates.has(yesterdayOnly)) {
|
||||
streak.lastDate = yesterdayOnly
|
||||
streak.count = Math.max(1, streak.count - 1)
|
||||
} else {
|
||||
streak.count = 0
|
||||
@@ -178,17 +213,20 @@ const validateStreak = () => {
|
||||
|
||||
const updateStreak = (date) => {
|
||||
const streak = getStreak()
|
||||
const today = date || getToday()
|
||||
const yesterday = getDateOffset(today, -1)
|
||||
const todayFull = date || getToday()
|
||||
const todayOnly = dateOnly(todayFull)
|
||||
const yesterdayOnly = dateOnly(getDateOffset(todayFull, -1))
|
||||
|
||||
if (streak.lastDate === today) return streak
|
||||
if (dateOnly(streak.lastDate) === todayOnly) return streak
|
||||
|
||||
if (streak.lastDate === yesterday) {
|
||||
if (dateOnly(streak.lastDate) === yesterdayOnly) {
|
||||
streak.count += 1
|
||||
} else {
|
||||
streak.count = 1
|
||||
}
|
||||
streak.lastDate = today
|
||||
// Store the date-ONLY portion so subsequent comparisons are stable
|
||||
// across multiple same-day trainings with different seconds.
|
||||
streak.lastDate = todayOnly
|
||||
wx.setStorageSync(STREAK_KEY, streak)
|
||||
cloud.pushAll()
|
||||
return streak
|
||||
@@ -197,8 +235,10 @@ const updateStreak = (date) => {
|
||||
const getToday = () => formatDate(new Date())
|
||||
|
||||
const getDateOffset = (dateStr, offset) => {
|
||||
// Use YYYY/MM/DD for iOS compatibility (YYYY-MM-DD may fail on some iOS)
|
||||
const d = new Date(dateStr.replace(/-/g, '/'))
|
||||
// Strip the time portion (formatDate now includes HH:MM:SS) and convert
|
||||
// dashes to slashes — `new Date("YYYY/MM/DD")` is the only reliably-
|
||||
// parsed form across both V8 (WeChat dev tools) and JSCore (iOS).
|
||||
const d = new Date(dateOnly(dateStr).replace(/-/g, '/'))
|
||||
d.setDate(d.getDate() + offset)
|
||||
return formatDate(d)
|
||||
}
|
||||
@@ -230,6 +270,8 @@ module.exports = {
|
||||
getCustomPlans,
|
||||
saveCustomPlan,
|
||||
resetCustomPlan,
|
||||
getProfile,
|
||||
saveProfile,
|
||||
getStreak,
|
||||
validateStreak,
|
||||
updateStreak,
|
||||
|
||||
+18
-3
@@ -33,17 +33,32 @@ const getMonthCalendar = (year, month) => {
|
||||
return weeks
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a Date as `YYYY-MM-DD HH:MM:SS` in local time.
|
||||
*
|
||||
* Used as the canonical `record.date` string so each record has a
|
||||
* precise timestamp (e.g. "2026-06-11 14:30:45"). Use `_dateOnly()`
|
||||
* to strip back to YYYY-MM-DD for date-level comparisons (streak,
|
||||
* leaderboard day filter, etc.).
|
||||
*/
|
||||
const formatDate = (date) => {
|
||||
const y = date.getFullYear()
|
||||
const m = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const mo = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const d = String(date.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${d}`
|
||||
const h = String(date.getHours()).padStart(2, '0')
|
||||
const mi = String(date.getMinutes()).padStart(2, '0')
|
||||
const s = String(date.getSeconds()).padStart(2, '0')
|
||||
return `${y}-${mo}-${d} ${h}:${mi}:${s}`
|
||||
}
|
||||
|
||||
/** Strip the time portion of a formatDate string → "YYYY-MM-DD". */
|
||||
const _dateOnly = (s) => (typeof s === 'string' && s.length >= 10) ? s.substring(0, 10) : ''
|
||||
|
||||
module.exports = {
|
||||
formatTime,
|
||||
formatDuration,
|
||||
getDaysInMonth,
|
||||
getMonthCalendar,
|
||||
formatDate
|
||||
formatDate,
|
||||
dateOnly: _dateOnly
|
||||
}
|
||||
|
||||
+43
-10
@@ -2,12 +2,15 @@
|
||||
* Voice prompt utility for the timer.
|
||||
*
|
||||
* 4 fixed, polished prompts live in `cloudfunctions/tts`. We call that
|
||||
* cloud function with a key, get back an audio URL (cached in cloud
|
||||
* storage after first synthesis), and play it via createInnerAudioContext.
|
||||
* cloud function with a key, get back an audio URL and permanent fileID,
|
||||
* and play it via createInnerAudioContext.
|
||||
*
|
||||
* The in-memory `_urlCache` avoids hitting the cloud function more than
|
||||
* once per prompt per session. The audio context is a singleton so
|
||||
* overlapping prompts interrupt each other cleanly.
|
||||
* Two-level caching so TTS synthesis happens at most once per prompt,
|
||||
* ever (not once per app launch):
|
||||
* 1. In-memory `_urlCache` — avoids cloud calls within a single session
|
||||
* 2. Persistent `_fileIDCache` in wx storage — survives app restarts;
|
||||
* we pass the permanent fileID back to the cloud function so it can
|
||||
* call getTempFileURL directly instead of re-synthesizing.
|
||||
*
|
||||
* If the cloud function is unconfigured (no TTS credentials) and returns
|
||||
* `success: false`, we fall back to a silent no-op — better than spamming
|
||||
@@ -21,8 +24,24 @@ const PROMPTS = {
|
||||
complete: '太棒了!今天的目标已完成,继续加油!'
|
||||
}
|
||||
|
||||
const FILEID_CACHE_KEY = 'tts_fileid_cache'
|
||||
|
||||
let _ctx = null
|
||||
const _urlCache = {} // { promptKey: audioUrl }
|
||||
const _urlCache = {} // { promptKey: audioUrl } — per-session, volatile
|
||||
let _fileIDCache = null // { promptKey: fileID } — persisted, lazy-loaded
|
||||
|
||||
const _loadFileIDCache = () => {
|
||||
if (_fileIDCache) return
|
||||
try {
|
||||
_fileIDCache = wx.getStorageSync(FILEID_CACHE_KEY) || {}
|
||||
} catch (e) {
|
||||
_fileIDCache = {}
|
||||
}
|
||||
}
|
||||
|
||||
const _saveFileIDCache = () => {
|
||||
try { wx.setStorageSync(FILEID_CACHE_KEY, _fileIDCache) } catch (e) {}
|
||||
}
|
||||
|
||||
const _getCtx = () => {
|
||||
if (!_ctx) {
|
||||
@@ -30,23 +49,37 @@ const _getCtx = () => {
|
||||
// Play even when the device is in silent mode — we want the user to
|
||||
// actually hear training cues during a session.
|
||||
_ctx.obeyMuteSwitch = false
|
||||
_ctx.onError((err) => {
|
||||
console.log('[voice] audio error:', err.errCode, err.errMsg)
|
||||
})
|
||||
}
|
||||
return _ctx
|
||||
}
|
||||
|
||||
const _fetchUrl = async (promptKey) => {
|
||||
// 1. In-memory cache: same-session instant return
|
||||
if (_urlCache[promptKey]) return _urlCache[promptKey]
|
||||
|
||||
// 2. Persistent fileID cache: pass to cloud function for instant getTempFileURL
|
||||
_loadFileIDCache()
|
||||
const cachedFileID = _fileIDCache[promptKey] || null
|
||||
|
||||
try {
|
||||
const res = await wx.cloud.callFunction({
|
||||
name: 'tts',
|
||||
data: { promptKey },
|
||||
// Default WeChat cloud timeout is 3s, which is exactly the TTS
|
||||
// first-call budget (synth + upload + tempURL). Bump to 30s for
|
||||
// cold starts; cached calls return in <500ms.
|
||||
data: { promptKey, fileID: cachedFileID },
|
||||
// Timeout: 30s for first synthesis (cold start), <1s for cached
|
||||
config: { timeout: 30000 }
|
||||
})
|
||||
if (res && res.result && res.result.success && res.result.audioUrl) {
|
||||
_urlCache[promptKey] = res.result.audioUrl
|
||||
|
||||
// Persist the fileID if we got a new one (first synthesis or
|
||||
// re-synthesis after cache invalidation).
|
||||
if (res.result.fileID && res.result.fileID !== cachedFileID) {
|
||||
_fileIDCache[promptKey] = res.result.fileID
|
||||
_saveFileIDCache()
|
||||
}
|
||||
return res.result.audioUrl
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
Reference in New Issue
Block a user