1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-11-27 08:21:03 +02:00
joplin/packages/app-mobile/root.tsx

1338 lines
50 KiB
TypeScript
Raw Normal View History

2020-12-30 13:51:43 +02:00
const React = require('react');
import shim from '@joplin/lib/shim';
shim.setReact(React);
import setupQuickActions from './setupQuickActions';
import PluginAssetsLoader from './PluginAssetsLoader';
2020-12-30 12:54:00 +02:00
import AlarmService from '@joplin/lib/services/AlarmService';
import Alarm from '@joplin/lib/models/Alarm';
import time from '@joplin/lib/time';
import Logger, { TargetType } from '@joplin/utils/Logger';
2020-12-30 12:54:00 +02:00
import BaseModel from '@joplin/lib/BaseModel';
import BaseService from '@joplin/lib/services/BaseService';
import ResourceService from '@joplin/lib/services/ResourceService';
import KvStore from '@joplin/lib/services/KvStore';
import NoteScreen from './components/screens/Note';
import UpgradeSyncTargetScreen from './components/screens/UpgradeSyncTargetScreen';
import Setting, { AppType, Env } from '@joplin/lib/models/Setting';
2020-12-30 12:54:00 +02:00
import PoorManIntervals from '@joplin/lib/PoorManIntervals';
import reducer, { NotesParent, parseNotesParent, serializeNotesParent } from '@joplin/lib/reducer';
2020-12-30 12:54:00 +02:00
import ShareExtension from './utils/ShareExtension';
import handleShared from './utils/shareHandler';
import uuid from '@joplin/lib/uuid';
import { loadKeychainServiceAndSettings } from '@joplin/lib/services/SettingUtils';
import KeychainServiceDriverMobile from '@joplin/lib/services/keychain/KeychainServiceDriver.mobile';
import { _, setLocale } from '@joplin/lib/locale';
2020-12-30 12:54:00 +02:00
import SyncTargetJoplinServer from '@joplin/lib/SyncTargetJoplinServer';
2021-06-03 17:12:07 +02:00
import SyncTargetJoplinCloud from '@joplin/lib/SyncTargetJoplinCloud';
import SyncTargetOneDrive from '@joplin/lib/SyncTargetOneDrive';
import initProfile from '@joplin/lib/services/profileConfig/initProfile';
2021-06-17 19:19:32 +02:00
const VersionInfo = require('react-native-version-info').default;
const { Keyboard, BackHandler, Animated, View, StatusBar, Platform, Dimensions } = require('react-native');
import { AppState as RNAppState, EmitterSubscription, Linking, NativeEventSubscription, Appearance, AccessibilityInfo } from 'react-native';
import getResponsiveValue from './components/getResponsiveValue';
import NetInfo from '@react-native-community/netinfo';
2020-12-30 12:54:00 +02:00
const DropdownAlert = require('react-native-dropdownalert').default;
2021-01-27 19:42:58 +02:00
const AlarmServiceDriver = require('./services/AlarmServiceDriver').default;
2020-11-05 18:58:23 +02:00
const SafeAreaView = require('./components/SafeAreaView');
const { connect, Provider } = require('react-redux');
import { Provider as PaperProvider, MD3DarkTheme, MD3LightTheme } from 'react-native-paper';
2020-11-05 18:58:23 +02:00
const { BackButtonService } = require('./services/back-button.js');
import NavService from '@joplin/lib/services/NavService';
import { createStore, applyMiddleware, Dispatch } from 'redux';
import reduxSharedMiddleware from '@joplin/lib/components/shared/reduxSharedMiddleware';
import shimInit from './utils/shim-init-react';
2020-11-05 18:58:23 +02:00
const { AppNav } = require('./components/app-nav.js');
import Note from '@joplin/lib/models/Note';
import Folder from '@joplin/lib/models/Folder';
import BaseSyncTarget from '@joplin/lib/BaseSyncTarget';
import Resource from '@joplin/lib/models/Resource';
import Tag from '@joplin/lib/models/Tag';
import NoteTag from '@joplin/lib/models/NoteTag';
import BaseItem from '@joplin/lib/models/BaseItem';
import MasterKey from '@joplin/lib/models/MasterKey';
import Revision from '@joplin/lib/models/Revision';
import RevisionService from '@joplin/lib/services/RevisionService';
import JoplinDatabase from '@joplin/lib/JoplinDatabase';
import Database from '@joplin/lib/database';
import NotesScreen from './components/screens/Notes';
2020-11-05 18:58:23 +02:00
const { TagsScreen } = require('./components/screens/tags.js');
2023-07-18 15:58:06 +02:00
import ConfigScreen from './components/screens/ConfigScreen/ConfigScreen';
2020-11-05 18:58:23 +02:00
const { FolderScreen } = require('./components/screens/folder.js');
import LogScreen from './components/screens/LogScreen';
import StatusScreen from './components/screens/status';
2020-11-05 18:58:23 +02:00
const { SearchScreen } = require('./components/screens/search.js');
const { OneDriveLoginScreen } = require('./components/screens/onedrive-login.js');
import EncryptionConfigScreen from './components/screens/encryption-config';
2020-11-05 18:58:23 +02:00
const { DropboxLoginScreen } = require('./components/screens/dropbox-login.js');
import { MenuProvider } from 'react-native-popup-menu';
import SideMenu from './components/SideMenu';
import SideMenuContent from './components/side-menu-content';
2020-11-05 18:58:23 +02:00
const { SideMenuContentNote } = require('./components/side-menu-content-note.js');
const { DatabaseDriverReactNative } = require('./utils/database-driver-react-native');
import { reg } from '@joplin/lib/registry';
const { defaultState } = require('@joplin/lib/reducer');
import FileApiDriverLocal from '@joplin/lib/file-api-driver-local';
import ResourceFetcher from '@joplin/lib/services/ResourceFetcher';
import SearchEngine from '@joplin/lib/services/search/SearchEngine';
import WelcomeUtils from '@joplin/lib/WelcomeUtils';
import { themeStyle } from './components/global-style';
2021-08-16 16:20:14 +02:00
import SyncTargetRegistry from '@joplin/lib/SyncTargetRegistry';
import SyncTargetFilesystem from '@joplin/lib/SyncTargetFilesystem';
const SyncTargetNextcloud = require('@joplin/lib/SyncTargetNextcloud.js');
const SyncTargetWebDAV = require('@joplin/lib/SyncTargetWebDAV.js');
const SyncTargetDropbox = require('@joplin/lib/SyncTargetDropbox.js');
const SyncTargetAmazonS3 = require('@joplin/lib/SyncTargetAmazonS3.js');
import BiometricPopup from './components/biometrics/BiometricPopup';
2023-08-04 11:57:54 +02:00
import initLib from '@joplin/lib/initLib';
import { isCallbackUrl, parseCallbackUrl, CallbackUrlCommand } from '@joplin/lib/callbackUrlUtils';
import JoplinCloudLoginScreen from './components/screens/JoplinCloudLoginScreen';
2021-08-16 19:05:22 +02:00
SyncTargetRegistry.addClass(SyncTargetNone);
SyncTargetRegistry.addClass(SyncTargetOneDrive);
SyncTargetRegistry.addClass(SyncTargetNextcloud);
SyncTargetRegistry.addClass(SyncTargetWebDAV);
2018-03-27 01:55:44 +02:00
SyncTargetRegistry.addClass(SyncTargetDropbox);
SyncTargetRegistry.addClass(SyncTargetFilesystem);
SyncTargetRegistry.addClass(SyncTargetAmazonS3);
2020-12-30 12:54:00 +02:00
SyncTargetRegistry.addClass(SyncTargetJoplinServer);
2021-06-03 17:12:07 +02:00
SyncTargetRegistry.addClass(SyncTargetJoplinCloud);
import FsDriverRN from './utils/fs-driver/fs-driver-rn';
import DecryptionWorker from '@joplin/lib/services/DecryptionWorker';
import EncryptionService from '@joplin/lib/services/e2ee/EncryptionService';
import MigrationService from '@joplin/lib/services/MigrationService';
import { clearSharedFilesCache } from './utils/ShareUtils';
import setIgnoreTlsErrors from './utils/TlsUtils';
import ShareService from '@joplin/lib/services/share/ShareService';
import setupNotifications from './utils/setupNotifications';
import { loadMasterKeysFromSettings, migrateMasterPassword } from '@joplin/lib/services/e2ee/utils';
2021-10-03 18:38:13 +02:00
import SyncTargetNone from '@joplin/lib/SyncTargetNone';
import { setRSA } from '@joplin/lib/services/e2ee/ppk';
import RSA from './services/e2ee/RSA.react-native';
import { runIntegrationTests as runRsaIntegrationTests } from '@joplin/lib/services/e2ee/ppkTestUtils';
import { Theme, ThemeAppearance } from '@joplin/lib/themes/type';
import ProfileSwitcher from './components/ProfileSwitcher/ProfileSwitcher';
import ProfileEditor from './components/ProfileSwitcher/ProfileEditor';
import sensorInfo, { SensorInfo } from './components/biometrics/sensorInfo';
import { getCurrentProfile } from '@joplin/lib/services/profileConfig';
import { getDatabaseName, getPluginDataDir, getProfilesRootDir, getResourceDir, setDispatch } from './services/profiles';
import userFetcher, { initializeUserFetcher } from '@joplin/lib/utils/userFetcher';
import { ReactNode } from 'react';
import { parseShareCache } from '@joplin/lib/services/share/reducer';
import autodetectTheme, { onSystemColorSchemeChange } from './utils/autodetectTheme';
import runOnDeviceFsDriverTests from './utils/fs-driver/runOnDeviceTests';
import PluginRunnerWebView from './components/plugins/PluginRunnerWebView';
import { refreshFolders, scheduleRefreshFolders } from '@joplin/lib/folders-screen-utils';
import KeymapService from '@joplin/lib/services/KeymapService';
import PluginService from '@joplin/lib/services/plugins/PluginService';
import initializeCommandService from './utils/initializeCommandService';
import PlatformImplementation from './services/plugins/PlatformImplementation';
import ShareManager from './components/screens/ShareManager';
import appDefaultState, { DEFAULT_ROUTE } from './utils/appDefaultState';
import { setDateFormat, setTimeFormat, setTimeLocale } from '@joplin/utils/time';
import { AppState } from './utils/types';
import { getDisplayParentId } from '@joplin/lib/services/trash';
type SideMenuPosition = 'left' | 'right';
2017-12-30 21:57:34 +02:00
2023-02-19 21:00:17 +02:00
const logger = Logger.create('root');
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
let storeDispatch: any = function(_action: any) {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
const logReducerAction = function(action: any) {
if (['SIDE_MENU_OPEN_PERCENT', 'SYNC_REPORT_UPDATE'].indexOf(action.type) >= 0) return;
const msg = [action.type];
if (action.routeName) msg.push(action.routeName);
// reg.logger().debug('Reducer action', msg.join(', '));
};
const biometricsEnabled = (sensorInfo: SensorInfo): boolean => {
return !!sensorInfo && sensorInfo.enabled;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
const generalMiddleware = (store: any) => (next: any) => async (action: any) => {
logReducerAction(action);
PoorManIntervals.update(); // This function needs to be called regularly so put it here
const result = next(action);
const newState: AppState = store.getState();
let doRefreshFolders = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
await reduxSharedMiddleware(store, next, action, storeDispatch as any);
if (action.type === 'NAV_GO') Keyboard.dismiss();
if (['NOTE_UPDATE_ONE', 'NOTE_DELETE', 'FOLDER_UPDATE_ONE', 'FOLDER_DELETE'].indexOf(action.type) >= 0) {
if (!await reg.syncTarget().syncStarted()) void reg.scheduleSync(1000, { syncSteps: ['update_remote', 'delete_remote'] }, true);
SearchEngine.instance().scheduleSyncTables();
}
if (['FOLDER_UPDATE_ONE'].indexOf(action.type) >= 0) {
doRefreshFolders = true;
}
if (['EVENT_NOTE_ALARM_FIELD_CHANGE', 'NOTE_DELETE'].indexOf(action.type) >= 0) {
await AlarmService.updateNoteNotification(action.id, action.type === 'NOTE_DELETE');
2017-11-28 20:58:04 +02:00
}
if (action.type === 'NOTE_DELETE' && newState.route?.routeName === 'Note' && newState.route.noteId === action.id) {
const parentItem = action.originalItem?.parent_id ? await Folder.load(action.originalItem?.parent_id) : null;
const parentId = getDisplayParentId(action.originalItem, parentItem);
await NavService.go('Notes', { folderId: parentId });
}
if (action.type === 'SETTING_UPDATE_ONE' && action.key === 'sync.interval' || action.type === 'SETTING_UPDATE_ALL') {
reg.setupRecurrentSync();
}
if ((action.type === 'SETTING_UPDATE_ONE' && (action.key === 'dateFormat' || action.key === 'timeFormat')) || (action.type === 'SETTING_UPDATE_ALL')) {
time.setDateFormat(Setting.value('dateFormat'));
time.setTimeFormat(Setting.value('timeFormat'));
setDateFormat(Setting.value('dateFormat'));
setTimeFormat(Setting.value('timeFormat'));
}
if (action.type === 'SETTING_UPDATE_ONE' && action.key === 'locale' || action.type === 'SETTING_UPDATE_ALL') {
setLocale(Setting.value('locale'));
setTimeLocale(Setting.value('locale'));
}
if ((action.type === 'SETTING_UPDATE_ONE' && (action.key.indexOf('encryption.') === 0)) || (action.type === 'SETTING_UPDATE_ALL')) {
await loadMasterKeysFromSettings(EncryptionService.instance());
void DecryptionWorker.instance().scheduleStart();
const loadedMasterKeyIds = EncryptionService.instance().loadedMasterKeyIds();
storeDispatch({
type: 'MASTERKEY_REMOVE_NOT_LOADED',
ids: loadedMasterKeyIds,
});
// Schedule a sync operation so that items that need to be encrypted
// are sent to sync target.
void reg.scheduleSync(null, null, true);
}
2017-11-03 20:51:13 +02:00
if (
action.type === 'AUTODETECT_THEME'
|| action.type === 'SETTING_UPDATE_ALL'
|| (action.type === 'SETTING_UPDATE_ONE' && ['themeAutoDetect', 'preferredLightTheme', 'preferredDarkTheme'].includes(action.key))
) {
autodetectTheme();
}
if (action.type === 'NAV_GO' && action.routeName === 'Notes') {
if ('selectedFolderId' in newState) {
Setting.setValue('activeFolderId', newState.selectedFolderId);
}
const notesParent: NotesParent = {
type: action.smartFilterId ? 'SmartFilter' : 'Folder',
selectedItemId: action.smartFilterId ? action.smartFilterId : newState.selectedFolderId,
};
Setting.setValue('notesParent', serializeNotesParent(notesParent));
}
if (action.type === 'SYNC_GOT_ENCRYPTED_ITEM') {
void DecryptionWorker.instance().scheduleStart();
2017-12-30 21:57:34 +02:00
}
if (action.type === 'SYNC_CREATED_OR_UPDATED_RESOURCE') {
void ResourceFetcher.instance().autoAddResources();
}
if (doRefreshFolders) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
await scheduleRefreshFolders((action: any) => storeDispatch(action), newState.selectedFolderId);
}
return result;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
const navHistory: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
function historyCanGoBackTo(route: any) {
2018-03-18 01:00:01 +02:00
if (route.routeName === 'Note') return false;
if (route.routeName === 'Folder') return false;
// There's no point going back to these screens in general and, at least in OneDrive case,
// it can be buggy to do so, due to incorrectly relying on global state (reg.syncTarget...)
if (route.routeName === 'OneDriveLogin') return false;
if (route.routeName === 'DropboxLogin') return false;
return true;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
const appReducer = (state = appDefaultState, action: any) => {
let newState = state;
let historyGoingBack = false;
try {
switch (action.type) {
case 'NAV_BACK':
case 'NAV_GO':
if (action.type === 'NAV_BACK') {
if (!navHistory.length) break;
let newAction = null;
while (navHistory.length) {
newAction = navHistory.pop();
if (newAction.routeName !== state.route.routeName) break;
}
action = newAction ? newAction : navHistory.pop();
historyGoingBack = true;
}
{
const currentRoute = state.route;
2020-12-30 12:54:00 +02:00
if (!historyGoingBack && historyCanGoBackTo(currentRoute)) {
2020-02-19 02:09:19 +02:00
// If the route *name* is the same (even if the other parameters are different), we
// overwrite the last route in the history with the current one. If the route name
// is different, we push a new history entry.
if (currentRoute.routeName === action.routeName) {
// nothing
} else {
navHistory.push(currentRoute);
}
}
// HACK: whenever a new screen is loaded, all the previous screens of that type
// are overwritten with the new screen parameters. This is because the way notes
// are currently loaded is not optimal (doesn't retain history properly) so
// this is a simple fix without doing a big refactoring to change the way notes
// are loaded. Might be good enough since going back to different folders
// is probably not a common workflow.
for (let i = 0; i < navHistory.length; i++) {
const n = navHistory[i];
if (n.routeName === action.routeName) {
navHistory[i] = { ...action };
}
}
newState = { ...state };
newState.selectedNoteHash = '';
if ('noteId' in action) {
2017-11-22 20:35:31 +02:00
newState.selectedNoteIds = action.noteId ? [action.noteId] : [];
}
if ('folderId' in action) {
newState.selectedFolderId = action.folderId;
newState.notesParentType = 'Folder';
}
if ('tagId' in action) {
newState.selectedTagId = action.tagId;
newState.notesParentType = 'Tag';
}
if ('smartFilterId' in action) {
newState.smartFilterId = action.smartFilterId;
newState.selectedSmartFilterId = action.smartFilterId;
newState.notesParentType = 'SmartFilter';
}
if ('itemType' in action) {
newState.selectedItemType = action.itemType;
}
if ('noteHash' in action) {
newState.selectedNoteHash = action.noteHash;
}
if ('sharedData' in action) {
newState.sharedData = action.sharedData;
} else {
newState.sharedData = null;
}
newState.route = action;
newState.historyCanGoBack = !!navHistory.length;
}
break;
case 'SIDE_MENU_TOGGLE':
newState = { ...state };
newState.showSideMenu = !newState.showSideMenu;
break;
case 'SIDE_MENU_OPEN':
newState = { ...state };
newState.showSideMenu = true;
break;
case 'SIDE_MENU_CLOSE':
newState = { ...state };
newState.showSideMenu = false;
break;
case 'SIDE_MENU_OPEN_PERCENT':
newState = { ...state };
newState.sideMenuOpenPercent = action.value;
break;
case 'SET_PLUGIN_PANELS_DIALOG_VISIBLE':
newState = { ...state };
newState.showPanelsDialog = action.visible;
break;
case 'NOTE_SELECTION_TOGGLE':
{
newState = { ...state };
const noteId = action.id;
const newSelectedNoteIds = state.selectedNoteIds.slice();
const existingIndex = state.selectedNoteIds.indexOf(noteId);
if (existingIndex >= 0) {
newSelectedNoteIds.splice(existingIndex, 1);
} else {
newSelectedNoteIds.push(noteId);
}
newState.selectedNoteIds = newSelectedNoteIds;
newState.noteSelectionEnabled = !!newSelectedNoteIds.length;
}
break;
case 'NOTE_SELECTION_START':
if (!state.noteSelectionEnabled) {
newState = { ...state };
newState.noteSelectionEnabled = true;
newState.selectedNoteIds = [action.id];
}
break;
case 'NOTE_SELECTION_END':
newState = { ...state };
newState.noteSelectionEnabled = false;
newState.selectedNoteIds = [];
break;
case 'NOTE_SIDE_MENU_OPTIONS_SET':
2019-07-11 18:43:55 +02:00
newState = { ...state };
newState.noteSideMenuOptions = action.options;
break;
case 'SET_SIDE_MENU_TOUCH_GESTURES_DISABLED':
newState = { ...state };
newState.disableSideMenuGestures = action.disableSideMenuGestures;
break;
case 'MOBILE_DATA_WARNING_UPDATE':
newState = { ...state };
newState.isOnMobileData = action.isOnMobileData;
break;
}
} catch (error) {
2019-09-19 23:51:18 +02:00
error.message = `In reducer: ${error.message} Action: ${JSON.stringify(action)}`;
throw error;
}
return reducer(newState, action);
};
const store = createStore(appReducer, applyMiddleware(generalMiddleware));
storeDispatch = store.dispatch;
2017-05-09 22:46:54 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
function resourceFetcher_downloadComplete(event: any) {
if (event.encrypted) {
void DecryptionWorker.instance().scheduleStart();
}
}
function decryptionWorker_resourceMetadataButNotBlobDecrypted() {
ResourceFetcher.instance().scheduleAutoAddResources();
}
2023-07-18 15:58:06 +02:00
const initializeTempDir = async () => {
const tempDir = `${getProfilesRootDir()}/tmp`;
// Re-create the temporary directory.
try {
await shim.fsDriver().remove(tempDir);
} catch (_error) {
// The logger may not exist yet. Do nothing.
}
await shim.fsDriver().mkdir(tempDir);
return tempDir;
};
const getInitialActiveFolder = async () => {
let folderId = Setting.value('activeFolderId');
// In some cases (e.g. new profile/install), activeFolderId hasn't been set yet.
// Because activeFolderId is used to determine the parent for new notes, initialize
// it here:
if (!folderId) {
folderId = (await Folder.defaultFolder())?.id;
if (folderId) {
Setting.setValue('activeFolderId', folderId);
}
}
return await Folder.load(folderId);
};
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
async function initialize(dispatch: Dispatch) {
2017-07-10 20:09:58 +02:00
shimInit();
2017-07-07 19:19:24 +02:00
setDispatch(dispatch);
const { profileConfig, isSubProfile } = await initProfile(getProfilesRootDir());
const currentProfile = getCurrentProfile(profileConfig);
dispatch({
type: 'PROFILE_CONFIG_SET',
value: profileConfig,
});
Setting.setConstant('env', __DEV__ ? Env.Dev : Env.Prod);
Setting.setConstant('appId', 'net.cozic.joplin-mobile');
Setting.setConstant('appType', AppType.Mobile);
2023-07-18 15:58:06 +02:00
Setting.setConstant('tempDir', await initializeTempDir());
Setting.setConstant('cacheDir', `${getProfilesRootDir()}/cache`);
const resourceDir = getResourceDir(currentProfile, isSubProfile);
Setting.setConstant('resourceDir', resourceDir);
Setting.setConstant('pluginDir', `${getProfilesRootDir()}/plugins`);
Setting.setConstant('pluginDataDir', getPluginDataDir(currentProfile, isSubProfile));
await shim.fsDriver().mkdir(resourceDir);
2017-07-10 00:57:15 +02:00
const logDatabase = new Database(new DatabaseDriverReactNative());
await logDatabase.open({ name: 'log.sqlite' });
2017-07-10 00:57:15 +02:00
await logDatabase.exec(Logger.databaseCreateTableSql());
2017-07-15 01:12:32 +02:00
const mainLogger = new Logger();
2020-12-30 12:54:00 +02:00
mainLogger.addTarget(TargetType.Database, { database: logDatabase, source: 'm' });
2017-12-31 15:58:50 +02:00
mainLogger.setLevel(Logger.LEVEL_INFO);
if (Setting.value('env') === 'dev') {
2020-12-30 12:54:00 +02:00
mainLogger.addTarget(TargetType.Console);
2017-12-31 15:58:50 +02:00
mainLogger.setLevel(Logger.LEVEL_DEBUG);
}
2017-07-15 01:12:32 +02:00
Logger.initializeGlobalLogger(mainLogger);
2023-08-04 11:57:54 +02:00
initLib(mainLogger);
2017-07-15 01:12:32 +02:00
reg.setLogger(mainLogger);
2020-12-30 12:54:00 +02:00
reg.setShowErrorMessageBoxHandler((message: string) => { alert(message); });
reg.setDispatch(dispatch);
2017-07-10 00:57:15 +02:00
BaseService.logger_ = mainLogger;
// require('@joplin/lib/ntpDate').setLogger(reg.logger());
reg.logger().info('====================================');
2021-06-17 19:19:32 +02:00
reg.logger().info(`Starting application ${Setting.value('appId')} v${VersionInfo.appVersion} (${Setting.value('env')})`);
2017-07-10 00:57:15 +02:00
2017-07-15 01:12:32 +02:00
const dbLogger = new Logger();
2020-12-30 12:54:00 +02:00
dbLogger.addTarget(TargetType.Database, { database: logDatabase, source: 'm' });
if (Setting.value('env') === 'dev') {
2020-12-30 12:54:00 +02:00
dbLogger.addTarget(TargetType.Console);
dbLogger.setLevel(Logger.LEVEL_INFO); // Set to LEVEL_DEBUG for full SQL queries
2017-07-15 19:08:54 +02:00
} else {
dbLogger.setLevel(Logger.LEVEL_INFO);
}
2017-07-15 01:12:32 +02:00
const db = new JoplinDatabase(new DatabaseDriverReactNative());
2017-07-15 01:12:32 +02:00
db.setLogger(dbLogger);
2017-07-10 00:57:15 +02:00
reg.setDb(db);
// reg.dispatch = dispatch;
2017-07-10 00:57:15 +02:00
BaseModel.dispatch = dispatch;
BaseSyncTarget.dispatch = dispatch;
NavService.dispatch = dispatch;
BaseModel.setDb(db);
2017-07-10 00:57:15 +02:00
KvStore.instance().setDb(reg.db());
BaseItem.loadClass('Note', Note);
BaseItem.loadClass('Folder', Folder);
BaseItem.loadClass('Resource', Resource);
BaseItem.loadClass('Tag', Tag);
BaseItem.loadClass('NoteTag', NoteTag);
BaseItem.loadClass('MasterKey', MasterKey);
BaseItem.loadClass('Revision', Revision);
2017-07-10 00:57:15 +02:00
2017-12-30 21:57:34 +02:00
const fsDriver = new FsDriverRN();
Resource.fsDriver_ = fsDriver;
FileApiDriverLocal.fsDriver_ = fsDriver;
2017-12-30 21:57:34 +02:00
Mobile: Upgraded React Native to v0.63 commit 2fb6cee90174bfcc02f77ba1606bfd8c4e2c8fc8 Merge: 4e303be85f db509955f6 Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 16:24:07 2020 +0100 Merge branch 'dev' into rn_63 commit 4e303be85f7b3162b7e5b96e18557da13acfc988 Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 16:14:39 2020 +0100 Clean up commit e3a37ec2d6f3e6cc07c018b11b3f80ca8256063e Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 15:57:55 2020 +0100 Use different script for pre-commit and manual start commit bd236648fcd92a812cd16369dfa2238d38c6638f Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 15:56:45 2020 +0100 Removed RN eslint config commit e7feda41c9b473cd18768f2ce7686611fa2b3d08 Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 15:27:08 2020 +0100 Revert "Disable git hook for now" This reverts commit 89263ac7425bae5b03b60742ab186441217b37dc. commit cfd63fe46fbc714c065f13dd9add5a0b8e18bf1f Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 13:02:32 2020 +0100 Ask permission to use geo-location commit 66059939a38460ba05c09eed7f3b19fc4ead924c Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 12:26:20 2020 +0100 Fixed WebView race condition commit 1e0d2b7b86d88629f19ae6574f73c945d422d0b5 Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 11:56:21 2020 +0100 Fixed webview issues commit f537d22d7fc4bcf6ddb54a4faadf72f585ae271c Author: Laurent Cozic <laurent@cozic.net> Date: Fri Oct 16 11:08:29 2020 +0100 Improve resource file watching commit eec32cf70aaf69b04a703ce49c3ede48a6ac1067 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 18:40:13 2020 +0100 Removed cache package dependency and implemented one more suitable for React Native commit efa346fea48414c98c1e577bf0d74a6e90a78044 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 14:57:21 2020 +0100 iOS: Added fonts to Info.plist although it was working without it commit 572b647bc0ff5b12ddd555ad7ca2bb18ccaeb512 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 14:56:49 2020 +0100 Specify content-type header for OneDrive to prevent network error commit bcedf6c7f0c35a428fd1c0800d4f17de662a49ff Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 12:45:01 2020 +0100 iOS: Disable long press menu since it is already built-in commit 7359dd61d1a609dbfce87b0deb169b8c5e2ace14 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 12:37:40 2020 +0100 Removed unused react-native-device-info commit 2d63ab36d32775f07236dae62f6cc7792dac435a Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 12:35:54 2020 +0100 iOS: Fixed taking a picture commit 8e2875a91c87b48ba3e230e9296d032cd05a267c Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 12:11:13 2020 +0100 iOS: Restored camera roll functionality commit 75f5edf2addfe3590d1a37bdac99680cb1a5c84c Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 11:40:13 2020 +0100 iOS: Fixed build settings commit b220c984198e78a2401387f4385bfdd331852d78 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 11:40:03 2020 +0100 iOS: Got images to work with WebKit commit c34b43e841b768104f19e86900133a1986b53af9 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 10:24:52 2020 +0100 iOS: Restore more settings commit 32997611e625f1775df05af966782ae763c1aa17 Author: Laurent Cozic <laurent@cozic.net> Date: Thu Oct 15 10:15:14 2020 +0100 iOS: Added back icons and other properties commit b5811d7f7cff227a30bb10ecad76f52cb212170a Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 23:53:14 2020 +0100 Got iOS build to work commit dc6d7c00e0048088cca653d5214d1cc4679ca005 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 18:40:06 2020 +0100 Imported old settings in gradle build commit dff59f560317d260b8540a9324bcdd5e749a0c0b Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 18:20:00 2020 +0100 Restored sharing commit 0bdb449e72ef1766bd5aac878f44106c36e662c2 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 17:25:40 2020 +0100 Updated NoteBodyViewer commit 0c0d228815251cfaf66ba25a276852d32192f106 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 16:54:42 2020 +0100 Fixed networking commit 6ff45ce485d59e3e0fe66a9658a678499c887058 Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 13:11:00 2020 +0100 Fixed document picker commit cc889182b66052b8dfad03b46121e6a14763a51a Author: Laurent Cozic <laurent@cozic.net> Date: Wed Oct 14 12:56:27 2020 +0100 Added back support for alarms commit 040261abfad89e5a58617d4c2d4f811d324ea488 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 22:04:49 2020 +0100 Fixed Clipboard and remove image-picker package commit 1077ad8f16481afcc63d92020e91cd37f077f207 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 21:54:52 2020 +0100 Fixed Select Alarm dialog and PoorManIntervals class commit 8296676fd52878b2f1cc2028a099f31909e6f286 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 21:32:52 2020 +0100 Fixed icons and warnings commit 3b0e3f6f43c83bb103132e8296d3887fccd386b5 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 17:02:59 2020 +0100 Got app to build again commit 89263ac7425bae5b03b60742ab186441217b37dc Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 15:41:17 2020 +0100 Disable git hook for now commit d6da162f674f94ba2c462268e39c161fa6126220 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 15:39:12 2020 +0100 Restored back all RN packages commit 7f8ce3732cf4c8ff6dcbcc0a8918c680adadd3f4 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 15:13:12 2020 +0100 Restored base packages commit ea59726eb3e0414afcdbe8af30a7765875239225 Author: Laurent Cozic <laurent@cozic.net> Date: Tue Oct 13 15:05:17 2020 +0100 Started over from scratch
2020-10-16 17:26:19 +02:00
AlarmService.setDriver(new AlarmServiceDriver(mainLogger));
AlarmService.setLogger(mainLogger);
// Currently CommandService is just used for plugins.
initializeCommandService(store);
// KeymapService is also present for plugin compatibility
KeymapService.instance().initialize();
// Even if there are no plugins, we need to initialize the PluginService so that
// plugin search can work.
const platformImplementation = PlatformImplementation.instance();
PluginService.instance().initialize(
platformImplementation.versionInfo.version, platformImplementation, null, store,
);
setRSA(RSA);
2017-07-10 00:57:15 +02:00
try {
if (Setting.value('env') === 'prod') {
await db.open({ name: getDatabaseName(currentProfile, isSubProfile) });
2017-07-10 00:57:15 +02:00
} else {
await db.open({ name: getDatabaseName(currentProfile, isSubProfile, '-20240127-1') });
// await db.clearForTesting();
2017-07-10 00:57:15 +02:00
}
2017-05-16 23:46:21 +02:00
reg.logger().info('Database is ready.');
reg.logger().info('Loading settings...');
await loadKeychainServiceAndSettings(KeychainServiceDriverMobile);
await migrateMasterPassword();
if (!Setting.value('clientId')) Setting.setValue('clientId', uuid.create());
2022-09-30 18:38:22 +02:00
reg.logger().info(`Client ID: ${Setting.value('clientId')}`);
BaseItem.syncShareCache = parseShareCache(Setting.value('sync.shareCache'));
2023-06-01 17:48:02 +02:00
if (Setting.value('firstStart')) {
2023-06-01 17:48:02 +02:00
const detectedLocale = shim.detectAndSetLocale(Setting);
reg.logger().info(`First start: detected locale as ${detectedLocale}`);
Setting.skipDefaultMigrations();
Setting.setValue('firstStart', false);
} else {
Setting.applyDefaultMigrations();
}
if (Setting.value('env') === Env.Dev) {
// Setting.setValue('sync.10.path', 'https://api.joplincloud.com');
// Setting.setValue('sync.10.userContentPath', 'https://joplinusercontent.com');
Setting.setValue('sync.10.path', 'http://api.joplincloud.local:22300');
Setting.setValue('sync.10.userContentPath', 'http://joplinusercontent.local:22300');
Setting.setValue('sync.10.website', 'http://joplincloud.local:22300');
// Setting.setValue('sync.target', 10);
// Setting.setValue('sync.10.username', 'user1@example.com');
2022-04-12 18:06:53 +02:00
// Setting.setValue('sync.10.password', '111111');
}
2017-07-25 20:57:06 +02:00
if (Setting.value('db.ftsEnabled') === -1) {
const ftsEnabled = await db.ftsEnabled();
Setting.setValue('db.ftsEnabled', ftsEnabled ? 1 : 0);
reg.logger().info('db.ftsEnabled = ', Setting.value('db.ftsEnabled'));
2017-07-25 20:57:06 +02:00
}
if (Setting.value('env') === 'dev') {
Setting.setValue('welcome.enabled', false);
}
PluginAssetsLoader.instance().setLogger(mainLogger);
await PluginAssetsLoader.instance().importAssets();
// eslint-disable-next-line require-atomic-updates
BaseItem.revisionService_ = RevisionService.instance();
// Note: for now we hard-code the folder sort order as we need to
// create a UI to allow customisation (started in branch mobile_add_sidebar_buttons)
Setting.setValue('folders.sortOrder.field', 'title');
Setting.setValue('folders.sortOrder.reverse', false);
2019-09-19 23:51:18 +02:00
reg.logger().info(`Sync target: ${Setting.value('sync.target')}`);
setLocale(Setting.value('locale'));
2017-07-19 23:26:30 +02:00
if (Platform.OS === 'android') {
const ignoreTlsErrors = Setting.value('net.ignoreTlsErrors');
if (ignoreTlsErrors) {
await setIgnoreTlsErrors(ignoreTlsErrors);
}
}
2017-12-30 21:57:34 +02:00
// ----------------------------------------------------------------
// E2EE SETUP
// ----------------------------------------------------------------
EncryptionService.fsDriver_ = fsDriver;
// eslint-disable-next-line require-atomic-updates
2017-12-30 21:57:34 +02:00
BaseItem.encryptionService_ = EncryptionService.instance();
BaseItem.shareService_ = ShareService.instance();
Resource.shareService_ = ShareService.instance();
DecryptionWorker.instance().dispatch = dispatch;
2017-12-30 21:57:34 +02:00
DecryptionWorker.instance().setLogger(mainLogger);
DecryptionWorker.instance().setKvStore(KvStore.instance());
2017-12-30 21:57:34 +02:00
DecryptionWorker.instance().setEncryptionService(EncryptionService.instance());
await loadMasterKeysFromSettings(EncryptionService.instance());
DecryptionWorker.instance().on('resourceMetadataButNotBlobDecrypted', decryptionWorker_resourceMetadataButNotBlobDecrypted);
2017-12-30 21:57:34 +02:00
// ----------------------------------------------------------------
// / E2EE SETUP
// ----------------------------------------------------------------
await ShareService.instance().initialize(store, EncryptionService.instance());
reg.logger().info('Loading folders...');
2017-07-06 23:30:45 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
await refreshFolders((action: any) => dispatch(action), '');
2017-07-09 00:57:09 +02:00
const tags = await Tag.allWithNotes();
2017-07-25 20:36:52 +02:00
dispatch({
type: 'TAG_UPDATE_ALL',
items: tags,
2017-07-25 20:36:52 +02:00
});
// const masterKeys = await MasterKey.all();
2017-12-30 21:57:34 +02:00
// dispatch({
// type: 'MASTERKEY_UPDATE_ALL',
// items: masterKeys,
// });
2017-12-30 21:57:34 +02:00
const folder = await getInitialActiveFolder();
2017-07-23 20:26:50 +02:00
dispatch({
type: 'FOLDER_SET_COLLAPSED_ALL',
ids: Setting.value('collapsedFolderIds'),
});
const notesParent = parseNotesParent(Setting.value('notesParent'), Setting.value('activeFolderId'));
if (notesParent && notesParent.type === 'SmartFilter') {
dispatch(DEFAULT_ROUTE);
} else if (!folder) {
dispatch(DEFAULT_ROUTE);
2017-07-24 23:52:30 +02:00
} else {
2017-07-25 20:09:01 +02:00
dispatch({
type: 'NAV_GO',
routeName: 'Notes',
2017-07-25 20:09:01 +02:00
folderId: folder.id,
});
2017-07-24 23:52:30 +02:00
}
await clearSharedFilesCache();
2017-07-10 00:57:15 +02:00
} catch (error) {
2019-09-19 23:51:18 +02:00
alert(`Initialization error: ${error.message}`);
reg.logger().error('Initialization error:', error);
2017-07-10 00:57:15 +02:00
}
reg.setupRecurrentSync();
2017-07-22 19:35:39 +02:00
initializeUserFetcher();
PoorManIntervals.setInterval(() => { void userFetcher(); }, 1000 * 60 * 60);
2017-11-28 20:58:04 +02:00
PoorManIntervals.setTimeout(() => {
2020-12-30 12:54:00 +02:00
void AlarmService.garbageCollect();
2017-11-28 20:58:04 +02:00
}, 1000 * 60 * 60);
2017-11-24 20:06:45 +02:00
2018-03-16 16:32:47 +02:00
ResourceService.runInBackground();
ResourceFetcher.instance().setFileApi(() => { return reg.syncTarget().fileApi(); });
ResourceFetcher.instance().setLogger(reg.logger());
ResourceFetcher.instance().dispatch = dispatch;
ResourceFetcher.instance().on('downloadComplete', resourceFetcher_downloadComplete);
void ResourceFetcher.instance().start();
SearchEngine.instance().setDb(reg.db());
SearchEngine.instance().setLogger(reg.logger());
SearchEngine.instance().scheduleSyncTables();
await MigrationService.instance().run();
// When the app starts we want the full sync to
// start almost immediately to get the latest data.
// doWifiConnectionCheck set to true so initial sync
// doesn't happen on mobile data
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
void reg.scheduleSync(100, null, true).then(() => {
2017-11-28 20:58:04 +02:00
// Wait for the first sync before updating the notifications, since synchronisation
// might change the notifications.
2020-12-30 12:54:00 +02:00
void AlarmService.updateAllNotifications();
2017-12-30 21:57:34 +02:00
void DecryptionWorker.instance().scheduleStart();
2017-11-28 20:58:04 +02:00
});
2017-11-24 20:06:45 +02:00
await WelcomeUtils.install(Setting.value('locale'), dispatch);
2019-02-05 20:46:32 +02:00
// Collect revisions more frequently on mobile because it doesn't auto-save
// and it cannot collect anything when the app is not active.
RevisionService.instance().runInBackground(1000 * 30);
// ----------------------------------------------------------------------------
// Plugin service setup
// ----------------------------------------------------------------------------
// On startup, we can clear plugin update state -- plugins that were updated when the
// user last ran the app have been updated and will be reloaded.
const pluginService = PluginService.instance();
const pluginSettings = pluginService.unserializePluginSettings(Setting.value('plugins.states'));
const updatedSettings = pluginService.clearUpdateState(pluginSettings);
Setting.setValue('plugins.states', updatedSettings);
// ----------------------------------------------------------------------------
// Keep this below to test react-native-rsa-native
// ----------------------------------------------------------------------------
// const testData = await createTestData();
// await checkTestData(testData);
// const testData = {
// "publicKey": "-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAoMx9NBioka8DUjO3bKrWMn8uJ23LH1xySogQFR6yh6qbl6i5LKTw\nPgqvv55FUuQtYTMtUTVLggYQhdCBvwbBrD1OqO4xU6Ew7x5/TQKPV3MSgYaps3FF\nOdipC4FyA00jBe6Z1CIpL+ZaSnvjDbMUf5lW8bmfRuXfdBGAcdSBjqm9ttajOws+\n7BBSQ9nI5dnBnWRIVEUb7e9bulgANzM1LMUOE+gaef7T3uKzc+Cx3BhHgw1JdFbL\nZAndYtP52KI5N3oiFM4II26DxmDrO1tQokNM88l5xT0BXPhYiEl1CeBpo5VHZBY2\nRHr4MM/OyAXSUdulsDzbntpE+Y85zv7gpQIDAQAB\n-----END RSA PUBLIC KEY-----",
// "privateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAoMx9NBioka8DUjO3bKrWMn8uJ23LH1xySogQFR6yh6qbl6i5\nLKTwPgqvv55FUuQtYTMtUTVLggYQhdCBvwbBrD1OqO4xU6Ew7x5/TQKPV3MSgYap\ns3FFOdipC4FyA00jBe6Z1CIpL+ZaSnvjDbMUf5lW8bmfRuXfdBGAcdSBjqm9ttaj\nOws+7BBSQ9nI5dnBnWRIVEUb7e9bulgANzM1LMUOE+gaef7T3uKzc+Cx3BhHgw1J\ndFbLZAndYtP52KI5N3oiFM4II26DxmDrO1tQokNM88l5xT0BXPhYiEl1CeBpo5VH\nZBY2RHr4MM/OyAXSUdulsDzbntpE+Y85zv7gpQIDAQABAoIBAEA0Zmm+ztAcyX6x\nF7RUImLXVV55AHntN9V6rrFAKJjzDl1oCUhCM4sSSUqBr7yBT31YKegbF6M7OK21\nq5jS4dIcSKQ7N4bk/dz8mGfvdby9Pc5qLqhvuex3DkiBzzxyOGHN+64wVbHCkJrd\nDLQTpUOtvoGWVHrCno6Bzn+lEnYbvdr0hqI5H4D0ubk6TYed1/4ZlJf0R/o/4jnl\nou0UG2hpJN4ur506cttkZJSTxLjzdO38JuQIAkCEglrMYVY61lBNPxC11Kr3ZN7o\ncm7gWZVyP26KoU27t/g+2FoiBGsWLqGYiuTaqT6dKZ2vHyJGjJIZZStv5ye2Ez8V\nKQwpjQECgYEA3xtwYu4n/G5UjEMumkXHNd/bDamelo1aQvvjkVvxKeASNBqV8cM0\n6Jb2FCuT9Y3mWbFTM0jpqXehpHUOCCnrPKGKnJ0ZS4/SRIrtw0iM6q17fTAqmuOt\nhX0pJ77Il8lVCtx4ItsW+LUGbm6CwotlYLVUuyluhKe0pGw2yafi2N0CgYEAuIFk\ng4p7x0i1LFAlIP0YQ07bJQ0E6FEWbCfMgrV3VjtbnT99EaqPOHhMasITCuoEFlh8\ncgyZ6oH7GEy4IRWrM+Mlm47S+NTrr6KgnTGf570ZAFuqnJac97oFB7BvlQsQot6F\n0L2JKM7dQKIMlvwA9DoXZdKX/9ykiqqIpawNxmkCgYEAuyJOwAw2ads4+3UWT7wb\nfarIF8ugA3OItAqHNFNEEvWpDx8FigVMCZMl0IFE14AwKCc+PBP6OXTolgLAxEQ0\n1WRB2V9D6kc1/Nvy1guydt0QaU7PTZ+O2hrDPF0f74Cl3jhSZBoUSIO+Yz46W2eE\nnvs5mMsFsirgr9E8myRAd9kCgYAGMCDE4KIiHugkolN8dcCYkU58QaGGgSG1YuhT\nAe8Mr1T1QynYq9W92RsHAZdN6GdWsIUL9iw7VzyqpfgO9AEX7mhWfUXKHqoA6/1j\nCEUKqqbqAikIs2x0SoLcrSgw4XwfWkM2qwSsn7N/9W9iqPUHO+OJALUkWawTEoEe\nvVSA8QKBgQCEYCPnxgeQSZkrv7x5soXzgF1YN5EZRa1mTUqPBubs564ZjIIY66mI\nCTaHl7U1cPAhx7mHkSzP/i5NjjLqPZZNOyawWDEEmOzxX69OIzKImb6mEQNyS3do\nI8jnpN5q9pw5TvuEIYSrGqQVnHeaEjSvcT48W9GuzjNVscGfw76fPg==\n-----END RSA PRIVATE KEY-----",
// "plaintext": "just testing",
// "ciphertext": "BfkKLdrmd2UX4sPf0bzhfqrg3rKwH5DS7dPAqdmoQuHlrvEBrYKqheekwpnWQgGggGcm/orlrsQRwlexLv7jfRbb0bMnElkySMu4w6wTxILB66RX9H3vXCz02SwHKFRcuGJxlzTPUC23ki6f/McYJ2n/2L8qYxBO8fncTKutIWV54jY19RS1wQ4IdVDBqzji8D0QsRxUhVlpRk4qxsVnyuoyg9AyDe91LOYKfRc6NdapFij996nKzjxFcKOdBqpis34fN3Cg7avcs2Dm5vi7zlRhyGqJJhORXTU3x6hVwOBkVAisgaB7xS3lHiYp6Fs5tP3hBd0kFwVVx8gALbHsgg=="
// };
// await checkTestData(testData);
// await printTestData();
// ----------------------------------------------------------------------------
// On desktop and CLI we run various tests to check that node-rsa is working
// as expected. On mobile however we cannot run test units directly on
// device, and that's what would be needed to automatically verify
// react-native-rsa-native. So instead we run the tests every time the
// mobile app is started in dev mode. If there's any regression the below
// call will throw an error, alerting us of the issue. Otherwise it will
// just print some messages in the console.
// ----------------------------------------------------------------------------
if (Setting.value('env') === 'dev') {
await runRsaIntegrationTests();
await runOnDeviceFsDriverTests();
}
reg.logger().info('Application initialized');
2017-07-10 00:57:15 +02:00
}
class AppComponent extends React.Component {
private urlOpenListener_: EmitterSubscription|null = null;
private appStateChangeListener_: NativeEventSubscription|null = null;
private themeChangeListener_: NativeEventSubscription|null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private dropdownAlert_ = (_data: any) => new Promise<any>(res => res);
private callbackUrl: string|null = null;
public constructor() {
super();
this.state = {
sideMenuContentOpacity: new Animated.Value(0),
sideMenuWidth: this.getSideMenuWidth(),
sensorInfo: null,
};
this.lastSyncStarted_ = defaultState.syncStarted;
this.backButtonHandler_ = () => {
return this.backButtonHandler();
};
this.onAppStateChange_ = () => {
PoorManIntervals.update();
};
2021-04-24 10:22:11 +02:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2021-04-24 10:22:11 +02:00
this.handleOpenURL_ = (event: any) => {
// logger.info('Sharing: handleOpenURL_: start');
2023-02-19 21:00:17 +02:00
// If this is called while biometrics haven't been done yet, we can
// ignore the call, because handleShareData() will be called once
// biometricsDone is `true`.
if (event.url === ShareExtension.shareURL && this.props.biometricsDone) {
2023-02-19 21:00:17 +02:00
logger.info('Sharing: handleOpenURL_: Processing share data');
2021-04-24 10:22:11 +02:00
void this.handleShareData();
} else if (isCallbackUrl(event.url)) {
logger.info('received callback url: ', event.url);
this.callbackUrl = event.url;
if (this.props.biometricsDone) {
void this.handleCallbackUrl();
}
2021-04-24 10:22:11 +02:00
}
};
this.handleNewShare_ = () => {
// logger.info('Sharing: handleNewShare_: start');
2023-02-19 21:00:17 +02:00
// look at this.handleOpenURL_ comment
if (this.props.biometricsDone) {
2023-02-19 21:00:17 +02:00
logger.info('Sharing: handleNewShare_: Processing share data');
void this.handleShareData();
}
};
this.unsubscribeNewShareListener_ = ShareExtension.addShareListener(this.handleNewShare_);
this.handleScreenWidthChange_ = this.handleScreenWidthChange_.bind(this);
}
// 2020-10-08: It seems the initialisation code is quite fragile in general and should be kept simple.
// For example, adding a loading screen as was done in this commit: https://github.com/laurent22/joplin/commit/569355a3182bc12e50a54249882e3d68a72c2b28.
// had for effect that sharing with the app would create multiple instances of the app, thus breaking
// database access and so on. It's unclear why it happens and how to fix it but reverting that commit
// fixed the issue for now.
//
// Changing app launch mode doesn't help.
//
// It's possible that it's a bug in React Native, or perhaps the framework expects that the whole app can be
// mounted/unmounted or multiple ones can be running at the same time, but the app was not designed in this
// way.
//
// More reports and info about the multiple instance bug:
//
// https://github.com/laurent22/joplin/issues/3800
// https://github.com/laurent22/joplin/issues/3804
// https://github.com/laurent22/joplin/issues/3807
// https://discourse.joplinapp.org/t/webdav-config-encryption-config-randomly-lost-on-android/11364
// https://discourse.joplinapp.org/t/android-keeps-on-resetting-my-sync-and-theme/11443
public async componentDidMount() {
if (this.props.appState === 'starting') {
2017-08-01 19:41:58 +02:00
this.props.dispatch({
type: 'APP_STATE_SET',
state: 'initializing',
2017-08-01 19:41:58 +02:00
});
try {
NetInfo.configure({
reachabilityUrl: 'https://joplinapp.org/connection_check/',
reachabilityTest: async (response) => response.status === 200,
});
// This will be called right after adding the event listener
// so there's no need to check netinfo on startup
this.unsubscribeNetInfoHandler_ = NetInfo.addEventListener(({ type, details }) => {
const isMobile = details.isConnectionExpensive || type === 'cellular';
reg.setIsOnMobileData(isMobile);
this.props.dispatch({
type: 'MOBILE_DATA_WARNING_UPDATE',
isOnMobileData: isMobile,
});
});
} catch (error) {
reg.logger().warn('Something went wrong while checking network info');
reg.logger().info(error);
}
await initialize(this.props.dispatch);
const loadedSensorInfo = await sensorInfo();
this.setState({ sensorInfo: loadedSensorInfo });
// If biometrics is disabled we set biometricsDone to `true`. We do
// it with a delay so that the component is properly mounted, and
// the componentDidUpdate gets triggered (which in turns will handle
// the share data, if any).
setTimeout(() => {
if (!biometricsEnabled(loadedSensorInfo)) {
this.props.dispatch({
type: 'BIOMETRICS_DONE_SET',
value: true,
});
}
}, 100);
this.props.dispatch({
type: 'APP_STATE_SET',
state: 'ready',
2017-08-01 19:41:58 +02:00
});
// setTimeout(() => {
// this.props.dispatch({
// type: 'NAV_GO',
// routeName: 'ProfileSwitcher',
// });
// }, 1000);
}
2017-11-28 22:17:34 +02:00
this.urlOpenListener_ = Linking.addEventListener('url', this.handleOpenURL_);
2021-04-24 10:22:11 +02:00
BackButtonService.initialize(this.backButtonHandler_);
2020-12-30 12:54:00 +02:00
AlarmService.setInAppNotificationHandler(async (alarmId: string) => {
const alarm = await Alarm.load(alarmId);
const notification = await Alarm.makeNotification(alarm);
void this.dropdownAlert_({
type: 'info',
title: notification.title,
message: notification.body ? notification.body : '',
});
});
this.appStateChangeListener_ = RNAppState.addEventListener('change', this.onAppStateChange_);
this.unsubscribeScreenWidthChangeHandler_ = Dimensions.addEventListener('change', this.handleScreenWidthChange_);
this.themeChangeListener_ = Appearance.addChangeListener(
({ colorScheme }) => onSystemColorSchemeChange(colorScheme),
);
onSystemColorSchemeChange(Appearance.getColorScheme());
this.quickActionShortcutListener_ = await setupQuickActions(this.props.dispatch);
await setupNotifications(this.props.dispatch);
// Setting.setValue('encryption.masterPassword', 'WRONG');
// setTimeout(() => NavService.go('EncryptionConfig'), 2000);
}
public componentWillUnmount() {
if (this.appStateChangeListener_) {
this.appStateChangeListener_.remove();
this.appStateChangeListener_ = null;
}
if (this.urlOpenListener_) {
this.urlOpenListener_.remove();
this.urlOpenListener_ = null;
}
if (this.themeChangeListener_) {
this.themeChangeListener_.remove();
this.themeChangeListener_ = null;
}
if (this.unsubscribeScreenWidthChangeHandler_) {
this.unsubscribeScreenWidthChangeHandler_.remove();
this.unsubscribeScreenWidthChangeHandler_ = null;
}
if (this.unsubscribeNetInfoHandler_) this.unsubscribeNetInfoHandler_();
if (this.unsubscribeNewShareListener_) {
this.unsubscribeNewShareListener_();
this.unsubscribeNewShareListener_ = undefined;
}
if (this.quickActionShortcutListener_) {
this.quickActionShortcutListener_.remove();
this.quickActionShortcutListener_ = undefined;
}
2017-07-10 23:00:41 +02:00
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public async componentDidUpdate(prevProps: any) {
if (this.props.biometricsDone !== prevProps.biometricsDone && this.props.biometricsDone) {
2023-02-19 21:00:17 +02:00
logger.info('Sharing: componentDidUpdate: biometricsDone');
void this.handleShareData();
void this.handleCallbackUrl();
}
}
private async backButtonHandler() {
if (this.props.noteSelectionEnabled) {
this.props.dispatch({ type: 'NOTE_SELECTION_END' });
return true;
}
2017-07-10 23:00:41 +02:00
if (this.props.showSideMenu) {
this.props.dispatch({ type: 'SIDE_MENU_CLOSE' });
return true;
2017-07-10 23:00:41 +02:00
}
if (this.props.historyCanGoBack) {
this.props.dispatch({ type: 'NAV_BACK' });
2017-07-10 23:00:41 +02:00
return true;
}
BackHandler.exitApp();
2017-07-10 23:00:41 +02:00
return false;
2017-05-11 22:14:01 +02:00
}
private async handleShareData() {
2021-04-24 10:22:11 +02:00
const sharedData = await ShareExtension.data();
2023-02-19 21:00:17 +02:00
2021-04-24 10:22:11 +02:00
if (sharedData) {
reg.logger().info('Received shared data');
// selectedFolderId can be null if no screens other than "All notes"
// have been opened.
const targetFolder = this.props.selectedFolderId ?? (await Folder.defaultFolder())?.id;
if (targetFolder) {
2023-02-19 21:00:17 +02:00
logger.info('Sharing: handleShareData: Processing...');
await handleShared(sharedData, targetFolder, this.props.dispatch);
2021-04-24 10:22:11 +02:00
} else {
reg.logger().info('Cannot handle share - default folder id is not set');
}
} else {
logger.info('Sharing: received empty share data.');
2021-04-24 10:22:11 +02:00
}
}
private async handleCallbackUrl() {
const url = this.callbackUrl;
this.callbackUrl = null;
if (url === null) {
return;
}
const { command, params } = parseCallbackUrl(url);
// adopted from app-mobile/utils/shareHandler.ts
// We go back one screen in case there's already a note open -
// if we don't do this, the dispatch below will do nothing
// (because routeName wouldn't change)
this.props.dispatch({ type: 'NAV_BACK' });
this.props.dispatch({ type: 'SIDE_MENU_CLOSE' });
switch (command) {
case CallbackUrlCommand.OpenNote:
this.props.dispatch({
type: 'NAV_GO',
routeName: 'Note',
noteId: params.id,
});
break;
case CallbackUrlCommand.OpenTag:
this.props.dispatch({
type: 'NAV_GO',
routeName: 'Notes',
tagId: params.id,
});
break;
case CallbackUrlCommand.OpenFolder:
this.props.dispatch({
type: 'NAV_GO',
routeName: 'Notes',
folderId: params.id,
});
break;
}
}
private async handleScreenWidthChange_() {
this.setState({ sideMenuWidth: this.getSideMenuWidth() });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public UNSAFE_componentWillReceiveProps(newProps: any) {
if (newProps.syncStarted !== this.lastSyncStarted_) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
if (!newProps.syncStarted) void refreshFolders((action: any) => this.props.dispatch(action), this.props.selectedFolderId);
this.lastSyncStarted_ = newProps.syncStarted;
}
}
private sideMenu_change(isOpen: boolean) {
2017-05-24 21:27:13 +02:00
// Make sure showSideMenu property of state is updated
// when the menu is open/closed.
this.props.dispatch({
type: isOpen ? 'SIDE_MENU_OPEN' : 'SIDE_MENU_CLOSE',
2017-05-24 21:27:13 +02:00
});
AccessibilityInfo.announceForAccessibility(
isOpen ? _('Side menu opened') : _('Side menu closed'),
);
2017-05-24 21:27:13 +02:00
}
private getSideMenuWidth = () => {
const sideMenuWidth = getResponsiveValue({
sm: 250,
md: 260,
lg: 270,
xl: 280,
xxl: 290,
});
return sideMenuWidth;
};
public render() {
if (this.props.appState !== 'ready') return null;
const theme: Theme = themeStyle(this.props.themeId);
2017-08-01 19:41:58 +02:00
let sideMenuContent: ReactNode = null;
let menuPosition: SideMenuPosition = 'left';
let disableSideMenuGestures = this.props.disableSideMenuGestures;
2019-07-11 18:43:55 +02:00
if (this.props.routeName === 'Note') {
sideMenuContent = <SafeAreaView style={{ flex: 1, backgroundColor: theme.backgroundColor }}><SideMenuContentNote options={this.props.noteSideMenuOptions}/></SafeAreaView>;
2019-07-11 18:43:55 +02:00
menuPosition = 'right';
} else if (this.props.routeName === 'Config') {
disableSideMenuGestures = true;
2019-07-11 18:43:55 +02:00
} else {
sideMenuContent = <SafeAreaView style={{ flex: 1, backgroundColor: theme.backgroundColor }}><SideMenuContent/></SafeAreaView>;
2019-07-11 18:43:55 +02:00
}
2017-05-24 21:09:46 +02:00
2017-07-14 20:49:14 +02:00
const appNavInit = {
Notes: { screen: NotesScreen },
Note: { screen: NoteScreen },
Tags: { screen: TagsScreen },
2017-07-14 20:49:14 +02:00
Folder: { screen: FolderScreen },
OneDriveLogin: { screen: OneDriveLoginScreen },
2018-03-27 01:55:44 +02:00
DropboxLogin: { screen: DropboxLoginScreen },
JoplinCloudLogin: { screen: JoplinCloudLoginScreen },
2017-12-30 21:57:34 +02:00
EncryptionConfig: { screen: EncryptionConfigScreen },
UpgradeSyncTarget: { screen: UpgradeSyncTargetScreen },
ShareManager: { screen: ShareManager },
ProfileSwitcher: { screen: ProfileSwitcher },
ProfileEditor: { screen: ProfileEditor },
2017-07-14 20:49:14 +02:00
Log: { screen: LogScreen },
Status: { screen: StatusScreen },
2017-07-23 00:52:24 +02:00
Search: { screen: SearchScreen },
2017-07-23 20:26:50 +02:00
Config: { screen: ConfigScreen },
2017-07-14 20:49:14 +02:00
};
// const statusBarStyle = theme.appearance === 'light-content';
const statusBarStyle = 'light-content';
const shouldShowMainContent = !biometricsEnabled(this.state.sensorInfo) || this.props.biometricsDone;
logger.info('root.biometrics: biometricsDone', this.props.biometricsDone);
logger.info('root.biometrics: biometricsEnabled', biometricsEnabled(this.state.sensorInfo));
logger.info('root.biometrics: shouldShowMainContent', shouldShowMainContent);
logger.info('root.biometrics: this.state.sensorInfo', this.state.sensorInfo);
// The right sidemenu can be difficult to close due to a bug in the sidemenu
// library (right sidemenus can't be swiped closed).
//
// Additionally, it can interfere with scrolling in the note viewer, so we use
// a smaller edge hit width.
const menuEdgeHitWidth = menuPosition === 'right' ? 20 : 30;
const mainContent = (
<View style={{ flex: 1, backgroundColor: theme.backgroundColor }}>
<SideMenu
menu={sideMenuContent}
edgeHitWidth={menuEdgeHitWidth}
toleranceX={4}
toleranceY={20}
openMenuOffset={this.state.sideMenuWidth}
menuPosition={menuPosition}
onChange={(isOpen: boolean) => this.sideMenu_change(isOpen)}
disableGestures={disableSideMenuGestures}
onSliding={(percent: number) => {
this.props.dispatch({
type: 'SIDE_MENU_OPEN_PERCENT',
value: percent,
});
}}
>
<StatusBar barStyle={statusBarStyle} />
<MenuProvider style={{ flex: 1 }}>
<SafeAreaView style={{ flex: 0, backgroundColor: theme.backgroundColor2 }}/>
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, backgroundColor: theme.backgroundColor }}>
{ shouldShowMainContent && <AppNav screens={appNavInit} dispatch={this.props.dispatch} /> }
</View>
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied */}
2023-10-24 20:19:09 +02:00
<DropdownAlert alert={(func: any) => (this.dropdownAlert_ = func)} />
{ !shouldShowMainContent && <BiometricPopup
dispatch={this.props.dispatch}
themeId={this.props.themeId}
sensorInfo={this.state.sensorInfo}
/> }
</SafeAreaView>
</MenuProvider>
</SideMenu>
<PluginRunnerWebView />
</View>
2017-05-11 22:14:01 +02:00
);
const paperTheme = theme.appearance === ThemeAppearance.Dark ? MD3DarkTheme : MD3LightTheme;
// Wrap everything in a PaperProvider -- this allows using components from react-native-paper
return (
<PaperProvider theme={{
...paperTheme,
version: 3,
colors: {
...paperTheme.colors,
onPrimaryContainer: theme.color5,
primaryContainer: theme.backgroundColor5,
outline: theme.codeBorderColor,
primary: theme.color4,
onPrimary: theme.backgroundColor4,
background: theme.backgroundColor,
surface: theme.backgroundColor,
onSurface: theme.color,
secondaryContainer: theme.raisedBackgroundColor,
onSecondaryContainer: theme.raisedColor,
surfaceVariant: theme.backgroundColor3,
onSurfaceVariant: theme.color3,
elevation: {
level0: 'transparent',
level1: theme.oddBackgroundColor,
level2: theme.raisedBackgroundColor,
level3: theme.raisedBackgroundColor,
level4: theme.raisedBackgroundColor,
level5: theme.raisedBackgroundColor,
},
},
}}>
{mainContent}
</PaperProvider>
);
2017-05-11 22:14:01 +02:00
}
2017-05-10 20:58:02 +02:00
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
2020-12-30 12:54:00 +02:00
const mapStateToProps = (state: any) => {
2017-05-10 20:58:02 +02:00
return {
2017-11-04 18:40:34 +02:00
historyCanGoBack: state.historyCanGoBack,
showSideMenu: state.showSideMenu,
syncStarted: state.syncStarted,
appState: state.appState,
noteSelectionEnabled: state.noteSelectionEnabled,
2018-09-04 12:07:33 +02:00
selectedFolderId: state.selectedFolderId,
2019-07-11 18:43:55 +02:00
routeName: state.route.routeName,
2020-09-15 15:01:07 +02:00
themeId: state.settings.theme,
2019-07-11 18:43:55 +02:00
noteSideMenuOptions: state.noteSideMenuOptions,
disableSideMenuGestures: state.disableSideMenuGestures,
biometricsDone: state.biometricsDone,
biometricsEnabled: state.settings['security.biometricsEnabled'],
2017-11-04 18:40:34 +02:00
};
2017-05-10 20:58:02 +02:00
};
const App = connect(mapStateToProps)(AppComponent);
2020-12-30 12:54:00 +02:00
export default class Root extends React.Component {
public render() {
2017-05-09 22:46:54 +02:00
return (
<Provider store={store}>
<App/>
2017-05-09 22:46:54 +02:00
</Provider>
);
}
2017-05-09 21:59:14 +02:00
}