MM_30478 [v2] Database Manager (#5130)

* MM_30475 : ADDED default schema

* MM_30475 : ADDED todo for field 'value' of default/Global entity

* MM_30476 : Created schema for SERVER DB

* MM_30476 : Server model [ IN PROGRESS ]

* MM_30476 : Including types for group, groups_in_channel and role

* MM_30476 : ADDED models for Group

- @typings absolute path has been added to the tsconfig.json

* MM_30476 : ADDED typings to current models

* MM_30476 : ADDED typings to current models

* MM_30476 : ADDED models related to TEAM section of the ERD

* MM_30476 : ADDED models for User section of the ERD

* MM_30476 : ADDED models for POST section of the ERD

* MM_30476 : ADDED models for Channel section of the ERD

* MM_30475 : Updated typings and references to MM_TABLES

* MM_30476 : Verified all field names

* MM_30476 : Verified every table associations

* MM_30476 : Verified all relation fields

* MM_30476 : Updated primary id of the main models

We will override the wdb id at component level when we create a new records.  This involves the models : channel, group, post, team and user.

* MM_30476 : Including 1:1 relationship amongs some entities

* MM_30476 : ADDED Schema Managers

* The migration array will hold all the migration steps.

*  The initial app release (e.g. v2 )will have an empty array and subsequent releases  (e.g.  v2.1 ) will have the steps listed in that array.

* On initialization, the database will perform the migration to accomodate for new columns/tables creation and while it will conserve the mobile phone's data, it will also make it conform to this new schema.

* If a migration fails, the migration process will rollback any changes.  This migration will be thoroughly tested in development before pushing it live.

* Revert "MM_30476 : ADDED Schema Managers"

This reverts commit a505bd5e11124e8eb8f258ce8dbb8168a535f7ae.

* MM_30478 : Converted schema_manager into a function

* MM_30478 : Updated schema manager and included patch for wdb

* MM_30478:  Updated watermelondb patch package

* MM_30478 : Update function create_schema_manager to createSqliteAdaptorOptions

* MM_30476 : Update constant name to reflect directory name

* MM_30476 : Updated msgCount from my_channel model to message_count in server schema

* MM_30482 : Added tests for schema_manager

* MM_30482 : Database Manager [ IN PROGRESS ]

* MM_30478 : Returning an sqliteAdapter instead of an object

* MM_30476 : Apply suggestions from code review

Co-authored-by: Elias Nahum <nahumhbl@gmail.com>

* MM_30476 : Updated all imports as per instruction.

* MM_30476 : Shortening object chains by destructuring

* MM_30476 : Updated schema file structure

* MM_30476 : Prettifying @typings folder

* MM_30476 : Removing useless ids

* MM_30476 : Prettify imports for decorators

* MM_30476 : ADDED documentations and lazy queries to Channel and Channel_Info

* MM_30476 : ADDED documentations for default schema

* MM_30476 : Documentation [ IN PROGRESS ]

- Following JSDoc syntax for single line comment
- Removed redundant fields in the 'membership' tables and left only the @relation records.

* MM_30476 : Documentations [ IN PROGRESS ]

* MM_30476 : Documentations [ IN PROGRESS ]

* MM_30476 : Documentations [ IN PROGRESS ]

* MM_30476 : Documentations [ IN PROGRESS]

Updated
1)  my_team and team,
2) my_channel and  channel,

to each have 1:1 relationship  with one another

* MM_30476 : Updated all Typescript definitions

* MM_30476 :Updated @relation to @immutableRelation

* MM_30476 : Updated description for previous_post_id

* MM_30478 : Updated patch package for wdb module

* MM_30478: DB Manager [IN PROGRESS ]

* MM_30478: DB Manager [IN PROGRESS]

* MM_30478: DB Manager [IN PROGRESS]

* MM_30478 : DB Manager [IN PROGRESS]

* MM_30478 : Deleting .db file on iOS

* MM_30478: Successfully deleting .db files and directory on iOS side

* MM_30478 : Update definition for default/global

* MM_30478 : Updated all models

* MM_30478 : Doing a bit of house cleaning

* MM_30478: Record of new server connection  added to default/servers db

* TS Definitely Typed Assignment issue is now FIXED

* MM_30478 : TS Definitely Typed Assignment \n  Removed all the constructors but error still in editor tabs.  But this time the app is not crashing

* MM_30478 : Attempt 1 [SUCCESSFUL]

* MM_30478 : Removing useDefineForClassFields

* MM_30478 : Retrieving the servers in a list + Improved the DB Manager and Babel config

* MM_30478 : Updated babel.config.js

* MM_30478 : Minor UI correction

* MM_30478 : Jest and Typescript configuration

* MM_30478 : A bit of housekeeping

* MM_30478 : Installed WDB on Android

* MM_30478 : Deletes new server record from default DB

* MM_30478 : Returns subset of server db instances

* MM_30478 : Code clean up

* MM_30478 :  Code clean up on db manager

* MM_30478 : House keeping + Patch for WDB

* MM_30478 : Android - Saving & Deleting in FilesDir [COMPLETED]

* MM_30478 : Code clean up

* MM_30478 : Code clean up

* MM_30478 : Code clean up

* MM_30478 : Test successful on Android device

* MM_30478 : Rolling back change to jest.config.js

* MM_30478 : Updated test to test_integration

* MM_30478 : Fix imports

* MM_30478 : Refactored the manual testscript

* MM_30478 : Renamed database manager test file

* MM_30478 : Code clean up

* MM_30478 : Updated manual test file with a note.

* MM_30478 : Fixed JEST issue with TS

* MM_30478 : Fixed JEST issue with TS

* MM_30478 : Fixed JEST issue with TS

* MM_30478 : Implementing JEST test cases

* MM_30478 : Implementing JEST last  test cases

* MM_30478 : Jest fixing ts errors

* MM_30478 : Database Manager Jest testing [ IN PROGRESS ]

* Update mobile v2 detox deps

* MM_30478 : Add uniqueness check for duplicates server creation

* MM_30478 : Corrections from Joseph reviews

Co-authored-by: Elias Nahum <nahumhbl@gmail.com>
Co-authored-by: Avinash Lingaloo <>
Co-authored-by: Joseph Baylon <joseph.baylon@mattermost.com>
This commit is contained in:
Avinash Lingaloo 2021-02-12 00:52:23 +04:00 committed by GitHub
parent 619503eedb
commit d88b0f30b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 8219 additions and 608 deletions

View file

