chore: address PR reviews

pull/3022/head
Audric Ackermann 4 months ago
parent a8a564b4fe
commit 81c1263bfd

@ -2,6 +2,8 @@
const { clipboard, ipcRenderer, webFrame } = require('electron/main'); const { clipboard, ipcRenderer, webFrame } = require('electron/main');
const { Storage } = require('./ts/util/storage'); const { Storage } = require('./ts/util/storage');
const { isTestNet, isTestIntegration } = require('./ts/shared/env_vars');
const url = require('url'); const url = require('url');
const _ = require('lodash'); const _ = require('lodash');
@ -22,19 +24,14 @@ window.getTitle = () => title;
window.getEnvironment = () => configAny.environment; window.getEnvironment = () => configAny.environment;
window.getAppInstance = () => configAny.appInstance; window.getAppInstance = () => configAny.appInstance;
window.getVersion = () => configAny.version; window.getVersion = () => configAny.version;
window.isDev = () => config.environment === 'development';
window.getCommitHash = () => configAny.commitHash; window.getCommitHash = () => configAny.commitHash;
window.getNodeVersion = () => configAny.node_version; window.getNodeVersion = () => configAny.node_version;
window.sessionFeatureFlags = { window.sessionFeatureFlags = {
useOnionRequests: true, useOnionRequests: true,
useTestNet: Boolean( useTestNet: isTestNet(),
process.env.NODE_APP_INSTANCE && process.env.NODE_APP_INSTANCE.includes('testnet') integrationTestEnv: isTestIntegration(),
), useClosedGroupV3: false,
integrationTestEnv: Boolean(
process.env.NODE_APP_INSTANCE && process.env.NODE_APP_INSTANCE.includes('test-integration')
),
useClosedGroupV3: false || process.env.USE_CLOSED_GROUP_V3,
debug: { debug: {
debugLogging: !_.isEmpty(process.env.SESSION_DEBUG), debugLogging: !_.isEmpty(process.env.SESSION_DEBUG),
debugLibsessionDumps: !_.isEmpty(process.env.SESSION_DEBUG_LIBSESSION_DUMPS), debugLibsessionDumps: !_.isEmpty(process.env.SESSION_DEBUG_LIBSESSION_DUMPS),

@ -94,36 +94,36 @@ function useIsRenderedExpiresInItem(messageId: string) {
return expiryDetails.expirationTimestamp; return expiryDetails.expirationTimestamp;
} }
function formatExpiry({ diffMs }: { diffMs: number }) { function formatTimeLeft({ timeLeftMs }: { timeLeftMs: number }) {
const diff = moment(diffMs).utc(); const timeLeft = moment(timeLeftMs).utc();
if (diffMs <= 0) { if (timeLeftMs <= 0) {
return `0s`; return `0s`;
} }
const prefix = 'Message will expire in'; const prefix = 'Message will expire in';
if (diff.isBefore(moment.utc(0).add(1, 'minute'))) { if (timeLeft.isBefore(moment.utc(0).add(1, 'minute'))) {
return `${prefix} ${diff.seconds()}s`; return `${prefix} ${timeLeft.seconds()}s`;
} }
if (diff.isBefore(moment.utc(0).add(1, 'hour'))) { if (timeLeft.isBefore(moment.utc(0).add(1, 'hour'))) {
const extraUnit = diff.seconds() ? ` ${diff.seconds()}s` : ''; const extraUnit = timeLeft.seconds() ? ` ${timeLeft.seconds()}s` : '';
return `${prefix} ${diff.minutes()}m${extraUnit}`; return `${prefix} ${timeLeft.minutes()}m${extraUnit}`;
} }
if (diff.isBefore(moment.utc(0).add(1, 'day'))) { if (timeLeft.isBefore(moment.utc(0).add(1, 'day'))) {
const extraUnit = diff.minutes() ? ` ${diff.minutes()}m` : ''; const extraUnit = timeLeft.minutes() ? ` ${timeLeft.minutes()}m` : '';
return `${prefix} ${diff.hours()}h${extraUnit}`; return `${prefix} ${timeLeft.hours()}h${extraUnit}`;
} }
if (diff.isBefore(moment.utc(0).add(7, 'day'))) { if (timeLeft.isBefore(moment.utc(0).add(7, 'day'))) {
const extraUnit = diff.hours() ? ` ${diff.hours()}h` : ''; const extraUnit = timeLeft.hours() ? ` ${timeLeft.hours()}h` : '';
return `${prefix} ${diff.dayOfYear() - 1}d${extraUnit}`; return `${prefix} ${timeLeft.dayOfYear() - 1}d${extraUnit}`;
} }
if (diff.isBefore(moment.utc(0).add(31, 'day'))) { if (timeLeft.isBefore(moment.utc(0).add(31, 'day'))) {
const days = diff.dayOfYear() - 1; const days = timeLeft.dayOfYear() - 1;
const weeks = Math.floor(days / 7); const weeks = Math.floor(days / 7);
const daysLeft = days % 7; const daysLeft = days % 7;
const extraUnit = daysLeft ? ` ${daysLeft}d` : ''; const extraUnit = daysLeft ? ` ${daysLeft}d` : '';
@ -136,15 +136,18 @@ function formatExpiry({ diffMs }: { diffMs: number }) {
const ExpiresInItem = ({ expirationTimestamp }: { expirationTimestamp?: number | null }) => { const ExpiresInItem = ({ expirationTimestamp }: { expirationTimestamp?: number | null }) => {
// this boolean is just used to forceRefresh the state when we get to display seconds in the contextmenu // this boolean is just used to forceRefresh the state when we get to display seconds in the contextmenu
const [refresh, setRefresh] = useBoolean(false); const [refresh, setRefresh] = useBoolean(false);
const diffMs = (expirationTimestamp || 0) - Date.now(); const timeLeftMs = (expirationTimestamp || 0) - Date.now();
useInterval( useInterval(
() => { () => {
setRefresh(!refresh); setRefresh(!refresh);
}, },
diffMs > 0 && diffMs <= 2 * DURATION.MINUTES ? 500 : null // We want to force refresh this component a lot more if the message has more than 2 minutes before disappearing,
// because when that's the case we also display the seconds left (i.e. 1min 23s) and we want that 23s to be dynamic.
// Also, we use a refresh interval of 500 rather than 1s so that the counter is a bit smoother
timeLeftMs > 0 && timeLeftMs <= 2 * DURATION.MINUTES ? 500 : null
); );
if (!expirationTimestamp || diffMs < 0) { if (!expirationTimestamp || timeLeftMs < 0) {
return null; return null;
} }
@ -152,7 +155,7 @@ const ExpiresInItem = ({ expirationTimestamp }: { expirationTimestamp?: number |
<StyledExpiresIn> <StyledExpiresIn>
<SessionIcon iconSize={'small'} iconType="stopwatch" /> <SessionIcon iconSize={'small'} iconType="stopwatch" />
<SpacerSM /> <SpacerSM />
<span>{formatExpiry({ diffMs })}</span> <span>{formatTimeLeft({ timeLeftMs })}</span>
</StyledExpiresIn> </StyledExpiresIn>
); );
}; };

@ -19,6 +19,7 @@ import {
useMessageTimestamp, useMessageTimestamp,
} from '../../../../../../state/selectors'; } from '../../../../../../state/selectors';
import { isDevProd } from '../../../../../../shared/env_vars';
import { Flex } from '../../../../../basic/Flex'; import { Flex } from '../../../../../basic/Flex';
import { SpacerSM } from '../../../../../basic/Text'; import { SpacerSM } from '../../../../../basic/Text';
@ -64,8 +65,6 @@ const showDebugLog = () => {
ipcRenderer.send('show-debug-log'); ipcRenderer.send('show-debug-log');
}; };
const showDebugMessageInfo = false;
const DebugMessageInfo = ({ messageId }: { messageId: string }) => { const DebugMessageInfo = ({ messageId }: { messageId: string }) => {
const messageHash = useMessageHash(messageId); const messageHash = useMessageHash(messageId);
const serverId = useMessageServerId(messageId); const serverId = useMessageServerId(messageId);
@ -73,7 +72,7 @@ const DebugMessageInfo = ({ messageId }: { messageId: string }) => {
const expirationDurationMs = useMessageExpirationDurationMs(messageId); const expirationDurationMs = useMessageExpirationDurationMs(messageId);
const expirationTimestamp = useMessageExpirationTimestamp(messageId); const expirationTimestamp = useMessageExpirationTimestamp(messageId);
if (!showDebugMessageInfo) { if (!isDevProd()) {
return null; return null;
} }

@ -87,10 +87,9 @@ import { windowMarkShouldQuit, windowShouldQuit } from '../node/window_state'; /
let appStartInitialSpellcheckSetting = true; let appStartInitialSpellcheckSetting = true;
const isTestIntegration = Boolean( function openDevToolsTestIntegration() {
process.env.NODE_APP_INSTANCE && process.env.NODE_APP_INSTANCE.includes('test-integration') return isTestIntegration() && !isEmpty(process.env.TEST_OPEN_DEV_TOOLS);
); }
const openDevToolsTestIntegration = isTestIntegration && !isEmpty(process.env.TEST_OPEN_DEV_TOOLS);
async function getSpellCheckSetting() { async function getSpellCheckSetting() {
const json = sqlNode.getItemById('spell-check'); const json = sqlNode.getItemById('spell-check');
@ -159,6 +158,7 @@ if (windowFromUserConfig) {
import { getAppRootPath } from '../node/getRootPath'; import { getAppRootPath } from '../node/getRootPath';
import { setLastestRelease } from '../node/latest_desktop_release'; import { setLastestRelease } from '../node/latest_desktop_release';
import { load as loadLocale, LocaleMessagesWithNameType } from '../node/locale'; import { load as loadLocale, LocaleMessagesWithNameType } from '../node/locale';
import { isDevProd, isTestIntegration } from '../shared/env_vars';
import { classicDark } from '../themes'; import { classicDark } from '../themes';
// Both of these will be set after app fires the 'ready' event // Both of these will be set after app fires the 'ready' event
@ -215,7 +215,7 @@ function captureClicks(window: BrowserWindow) {
function getDefaultWindowSize() { function getDefaultWindowSize() {
return { return {
defaultWidth: 880, defaultWidth: 880,
defaultHeight: openDevToolsTestIntegration ? 1000 : 820, // the dev tools open at the bottom hide some stuff which should be visible defaultHeight: openDevToolsTestIntegration() ? 1000 : 820, // the dev tools open at the bottom hide some stuff which should be visible
minWidth: 880, minWidth: 880,
minHeight: 600, minHeight: 600,
}; };
@ -274,7 +274,7 @@ async function createWindow() {
y: (windowConfig as any).y, y: (windowConfig as any).y,
}; };
if (isTestIntegration) { if (isTestIntegration()) {
const screenWidth = const screenWidth =
screen.getPrimaryDisplay().workAreaSize.width - getDefaultWindowSize().defaultWidth; screen.getPrimaryDisplay().workAreaSize.width - getDefaultWindowSize().defaultWidth;
const screenHeight = const screenHeight =
@ -416,7 +416,7 @@ async function createWindow() {
const urlToLoad = prepareURL([getAppRootPath(), 'background.html']); const urlToLoad = prepareURL([getAppRootPath(), 'background.html']);
await mainWindow.loadURL(urlToLoad); await mainWindow.loadURL(urlToLoad);
if (openDevToolsTestIntegration) { if (openDevToolsTestIntegration()) {
setTimeout(() => { setTimeout(() => {
if (mainWindow && mainWindow.webContents) { if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.openDevTools({ mainWindow.webContents.openDevTools({
@ -427,7 +427,7 @@ async function createWindow() {
}, 5000); }, 5000);
} }
if ((process.env.NODE_APP_INSTANCE || '').startsWith('devprod')) { if (isDevProd()) {
// Open the DevTools. // Open the DevTools.
mainWindow.webContents.openDevTools({ mainWindow.webContents.openDevTools({
mode: 'bottom', mode: 'bottom',

@ -117,7 +117,7 @@ export function markAttributesAsReadIfNeeded(messageAttributes: MessageAttribute
latestUnreadForThisConvo?.lastRead && latestUnreadForThisConvo?.lastRead &&
sentAt <= latestUnreadForThisConvo.lastRead sentAt <= latestUnreadForThisConvo.lastRead
) { ) {
// That message was sent before our last read timestamp for that conversation. // The message was sent before our last read timestamp for that conversation.
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
messageAttributes.unread = READ_MESSAGE_STATE.read; messageAttributes.unread = READ_MESSAGE_STATE.read;
} }

@ -547,7 +547,7 @@ function getMessageReadyToDisappear(
/** /**
* Edge case: when we send a message before we poll for a message sent earlier, our convo volatile update will * Edge case: when we send a message before we poll for a message sent earlier, our convo volatile update will
* mark that incoming message as read right away (because it was sent earlier than our latest convolatile lastRead). * mark that incoming message as read right away (because it was sent earlier than our latest convolatile lastRead).
* To take care of this case, we need to check if the expiration of an incoming DaR, alreadt marked as read message looks to not have been updated yet. * To take care of this case, we need to check if an incoming DaR message is in a read state but its expiration has not been updated yet.
* The way we do it, is by checking that the swarm expiration is before (now + expireTimer). * The way we do it, is by checking that the swarm expiration is before (now + expireTimer).
* If it looks like this expiration was not updated yet, we need to trigger a UpdateExpiryJob for that message. * If it looks like this expiration was not updated yet, we need to trigger a UpdateExpiryJob for that message.
*/ */

@ -1,5 +1,5 @@
import { isEmpty } from 'lodash';
import moment from 'moment'; import moment from 'moment';
import { isDevProd } from '../../shared/env_vars';
import { LocalizerKeys } from '../../types/LocalizerKeys'; import { LocalizerKeys } from '../../types/LocalizerKeys';
type TimerOptionsEntry = { name: string; value: number }; type TimerOptionsEntry = { name: string; value: number };
@ -67,12 +67,7 @@ const VALUES: Array<number> = timerOptionsDurations.map(t => {
}); });
const filterOutDebugValues = (option: number) => { const filterOutDebugValues = (option: number) => {
// process.env.NODE_APP_INSTANCE is empty when the app is packaged, and not empty when starting from start-prod or start-dev return isDevProd() || option > 60; // when not a dev build, filter out options with less than 60s
const isPackaged = isEmpty(process.env.NODE_APP_INSTANCE);
if (isPackaged) {
return option > 60; // when packaged, filter out options with less than 60s
}
return true;
}; };
const DELETE_AFTER_READ = VALUES.filter(option => { const DELETE_AFTER_READ = VALUES.filter(option => {

@ -0,0 +1,16 @@
function envAppInstanceIncludes(prefix: string) {
if (!process.env.NODE_APP_INSTANCE) {
return false;
}
return !!process.env.NODE_APP_INSTANCE.includes(prefix);
}
export function isDevProd() {
return envAppInstanceIncludes('devprod');
}
export function isTestNet() {
return envAppInstanceIncludes('testnet');
}
export function isTestIntegration() {
return envAppInstanceIncludes('test-integration');
}

@ -3,6 +3,7 @@
import { escapeRegExp, isEmpty, isRegExp, isString } from 'lodash'; import { escapeRegExp, isEmpty, isRegExp, isString } from 'lodash';
import { compose } from 'lodash/fp'; import { compose } from 'lodash/fp';
import { getAppRootPath } from '../node/getRootPath'; import { getAppRootPath } from '../node/getRootPath';
import { isDevProd } from '../shared/env_vars';
const APP_ROOT_PATH = getAppRootPath(); const APP_ROOT_PATH = getAppRootPath();
const SESSION_ID_PATTERN = /\b((05)?[0-9a-f]{64})\b/gi; const SESSION_ID_PATTERN = /\b((05)?[0-9a-f]{64})\b/gi;
@ -103,7 +104,7 @@ function shouldNotRedactLogs() {
return true; return true;
} }
// otherwise we don't want to redact logs when running on the devprod env // otherwise we don't want to redact logs when running on the devprod env
return (process.env.NODE_APP_INSTANCE || '').startsWith('devprod'); return isDevProd();
} }
// redactAll :: String -> String // redactAll :: String -> String

13
ts/window.d.ts vendored

@ -17,14 +17,11 @@ If you import anything in global.d.ts, the type system won't work correctly.
declare global { declare global {
interface Window { interface Window {
CONSTANTS: any;
Events: any; Events: any;
Lodash: any;
Session: any; Session: any;
Whisper: any; Whisper: any;
clearLocalData: any; clearLocalData: () => Promise<void>;
clipboard: any; clipboard: any;
dcodeIO: any;
getSettingValue: (id: string, comparisonValue?: any) => any; getSettingValue: (id: string, comparisonValue?: any) => any;
setSettingValue: (id: string, value: any) => Promise<void>; setSettingValue: (id: string, value: any) => Promise<void>;
@ -43,22 +40,20 @@ declare global {
debugOnionRequests: boolean; debugOnionRequests: boolean;
}; };
}; };
SessionSnodeAPI: SessionSnodeAPI;
onLogin: (pw: string) => Promise<void>; onLogin: (pw: string) => Promise<void>;
persistStore?: Persistor; persistStore?: Persistor;
restart: any; restart: () => void;
getSeedNodeList: () => Array<string> | undefined; getSeedNodeList: () => Array<string> | undefined;
setPassword: any; setPassword: (newPassword: string | null, oldPassword: string | null) => Promise<void>;
isOnline: boolean; isOnline: boolean;
toggleMediaPermissions: () => Promise<void>; toggleMediaPermissions: () => Promise<void>;
toggleCallMediaPermissionsTo: (enabled: boolean) => Promise<void>; toggleCallMediaPermissionsTo: (enabled: boolean) => Promise<void>;
getCallMediaPermissions: () => boolean; getCallMediaPermissions: () => boolean;
toggleMenuBar: () => void; toggleMenuBar: () => void;
toggleSpellCheck: any; toggleSpellCheck: () => void;
primaryColor: PrimaryColorStateType; primaryColor: PrimaryColorStateType;
theme: ThemeStateType; theme: ThemeStateType;
setTheme: (newTheme: string) => Promise<void>; setTheme: (newTheme: string) => Promise<void>;
isDev?: () => boolean;
userConfig: any; userConfig: any;
versionInfo: any; versionInfo: any;
getConversations: () => ConversationCollection; getConversations: () => ConversationCollection;

Loading…
Cancel
Save