src/contacts/ContactCache.js
import Hashes from 'jshashes';
import {
getItem,
setItem,
removeItem,
} from '../utils';
const VALID_CACHE = 'validCache';
const SAVED_USER = 'savedUser';
const SAVED_DEVICE_CONTACTS = 'savedDeviceContacts';
const SAVED_DEVICE_WAC_CONTACTS = 'savedDeviceWacContacts';
const SAVED_WAC_CONTACTS = 'savedWacContacts';
const HASH_DEVICE_CONTACTS = 'hashDeviceContacts';
const HASH_WAC_CONTACTS = 'hashWacContacts';
const SAVED_AVATAR_DEVICE_CONTACTS = 'savedAvatarDeviceContacts';
const SAVED_FAVORITE_CONTACTS = 'favoriteContacts';
function doHash(data) {
let md5 = new Hashes.MD5();
return md5.hex(JSON.stringify(data));
}
/** @private */
export function getDeviceWacContacts() {
return getItem(SAVED_DEVICE_WAC_CONTACTS);
}
/** @private */
export function setDeviceWacContacts(deviceWacContacts) {
setItem(SAVED_DEVICE_WAC_CONTACTS, deviceWacContacts);
}
/** @private */
export function setAvatarDeviceContacts(avatars) {
setItem(SAVED_AVATAR_DEVICE_CONTACTS, avatars);
}
/** @private */
export function getAvatarDeviceContacts() {
return getItem(SAVED_AVATAR_DEVICE_CONTACTS);
}
/** @private */
export function setWacContacts(wacContacts) {
setItem(SAVED_WAC_CONTACTS, wacContacts);
setItem(HASH_WAC_CONTACTS, doHash(wacContacts));
}
/** @private */
export function getWacContacts() {
return getItem(SAVED_WAC_CONTACTS);
}
/** @private */
export function setDeviceContacts(deviceContacts) {
setItem(HASH_DEVICE_CONTACTS, doHash(deviceContacts));
setItem(SAVED_DEVICE_CONTACTS, deviceContacts);
}
/** @private */
export function validateCache() {
setItem(VALID_CACHE, true);
}
/** @private */
export function invalidateCache() {
setItem(VALID_CACHE, false);
removeItem(SAVED_DEVICE_CONTACTS);
removeItem(HASH_DEVICE_CONTACTS);
removeItem(SAVED_AVATAR_DEVICE_CONTACTS);
}
/** @private */
export function isValidCache() {
return getItem(VALID_CACHE);
}
/** @private */
export function isCacheUpdated(deviceContacts) {
let hashSavedContacts = getItem(HASH_DEVICE_CONTACTS);
let hashDeviceContacts = doHash(deviceContacts);
return hashSavedContacts === hashDeviceContacts;
}
/** @private */
export function getFavoriteContacts() {
return getItem(SAVED_FAVORITE_CONTACTS);
}
/** @private */
export function updateFavoriteContacts(favorites) {
setItem(SAVED_FAVORITE_CONTACTS, favorites);
}
/** @private */
export function emptyAllContactData() {
removeItem(SAVED_DEVICE_WAC_CONTACTS);
removeItem(SAVED_WAC_CONTACTS);
removeItem(HASH_WAC_CONTACTS);
removeItem(SAVED_USER);
invalidateCache();
}
/** @private */
export function invalidateCacheIfNeeded(stack) {
if (stack.getCurrentSession().user === getItem(SAVED_USER)) {
return;
}
emptyAllContactData();
setItem(SAVED_USER, stack.getCurrentSession().user);
}