@ -45,7 +45,8 @@
"@typescript-eslint/no-use-before-define": 0,
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-module-boundary-types": "off"
"@typescript-eslint/explicit-module-boundary-types": "off",
"no-underscore-dangle": "off"
},
"overrides": [
{

View file

@ -1,6 +1,6 @@
apply plugin: "com.android.application"
apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply plugin: 'kotlin-android'
import com.android.build.OutputFile
/**
@ -269,6 +269,8 @@ dependencies {
implementation 'com.facebook.fresco:webpsupport:2.0.0'
androidTestImplementation('com.wix:detox:+')
implementation project(':watermelondb')
}
// Run this once to be able to run the application with BUCK

View file

@ -47,6 +47,8 @@ import org.unimodules.adapters.react.ModuleRegistryAdapter;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.SingletonModule;
import com.nozbe.watermelondb.WatermelonDBPackage;
public class MainApplication extends NavigationApplication implements INotificationsApplication, INotificationsDrawerApplication {
public static MainApplication instance;
@ -78,6 +80,7 @@ public class MainApplication extends NavigationApplication implements INotificat
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new RNNotificationsPackage(MainApplication.this));
packages.add(new WatermelonDBPackage());
// Add unimodules
List<ReactPackage> unimodules = Arrays.<ReactPackage>asList(

View file

@ -8,9 +8,9 @@ buildscript {
targetSdkVersion = 29
supportLibVersion = "28.0.0"
kotlinVersion = "1.3.61"
kotlin_version = "1.3.61"
firebaseVersion = "21.0.0"
RNNKotlinVersion = kotlinVersion
}
repositories {
jcenter()
@ -64,7 +64,7 @@ allprojects {
maven {
url "https://www.jitpack.io"
}
maven {
maven {
url ("https://dl.bintray.com/rudderstack/rudderstack")
}
maven {

View file

@ -4,3 +4,6 @@ project(':reactnativenotifications').projectDir = new File(rootProject.projectDi
apply from: '../node_modules/react-native-unimodules/gradle.groovy'; includeUnimodulesProjects()
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
include ':watermelondb'
project(':watermelondb').projectDir =
new File(rootProject.projectDir, '../node_modules/@nozbe/watermelondb/native/android')

View file

@ -1,6 +1,8 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import keyMirror from '@utils/key_mirror';
export const MM_TABLES = {
DEFAULT: {
APP: 'app',
@ -39,6 +41,13 @@ export const MM_TABLES = {
},
};
export const MIGRATION_EVENTS = keyMirror({
MIGRATION_ERROR: null,
MIGRATION_STARTED: null,
MIGRATION_SUCCESS: null,
});
export default {
MM_TABLES,
MIGRATION_EVENTS,
};

View file

@ -2,6 +2,7 @@
// See LICENSE.txt for license information.
import Attachment from './attachment';
import Database from './database';
import DeepLink from './deep_linking';
import Device from './device';
import List from './list';
@ -13,6 +14,7 @@ import WebsocketEvents from './websocket';
export {
Attachment,
Database,
DeepLink,
Device,
List,

View file

@ -0,0 +1,319 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Database, Model, Q} from '@nozbe/watermelondb';
import LokiJSAdapter from '@nozbe/watermelondb/adapters/lokijs';
import {Class} from '@nozbe/watermelondb/utils/common';
import {MM_TABLES} from '@constants/database';
import type {DBInstance, DefaultNewServer, MMDatabaseConnection} from '@typings/database/database';
import IServers from '@typings/database/servers';
import DefaultMigration from '../../../default/migration';
import {App, Global, Servers} from '../../../default/models';
import {defaultSchema} from '../../../default/schema';
import ServerMigration from '../../../server/migration';
import {
Channel,
ChannelInfo,
ChannelMembership,
CustomEmoji,
Draft,
File,
Group,
GroupMembership,
GroupsInChannel,
GroupsInTeam,
MyChannel,
MyChannelSettings,
MyTeam,
Post,
PostMetadata,
PostsInChannel,
PostsInThread,
Preference,
Reaction,
Role,
SlashCommand,
System,
Team,
TeamChannelHistory,
TeamMembership,
TeamSearchHistory,
TermsOfService,
User,
} from '../../../server/models';
import {serverSchema} from '../../../server/schema';
const {SERVERS} = MM_TABLES.DEFAULT;
type Models = Class<Model>[]
// The elements needed to create a new connection
type DatabaseConnection = {
databaseConnection: MMDatabaseConnection, shouldAddToDefaultDatabase
: boolean
}
// The elements required to switch to another active server database
type ActiveServerDatabase = { displayName: string, serverUrl: string }
// The only two types of databases in the app
export enum DatabaseType {
DEFAULT,
SERVER
}
class DatabaseManager {
private activeDatabase: DBInstance;
private defaultDatabase: DBInstance;
private readonly defaultModels: Models;
private readonly iOSAppGroupDatabase: string | null;
private readonly androidFilesDirectory: string | null;
private readonly serverModels: Models;
constructor() {
this.defaultModels = [App, Global, Servers];
this.serverModels = [Channel, ChannelInfo, ChannelMembership, CustomEmoji, Draft, File, Group, GroupMembership,
GroupsInChannel, GroupsInTeam, MyChannel, MyChannelSettings, MyTeam, Post, PostMetadata, PostsInChannel,
PostsInThread, Preference, Reaction, Role, SlashCommand, System, Team, TeamChannelHistory, TeamMembership,
TeamSearchHistory, TermsOfService, User];
this.iOSAppGroupDatabase = null;
this.androidFilesDirectory = null;
}
/**
* createDatabaseConnection: Creates database connection and registers the new connection into the default database. However,
* if a database connection could not be created, it will return undefined.
* @param {MMDatabaseConnection} databaseConnection
* @param {boolean} shouldAddToDefaultDatabase
*
* @returns {Promise<DBInstance>}
*/
createDatabaseConnection = async ({
databaseConnection,
shouldAddToDefaultDatabase = true,
}: DatabaseConnection): Promise<DBInstance> => {
const {
actionsEnabled = true,
dbName = 'default',
dbType = DatabaseType.DEFAULT,
serverUrl = undefined,
} = databaseConnection;
try {
const databaseName = dbType === DatabaseType.DEFAULT ? 'default' : dbName;
// const databaseFilePath = this.getDatabaseDirectory(databaseName);
const migrations = dbType === DatabaseType.DEFAULT ? DefaultMigration : ServerMigration;
const modelClasses = dbType === DatabaseType.DEFAULT ? this.defaultModels : this.serverModels;
const schema = dbType === DatabaseType.DEFAULT ? defaultSchema : serverSchema;
const adapter = new LokiJSAdapter({
dbName: databaseName,
migrations,
schema,
});
// Registers the new server connection into the DEFAULT database
if (serverUrl && shouldAddToDefaultDatabase) {
await this.addServerToDefaultDatabase({databaseFilePath: databaseName, displayName: dbName, serverUrl});
}
return new Database({adapter, actionsEnabled, modelClasses});
} catch (e) {
// console.log(e);
}
return undefined;
};
/**
* setActiveServerDatabase: Set the new active server database. The serverUrl is used to ensure that we do not duplicate entries in the default database.
* This method should be called when switching to another server.
* @param {string} displayName
* @param {string} serverUrl
* @returns {Promise<void>}
*/
setActiveServerDatabase = async ({displayName, serverUrl}: ActiveServerDatabase) => {
const isServerPresent = await this.isServerPresent(serverUrl);
this.activeDatabase = await this.createDatabaseConnection({
databaseConnection: {
actionsEnabled: true,
dbName: displayName,
dbType: DatabaseType.SERVER,
serverUrl,
},
shouldAddToDefaultDatabase: Boolean(!isServerPresent),
});
};
/**
* isServerPresent : Confirms if the current serverUrl does not already exist in the database
* @param {String} serverUrl
* @returns {Promise<boolean>}
*/
isServerPresent = async (serverUrl: String) => {
const allServers = await this.getAllServers();
const existingServer = allServers?.filter((server) => {
return server.url === serverUrl;
});
return existingServer && existingServer.length > 0;
}
/**
* getActiveServerDatabase: The DatabaseManager should be the only one setting the active database. Hence, we have made the activeDatabase property private.
* Use this getter method to retrieve the active database if it has been set in your code.
* @returns {DBInstance}
*/
getActiveServerDatabase = (): DBInstance => {
return this.activeDatabase;
};
/**
* getDefaultDatabase : Returns the default database.
* @returns {Database} default database
*/
getDefaultDatabase = async (): Promise<DBInstance> => {
if (!this.defaultDatabase) {
await this.setDefaultDatabase();
}
return this.defaultDatabase;
};
/**
* retrieveDatabaseInstances: Using an array of server URLs, this method creates a database connection for each URL
* and return them to the caller.
*
* @param {string[]} serverUrls
* @returns {Promise<{url: string, dbInstance: DBInstance}[] | null>}
*/
retrieveDatabaseInstances = async (serverUrls?: string[]): Promise<{ url: string, dbInstance: DBInstance }[] | null> => {
if (serverUrls?.length) {
// Retrieve all server records from the default db
const allServers = await this.getAllServers();
// Filter only those servers that are present in the serverUrls array
const servers = allServers!.filter((server: IServers) => {
return serverUrls.includes(server.url);
});
// Creates server database instances
if (servers.length) {
const databasePromises = servers.map(async (server: IServers) => {
const {displayName, url} = server;
const databaseConnection = {
actionsEnabled: true,
dbName: displayName,
dbType: DatabaseType.SERVER,
serverUrl: url,
};
// Since we are retrieving existing URL ( and so database connections ) from the 'DEFAULT' database, shouldAddToDefaultDatabase is set to false
const dbInstance = await this.createDatabaseConnection({
databaseConnection,
shouldAddToDefaultDatabase: false,
});
return {url, dbInstance};
});
const databaseInstances = await Promise.all(databasePromises);
return databaseInstances;
}
return null;
}
return null;
};
/**
* deleteDatabase: Removes the *.db file from the App-Group directory for iOS or the files directory on Android.
* Also, it removes its entry in the 'servers' table from the DEFAULT database
* @param {string} serverUrl
* @returns {Promise<boolean>}
*/
deleteDatabase = async (serverUrl: string): Promise<boolean> => {
try {
const defaultDB = await this.getDefaultDatabase();
let server: IServers;
if (defaultDB) {
const serversRecords = await defaultDB.collections.get(SERVERS).query(Q.where('url', serverUrl)).fetch() as IServers[];
server = serversRecords?.[0] ?? undefined;
if (server) {
// Perform a delete operation for this server record on the 'servers' table in default database
await defaultDB.action(async () => {
await server.destroyPermanently();
});
return true;
}
return false;
}
return false;
} catch (e) {
// console.log('An error occurred while trying to delete database with name ', databaseName);
return false;
}
};
/**
* getAllServers : Retrieves all the servers registered in the default database
* @returns {Promise<undefined | Servers[]>}
*/
private getAllServers = async () => {
// Retrieve all server records from the default db
const defaultDatabase = await this.getDefaultDatabase();
const allServers = defaultDatabase && await defaultDatabase.collections.get(MM_TABLES.DEFAULT.SERVERS).query().fetch() as IServers[];
return allServers;
};
/**
* setDefaultDatabase : Sets the default database.
* @returns {Promise<DBInstance>}
*/
private setDefaultDatabase = async (): Promise<DBInstance> => {
this.defaultDatabase = await this.createDatabaseConnection({
databaseConnection: {dbName: 'default'},
shouldAddToDefaultDatabase: false,
});
return this.defaultDatabase;
};
/**
* addServerToDefaultDatabase: Adds a record into the 'default' database - into the 'servers' table - for this new server connection
* @param {string} databaseFilePath
* @param {string} displayName
* @param {string} serverUrl
* @returns {Promise<void>}
*/
private addServerToDefaultDatabase = async ({
databaseFilePath,
displayName,
serverUrl,
}: DefaultNewServer) => {
try {
const defaultDatabase = await this.getDefaultDatabase();
const isServerPresent = await this.isServerPresent(serverUrl);
if (defaultDatabase && !isServerPresent) {
await defaultDatabase.action(async () => {
const serversCollection = defaultDatabase.collections.get('servers');
await serversCollection.create((server: IServers) => {
server.dbPath = databaseFilePath;
server.displayName = displayName;
server.mentionCount = 0;
server.unreadCount = 0;
server.url = serverUrl;
});
});
}
} catch (e) {
// console.log({catchError: e});
}
};
}
export default new DatabaseManager();

View file

@ -0,0 +1,401 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Database, Model, Q} from '@nozbe/watermelondb';
import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
import {Class} from '@nozbe/watermelondb/utils/common';
import {DeviceEventEmitter, Platform} from 'react-native';
import {FileSystem} from 'react-native-unimodules';
import {MIGRATION_EVENTS, MM_TABLES} from '@constants/database';
import type {DBInstance, DefaultNewServer, MigrationEvents, MMDatabaseConnection} from '@typings/database/database';
import IServers from '@typings/database/servers';
import {deleteIOSDatabase, getIOSAppGroupDetails} from '@utils/mattermost_managed';
import DefaultMigration from '../../default/migration';
import {App, Global, Servers} from '../../default/models';
import {defaultSchema} from '../../default/schema';
import ServerMigration from '../../server/migration';
import {
Channel,
ChannelInfo,
ChannelMembership,
CustomEmoji,
Draft,
File,
Group,
GroupMembership,
GroupsInChannel,
GroupsInTeam,
MyChannel,
MyChannelSettings,
MyTeam,
Post,
PostMetadata,
PostsInChannel,
PostsInThread,
Preference,
Reaction,
Role,
SlashCommand,
System,
Team,
TeamChannelHistory,
TeamMembership,
TeamSearchHistory,
TermsOfService,
User,
} from '../../server/models';
import {serverSchema} from '../../server/schema';
const {SERVERS} = MM_TABLES.DEFAULT;
type Models = Class<Model>[]
// The elements needed to create a new connection
type DatabaseConnection = {
databaseConnection: MMDatabaseConnection, shouldAddToDefaultDatabase
: boolean
}
// The elements required to switch to another active server database
type ActiveServerDatabase = { displayName: string, serverUrl: string }
// The only two types of databases in the app
export enum DatabaseType {
DEFAULT,
SERVER
}
class DatabaseManager {
private activeDatabase: DBInstance;
private defaultDatabase: DBInstance;
private readonly defaultModels: Models;
private readonly iOSAppGroupDatabase: string | null;
private readonly androidFilesDirectory: string | null;
private readonly serverModels: Models;
constructor() {
this.defaultModels = [App, Global, Servers];
this.serverModels = [Channel, ChannelInfo, ChannelMembership, CustomEmoji, Draft, File, Group, GroupMembership,
GroupsInChannel, GroupsInTeam, MyChannel, MyChannelSettings, MyTeam, Post, PostMetadata, PostsInChannel,
PostsInThread, Preference, Reaction, Role, SlashCommand, System, Team, TeamChannelHistory, TeamMembership,
TeamSearchHistory, TermsOfService, User];
this.iOSAppGroupDatabase = Platform.OS === 'ios' ? getIOSAppGroupDetails().appGroupDatabase : null;
this.androidFilesDirectory = Platform.OS === 'android' ? FileSystem.documentDirectory : null;
}
/**
* createDatabaseConnection: Creates database connection and registers the new connection into the default database. However,
* if a database connection could not be created, it will return undefined.
* @param {MMDatabaseConnection} databaseConnection
* @param {boolean} shouldAddToDefaultDatabase
*
* @returns {Promise<DBInstance>}
*/
createDatabaseConnection = async ({
databaseConnection,
shouldAddToDefaultDatabase = true,
}: DatabaseConnection): Promise<DBInstance> => {
const {
actionsEnabled = true,
dbName = 'default',
dbType = DatabaseType.DEFAULT,
serverUrl = undefined,
} = databaseConnection;
try {
const databaseName = dbType === DatabaseType.DEFAULT ? 'default' : dbName;
const databaseFilePath = this.getDatabaseDirectory(databaseName);
const migrations = dbType === DatabaseType.DEFAULT ? DefaultMigration : ServerMigration;
const modelClasses = dbType === DatabaseType.DEFAULT ? this.defaultModels : this.serverModels;
const schema = dbType === DatabaseType.DEFAULT ? defaultSchema : serverSchema;
const adapter = new SQLiteAdapter({
dbName: databaseFilePath,
migrationEvents: this.buildMigrationCallbacks(databaseName),
migrations,
schema,
});
// Registers the new server connection into the DEFAULT database
if (serverUrl && shouldAddToDefaultDatabase) {
await this.addServerToDefaultDatabase({databaseFilePath, displayName: dbName, serverUrl});
}
return new Database({adapter, actionsEnabled, modelClasses});
} catch (e) {
// console.log(e);
}
return undefined;
};
/**
* setActiveServerDatabase: Set the new active server database. The serverUrl is used to ensure that we do not duplicate entries in the default database.
* This method should be called when switching to another server.
* @param {string} displayName
* @param {string} serverUrl
* @returns {Promise<void>}
*/
setActiveServerDatabase = async ({displayName, serverUrl}: ActiveServerDatabase) => {
const isServerPresent = await this.isServerPresent(serverUrl);
this.activeDatabase = await this.createDatabaseConnection({
databaseConnection: {
actionsEnabled: true,
dbName: displayName,
dbType: DatabaseType.SERVER,
serverUrl,
},
shouldAddToDefaultDatabase: Boolean(!isServerPresent),
});
};
/**
* isServerPresent : Confirms if the current serverUrl does not already exist in the database
* @param {String} serverUrl
* @returns {Promise<boolean>}
*/
isServerPresent = async (serverUrl: String) => {
const allServers = await this.getAllServers();
const existingServer = allServers?.filter((server) => {
return server.url === serverUrl;
});
return existingServer && existingServer.length > 0;
}
/**
* getActiveServerDatabase: The DatabaseManager should be the only one setting the active database. Hence, we have made the activeDatabase property private.
* Use this getter method to retrieve the active database if it has been set in your code.
* @returns {DBInstance}
*/
getActiveServerDatabase = (): DBInstance => {
return this.activeDatabase;
};
/**
* getDefaultDatabase : Returns the default database.
* @returns {Database} default database
*/
getDefaultDatabase = async (): Promise<DBInstance> => {
if (!this.defaultDatabase) {
await this.setDefaultDatabase();
}
return this.defaultDatabase;
};
/**
* retrieveDatabaseInstances: Using an array of server URLs, this method creates a database connection for each URL
* and return them to the caller.
*
* @param {string[]} serverUrls
* @returns {Promise<{url: string, dbInstance: DBInstance}[] | null>}
*/
retrieveDatabaseInstances = async (serverUrls?: string[]): Promise<{ url: string, dbInstance: DBInstance }[] | null> => {
if (serverUrls?.length) {
// Retrieve all server records from the default db
const allServers = await this.getAllServers();
// Filter only those servers that are present in the serverUrls array
const servers = allServers!.filter((server: IServers) => {
return serverUrls.includes(server.url);
});
// Creates server database instances
if (servers.length) {
const databasePromises = servers.map(async (server: IServers) => {
const {displayName, url} = server;
const databaseConnection = {
actionsEnabled: true,
dbName: displayName,
dbType: DatabaseType.SERVER,
serverUrl: url,
};
// Since we are retrieving existing URL ( and so database connections ) from the 'DEFAULT' database, shouldAddToDefaultDatabase is set to false
const dbInstance = await this.createDatabaseConnection({
databaseConnection,
shouldAddToDefaultDatabase: false,
});
return {url, dbInstance};
});
const databaseInstances = await Promise.all(databasePromises);
return databaseInstances;
}
return null;
}
return null;
};
/**
* deleteDatabase: Removes the *.db file from the App-Group directory for iOS or the files directory on Android.
* Also, it removes its entry in the 'servers' table from the DEFAULT database
* @param {string} serverUrl
* @returns {Promise<boolean>}
*/
deleteDatabase = async (serverUrl: string): Promise<boolean> => {
try {
const defaultDB = await this.getDefaultDatabase();
let server: IServers;
if (defaultDB) {
const serversRecords = await defaultDB.collections.get(SERVERS).query(Q.where('url', serverUrl)).fetch() as IServers[];
server = serversRecords?.[0] ?? undefined;
if (server) {
// Perform a delete operation for this server record on the 'servers' table in default database
await defaultDB.action(async () => {
await server.destroyPermanently();
});
const databaseName = server.displayName;
if (Platform.OS === 'ios') {
// On iOS, we'll delete the *.db file under the shared app-group/databases folder
deleteIOSDatabase({databaseName});
return true;
}
// On Android, we'll delete both the *.db file and the *.db-journal file
const androidFilesDir = `${this.androidFilesDirectory}databases/`;
const databaseFile = `${androidFilesDir}${databaseName}.db`;
const databaseJournal = `${androidFilesDir}${databaseName}.db-journal`;
await FileSystem.deleteAsync(databaseFile);
await FileSystem.deleteAsync(databaseJournal);
return true;
}
return false;
}
return false;
} catch (e) {
// console.log('An error occurred while trying to delete database with name ', databaseName);
return false;
}
};
/**
* factoryReset: Removes the databases directory and all its contents on the respective platform
* @param {boolean} shouldRemoveDirectory
* @returns {Promise<boolean>}
*/
factoryReset = async (shouldRemoveDirectory: boolean): Promise<boolean> => {
try {
//On iOS, we'll delete the databases folder under the shared AppGroup folder
if (Platform.OS === 'ios') {
deleteIOSDatabase({shouldRemoveDirectory});
return true;
}
// On Android, we'll remove the databases folder under the Document Directory
const androidFilesDir = `${FileSystem.documentDirectory}databases/`;
await FileSystem.deleteAsync(androidFilesDir);
return true;
} catch (e) {
// console.log('An error occurred while trying to delete the databases directory);
return false;
}
};
/**
* getAllServers : Retrieves all the servers registered in the default database
* @returns {Promise<undefined | Servers[]>}
*/
private getAllServers = async () => {
// Retrieve all server records from the default db
const defaultDatabase = await this.getDefaultDatabase();
const allServers = defaultDatabase && await defaultDatabase.collections.get(MM_TABLES.DEFAULT.SERVERS).query().fetch() as IServers[];
return allServers;
};
/**
* setDefaultDatabase : Sets the default database.
* @returns {Promise<DBInstance>}
*/
private setDefaultDatabase = async (): Promise<DBInstance> => {
this.defaultDatabase = await this.createDatabaseConnection({
databaseConnection: {dbName: 'default'},
shouldAddToDefaultDatabase: false,
});
return this.defaultDatabase;
};
/**
* addServerToDefaultDatabase: Adds a record into the 'default' database - into the 'servers' table - for this new server connection
* @param {string} databaseFilePath
* @param {string} displayName
* @param {string} serverUrl
* @returns {Promise<void>}
*/
private addServerToDefaultDatabase = async ({
databaseFilePath,
displayName,
serverUrl,
}: DefaultNewServer) => {
try {
const defaultDatabase = await this.getDefaultDatabase();
const isServerPresent = await this.isServerPresent(serverUrl);
if (defaultDatabase && !isServerPresent) {
await defaultDatabase.action(async () => {
const serversCollection = defaultDatabase.collections.get('servers');
await serversCollection.create((server: IServers) => {
server.dbPath = databaseFilePath;
server.displayName = displayName;
server.mentionCount = 0;
server.unreadCount = 0;
server.url = serverUrl;
});
});
}
} catch (e) {
// console.log({catchError: e});
}
};
/**
* buildMigrationCallbacks: Creates a set of callbacks that can be used to monitor the migration process.
* For example, we can display a processing spinner while we have a migration going on. Moreover, we can also
* hook into those callbacks to assess how many of our servers successfully completed their migration.
* @param {string} dbName
* @returns {MigrationEvents}
*/
private buildMigrationCallbacks = (dbName: string) => {
const migrationEvents: MigrationEvents = {
onSuccess: () => {
return DeviceEventEmitter.emit(MIGRATION_EVENTS.MIGRATION_SUCCESS, {dbName});
},
onStarted: () => {
return DeviceEventEmitter.emit(MIGRATION_EVENTS.MIGRATION_STARTED, {dbName});
},
onFailure: (error) => {
return DeviceEventEmitter.emit(MIGRATION_EVENTS.MIGRATION_ERROR, {dbName, error});
},
};
return migrationEvents;
};
/**
* getDatabaseDirectory: Using the database name, this method will return the database directory for each platform.
* On iOS, it will point towards the AppGroup shared directory while on Android, it will point towards the Files Directory.
* Please note that in each case, the *.db files will be created/grouped under a 'databases' sub-folder.
* iOS Simulator : appGroup => /Users/{username}/Library/Developer/CoreSimulator/Devices/DA6F1C73/data/Containers/Shared/AppGroup/ACA65327/databases"}
* Android Device: file:///data/user/0/com.mattermost.rnbeta/files/databases
*
* @param {string} dbName
* @returns {string}
*/
private getDatabaseDirectory = (dbName: string): string => {
return Platform.OS === 'ios' ? `${this.iOSAppGroupDatabase}/${dbName}.db` : `${FileSystem.documentDirectory}${dbName}.db`;
};
}
export default new DatabaseManager();

