// File IDs are persisted; stable API URLs are used for display only. const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'; function fileId(value) { if (value && typeof value === 'object') return fileId(value.file_id || value.fileId || (value.file && value.file.id) || value.id || value.path || value.url); if (typeof value !== 'string') return ''; if (new RegExp('^' + UUID + '$', 'i').test(value)) return value; var match = value.match(new RegExp('^(?:https?://[^/]+)?/api/files/(' + UUID + ')(?:[?#].*)?$', 'i')); return match ? match[1] : ''; } function uploadReference(value) { if (!value || value.error) throw value || new Error('上传失败'); var id = fileId(value); if (!id) throw new Error('上传响应缺少文件 ID,请重试'); return id; } function normalizeUploadResult(value) { if (!value || typeof value !== 'object' || value.error) return value; var id = fileId(value); if (!id) return value; return Object.assign({}, value, { file_id: id, path: '/api/files/' + id, url: '/api/files/' + id }); } function filePayload(action, data) { if (!data || typeof data !== 'object') return data; var mappings = { updateProfile: { avatar: 'avatar_file_id' }, updatePartnerProfile: { avatar: 'avatar_file_id' }, albumAdd: { cover: 'cover_file_id' }, albumUpdate: { cover: 'cover_file_id' }, photoAdd: { path: 'file_id' }, diaryAdd: { images: 'image_file_ids' }, diaryUpdate: { images: 'image_file_ids' }, timelineAdd: { bg_image: 'bg_image_file_id', images: 'image_file_ids' }, timelineUpdate: { bg_image: 'bg_image_file_id', images: 'image_file_ids' }, checkinDo: { photo: 'photo_file_id' } }; var out = Object.assign({}, data); Object.keys(mappings[action] || {}).forEach(function(key) { if (!Object.prototype.hasOwnProperty.call(out, key)) return; var target = mappings[action][key]; var value = out[key]; // Legacy references remain compatible; all new uploads supply UUIDs. var convert = function(v) { return fileId(v) || v; }; if (!Object.prototype.hasOwnProperty.call(out, target)) out[target] = Array.isArray(value) ? value.map(convert) : convert(value); delete out[key]; }); return out; } module.exports = { fileId, uploadReference, normalizeUploadResult, filePayload };