50 lines
2.5 KiB
JavaScript
50 lines
2.5 KiB
JavaScript
/* Account-scoped, local-only form preferences. No credentials or report data. */
|
|
(function(root, factory) {
|
|
if (typeof module === 'object' && module.exports) module.exports = factory();
|
|
else root.ProfileStore = factory();
|
|
})(typeof window !== 'undefined' ? window : this, function() {
|
|
'use strict';
|
|
function key(user) {
|
|
return user && ['wechat', 'browser_persistent'].indexOf(user.kind) >= 0 && typeof user.id === 'string' && user.id.length <= 128 && user.id
|
|
? (user.kind === 'browser_persistent' ? 'juzi.rednote.profile.v1.' : 'juzi.profile.v1.') + user.kind + '.' + encodeURIComponent(user.id) : null;
|
|
}
|
|
function age(birth, now) {
|
|
if (typeof birth !== 'string' || !/^\d{4}-(0[1-9]|1[0-2])$/.test(birth)) return null;
|
|
now = now || new Date();
|
|
var y = Number(birth.slice(0, 4)), m = Number(birth.slice(5));
|
|
var value = now.getFullYear() - y - (now.getMonth() + 1 < m ? 1 : 0);
|
|
return value >= 1 && value <= 99 ? value : null;
|
|
}
|
|
function clean(input, regions, skinCount, now) {
|
|
input = input && typeof input === 'object' ? input : {};
|
|
var region = input.region, validRegion = null;
|
|
if (region && typeof region === 'object') (regions || []).some(function(p) {
|
|
if (p[0] !== region.province || p[1].indexOf(region.city) < 0) return false;
|
|
validRegion = { province: p[0], city: region.city }; return true;
|
|
});
|
|
return { birth: age(input.birth, now) == null ? '' : input.birth,
|
|
gender: ['女', '男'].indexOf(input.gender) < 0 ? '' : input.gender,
|
|
region: validRegion, skinIndex: Number.isInteger(input.skinIndex) && input.skinIndex >= 0 && input.skinIndex < skinCount ? input.skinIndex : 0 };
|
|
}
|
|
function create(getStorage) {
|
|
var memory = Object.create(null);
|
|
return {
|
|
read: function(user) {
|
|
var name = key(user), raw;
|
|
if (!name) return null;
|
|
if (Object.prototype.hasOwnProperty.call(memory, name)) return memory[name];
|
|
try { raw = getStorage().getItem(name); } catch (_) { /* Private/restricted storage. */ }
|
|
if (raw == null) return null;
|
|
try { return raw.length <= 4096 ? JSON.parse(raw) : null; } catch (_) { return null; }
|
|
},
|
|
write: function(user, value) {
|
|
var name = key(user);
|
|
if (!name) return;
|
|
memory[name] = value;
|
|
try { getStorage().setItem(name, JSON.stringify(value)); } catch (_) { /* Keep this page usable without persistence. */ }
|
|
}
|
|
};
|
|
}
|
|
return { key: key, age: age, clean: clean, create: create };
|
|
});
|