View file

@ -0,0 +1,172 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Database} from '@nozbe/watermelondb';
import {MM_TABLES} from '@constants/database';
import {DBInstance} from '@typings/database/database';
import IServers from '@typings/database/servers';
import DatabaseManager, {DatabaseType} from './index';
jest.mock('./index');
const {SERVERS} = MM_TABLES.DEFAULT;
// NOTE : On the mock Database Manager, we cannot test for :
// 1. Android/iOS file path
// 2. Deletion of the 'databases' folder on those two platforms
describe('*** Database Manager tests ***', () => {
it('=> should return a default database', async () => {
expect.assertions(2);
const spyOnAddServerToDefaultDatabase = jest.spyOn(DatabaseManager as any, 'addServerToDefaultDatabase');
const defaultDB = await DatabaseManager.getDefaultDatabase();
expect(defaultDB).toBeInstanceOf(Database);
expect(spyOnAddServerToDefaultDatabase).not.toHaveBeenCalledTimes(1);
});
it('=> should create a new server connection', async () => {
expect.assertions(2);
const spyOnAddServerToDefaultDatabase = jest.spyOn(DatabaseManager as any, 'addServerToDefaultDatabase');
const connection1 = await DatabaseManager.createDatabaseConnection({
shouldAddToDefaultDatabase: true,
databaseConnection: {
actionsEnabled: true,
dbName: 'community mattermost',
dbType: DatabaseType.SERVER,
serverUrl: 'https://appv1.mattermost.com',
},
});
expect(connection1).toBeInstanceOf(Database);
expect(spyOnAddServerToDefaultDatabase).toHaveBeenCalledTimes(1);
});
it('=> should switch between active server connections', async () => {
expect.assertions(7);
let activeServer: DBInstance;
let adapter;
activeServer = await DatabaseManager.getActiveServerDatabase();
// as we haven't set an active server yet, we should be getting undefined in the activeServer variable
expect(activeServer).toBeUndefined();
const setActiveServer = async ({displayName, serverUrl}:{displayName: string, serverUrl: string}) => {
// now we set the active database
const server = await DatabaseManager.setActiveServerDatabase({displayName, serverUrl});
// setActiveServer should be undefined as the method does not actually return anything
expect(server).toBeUndefined();
};
await setActiveServer({displayName: 'community mattermost', serverUrl: 'https://appv1.mattermost.com'});
// let's verify if we now have a value for activeServer
activeServer = await DatabaseManager.getActiveServerDatabase();
expect(activeServer).toBeDefined();
adapter = activeServer!.adapter as any;
const currentDBName = adapter.underlyingAdapter._dbName;
expect(currentDBName).toStrictEqual('community mattermost');
// spice things up; we'll set a new server and verify if the value of activeServer changes
await setActiveServer({displayName: 'appv2', serverUrl: 'https://appv2.mattermost.com'});
activeServer = await DatabaseManager.getActiveServerDatabase();
expect(activeServer).toBeDefined();
adapter = activeServer!.adapter as any;
const newDBName = adapter.underlyingAdapter._dbName;
expect(newDBName).toStrictEqual('appv2');
});
it('=> should retrieve all database instances matching serverUrls parameter', async () => {
expect.assertions(3);
const spyOnCreateDatabaseConnection = jest.spyOn(DatabaseManager, 'createDatabaseConnection');
const dbInstances = await DatabaseManager.retrieveDatabaseInstances([
'https://xunity2.mattermost.com',
'https://appv2.mattermost.com',
'https://appv1.mattermost.com',
]);
expect(dbInstances).toBeTruthy();
const numDbInstances = dbInstances && dbInstances.length ? dbInstances.length : 0;
// The Database Manager will call the 'createDatabaseConnection' method in consequence of the number of database connection present in dbInstances array
expect(spyOnCreateDatabaseConnection).toHaveBeenCalledTimes(numDbInstances);
// We should have two active database connection
expect(numDbInstances).toEqual(2);
});
it('=> should have records of Servers set in the servers table of the default database', async () => {
expect.assertions(3);
const defaultDB = await DatabaseManager.getDefaultDatabase();
expect(defaultDB).toBeDefined();
const serversRecords = await defaultDB!.collections.get(SERVERS).query().fetch() as IServers[];
expect(serversRecords).toBeDefined();
// We have call the 'DatabaseManager.setActiveServerDatabase' twice in the previous test case; that implies that we have 2 records in the 'servers' table
expect(serversRecords.length).toEqual(2);
});
it('=> should delete appv1 server from the servers table of Default database', async () => {
expect.assertions(3);
// Removing database for appv1 connection
const isAppV1Removed = await DatabaseManager.deleteDatabase('https://appv1.mattermost.com');
expect(isAppV1Removed).toBe(true);
// Verifying in the database to confirm if its record was deleted
const defaultDB = await DatabaseManager.getDefaultDatabase();
const serversRecords = await defaultDB!.collections.get(SERVERS).query().fetch() as IServers[];
expect(serversRecords).toBeDefined();
expect(serversRecords.length).toEqual(1);
});
it('=> should enforce uniqueness of connections using serverUrl as key', async () => {
expect.assertions(2);
// We can't have more than one connection with the same server url
const serverUrl = 'https://appv3.mattermost.com';
await DatabaseManager.createDatabaseConnection({
shouldAddToDefaultDatabase: true,
databaseConnection: {
actionsEnabled: true,
dbName: 'community mattermost',
dbType: DatabaseType.SERVER,
serverUrl,
},
});
await DatabaseManager.createDatabaseConnection({
shouldAddToDefaultDatabase: true,
databaseConnection: {
actionsEnabled: true,
dbName: 'duplicate server',
dbType: DatabaseType.SERVER,
serverUrl,
},
});
const defaultDB = await DatabaseManager.getDefaultDatabase();
const allServers = defaultDB && await defaultDB.collections.get(SERVERS).query().fetch() as IServers[];
// We should be having some servers returned here
expect(allServers?.length).toBeGreaterThan(0);
const occurrences = allServers?.map((server) => server.url).reduce((acc, cur) => (cur === serverUrl ? acc + 1 : acc), 0);
// We should only have one occurence of the 'https://appv3.mattermost.com' url
expect(occurrences).toEqual(1);
});
});

