Skip to content

Commit

Permalink
fix cors issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Kalydosos committed Dec 8, 2024
1 parent a655399 commit 9f29282
Show file tree
Hide file tree
Showing 6 changed files with 23 additions and 52 deletions.
Binary file removed assets/images/loadingspinner.gif
Binary file not shown.
56 changes: 18 additions & 38 deletions src/components/Image/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import {useSession} from '@components/OnyxProvider';
import {isExpiredSession} from '@libs/actions/Session';
import {activate as activateReauthenticator} from '@libs/actions/Session/Reauthenticator';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import BaseImage from './BaseImage';
import {ImageBehaviorContext} from './ImageBehaviorContextProvider';
import type {ImageOnLoadEvent, ImageProps} from './types';
Expand All @@ -12,13 +12,12 @@ function Image({source: propsSource, isAuthTokenRequired = false, onLoad, object
const [aspectRatio, setAspectRatio] = useState<string | number | null>(null);
const isObjectPositionTop = objectPosition === CONST.IMAGE_OBJECT_POSITION.TOP;
const session = useSession();
if (session.creationDate) console.log(`@51888 initialize with session ${new Date(session.creationDate).toISOString()} `);
let displayActivityIndicator = false;

const {shouldSetAspectRatioInStyle} = useContext(ImageBehaviorContext);

const updateAspectRatio = useCallback(
(width: number, height: number) => {
console.log(`@51888 updateAspectRatio`);
if (!isObjectPositionTop) {
return;
}
Expand All @@ -36,63 +35,46 @@ function Image({source: propsSource, isAuthTokenRequired = false, onLoad, object
const handleLoad = useCallback(
(event: ImageOnLoadEvent) => {
const {width, height} = event.nativeEvent;
console.log(`@51888 onload image width ${width} height ${height}`);
onLoad?.(event);
updateAspectRatio(width, height);
},
[onLoad, updateAspectRatio],
);

// an accpeted session is either received less than 60s after the previous
// or is dated from 2H after and is now quite
const isAcceptedSession = useCallback(
(sessionCreationDateDiff : number, sessionCreationDate : number) => {
return (sessionCreationDateDiff < 60000
|| (sessionCreationDateDiff >= CONST.SESSIONS_MAXIDLE_TIME_MS
&& new Date().getTime() - sessionCreationDate < 60000));
},[]
);
// an accepted session is either received less than 60s after the previous
// or is the first valid session since previous session expired
const isAcceptedSession = useCallback((sessionCreationDateDiff: number, sessionCreationDate: number) => {
return sessionCreationDateDiff < 60000 || (sessionCreationDateDiff >= CONST.SESSIONS_MAXIDLE_TIME_MS && new Date().getTime() - sessionCreationDate < 60000);
}, []);

/**
* trying to figure out if the current session is expired or fresh from a necessary reauthentication
*/
const previousSessionAge = useRef<number | undefined>();
const validSessionAge: number | undefined = useMemo(() => {
// for performance gain, the processing is reserved to attachments images only
if (!isAuthTokenRequired){
if (!isAuthTokenRequired) {
return undefined;
}
if (session?.creationDate) {
console.log(`@51888 setting validSessionAge with session ${new Date(session.creationDate).toISOString()} `);
if (previousSessionAge.current) {
console.log(`@51888 setting validSessionAge with previousSessionAge.current ${new Date(previousSessionAge.current).toISOString()} `);
// most likely a reauthentication happens
// but unless the calculated source is different from the previous, the image wont reload
if (isAcceptedSession(session.creationDate - previousSessionAge.current, session.creationDate)) {
console.log(`@51888 setting validSessionAge to new session received less than 60s ago or newer from 2H`);
return session.creationDate;
}
console.log(`@51888 setting validSessionAge to unchanged`);
return previousSessionAge.current;
}
else {
console.log(`@51888 setting validSessionAge with previousSessionAge.current ${previousSessionAge?.current}`);
}
if (isExpiredSession(session.creationDate)) {
console.log(`@51888 setting validSessionAge to now as session is expired`);
return new Date().getTime();
}
console.log(`@51888 setting validSessionAge to current session ${new Date(session.creationDate).toISOString()}`);
return session.creationDate;
}
console.log(`@51888 setting validSessionAge with session ${session?.creationDate} `);
return undefined;
}, [session]);

Check warning on line 74 in src/components/Image/index.tsx

View workflow job for this annotation

GitHub Actions / ESLint check

React Hook useMemo has missing dependencies: 'isAcceptedSession' and 'isAuthTokenRequired'. Either include them or remove the dependency array

Check warning on line 74 in src/components/Image/index.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

React Hook useMemo has missing dependencies: 'isAcceptedSession' and 'isAuthTokenRequired'. Either include them or remove the dependency array
useEffect(() => {

Check failure on line 75 in src/components/Image/index.tsx

View workflow job for this annotation

GitHub Actions / ESLint check

Prefer an early return to a conditionally-wrapped function body

Check failure on line 75 in src/components/Image/index.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Prefer an early return to a conditionally-wrapped function body
// for performance gain, the processing is reserved to attachments images only
if (isAuthTokenRequired){
if (isAuthTokenRequired) {
previousSessionAge.current = validSessionAge;
console.log(`@51888 useEffect setting previousSessionAge to ${validSessionAge?new Date(validSessionAge).toISOString():validSessionAge}`);
}
});

Expand All @@ -103,32 +85,29 @@ function Image({source: propsSource, isAuthTokenRequired = false, onLoad, object
// source could be a result of require or a number or an object but all are expected so no unsafe-assignment
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const source = useMemo(() => {
console.log(`@51888 calculating source`);
if (typeof propsSource === 'object' && 'uri' in propsSource) {
if (typeof propsSource.uri === 'number') {
console.log(`@51888 source as number `, propsSource.uri);
return propsSource.uri;
}
const authToken = session?.encryptedAuthToken ?? null;
if (isAuthTokenRequired && authToken) {
if (!!session?.creationDate && !isExpiredSession(session.creationDate)) {
// session valid
console.log(`@51888 source with token `, propsSource);
return {
...propsSource,
headers: {
[CONST.CHAT_ATTACHMENT_TOKEN_KEY]: authToken,
},
};
}
console.log(`@51888 source as spinner `);
if (session) activateReauthenticator(session);
// source could be a result of require, it is expected so no unsafe-assignment
if (session) {
activateReauthenticator(session);
}
displayActivityIndicator = true;

Check warning on line 106 in src/components/Image/index.tsx

View workflow job for this annotation

GitHub Actions / ESLint check

Assignments to the 'displayActivityIndicator' variable from inside React Hook useMemo will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useMemo

Check warning on line 106 in src/components/Image/index.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Assignments to the 'displayActivityIndicator' variable from inside React Hook useMemo will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useMemo
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return require('@assets/images/loadingspinner.gif'); // loading before session changes
return undefined;
}
}
console.log(`@51888 source as default `, propsSource);
return propsSource;
// The session prop is not required, as it causes the image to reload whenever the session changes. For more information, please refer to issue #26034.
// but we still need the image to reload sometimes (exemple : when the current session is expired)
Expand All @@ -141,7 +120,9 @@ function Image({source: propsSource, isAuthTokenRequired = false, onLoad, object
*/
const shouldOpacityBeZero = isObjectPositionTop && !aspectRatio;

return (
return displayActivityIndicator ? (
<FullScreenLoadingIndicator />
) : (
<BaseImage
// eslint-disable-next-line react/jsx-props-no-spreading
{...forwardedProps}
Expand All @@ -154,7 +135,6 @@ function Image({source: propsSource, isAuthTokenRequired = false, onLoad, object
}

function imagePropsAreEqual(prevProps: ImageProps, nextProps: ImageProps) {
console.log(`@51888 imagePropsAreEqual? `, {'prev' : prevProps.source, 'next' : nextProps.source});
return prevProps.source === nextProps.source;
}

Expand Down
1 change: 0 additions & 1 deletion src/components/Image/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ type ExpoImageSource = ImageSource | number | ImageSource[];

type ImageObjectPosition = ValueOf<typeof CONST.IMAGE_OBJECT_POSITION>;


type ImageOnLoadEvent = {
nativeEvent: {
width: number;
Expand Down
3 changes: 0 additions & 3 deletions src/libs/Middleware/Reauthentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ function resetReauthentication(): void {
const Reauthentication: Middleware = (response, request, isFromSequentialQueue) =>
response
.then((data) => {
console.log(`@51888 middleware reauthenttication has reauthenticate`);
// If there is no data for some reason then we cannot reauthenticate
if (!data) {
Log.hmmm('Undefined data in Reauthentication');
Expand Down Expand Up @@ -98,7 +97,6 @@ const Reauthentication: Middleware = (response, request, isFromSequentialQueue)
MainQueue.replay(request);
return data;
}

return reauthenticate(request?.commandName)
.then((authenticateResponse) => {
if (isFromSequentialQueue || apiRequestType === CONST.API_REQUEST_TYPE.MAKE_REQUEST_WITH_SIDE_EFFECTS) {
Expand Down Expand Up @@ -135,7 +133,6 @@ const Reauthentication: Middleware = (response, request, isFromSequentialQueue)
return data;
})
.catch((error) => {
console.log(`@51888 middleware reauthenttication failed reauthenticate`);
// If the request is on the sequential queue, re-throw the error so we can decide to retry or not
if (isFromSequentialQueue) {
throw error;
Expand Down
14 changes: 5 additions & 9 deletions src/libs/actions/Session/Reauthenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ let isOffline = false;
let active = false;
let currentActiveSession: Session = {};
let timer: NodeJS.Timeout;
const TIMING_BEFORE_REAUTHENTICATION_MS = 10000; // 10
const TIMING_BEFORE_REAUTHENTICATION_MS = 8500; // 8.5s

// We subscribe to network's online/offline status
Onyx.connect({
Expand All @@ -16,17 +16,18 @@ Onyx.connect({
if (!network) {
return;
}
isOffline = !!network.isOffline || !!network.shouldForceOffline;
isOffline = !!network.shouldForceOffline || !!network.isOffline;
},
});

// We subscribe to sessions changes
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {

Check failure on line 26 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / ESLint check

Prefer an early return to a conditionally-wrapped function body

Check failure on line 26 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Prefer an early return to a conditionally-wrapped function body
console.log(`@51888 reauthenticator new session received`, value);
if (value && !isSameSession(value)) {
if (active) deactivate();
if (active) {
deactivate();
}
}
},
});
Expand All @@ -36,7 +37,6 @@ function isSameSession(session: Session): boolean {
}

function deactivate() {
console.log(`@51888 reauthenticator deactivating`);
active = false;
currentActiveSession = {};
clearInterval(timer);
Expand All @@ -50,10 +50,8 @@ function deactivate() {
*/
function activate(session: Session) {
if (!session || isSameSession(session) || isOffline) {
console.log(`@51888 reauthenticator activation requested but already active or offline`);
return;
}
console.log(`@51888 reauthenticator activating`);
currentActiveSession = session;
active = true;
// no need to Timers.register()
Expand All @@ -62,11 +60,9 @@ function activate(session: Session) {

function tryReauthenticate() {

Check failure on line 61 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / ESLint check

Prefer an early return to a conditionally-wrapped function body

Check failure on line 61 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Prefer an early return to a conditionally-wrapped function body
if (!isOffline && active) {
console.log(`@51888 reauthenticator reauthenticating`);
reauthenticate();
return;

Check failure on line 64 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / ESLint check

Unnecessary return statement

Check failure on line 64 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Unnecessary return statement
}
console.log(`@51888 reauthenticator must not reauthenticating`);
}

export {activate};

Check failure on line 68 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / ESLint check

Prefer default export on a file with single export

Check failure on line 68 in src/libs/actions/Session/Reauthenticator.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Prefer default export on a file with single export
1 change: 0 additions & 1 deletion src/libs/actions/Session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (value) => {
session = value ?? {};
console.log(`@51888 Session received new session `, value);
if (!session.creationDate) {
session.creationDate = new Date().getTime();
}
Expand Down

0 comments on commit 9f29282

Please sign in to comment.