changed the database keys to enums

alpha
Jan Umbach 2023-03-10 17:54:09 +01:00
parent 74a5ba5106
commit 28a03d3844
24 changed files with 459 additions and 254 deletions

View File

@ -20,7 +20,7 @@ import {initKey} from '@caj/helper/storage/bdm/encryption';
import UserManager from '@caj/user/UserManager'; import UserManager from '@caj/user/UserManager';
import MyUserManager from '@caj/user/MyUserManager'; import MyUserManager from '@caj/user/MyUserManager';
import DBSchemas from '@caj/helper/storage/bdm/schemas'; import DBSchemas from '@caj/helper/storage/bdm/schemas';
import {chatTags, chatType} from '@caj/components/chat/types'; import {chatTags} from '@caj/components/chat/types';
const AnimationView = animated(View); const AnimationView = animated(View);
@ -31,41 +31,26 @@ function onAppStart() {
BigDataManager.initDatabase() BigDataManager.initDatabase()
.then(async () => { .then(async () => {
console.log('finish'); console.log('finish');
const usrDBKeys = BigDataManager.databases.users.keys;
await BigDataManager.databases.users.setEntry({ await BigDataManager.databases.users.setEntry({
UserId: 'test', [usrDBKeys.UserId]: 'test',
AccountName: '#845613', [usrDBKeys.AccountName]: '#845613',
Username: 'TestGroupVirtual', [usrDBKeys.Username]: 'TestGroupVirtual',
Description: 'This is a test account that is not real. ^^', [usrDBKeys.Description]:
FollowersCount: 2, 'This is a test account that is not real. ^^',
FollowingCount: 24, [usrDBKeys.FollowersCount]: 2,
lastUpdateTimestamp: 412341234, [usrDBKeys.FollowingCount]: 24,
ProfilePicture: '', [usrDBKeys.lastUpdateTimestamp]: 412341234,
ProfilePictureBinaryHQ: new ArrayBuffer(0), [usrDBKeys.ProfilePicture]: '',
ProfilePictureBinaryLQ: new ArrayBuffer(0), [usrDBKeys.ProfilePictureBinaryHQ]: new ArrayBuffer(0),
XpLevel: 0, [usrDBKeys.ProfilePictureBinaryLQ]: new ArrayBuffer(0),
XpPoints: 0, [usrDBKeys.XpLevel]: 0,
[usrDBKeys.XpPoints]: 0,
}); });
store.dispatch( store.dispatch(
appNonSaveVarActions.setAppStatus(appStatus.APP_RUNNING), appNonSaveVarActions.setAppStatus(appStatus.APP_RUNNING),
); );
store.dispatch(
appNonSaveVarActions.setChatEntity({
id: MyUserManager.getSelectedUserId(),
type: chatType.User,
tags: [chatTags.GOOD_FRIEND],
unreadMessages: 1234,
}),
);
store.dispatch(
appNonSaveVarActions.setChatEntity({
id: 'test',
type: chatType.User,
tags: [chatTags.GROUP, chatTags.GOOD_FRIEND, chatTags.FRIEND],
unreadMessages: 0,
}),
);
}) })
.catch(err => { .catch(err => {
console.error("Database Error! Can't start App :(", err); console.error("Database Error! Can't start App :(", err);

View File

@ -980,7 +980,7 @@ function StepFinal() {
icon={ icon={
<MaterialIcons <MaterialIcons
size={20} size={20}
color={colors.white[200]} color={colors.white[600]}
name={showPassword ? 'visibility' : 'visibility-off'} name={showPassword ? 'visibility' : 'visibility-off'}
/> />
} }
@ -1413,7 +1413,7 @@ function Login() {
icon={ icon={
<MaterialIcons <MaterialIcons
size={20} size={20}
color={colors.white[200]} color={colors.white[600]}
name={showPassword ? 'visibility' : 'visibility-off'} name={showPassword ? 'visibility' : 'visibility-off'}
/> />
} }

View File

@ -0,0 +1,18 @@
import {appNonSaveVarActions} from '@caj/configs/appNonSaveVarReducer';
import BigDataManager from '@caj/helper/storage/BigDataManager';
import {store} from '@caj/redux/store';
import {chatEntity} from './types';
async function initChatDatabase(chat: chatEntity) {
const keys = BigDataManager.databases.chatRoomInfos.keys;
await BigDataManager.databases.chatRoomInfos.setEntry({
[keys.RoomId]: chat.roomId,
[keys.initSyncId]: chat.initSyncId,
[keys.syncId]: chat.syncId,
[keys.unreadMessages]: chat.unreadMessages,
[keys.users]: chat.users,
});
store.dispatch(appNonSaveVarActions.setChatEntity(chat));
}
export default initChatDatabase;

View File

@ -1,9 +1,11 @@
import {appNonSaveVarActions} from '@caj/configs/appNonSaveVarReducer'; import {appNonSaveVarActions} from '@caj/configs/appNonSaveVarReducer';
import {ThemeMode} from '@caj/configs/appVar';
import { import {
darkThemeStyle, darkThemeStyle,
getBackgroundColor, getBackgroundColor,
themeSelector, themeSelector,
} from '@caj/configs/colors'; } from '@caj/configs/colors';
import LangFormat from '@caj/lang/default';
import {HomeScreenNavigationProp} from '@caj/Navigation'; import {HomeScreenNavigationProp} from '@caj/Navigation';
import {RootState, store} from '@caj/redux/store'; import {RootState, store} from '@caj/redux/store';
import {ChatScreenNavigationProp} from '@caj/tabs/main/ChatTab'; import {ChatScreenNavigationProp} from '@caj/tabs/main/ChatTab';
@ -14,44 +16,32 @@ import {useSelector} from 'react-redux';
import {start} from 'repl'; import {start} from 'repl';
import {ProfilePicture} from '../ProfilePicture'; import {ProfilePicture} from '../ProfilePicture';
import {TextSkeleton} from '../simple/Skeleton'; import {TextSkeleton} from '../simple/Skeleton';
import {chatType, getTagUI} from './types'; import {chatEntity, getTagUI} from './types';
export function ListChats() { function ChatItem(props: {
const theme = themeSelector(); chat: chatEntity;
const chats = useSelector((state: RootState) => state.nonSaveVariables.chats); navigation: HomeScreenNavigationProp;
const chatActivity = useSelector( theme: ThemeMode;
(state: RootState) => state.nonSaveVariables.chatActivity, ppSize: number;
); tagSize: number;
const selectedChat = useSelector( space: number;
(state: RootState) => state.nonSaveVariables.selectedChat, lang: LangFormat;
); }) {
const chat = props.chat;
const navigation = props.navigation;
const theme = props.theme;
const ppSize = props.ppSize;
const tagSize = props.tagSize;
const space = props.space;
const lang = props.lang;
console.log('selectedChat', selectedChat); const roomId = chat.roomId;
const user = UserManager.getUserSelector(chat.users[0]);
const space = 4;
const ppSize = 64;
const tagSize = 24;
const lang = useSelector((state: RootState) => state.appVariables.lang);
const navigation = useNavigation<HomeScreenNavigationProp>();
return (
<VStack
mt={space * 2 + 'px'}
space={tagSize * 0.3 + space + 'px'}
width="100%"
marginY={space + 'px'}>
{chatActivity.map((chatId, i) => {
const chat = chats[chatId];
if (chat.type === chatType.User) {
const user = UserManager.getUserSelector(chatId);
return ( return (
<Pressable <Pressable
key={'chatList_i' + i + chatId}
onPress={() => { onPress={() => {
store.dispatch(appNonSaveVarActions.setSelectedChat(chatId)); store.dispatch(appNonSaveVarActions.setSelectedChat(roomId));
navigation.navigate('ChatList', {screen: 'Chat'}); navigation.navigate('ChatList', {screen: 'Chat'});
//navigation.navigate('Register', {screen: 'RegStepOne'}); //navigation.navigate('Register', {screen: 'RegStepOne'});
}}> }}>
@ -62,14 +52,10 @@ export function ListChats() {
{...darkThemeStyle(theme, 'black.400')} {...darkThemeStyle(theme, 'black.400')}
borderRadius={ppSize / 2 + 'px'} borderRadius={ppSize / 2 + 'px'}
borderTopRightRadius={ borderTopRightRadius={
chat.unreadMessages !== 0 chat.unreadMessages !== 0 ? tagSize / 2 + 'px' : ppSize / 2 + 'px'
? tagSize / 2 + 'px'
: ppSize / 2 + 'px'
} }
borderBottomLeftRadius={ borderBottomLeftRadius={
chat.tags.length > 0 chat.tags.length > 0 ? tagSize / 2 + 'px' : ppSize / 2 + 'px'
? tagSize / 2 + 'px'
: ppSize / 2 + 'px'
} }
marginX={space + 'px'} marginX={space + 'px'}
padding={space + 'px'}> padding={space + 'px'}>
@ -116,9 +102,7 @@ export function ListChats() {
</HStack> </HStack>
<VStack> <VStack>
<HStack space={space + 'px'}> <HStack space={space + 'px'}>
<ProfilePicture <ProfilePicture UserId={roomId} size={ppSize}></ProfilePicture>
UserId={chatId}
size={ppSize}></ProfilePicture>
<VStack mt={ppSize / 6 + 'px'}> <VStack mt={ppSize / 6 + 'px'}>
<TextSkeleton <TextSkeleton
lineHeight={ppSize / 3 + 'px'} lineHeight={ppSize / 3 + 'px'}
@ -150,7 +134,7 @@ export function ListChats() {
let tagName = tagObj.name; let tagName = tagObj.name;
return ( return (
<Box <Box
key={'tag' + i + tag + chat.id} key={'tag' + i + tag + chat.roomId}
height={tagSize + 'px'} height={tagSize + 'px'}
mr={space + 'px'} mr={space + 'px'}
mt={space + 'px'} mt={space + 'px'}
@ -175,6 +159,48 @@ export function ListChats() {
</Pressable> </Pressable>
); );
} }
export function ListChats() {
const theme = themeSelector();
const chats = useSelector((state: RootState) => state.nonSaveVariables.chats);
const chatActivity = useSelector(
(state: RootState) => state.nonSaveVariables.chatActivity,
);
const selectedChat = useSelector(
(state: RootState) => state.nonSaveVariables.selectedChat,
);
console.log('selectedChat', selectedChat);
const space = 4;
const ppSize = 64;
const tagSize = 24;
const lang = useSelector((state: RootState) => state.appVariables.lang);
const navigation = useNavigation<HomeScreenNavigationProp>();
return (
<VStack
mt={space * 2 + 'px'}
space={tagSize * 0.3 + space + 'px'}
width="100%"
marginY={space + 'px'}>
{chatActivity.map((roomId, i) => {
const chat = chats[roomId];
return (
<ChatItem
key={'chatList_i' + i + roomId}
navigation={navigation}
chat={chat}
theme={theme}
space={space}
ppSize={ppSize}
tagSize={tagSize}
lang={lang}
/>
);
})} })}
</VStack> </VStack>
); );

View File

@ -1,13 +1,6 @@
import {UserId} from '@caj/configs/types'; import {UserId} from '@caj/configs/types';
import LangFormat from '@caj/lang/default'; import LangFormat from '@caj/lang/default';
type GroupId = string;
export enum chatType {
User = 0,
Group = 1,
}
export enum chatTags { export enum chatTags {
GROUP = 0, GROUP = 0,
FRIEND = 1, FRIEND = 1,
@ -52,12 +45,20 @@ export function getTagUI(tagKey: chatTags, lang?: LangFormat): tagUITypeFinal {
return tag as tagUITypeFinal; return tag as tagUITypeFinal;
} }
export type chatId = UserId | GroupId; export type roomId = string;
type syncId = number;
export interface chatEntity { export interface chatEntity {
type: chatType; roomId: roomId;
id: chatId;
syncId: syncId;
initSyncId: syncId;
users: [UserId, ...UserId[]];
title?: string; title?: string;
unreadMessages: number; unreadMessages: number;
tags: chatTags[]; tags: chatTags[];
} }

View File

@ -1,6 +1,6 @@
//these variables should not changed by the user and will not be saved in storage //these variables should not changed by the user and will not be saved in storage
import {chatEntity, chatId} from '@caj/components/chat/types'; import {chatEntity, roomId} from '@caj/components/chat/types';
import {getVersionByNum, VersionType} from '@caj/helper/version'; import {getVersionByNum, VersionType} from '@caj/helper/version';
import {User} from '@caj/user/types'; import {User} from '@caj/user/types';
import {UserId} from './types'; import {UserId} from './types';
@ -26,9 +26,9 @@ export interface NON_SAVE_VARS {
appStatus: appStatus; appStatus: appStatus;
connectionStatus: connectionStatus; connectionStatus: connectionStatus;
cachedUsers: {[key: UserId]: User}; cachedUsers: {[key: UserId]: User};
chats: {[key: chatId]: chatEntity}; chats: {[key: roomId]: chatEntity};
chatActivity: chatId[]; chatActivity: roomId[];
selectedChat: chatId | 'none'; selectedChat: roomId | 'none';
} }
export const non_save_vars: NON_SAVE_VARS = { export const non_save_vars: NON_SAVE_VARS = {

View File

@ -4,7 +4,7 @@ import type {PayloadAction} from '@reduxjs/toolkit';
import {appStatus, non_save_vars} from './appNonSaveVar'; import {appStatus, non_save_vars} from './appNonSaveVar';
import {User} from '@caj/user/types'; import {User} from '@caj/user/types';
import {UserId} from './types'; import {UserId} from './types';
import {chatEntity, chatId} from '@caj/components/chat/types'; import {chatEntity, roomId} from '@caj/components/chat/types';
export const appNonSaveVariablesSlice = createSlice({ export const appNonSaveVariablesSlice = createSlice({
name: 'non_save_vars', name: 'non_save_vars',
@ -19,29 +19,29 @@ export const appNonSaveVariablesSlice = createSlice({
removeCachedUser: (state, action: PayloadAction<UserId>) => { removeCachedUser: (state, action: PayloadAction<UserId>) => {
delete state.cachedUsers[action.payload]; delete state.cachedUsers[action.payload];
}, },
setSelectedChat: (state, action: PayloadAction<chatId>) => { setSelectedChat: (state, action: PayloadAction<roomId>) => {
state.selectedChat = action.payload; state.selectedChat = action.payload;
}, },
setChatEntity: (state, action: PayloadAction<chatEntity>) => { setChatEntity: (state, action: PayloadAction<chatEntity>) => {
const chatId = action.payload.id; const roomId = action.payload.roomId;
state.chats[chatId] = action.payload; state.chats[roomId] = action.payload;
if (state.chatActivity.includes(chatId) === false) if (state.chatActivity.includes(roomId) === false)
state.chatActivity.unshift(chatId); state.chatActivity.unshift(roomId);
}, },
changeChatEntity: (state, action: PayloadAction<chatEntity>) => { changeChatEntity: (state, action: PayloadAction<chatEntity>) => {
const chatId = action.payload.id; const roomId = action.payload.roomId;
state.chats[chatId] = action.payload; state.chats[roomId] = action.payload;
if (state.chatActivity.includes(chatId) === false) if (state.chatActivity.includes(roomId) === false)
state.chatActivity.unshift(chatId); state.chatActivity.unshift(roomId);
state.chatActivity.sort(function (x, y) { state.chatActivity.sort(function (x, y) {
return x == chatId ? -1 : y == chatId ? 1 : 0; return x == roomId ? -1 : y == roomId ? 1 : 0;
}); });
}, },
removeChatEntity: (state, action: PayloadAction<chatId>) => { removeChatEntity: (state, action: PayloadAction<roomId>) => {
delete state.chats[action.payload]; delete state.chats[action.payload];
state.chatActivity = state.chatActivity.filter(function (ele) { state.chatActivity = state.chatActivity.filter(function (ele) {

View File

@ -1,7 +1,7 @@
import {getDatabase} from './getDB'; import {getDatabase} from './getDB';
import {databaseConf, possibleDBKeys} from './types'; import {databaseConf, possibleDBKeys} from './types';
export const getEntry = async <T2 extends databaseConf<T>, T>( export const getEntry = async <T2 extends databaseConf<T, any>, T>(
schema: T2, schema: T2,
key: possibleDBKeys, key: possibleDBKeys,
): Promise<null | T> => { ): Promise<null | T> => {

View File

@ -1,7 +1,7 @@
import {getDatabase} from './getDB.web'; import {getDatabase} from './getDB.web';
import {databaseConf, possibleDBKeys} from './types'; import {databaseConf, possibleDBKeys} from './types';
export const getEntry = async <T2 extends databaseConf<T>, T>( export const getEntry = async <T2 extends databaseConf<T, any>, T>(
schema: T2, schema: T2,
key: possibleDBKeys, key: possibleDBKeys,
): Promise<null | T> => { ): Promise<null | T> => {

View File

@ -5,6 +5,7 @@ import {getKey} from './encryption';
import {databaseConf, databaseNames} from './types'; import {databaseConf, databaseNames} from './types';
import RNFS from 'react-native-fs'; import RNFS from 'react-native-fs';
import {databaseConfType} from './schemas';
const closeTimeout = 5; // in seconds // when DB read/writes is too long in idle it will be closed const closeTimeout = 5; // in seconds // when DB read/writes is too long in idle it will be closed
@ -12,7 +13,7 @@ type DBType = Realm;
export interface DBObject { export interface DBObject {
name: databaseNames; name: databaseNames;
schema: databaseConf<{[key: string]: string}>; schema: databaseConfType;
db: DBType | undefined; db: DBType | undefined;
lastUsedTimestamp?: timestamp; // when timeout is undefined then db is closed lastUsedTimestamp?: timestamp; // when timeout is undefined then db is closed
} }
@ -53,7 +54,7 @@ export function closeAllDatabases() {
} }
export async function openMyDatabase( export async function openMyDatabase(
schema: databaseConf<{[key: string]: string}>, schema: databaseConfType,
): Promise<DBType> { ): Promise<DBType> {
const folderPath = MyUserManager.getSelectedUserId(); const folderPath = MyUserManager.getSelectedUserId();
const path = folderPath + '/' + schema.filePath; const path = folderPath + '/' + schema.filePath;

View File

@ -1,6 +1,7 @@
import {timestamp} from '@caj/configs/types'; import {timestamp} from '@caj/configs/types';
import MyUserManager from '@caj/user/MyUserManager'; import MyUserManager from '@caj/user/MyUserManager';
import {IDBPDatabase, openDB} from 'idb'; import {IDBPDatabase, openDB} from 'idb';
import {databaseConfType} from './schemas';
import {databaseConf, databaseNames} from './types'; import {databaseConf, databaseNames} from './types';
const closeTimeout = 5; // in seconds // when DB read/writes is too long in idle it will be closed const closeTimeout = 5; // in seconds // when DB read/writes is too long in idle it will be closed
@ -9,7 +10,7 @@ type DBType = IDBPDatabase<unknown>;
export interface DBObject { export interface DBObject {
name: databaseNames; name: databaseNames;
schema: databaseConf<{[key: string]: string}>; schema: databaseConfType;
db: DBType | undefined; db: DBType | undefined;
lastUsedTimestamp?: timestamp; // when timeout is undefined then db is closed lastUsedTimestamp?: timestamp; // when timeout is undefined then db is closed
} }
@ -50,7 +51,7 @@ export function closeAllDatabases() {
} }
export async function openMyDatabase( export async function openMyDatabase(
schema: databaseConf<{[key: string]: string}>, schema: databaseConfType,
init?: boolean, init?: boolean,
): Promise<DBType> { ): Promise<DBType> {
const db = await openDB( const db = await openDB(

View File

@ -1,6 +1,7 @@
import {openDB, deleteDB, wrap, unwrap} from 'idb'; import {openDB, deleteDB, wrap, unwrap} from 'idb';
import {closeAllDatabases, databases, DBObject, getDatabase} from './getDB'; import {closeAllDatabases, databases, DBObject, getDatabase} from './getDB';
import DBSchemas from './schemas'; import DBSchemas from './schemas';
import {databaseConf} from './types';
export const initDatabase = (): Promise<void> => { export const initDatabase = (): Promise<void> => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {

View File

@ -3,7 +3,7 @@ import DBSchemas from './schemas';
import {databaseConf, databaseNames} from './types'; import {databaseConf, databaseNames} from './types';
export const DBMigration: {[key in databaseNames]: any} = { export const DBMigration: {[key in databaseNames]: any} = {
users: (Schema: databaseConf<typeof DBSchemas.users.defaultProps>) => { users: (Schema: typeof DBSchemas.users) => {
const callback: MigrationCallback = (oldRealm, newRealm) => { const callback: MigrationCallback = (oldRealm, newRealm) => {
/*// only apply this change if upgrading to schemaVersion 2 /*// only apply this change if upgrading to schemaVersion 2
if (oldRealm.schemaVersion < 2) { if (oldRealm.schemaVersion < 2) {
@ -20,7 +20,7 @@ export const DBMigration: {[key in databaseNames]: any} = {
return callback; return callback;
}, },
chat: (Schema: databaseConf<typeof DBSchemas.chat.defaultProps>) => { chat: (Schema: typeof DBSchemas.chat) => {
const callback: MigrationCallback = (oldRealm, newRealm) => { const callback: MigrationCallback = (oldRealm, newRealm) => {
/*// only apply this change if upgrading to schemaVersion 2 /*// only apply this change if upgrading to schemaVersion 2
if (oldRealm.schemaVersion < 2) { if (oldRealm.schemaVersion < 2) {
@ -35,6 +35,11 @@ export const DBMigration: {[key in databaseNames]: any} = {
}*/ }*/
}; };
return callback;
},
chatRoomInfos: (Schema: typeof DBSchemas.chatRoomInfos) => {
const callback: MigrationCallback = (oldRealm, newRealm) => {};
return callback; return callback;
}, },
}; };

View File

@ -21,7 +21,7 @@ type upgradeFunc = (
) => void; ) => void;
export const DBMigration: {[key in databaseNames]: any} = { export const DBMigration: {[key in databaseNames]: any} = {
users: (Schema: databaseConf<typeof DBSchemas.users.defaultProps>) => { users: (Schema: typeof DBSchemas.users) => {
const callback: upgradeFunc = ( const callback: upgradeFunc = (
db, db,
oldVersion, oldVersion,
@ -47,7 +47,33 @@ export const DBMigration: {[key in databaseNames]: any} = {
return callback; return callback;
}, },
chat: (Schema: databaseConf<typeof DBSchemas.chat.defaultProps>) => { chat: (Schema: typeof DBSchemas.chat) => {
const callback: upgradeFunc = (
db,
oldVersion,
newVersion,
transaction,
event,
) => {
if (oldVersion == 0) {
// perform the initialization
db.createObjectStore(Schema.details.name, {
keyPath: Schema.details.primaryKey,
});
} else if (newVersion !== null) {
let ver = oldVersion;
while (ver < newVersion) {
console.log('upgrade from v', ver, ' to v', ver + 1);
ver++;
}
}
};
return callback;
},
chatRoomInfos: (Schema: typeof DBSchemas.chatRoomInfos) => {
const callback: upgradeFunc = ( const callback: upgradeFunc = (
db, db,
oldVersion, oldVersion,

View File

@ -1,5 +1,7 @@
import chat from './schemas/chat'; import chat from './schemas/chat';
import users from './schemas/users'; import users from './schemas/users';
import chatRoomInfos from './schemas/chatRoomInfos';
const DBSchemas = {users, chat}; const DBSchemas = {users, chat, chatRoomInfos};
export default DBSchemas; export default DBSchemas;
export type databaseConfType = typeof DBSchemas[keyof typeof DBSchemas];

View File

@ -4,22 +4,28 @@ import {setEntry} from '../set';
import {databaseConf, possibleDBKeys} from '../types'; import {databaseConf, possibleDBKeys} from '../types';
enum keys {
UserId = 'a',
msg = 'b',
}
const name = 'chat'; const name = 'chat';
const primaryKey: keyof typeof propsDefault = 'UserId'; const primaryKey: keyof typeof propsDefault = keys.UserId;
const propsType: {[key in keyof typeof propsDefault]: string} = { const propsType: {[key in keyof typeof propsDefault]: string} = {
UserId: 'string', [keys.UserId]: 'string',
msg: 'string', [keys.msg]: 'string',
}; };
const propsDefault = { const propsDefault = {
UserId: 'test', [keys.UserId]: 'test',
msg: 'test', [keys.msg]: 'test',
}; };
const thisSchema: databaseConf<typeof propsDefault> = { const thisSchema: databaseConf<typeof propsDefault, typeof keys> = {
filePath: name, filePath: name,
version: 1, version: 1,
keys,
migration: () => { migration: () => {
return DBMigration[name](thisSchema); return DBMigration[name](thisSchema);
}, },

View File

@ -0,0 +1,61 @@
import {getEntry} from '../get';
import {DBMigration} from '../migration';
import {setEntry} from '../set';
import {databaseConf, possibleDBKeys} from '../types';
enum keys {
RoomId = 'a',
syncId = 'b',
initSyncId = 'c',
unreadMessages = 'd',
users = 'e',
}
const name = 'chatRoomInfos';
const primaryKey: keyof typeof propsDefault = keys.RoomId;
const propsType: {[key in keyof typeof propsDefault]: string} = {
[keys.RoomId]: 'string',
[keys.syncId]: 'int',
[keys.initSyncId]: 'int',
[keys.unreadMessages]: 'int',
[keys.users]: 'string[]',
};
const propsDefault = {
[keys.RoomId]: '',
[keys.syncId]: 0,
[keys.initSyncId]: 0,
[keys.unreadMessages]: 0,
[keys.users]: ['none'],
};
const thisSchema: databaseConf<typeof propsDefault, typeof keys> = {
filePath: name,
version: 1,
keys,
migration: () => {
return DBMigration[name](thisSchema);
},
setEntry: (val: typeof thisSchema.defaultProps) => {
return setEntry<typeof thisSchema, typeof thisSchema.defaultProps>(
thisSchema,
val,
);
},
getEntry: (key: possibleDBKeys) => {
return getEntry<typeof thisSchema, typeof thisSchema.defaultProps>(
thisSchema,
key,
);
},
defaultProps: propsDefault,
details: {
name,
properties: propsType,
primaryKey,
},
};
export default thisSchema;

View File

@ -4,43 +4,60 @@ import {setEntry} from '../set';
import {databaseConf, possibleDBKeys} from '../types'; import {databaseConf, possibleDBKeys} from '../types';
enum keys {
UserId = 'a',
AccountName = 'b',
Username = 'c',
Description = 'd',
FollowersCount = 'e',
FollowingCount = 'f',
lastUpdateTimestamp = 'g',
ProfilePicture = 'h',
ProfilePictureBinaryLQ = 'i',
ProfilePictureBinaryHQ = 'j',
XpLevel = 'k',
XpPoints = 'l',
}
const name = 'users'; const name = 'users';
const primaryKey: keyof typeof propsDefault = 'UserId'; const primaryKey: keyof typeof propsDefault = keys.UserId;
const propsType: {[key in keyof typeof propsDefault]: string} = { const propsType: {[key in keyof typeof propsDefault]: string} = {
UserId: 'string', [keys.UserId]: 'string',
AccountName: 'string', [keys.AccountName]: 'string',
Username: 'string', [keys.Username]: 'string',
Description: 'string', [keys.Description]: 'string',
FollowersCount: 'int', [keys.FollowersCount]: 'int',
FollowingCount: 'int', [keys.FollowingCount]: 'int',
lastUpdateTimestamp: 'int', [keys.lastUpdateTimestamp]: 'int',
ProfilePicture: 'string', //URL [keys.ProfilePicture]: 'string', //URL
ProfilePictureBinaryLQ: 'data', [keys.ProfilePictureBinaryLQ]: 'data',
ProfilePictureBinaryHQ: 'data', [keys.ProfilePictureBinaryHQ]: 'data',
XpLevel: 'int', [keys.XpLevel]: 'int',
XpPoints: 'int', [keys.XpPoints]: 'int',
}; };
const propsDefault = { const propsDefault = {
UserId: '', [keys.UserId]: '',
AccountName: '', [keys.AccountName]: '',
Username: '', [keys.Username]: '',
Description: '', [keys.Description]: '',
FollowersCount: 0, [keys.FollowersCount]: 0,
FollowingCount: 0, [keys.FollowingCount]: 0,
lastUpdateTimestamp: 0, [keys.lastUpdateTimestamp]: 0,
ProfilePicture: '', //URL [keys.ProfilePicture]: '', //URL
ProfilePictureBinaryLQ: new ArrayBuffer(0), [keys.ProfilePictureBinaryLQ]: new ArrayBuffer(0),
ProfilePictureBinaryHQ: new ArrayBuffer(0), [keys.ProfilePictureBinaryHQ]: new ArrayBuffer(0),
XpLevel: 0, [keys.XpLevel]: 0,
XpPoints: 0, [keys.XpPoints]: 0,
}; };
const thisSchema: databaseConf<typeof propsDefault> = { const thisSchema: databaseConf<typeof propsDefault, typeof keys> = {
filePath: name, filePath: name,
version: 1, version: 1,
keys,
migration: () => { migration: () => {
return DBMigration[name](thisSchema); return DBMigration[name](thisSchema);
}, },

View File

@ -1,7 +1,7 @@
import {getDatabase} from './getDB'; import {getDatabase} from './getDB';
import {databaseConf} from './types'; import {databaseConf} from './types';
export const setEntry = async <T2 extends databaseConf<T>, T>( export const setEntry = async <T2 extends databaseConf<T, any>, T>(
schema: T2, schema: T2,
value: T, value: T,
) => { ) => {

View File

@ -1,7 +1,7 @@
import {getDatabase} from './getDB.web'; import {getDatabase} from './getDB.web';
import {databaseConf} from './types'; import {databaseConf} from './types';
export const setEntry = async <T2 extends databaseConf<T>, T>( export const setEntry = async <T2 extends databaseConf<T, any>, T>(
schema: T2, schema: T2,
value: T, value: T,
) => { ) => {

View File

@ -1,10 +1,11 @@
export type databaseNames = 'users' | 'chat'; export type databaseNames = 'users' | 'chat' | 'chatRoomInfos';
export type possibleDBKeys = string; export type possibleDBKeys = string;
export interface databaseConf<props> { export interface databaseConf<props, enums> {
filePath: string; filePath: string;
version: number; version: number;
migration?: any; migration?: any;
keys: enums;
getEntry: (key: possibleDBKeys) => Promise<props | null>; getEntry: (key: possibleDBKeys) => Promise<props | null>;
setEntry: (val: props) => Promise<void>; setEntry: (val: props) => Promise<void>;
defaultProps: props; defaultProps: props;

View File

@ -10,8 +10,11 @@ import {
createNativeStackNavigator, createNativeStackNavigator,
NativeStackNavigationProp, NativeStackNavigationProp,
} from '@react-navigation/native-stack'; } from '@react-navigation/native-stack';
import {Box, Center, Container, Text} from 'native-base'; import {Box, Button, Center, Container, Text} from 'native-base';
import {useSelector} from 'react-redux'; import {useSelector} from 'react-redux';
import initChatDatabase from '@caj/components/chat/initChatDatabase';
import MyUserManager from '@caj/user/MyUserManager';
import {chatTags} from '@caj/components/chat/types';
export const AccountTabName = 'Account'; export const AccountTabName = 'Account';
@ -66,6 +69,35 @@ function AccountScreen() {
<MyUserAccountInfoBanner /> <MyUserAccountInfoBanner />
</Box> </Box>
<NotLoggedIn /> <NotLoggedIn />
<Center mt={100}>
<Button
w="72"
colorScheme="primary"
rounded="xl"
_text={{fontSize: 'xl'}}
onPress={() => {
initChatDatabase({
roomId: MyUserManager.getSelectedUserId(),
users: [MyUserManager.getSelectedUserId()],
initSyncId: 0,
syncId: 10,
tags: [chatTags.GOOD_FRIEND],
unreadMessages: 1234,
});
initChatDatabase({
roomId: 'test',
users: ['test'],
initSyncId: 0,
syncId: 0,
tags: [chatTags.GROUP, chatTags.GOOD_FRIEND, chatTags.FRIEND],
unreadMessages: 0,
});
}}>
Init Chats
</Button>
</Center>
</> </>
); );
} }

View File

@ -57,37 +57,58 @@ async function getUser(
} }
if (user === undefined) { if (user === undefined) {
const usrDBKeys = BigDataManager.databases.users.keys;
const usr = await BigDataManager.databases.users.getEntry(UserId); const usr = await BigDataManager.databases.users.getEntry(UserId);
if (usr !== undefined && usr !== null) { if (usr !== undefined && usr !== null) {
let ProfilePicture = { let ProfilePicture = {
lq: lq:
usr.ProfilePictureBinaryLQ.byteLength !== 0 usr[usrDBKeys.ProfilePictureBinaryLQ].byteLength !== 0
? createUserProp( ? createUserProp(
SourceProp.offline, SourceProp.offline,
new Blob([usr.ProfilePictureBinaryLQ]), new Blob([usr[usrDBKeys.ProfilePictureBinaryLQ]]),
) )
: createUserProp(SourceProp.online, undefined, usr.ProfilePicture), : createUserProp(
SourceProp.online,
undefined,
usr[usrDBKeys.ProfilePicture],
),
hq: hq:
usr.ProfilePictureBinaryHQ.byteLength !== 0 usr[usrDBKeys.ProfilePictureBinaryHQ].byteLength !== 0
? createUserProp( ? createUserProp(
SourceProp.offline, SourceProp.offline,
new Blob([usr.ProfilePictureBinaryHQ]), new Blob([usr[usrDBKeys.ProfilePictureBinaryHQ]]),
) )
: createUserProp(SourceProp.online, undefined, usr.ProfilePicture), : createUserProp(
SourceProp.online,
undefined,
usr[usrDBKeys.ProfilePicture],
),
}; };
user = { user = {
AccountName: createUserProp(SourceProp.offline, usr.AccountName), AccountName: createUserProp(
Description: createUserProp(SourceProp.offline, usr.Description), SourceProp.offline,
FollowersCount: createUserProp(SourceProp.offline, usr.FollowersCount), usr[usrDBKeys.AccountName],
FollowingCount: createUserProp(SourceProp.offline, usr.FollowingCount), ),
lastUpdateTimestamp: usr.lastUpdateTimestamp, Description: createUserProp(
SourceProp.offline,
usr[usrDBKeys.Description],
),
FollowersCount: createUserProp(
SourceProp.offline,
usr[usrDBKeys.FollowersCount],
),
FollowingCount: createUserProp(
SourceProp.offline,
usr[usrDBKeys.FollowingCount],
),
lastUpdateTimestamp: usr[usrDBKeys.lastUpdateTimestamp],
ProfilePicture, ProfilePicture,
UserId, UserId,
Username: createUserProp(SourceProp.offline, usr.Username), Username: createUserProp(SourceProp.offline, usr[usrDBKeys.Username]),
XpLevel: createUserProp(SourceProp.offline, usr.XpLevel), XpLevel: createUserProp(SourceProp.offline, usr[usrDBKeys.XpLevel]),
XpPoints: createUserProp(SourceProp.offline, usr.XpPoints), XpPoints: createUserProp(SourceProp.offline, usr[usrDBKeys.XpPoints]),
}; };
} }
} }

View File

@ -1,5 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"outDir": "./dist",
"baseUrl": ".", "baseUrl": ".",
"paths" : { "paths" : {
"@caj/*": ["src/caj/*"] "@caj/*": ["src/caj/*"]