View file

@ -0,0 +1,78 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Platform} from 'react-native';
import DBManager, {DatabaseType} from './index';
import {getIOSAppGroupDetails} from '@utils/mattermost_managed';
export default async () => {
// Test: It should return the iOS App-Group shared directory
const testAppGroupDirectory = () => {
if (Platform.OS === 'ios') {
getIOSAppGroupDetails();
}
};
// Test: It should return an instance of the default database
const testGetDefaultDatabase = () => {
DBManager.getDefaultDatabase();
};
// Test: It should creates a new server connection
const testNewServerConnection = async () => {
await DBManager.createDatabaseConnection({
shouldAddToDefaultDatabase: true,
databaseConnection: {
actionsEnabled: true,
dbName: 'community mattermost',
dbType: DatabaseType.SERVER,
serverUrl: 'https://comm4.mattermost.com',
},
});
};
// Test: It should return the current active server database
const testGetActiveServerConnection = () => {
// const activeServer = DBManager.getActiveServerDatabase();
};
// Test: It should set the current active server database to the provided server url.
const testSetActiveServerConnection = async () => {
await DBManager.setActiveServerDatabase({
displayName: 'comm4',
serverUrl: 'https://comm4.mattermost.com',
});
};
// Test: It should return database instance(s) if there are valid server urls in the provided list.
const testRetrieveAllDatabaseConnections = async () => {
await DBManager.retrieveDatabaseInstances([
'https://xunity2.mattermost.com',
'https://comm5.mattermost.com',
'https://comm4.mattermost.com',
]);
};
// Test: It should delete the associated *.db file for this server url
const testDeleteSQLFile = async () => {
await DBManager.deleteDatabase('https://comm4.mattermost.com');
};
// Test: It should wipe out the databases folder under the documents direction on Android and in the shared directory for the AppGroup on iOS
const testFactoryReset = async () => {
await DBManager.factoryReset(true);
};
// NOTE : Comment and test the below functions one at a time. It starts with creating a default database and ends with a factory reset.
testAppGroupDirectory();
testGetDefaultDatabase();
await testNewServerConnection();
testGetActiveServerConnection();
await testSetActiveServerConnection();
await testRetrieveAllDatabaseConnections();
await testDeleteSQLFile();
await testFactoryReset();
};

View file

@ -1,5 +1,6 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {schemaMigrations} from '@nozbe/watermelondb/Schema/migrations';
// NOTE : To implement migration, please follow this document

View file

@ -4,11 +4,13 @@
import {AppSchema, appSchema, tableSchema} from '@nozbe/watermelondb';
import {MM_TABLES} from '@constants/database';
const {APP, GLOBAL, SERVERS} = MM_TABLES.DEFAULT;
export const defaultSchema: AppSchema = appSchema({
version: 1,
tables: [
tableSchema({
name: MM_TABLES.DEFAULT.APP,
name: APP,
columns: [
{name: 'build_number', type: 'string'},
{name: 'created_at', type: 'number'},
@ -16,14 +18,14 @@ export const defaultSchema: AppSchema = appSchema({
],
}),
tableSchema({
name: MM_TABLES.DEFAULT.GLOBAL,
name: GLOBAL,
columns: [
{name: 'name', type: 'string', isIndexed: true},
{name: 'value', type: 'string'},
],
}),
tableSchema({
name: MM_TABLES.DEFAULT.SERVERS,
name: SERVERS,
columns: [
{name: 'db_path', type: 'string'},
{name: 'display_name', type: 'string'},

View file

@ -0,0 +1,17 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {tableSchema} from '@nozbe/watermelondb';
import {MM_TABLES} from '@constants/database';
const {APP} = MM_TABLES.DEFAULT;
export default tableSchema({
name: APP,
columns: [
{name: 'build_number', type: 'string'},
{name: 'created_at', type: 'number'},
{name: 'version_number', type: 'string'},
],
});

View file

@ -0,0 +1,16 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {tableSchema} from '@nozbe/watermelondb';
import {MM_TABLES} from '@constants/database';
const {GLOBAL} = MM_TABLES.DEFAULT;
export default tableSchema({
name: GLOBAL,
columns: [
{name: 'name', type: 'string', isIndexed: true},
{name: 'value', type: 'string'},
],
});

View file

@ -0,0 +1,6 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
export {default as app} from './app';
export {default as global} from './global';
export {default as servers} from './servers';

View file

@ -0,0 +1,19 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {tableSchema} from '@nozbe/watermelondb';
import {MM_TABLES} from '@constants/database';
const {SERVERS} = MM_TABLES.DEFAULT;
export default tableSchema({
name: SERVERS,
columns: [
{name: 'db_path', type: 'string'},
{name: 'display_name', type: 'string'},
{name: 'mention_count', type: 'number'},
{name: 'unread_count', type: 'number'},
{name: 'url', type: 'string', isIndexed: true},
],
});

View file

@ -2,14 +2,14 @@
// See LICENSE.txt for license information.
import {Q, Query, Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {children, field, immutableRelation, lazy} from '@nozbe/watermelondb/decorators';
import ChannelInfo from '@typings/database/channel_info';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import ChannelInfo from '@typings/database/channel_info';
import ChannelMembership from '@typings/database/channel_membership';
import Draft from '@typings/database/draft';
import GroupsInChannel from '@typings/database/groups_in_channel';
import {MM_TABLES} from '@constants/database';
import MyChannel from '@typings/database/my_channel';
import MyChannelSettings from '@typings/database/my_channel_settings';
import Post from '@typings/database/post';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';

View file

@ -5,8 +5,8 @@ import {Q, Query, Relation} from '@nozbe/watermelondb';
import {field, immutableRelation, lazy} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';
import {MM_TABLES} from '@constants/database';
import User from '@typings/database/user';
const {CHANNEL, CHANNEL_MEMBERSHIP, USER} = MM_TABLES.SERVER;

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Q, Query, Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation, lazy} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Group from '@typings/database/group';

View file

@ -2,11 +2,11 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Group from '@typings/database/group';
import {MM_TABLES} from '@constants/database';
import Team from '@typings/database/team';
const {GROUP, GROUPS_IN_TEAM, TEAM} = MM_TABLES.SERVER;

View file

@ -2,11 +2,11 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';
import {MM_TABLES} from '@constants/database';
const {CHANNEL, MY_CHANNEL} = MM_TABLES.SERVER;

View file

@ -2,11 +2,11 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import {field, immutableRelation, json} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, json, immutableRelation} from '@nozbe/watermelondb/decorators';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';
import {MM_TABLES} from '@constants/database';
const {CHANNEL, MY_CHANNEL_SETTINGS} = MM_TABLES.SERVER;

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, relation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Team from '@typings/database/team';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Q, Query, Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {children, field, immutableRelation, json, lazy} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation, json} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Post from '@typings/database/post';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Post from '@typings/database/post';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import User from '@typings/database/user';

View file

@ -2,12 +2,12 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import User from '@typings/database/user';
import Post from '@typings/database/post';
import User from '@typings/database/user';
const {POST, REACTION, USER} = MM_TABLES.SERVER;

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Team from '@typings/database/team';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Q, Query} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {children, field, lazy} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation, json} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Team from '@typings/database/team';

View file

@ -2,12 +2,12 @@
// See LICENSE.txt for license information.
import {Q, Query, Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation, lazy} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import User from '@typings/database/user';
import Team from '@typings/database/team';
import User from '@typings/database/user';
const {TEAM, TEAM_MEMBERSHIP, USER} = MM_TABLES.SERVER;

View file

@ -2,8 +2,8 @@
// See LICENSE.txt for license information.
import {Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {field, immutableRelation, text} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Team from '@typings/database/team';

View file

@ -2,12 +2,12 @@
// See LICENSE.txt for license information.
import {children, field, json} from '@nozbe/watermelondb/decorators';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import {MM_TABLES} from '@constants/database';
import Channel from '@typings/database/channel';
import ChannelMembership from '@typings/database/channel_membership';
import GroupMembership from '@typings/database/group_membership';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import Post from '@typings/database/post';
import Preference from '@typings/database/preference';
import Reaction from '@typings/database/reaction';

View file

@ -2,6 +2,7 @@
// See LICENSE.txt for license information.
import {MM_TABLES} from '@constants/database';
import {serverSchema} from './index';
const {

View file

@ -2,20 +2,12 @@
// See LICENSE.txt for license information.
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, View} from 'react-native';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
@ -109,4 +101,4 @@ const styles = StyleSheet.create({
},
});
export default Channel;
export default Channel;

View file

@ -2,27 +2,13 @@
// See LICENSE.txt for license information.
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import {SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, View} from 'react-native';
import {Colors, DebugInstructions, LearnMoreLinks, ReloadInstructions} from 'react-native/Libraries/NewAppScreen';
import {Screens} from '@constants';
import {goToScreen} from '@screens/navigation';
declare const global: {HermesInternal: null | {}};
declare const global: { HermesInternal: null | {} };
const App = () => {
return (
@ -33,7 +19,6 @@ const App = () => {
contentInsetAdjustmentBehavior='automatic'
style={styles.scrollView}
>
<Header/>
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>{'Engine: Hermes'}</Text>
@ -43,8 +28,11 @@ const App = () => {
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>{'Step One'}</Text>
<Text style={styles.sectionDescription}>
{'Edit '}<Text style={styles.highlight}>{'screens/server/index.tsx'}</Text>{' to change this'}
{'screen and then come back to see your edits.'}
{'Edit '}
<Text
style={styles.highlight}
>{'screens/server/index.tsx'}</Text>{' to change this'}
{'XXXXXscreen and then come back to see your edits.'}
</Text>
</View>
<View style={styles.sectionContainer}>
@ -115,4 +103,4 @@ const styles = StyleSheet.create({
},
});
export default App;
export default App;

View file

@ -0,0 +1,45 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {NativeModules} from 'react-native';
const {MattermostManaged} = NativeModules;
type IOSDeleteDatabase = { databaseName?: string, shouldRemoveDirectory?: boolean }
type IOSAppGroupDetails = { appGroupIdentifier: string, appGroupSharedDirectory: string, appGroupDatabase: string }
/**
* Retrieves information relative to the iOS AppGroup identifier and folders
* @returns {{appGroupIdentifier: string, appGroupSharedDirectory: string, appGroupDatabase: string}}
*/
export const getIOSAppGroupDetails = (): IOSAppGroupDetails => {
const {
appGroupIdentifier,
appGroupSharedDirectory: {sharedDirectory, databasePath},
} = MattermostManaged.getConstants();
const appGroup = {
appGroupIdentifier,
appGroupSharedDirectory: sharedDirectory,
appGroupDatabase: databasePath,
};
// console.log('appGroup => ', appGroup.appGroupDatabase);
return appGroup;
};
/**
* BEWARE: deleteIOSDatabase is used to either delete a single .db file by its name or can also be used to delete the whole 'database' directory under the shared AppGroup directory.
* USE WITH CAUTION.
* @param {string} databaseName
* @param {boolean} shouldRemoveDirectory
* e.g :
* MattermostManaged.deleteDatabaseDirectory(databaseName, shouldRemoveDirectory, (error: any, success: any) => { });
*/
export const deleteIOSDatabase = ({
databaseName = undefined,
shouldRemoveDirectory = false,
}: IOSDeleteDatabase) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
MattermostManaged.deleteDatabaseDirectory(databaseName, shouldRemoveDirectory, () => null);
};

View file

@ -8,8 +8,8 @@ const {
} = require('detox/runners/jest-circus');
class CustomDetoxEnvironment extends DetoxCircusEnvironment {
constructor(config) {
super(config);
constructor(config, context) {
super(config, context);
this.initTimeout = 300000;

2780
detox/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -4,23 +4,23 @@
"repository": "git@github.com:mattermost/mattermost-mobile.git",
"author": "Mattermost, Inc.",
"devDependencies": {
"@babel/plugin-proposal-class-properties": "7.12.1",
"@babel/plugin-transform-modules-commonjs": "7.12.1",
"@babel/plugin-transform-runtime": "7.12.1",
"@babel/preset-env": "7.12.1",
"axios": "0.21.0",
"@babel/plugin-proposal-class-properties": "7.12.13",
"@babel/plugin-transform-modules-commonjs": "7.12.13",
"@babel/plugin-transform-runtime": "7.12.15",
"@babel/preset-env": "7.12.13",
"axios": "0.21.1",
"babel-jest": "26.6.3",
"babel-plugin-module-resolver": "4.0.0",
"babel-plugin-module-resolver": "4.1.0",
"deepmerge": "4.2.2",
"detox": "17.11.4",
"detox": "18.3.1",
"form-data": "3.0.0",
"jest": "26.6.3",
"jest-circus": "26.6.3",
"jest-cli": "26.6.3",
"jest-html-reporters": "2.1.0",
"jest-html-reporters": "2.1.2",
"jest-junit": "12.0.0",
"sanitize-filename": "1.6.3",
"uuid": "8.3.1"
"uuid": "8.3.2"
},
"scripts": {
"e2e:android-create-emulator": "avdmanager create avd -n detox_emu_api_30 -k 'system-images;android-30;google_apis;x86' -g google_apis -d 'pixel'",

View file

@ -23,14 +23,33 @@ RCT_EXPORT_MODULE();
return appGroupId;
}
-(NSDictionary * ) appGroupSharedDirectory {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *sharedDirectory = [fileManager containerURLForSecurityApplicationGroupIdentifier: [self appGroupId]];
NSURL * databasePath = [sharedDirectory URLByAppendingPathComponent:@"databases"];
[fileManager createDirectoryAtPath:[databasePath path]
withIntermediateDirectories:true
attributes:nil
error:nil
];
return @{
@"sharedDirectory": [sharedDirectory path ],
@"databasePath" : [databasePath path]
};
}
- (NSDictionary *)constantsToExport {
return @{
@"appGroupIdentifier": [self appGroupId]
@"appGroupIdentifier": [self appGroupId],
@"appGroupSharedDirectory" : [self appGroupSharedDirectory]
};
}
RCT_EXPORT_METHOD(isRunningInSplitView:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
RCT_EXPORT_METHOD(isRunningInSplitView:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
BOOL isRunningInFullScreen = CGRectEqualToRect(
[UIApplication sharedApplication].delegate.window.frame,
[UIApplication sharedApplication].delegate.window.screen.bounds);
@ -39,4 +58,32 @@ RCT_EXPORT_METHOD(isRunningInSplitView:(RCTPromiseResolveBlock)resolve
});
}
RCT_EXPORT_METHOD(deleteDatabaseDirectory: (NSString *)databaseName shouldRemoveDirectory: (BOOL) shouldRemoveDirectory callback: (RCTResponseSenderBlock)callback){
@try {
NSDictionary * appGroupDir = [self appGroupSharedDirectory];
NSString * databaseDir;
if(databaseName){
databaseDir = [NSString stringWithFormat:@"%@/%@%@", appGroupDir[@"databasePath"], databaseName , @".db"];
}
if(shouldRemoveDirectory){
databaseDir = appGroupDir[@"databasePath"];
}
NSFileManager * fileManager = [NSFileManager defaultManager];
NSError *error = nil;
BOOL successCode = [fileManager removeItemAtPath:databaseDir error:&error];
NSNumber * success= [NSNumber numberWithBool:successCode];
callback(@[error, success]);
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
}
}
@end

View file

@ -6,9 +6,10 @@ module.exports = {
verbose: true,
globals: {
'ts-jest': {
tsConfigFile: 'tsconfig.jest.json',
tsConfigFile: 'tsconfig.test.json',
},
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
clearMocks: true,
setupFilesAfterEnv: [
'<rootDir>/test/setup.ts',
@ -28,6 +29,6 @@ module.exports = {
'assets/images/video_player/(.*).png': '<rootDir>/dist/assets/images/video_player/$1@2x.png',
},
transformIgnorePatterns: [
'node_modules/(?!react-native|jail-monkey|@sentry/react-native|react-navigation|@react-native-community/cameraroll)',
'node_modules/(?!react-native|jail-monkey|@sentry/react-native|react-navigation|@react-native-community/cameraroll|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|sentry-expo|native-base|unimodules-permissions-interface)',
],
};

36
package-lock.json generated
View file

@ -6319,13 +6319,6 @@
"rambdax": "2.15.0",
"rxjs": "^6.5.3",
"sql-escape-string": "^1.1.0"
},
"dependencies": {
"lokijs": {
"version": "npm:@nozbe/lokijs@1.5.10-wmelon3",
"resolved": "https://registry.npmjs.org/@nozbe/lokijs/-/lokijs-1.5.10-wmelon3.tgz",
"integrity": "sha512-yfuj/SzYiVVn0e3OP8vjcbekumUR62Df90deG8uH7+5nqJqTLe4HkEzlmwJfss9UE0K8PsTQLACFOUq/2aAJ2A=="
}
}
},
"@nozbe/with-observables": {
@ -12327,9 +12320,9 @@
"dev": true
},
"bunyan": {
"version": "1.8.14",
"resolved": "https://registry.npmjs.org/bunyan/-/bunyan-1.8.14.tgz",
"integrity": "sha512-LlahJUxXzZLuw/hetUQJmRgZ1LF6+cr5TPpRj6jf327AsiIq2jhYEH4oqUUkVKTor+9w2BT3oxVwhzE5lw9tcg==",
"version": "1.8.15",
"resolved": "https://registry.npmjs.org/bunyan/-/bunyan-1.8.15.tgz",
"integrity": "sha512-0tECWShh6wUysgucJcBAoYegf3JJoZWibxdqhTm7OHPeT42qdjkZ29QCMcKwbgU1kiH+auSIasNRXMLWXafXig==",
"dev": true,
"requires": {
"dtrace-provider": "~0.8",
@ -13760,9 +13753,9 @@
}
},
"detox": {
"version": "17.11.4",
"resolved": "https://registry.npmjs.org/detox/-/detox-17.11.4.tgz",
"integrity": "sha512-duZpv5JHTSqEwDt/RFkGz18qIbgBDdAX/ktQZLHljtezeF0G2Cp+DF/b964ULRY48kaPBhovzfN/ChCq1lq3lQ==",
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/detox/-/detox-18.3.1.tgz",
"integrity": "sha512-eYvBTkJ0bvBcaWxubQBhRk+sT0Yd21npebd/s25BFrfB+8Ts4ctGASXh2uqlHkvCzUIDzRTEgFLu9I5k3g89Fw==",
"dev": true,
"requires": {
"bunyan": "^1.8.12",
@ -13978,9 +13971,9 @@
"dev": true
},
"yargs": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-16.1.1.tgz",
"integrity": "sha512-hAD1RcFP/wfgfxgMVswPE+z3tlPFtxG8/yWUrG2i17sTWGCGqWnxKcLTF4cUKDUK8fzokwsmO9H0TDkRbMHy8w==",
"version": "16.2.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz",
"integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==",
"dev": true,
"requires": {
"cliui": "^7.0.2",
@ -23104,6 +23097,11 @@
}
}
},
"lokijs": {
"version": "npm:@nozbe/lokijs@1.5.10-wmelon3",
"resolved": "https://registry.npmjs.org/@nozbe/lokijs/-/lokijs-1.5.10-wmelon3.tgz",
"integrity": "sha512-yfuj/SzYiVVn0e3OP8vjcbekumUR62Df90deG8uH7+5nqJqTLe4HkEzlmwJfss9UE0K8PsTQLACFOUq/2aAJ2A=="
},
"loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@ -28948,9 +28946,9 @@
}
},
"tail": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/tail/-/tail-2.0.4.tgz",
"integrity": "sha512-xHkZdNWIzO++g+V/rHGqVoHd2LRxz+8t8bj6FGelfb8FHBjg5yjkX7Su/8sQSBo5alIspYkRp/fU0A2SM5h+5A==",
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/tail/-/tail-2.2.0.tgz",
"integrity": "sha512-QqUMtWlnzArTvGyjVnAE5fAiXEm2Psvk/BlE7vWx2/dIEWMsAhcNPz7iW6WTiSM8h1fjtCkRMsaWBS1j6rpGBg==",
"dev": true
},
"tapable": {

View file

@ -114,7 +114,7 @@
"babel-plugin-module-resolver": "4.0.0",
"babel-plugin-transform-remove-console": "6.9.4",
"deep-freeze": "0.0.1",
"detox": "17.11.4",
"detox": "18.3.1",
"enzyme": "3.11.0",
"enzyme-adapter-react-16": "1.15.5",
"enzyme-to-json": "3.6.1",

File diff suppressed because it is too large Load diff

33
types/database/database.d.ts vendored Normal file
View file

@ -0,0 +1,33 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Migration} from '@nozbe/watermelondb/Schema/migrations';
import {AppSchema, Database} from '@nozbe/watermelondb';
export type MigrationEvents = {
onSuccess: () => void,
onStarted: () => void,
onFailure: (error: string) => void,
}
export type MMAdaptorOptions = {
dbPath : string,
schema: AppSchema,
migrationSteps?: Migration [],
migrationEvents?: MigrationEvents
}
export type MMDatabaseConnection = {
actionsEnabled?: boolean,
dbName: string,
dbType?: DatabaseType.DEFAULT | DatabaseType.SERVER,
serverUrl?: string,
}
export type DefaultNewServer = {
databaseFilePath: string,
displayName: string,
serverUrl: string
}
// A database connection is of type 'Database'; unless it fails to be initialize and in which case it becomes 'undefined'
type DBInstance = Database | undefined

View file

@ -1,7 +1,9 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Query, Relation} from '@nozbe/watermelondb';
import Model, {Associations} from '@nozbe/watermelondb/Model';
import User from '@typings/database/user';
import Team from '@typings/database/team';